summaryrefslogtreecommitdiff
path: root/Source/Core
diff options
context:
space:
mode:
authorGravatar tabarbe <unknown>2010-08-20 22:32:24 +0000
committerGravatar tabarbe <unknown>2010-08-20 22:32:24 +0000
commit72b39a6962d7f6c7ca1aab9919791238c7baba3f (patch)
tree75bb9c1b956d1b368f4cf2983a20a913211dd350 /Source/Core
parent96d9624e9e22dbe9090e0bd7d538cafbf0a16463 (diff)
Boogie: Committing changed source files
Diffstat (limited to 'Source/Core')
-rw-r--r--Source/Core/Absy.cs3273
-rw-r--r--Source/Core/AbsyCmd.cs2047
-rw-r--r--Source/Core/AbsyExpr.cs3080
-rw-r--r--Source/Core/AbsyQuant.cs836
-rw-r--r--Source/Core/AbsyType.cs2539
-rw-r--r--Source/Core/BoogiePL.atg561
-rw-r--r--Source/Core/CommandLineOptions.cs1276
-rw-r--r--Source/Core/Core.csproj370
-rw-r--r--Source/Core/DeadVarElim.cs2347
-rw-r--r--Source/Core/Duplicator.cs656
-rw-r--r--Source/Core/GraphAlgorithms.cs249
-rw-r--r--Source/Core/Inline.cs595
-rw-r--r--Source/Core/LambdaHelper.cs82
-rw-r--r--Source/Core/LoopUnroll.cs194
-rw-r--r--Source/Core/Makefile8
-rw-r--r--Source/Core/OOLongUtil.cs82
-rw-r--r--Source/Core/Parser.cs747
-rw-r--r--Source/Core/ParserHelper.cs346
-rw-r--r--Source/Core/PureCollections.cs990
-rw-r--r--Source/Core/ResolutionContext.cs995
-rw-r--r--Source/Core/Scanner.cs88
-rw-r--r--Source/Core/StandardVisitor.cs500
-rw-r--r--Source/Core/TypeAmbiguitySeeker.cs99
-rw-r--r--Source/Core/Util.cs860
-rw-r--r--Source/Core/VCExp.cs156
-rw-r--r--Source/Core/Xml.cs318
26 files changed, 13479 insertions, 9815 deletions
diff --git a/Source/Core/Absy.cs b/Source/Core/Absy.cs
index 4d0113ee..e8fdc385 100644
--- a/Source/Core/Absy.cs
+++ b/Source/Core/Absy.cs
@@ -6,23 +6,33 @@
//---------------------------------------------------------------------------------------------
// BoogiePL - Absy.cs
//---------------------------------------------------------------------------------------------
-namespace Microsoft.Boogie.AbstractInterpretation
-{
+namespace Microsoft.Boogie.AbstractInterpretation {
using System.Diagnostics;
+ using System.Diagnostics.Contracts;
using CCI = System.Compiler;
using System.Collections;
using AI = Microsoft.AbstractInterpretationFramework;
- public class CallSite
- {
- public readonly Implementation! Impl;
- public readonly Block! Block;
+ public class CallSite {
+ public readonly Implementation/*!*/ Impl;
+ public readonly Block/*!*/ Block;
public readonly int Statement; // invariant: Block[Statement] is CallCmd
- public readonly AI.Lattice.Element! KnownBeforeCall;
- public readonly ProcedureSummaryEntry! SummaryEntry;
-
- public CallSite (Implementation! impl, Block! b, int stmt, AI.Lattice.Element! e, ProcedureSummaryEntry! summaryEntry)
- {
+ public readonly AI.Lattice.Element/*!*/ KnownBeforeCall;
+ public readonly ProcedureSummaryEntry/*!*/ SummaryEntry;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Impl != null);
+ Contract.Invariant(Block != null);
+ Contract.Invariant(KnownBeforeCall != null);
+ Contract.Invariant(SummaryEntry != null);
+ }
+
+
+ public CallSite(Implementation impl, Block b, int stmt, AI.Lattice.Element e, ProcedureSummaryEntry summaryEntry) {
+ Contract.Requires(summaryEntry != null);
+ Contract.Requires(e != null);
+ Contract.Requires(b != null);
+ Contract.Requires(impl != null);
this.Impl = impl;
this.Block = b;
this.Statement = stmt;
@@ -31,15 +41,23 @@ namespace Microsoft.Boogie.AbstractInterpretation
}
}
- public class ProcedureSummaryEntry
- {
- public AI.Lattice! Lattice;
- public AI.Lattice.Element! OnEntry;
- public AI.Lattice.Element! OnExit;
- public CCI.IMutableSet/*<CallSite>*/! ReturnPoints; // whenever OnExit changes, we start analysis again at all the ReturnPoints
+ public class ProcedureSummaryEntry {
+ public AI.Lattice/*!*/ Lattice;
+ public AI.Lattice.Element/*!*/ OnEntry;
+ public AI.Lattice.Element/*!*/ OnExit;
+ public CCI.IMutableSet/*<CallSite>*//*!*/ ReturnPoints; // whenever OnExit changes, we start analysis again at all the ReturnPoints
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Lattice != null);
+ Contract.Invariant(OnEntry != null);
+ Contract.Invariant(OnExit != null);
+ Contract.Invariant(ReturnPoints != null);
+ }
- public ProcedureSummaryEntry (AI.Lattice! lattice, AI.Lattice.Element! onEntry)
- {
+
+ public ProcedureSummaryEntry(AI.Lattice lattice, AI.Lattice.Element onEntry) {
+ Contract.Requires(onEntry != null);
+ Contract.Requires(lattice != null);
this.Lattice = lattice;
this.OnEntry = onEntry;
this.OnExit = lattice.Bottom;
@@ -51,41 +69,56 @@ namespace Microsoft.Boogie.AbstractInterpretation
public class ProcedureSummary : ArrayList/*<ProcedureSummaryEntry>*/
{
- invariant !IsReadOnly && !IsFixedSize;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(
+ !IsReadOnly && !IsFixedSize);
+ }
- public new ProcedureSummaryEntry! this [int i]
- {
- get
- requires 0 <= i && i < Count;
- { return (ProcedureSummaryEntry!) base[i]; }
+ public new ProcedureSummaryEntry/*!*/ this[int i] {
+ get {
+ Contract.Requires(0 <= i && i < Count);
+ Contract.Ensures(Contract.Result<ProcedureSummaryEntry>() != null);
+ return cce.NonNull((ProcedureSummaryEntry/*!*/)base[i]);
+ }
}
} // class
} // namespace
-
-namespace Microsoft.Boogie
-{
+namespace Microsoft.Boogie {
using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
+ using System.Diagnostics.Contracts;
using Microsoft.Boogie.AbstractInterpretation;
using AI = Microsoft.AbstractInterpretationFramework;
- using Microsoft.Contracts;
using Graphing;
-
- public abstract class Absy
- {
- public IToken! tok;
+ [ContractClass(typeof(AbsyContracts))]
+ public abstract class Absy {
+ public IToken/*!*/ tok;
private int uniqueId;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ }
+
- public int Line { get { return tok != null ? tok.line : -1; } }
- public int Col { get { return tok != null ? tok.col : -1; } }
+ public int Line {
+ get {
+ return tok != null ? tok.line : -1;
+ }
+ }
+ public int Col {
+ get {
+ return tok != null ? tok.col : -1;
+ }
+ }
- public Absy (IToken! tok)
- {
+ public Absy(IToken tok) {
+ Contract.Requires(tok != null);
this.tok = tok;
this.uniqueId = AbsyNodeCount++;
// base();
@@ -96,59 +129,85 @@ namespace Microsoft.Boogie
// We uniquely number every AST node to make them
// suitable for our implementation of functional maps.
//
- public int UniqueId { get { return this.uniqueId; } }
+ public int UniqueId {
+ get {
+ return this.uniqueId;
+ }
+ }
private const int indent_size = 2;
- protected static string Indent (int level)
- {
+ protected static string Indent(int level) {
return new string(' ', (indent_size * level));
}
-
- public abstract void Resolve (ResolutionContext! rc);
+ [NeedsContracts]
+ public abstract void Resolve(ResolutionContext/*!*/ rc);
/// <summary>
/// Requires the object to have been successfully resolved.
/// </summary>
/// <param name="tc"></param>
- public abstract void Typecheck (TypecheckingContext! tc);
+ [NeedsContracts]
+ public abstract void Typecheck(TypecheckingContext/*!*/ tc);
/// <summary>
/// Intorduced this so the uniqueId is not the same on a cloned object.
/// </summary>
/// <param name="tc"></param>
- public virtual Absy! Clone()
- {
- Absy! result = (Absy!) this.MemberwiseClone();
+ public virtual Absy Clone() {
+ Contract.Ensures(Contract.Result<Absy>() != null);
+ Absy/*!*/ result = cce.NonNull((Absy/*!*/)this.MemberwiseClone());
result.uniqueId = AbsyNodeCount++; // BUGBUG??
return result;
}
- public virtual Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public virtual Absy StdDispatch(StandardVisitor visitor) {
+ Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
System.Diagnostics.Debug.Fail("Unknown Absy node type: " + this.GetType());
throw new System.NotImplementedException();
}
}
+ [ContractClassFor(typeof(Absy))]
+ public abstract class AbsyContracts : Absy {
+ public override void Resolve(ResolutionContext rc) {
+ Contract.Requires(rc != null);
+ throw new NotImplementedException();
+ }
+ public AbsyContracts() :base(null){
+
+ }
+ public override void Typecheck(TypecheckingContext tc) {
+ Contract.Requires(tc != null);
+ throw new NotImplementedException();
+ }
+ }
+
// TODO: Ideally, this would use generics.
- public interface IPotentialErrorNode
- {
- object ErrorData { get; set; }
+ public interface IPotentialErrorNode {
+ object ErrorData {
+ get;
+ set;
+ }
}
- public class Program : Absy
- {
+ public class Program : Absy {
[Rep]
- public List<Declaration!>! TopLevelDeclarations;
+ public List<Declaration/*!*/>/*!*/ TopLevelDeclarations;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(TopLevelDeclarations));
+ Contract.Invariant(globals == null || cce.NonNullElements(globals));
+ }
+
public Program()
- : base(Token.NoToken)
- {
- this.TopLevelDeclarations = new List<Declaration!>();
+ : base(Token.NoToken) {
+ this.TopLevelDeclarations = new List<Declaration>();
// base(Token.NoToken);
}
- public void Emit (TokenTextWriter! stream)
- {
+ public void Emit(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
stream.SetToken(this);
Emitter.Declarations(this.TopLevelDeclarations, stream);
}
@@ -156,29 +215,27 @@ namespace Microsoft.Boogie
/// Returns the number of name resolution errors.
/// </summary>
/// <returns></returns>
- public int Resolve ()
- {
- return Resolve((IErrorSink) null);
+ public int Resolve() {
+ return Resolve((IErrorSink)null);
}
- public int Resolve (IErrorSink errorSink)
- {
+ public int Resolve(IErrorSink errorSink) {
ResolutionContext rc = new ResolutionContext(errorSink);
Resolve(rc);
return rc.ErrorCount;
}
- public override void Resolve (ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
Helpers.ExtraTraceInformation("Starting resolution");
-
+
foreach (Declaration d in TopLevelDeclarations) {
d.Register(rc);
}
ResolveTypes(rc);
- List<Declaration!> prunedTopLevelDecls = CommandLineOptions.Clo.OverlookBoogieTypeErrors ? new List<Declaration!>() : null;
+ List<Declaration/*!*/> prunedTopLevelDecls = CommandLineOptions.Clo.OverlookBoogieTypeErrors ? new List<Declaration/*!*/>() : null;
foreach (Declaration d in TopLevelDeclarations) {
// resolve all the non-type-declarations
@@ -212,7 +269,8 @@ namespace Microsoft.Boogie
}
- private void ResolveTypes (ResolutionContext! rc) {
+ private void ResolveTypes(ResolutionContext rc) {
+ Contract.Requires(rc != null);
// first resolve type constructors
foreach (Declaration d in TopLevelDeclarations) {
if (d is TypeCtorDecl)
@@ -220,8 +278,9 @@ namespace Microsoft.Boogie
}
// collect type synonym declarations
- List<TypeSynonymDecl!>! synonymDecls = new List<TypeSynonymDecl!> ();
+ List<TypeSynonymDecl/*!*/>/*!*/ synonymDecls = new List<TypeSynonymDecl/*!*/>();
foreach (Declaration d in TopLevelDeclarations) {
+ Contract.Assert(d != null);
if (d is TypeSynonymDecl)
synonymDecls.Add((TypeSynonymDecl)d);
}
@@ -230,22 +289,19 @@ namespace Microsoft.Boogie
// fixed-point iteration
TypeSynonymDecl.ResolveTypeSynonyms(synonymDecls, rc);
}
-
- public int Typecheck ()
- {
- return this.Typecheck((IErrorSink) null);
+ public int Typecheck() {
+ return this.Typecheck((IErrorSink)null);
}
- public int Typecheck (IErrorSink errorSink)
- {
+ public int Typecheck(IErrorSink errorSink) {
TypecheckingContext tc = new TypecheckingContext(errorSink);
Typecheck(tc);
return tc.ErrorCount;
}
- public override void Typecheck (TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
Helpers.ExtraTraceInformation("Starting typechecking");
int oldErrorCount = tc.ErrorCount;
@@ -255,7 +311,7 @@ namespace Microsoft.Boogie
if (oldErrorCount == tc.ErrorCount) {
// check whether any type proxies have remained uninstantiated
- TypeAmbiguitySeeker! seeker = new TypeAmbiguitySeeker (tc);
+ TypeAmbiguitySeeker/*!*/ seeker = new TypeAmbiguitySeeker(tc);
foreach (Declaration d in TopLevelDeclarations) {
seeker.Visit(d);
}
@@ -265,15 +321,13 @@ namespace Microsoft.Boogie
expander.CollectExpansions();
}
- public void ComputeStronglyConnectedComponents()
- {
- foreach(Declaration d in this.TopLevelDeclarations) {
+ public void ComputeStronglyConnectedComponents() {
+ foreach (Declaration d in this.TopLevelDeclarations) {
d.ComputeStronglyConnectedComponents();
}
}
- public void InstrumentWithInvariants ()
- {
+ public void InstrumentWithInvariants() {
foreach (Declaration d in this.TopLevelDeclarations) {
d.InstrumentWithInvariants();
}
@@ -282,301 +336,300 @@ namespace Microsoft.Boogie
/// <summary>
/// Reset the abstract stated computed before
/// </summary>
- public void ResetAbstractInterpretationState()
- {
- foreach(Declaration d in this.TopLevelDeclarations) {
+ public void ResetAbstractInterpretationState() {
+ foreach (Declaration d in this.TopLevelDeclarations) {
d.ResetAbstractInterpretationState();
}
}
- public void UnrollLoops(int n)
- requires 0 <= n;
- {
+ public void UnrollLoops(int n) {
+ Contract.Requires(0 <= n);
foreach (Declaration d in this.TopLevelDeclarations) {
Implementation impl = d as Implementation;
if (impl != null && impl.Blocks != null && impl.Blocks.Count > 0) {
- expose (impl) {
+ cce.BeginExpose(impl);
+ {
Block start = impl.Blocks[0];
- assume start != null;
- assume start.IsConsistent;
+ Contract.Assume(start != null);
+ Contract.Assume(cce.IsConsistent(start));
impl.Blocks = LoopUnroll.UnrollLoops(start, n);
}
+ cce.EndExpose();
}
}
}
- void CreateProceduresForLoops(Implementation! impl, Graph<Block!>! g, List<Implementation!>! loopImpls)
- {
- // Enumerate the headers
- // for each header h:
- // create implementation p_h with
- // inputs = inputs, outputs, and locals of impl
- // outputs = outputs and locals of impl
- // locals = empty set
- // add call o := p_h(i) at the beginning of the header block
- // break the back edges whose target is h
- // Enumerate the headers again to create the bodies of p_h
- // for each header h:
- // compute the loop corresponding to h
- // make copies of all blocks in the loop for h
- // delete all target edges that do not go to a block in the loop
- // create a new entry block and a new return block
- // add edges from entry block to the loop header and the return block
- // add calls o := p_h(i) at the end of the blocks that are sources of back edges
- Dictionary<Block!, string!>! loopHeaderToName = new Dictionary<Block!, string!>();
- Dictionary<Block!, VariableSeq!>! loopHeaderToInputs = new Dictionary<Block!, VariableSeq!>();
- Dictionary<Block!, VariableSeq!>! loopHeaderToOutputs = new Dictionary<Block!, VariableSeq!>();
- Dictionary<Block!, Hashtable!>! loopHeaderToSubstMap = new Dictionary<Block!, Hashtable!>();
- Dictionary<Block!, Procedure!>! loopHeaderToLoopProc = new Dictionary<Block!, Procedure!>();
- Dictionary<Block!, CallCmd!>! loopHeaderToCallCmd = new Dictionary<Block!, CallCmd!>();
- foreach (Block! header in g.Headers)
- {
- Contract.Assert(header != null);
- string name = header.ToString();
- loopHeaderToName[header] = name;
- VariableSeq inputs = new VariableSeq();
- VariableSeq outputs = new VariableSeq();
- ExprSeq callInputs = new ExprSeq();
- IdentifierExprSeq callOutputs = new IdentifierExprSeq();
- Hashtable substMap = new Hashtable(); // Variable -> IdentifierExpr
-
- foreach (Variable! v in impl.InParams)
- {
- callInputs.Add(new IdentifierExpr(Token.NoToken, v));
- Formal f = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "in_" + v.Name, v.TypedIdent.Type), true);
- inputs.Add(f);
- substMap[v] = new IdentifierExpr(Token.NoToken, f);
- }
- foreach (Variable! v in impl.OutParams)
- {
- callInputs.Add(new IdentifierExpr(Token.NoToken, v));
- inputs.Add(new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "in_" + v.Name, v.TypedIdent.Type), true));
- callOutputs.Add(new IdentifierExpr(Token.NoToken, v));
- Formal f = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "out_" + v.Name, v.TypedIdent.Type), false);
- outputs.Add(f);
- substMap[v] = new IdentifierExpr(Token.NoToken, f);
- }
- foreach (Variable! v in impl.LocVars)
- {
- callInputs.Add(new IdentifierExpr(Token.NoToken, v));
- inputs.Add(new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "in_" + v.Name, v.TypedIdent.Type), true));
- callOutputs.Add(new IdentifierExpr(Token.NoToken, v));
- Formal f = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "out_" + v.Name, v.TypedIdent.Type), false);
- outputs.Add(f);
- substMap[v] = new IdentifierExpr(Token.NoToken, f);
+ void CreateProceduresForLoops(Implementation impl, Graph<Block/*!*/>/*!*/ g, List<Implementation/*!*/>/*!*/ loopImpls) {
+ Contract.Requires(impl != null);
+ Contract.Requires(cce.NonNullElements(loopImpls));
+ Contract.Requires(cce.NonNullElements(g.TopologicalSort()));
+ // Enumerate the headers
+ // for each header h:
+ // create implementation p_h with
+ // inputs = inputs, outputs, and locals of impl
+ // outputs = outputs and locals of impl
+ // locals = empty set
+ // add call o := p_h(i) at the beginning of the header block
+ // break the back edges whose target is h
+ // Enumerate the headers again to create the bodies of p_h
+ // for each header h:
+ // compute the loop corresponding to h
+ // make copies of all blocks in the loop for h
+ // delete all target edges that do not go to a block in the loop
+ // create a new entry block and a new return block
+ // add edges from entry block to the loop header and the return block
+ // add calls o := p_h(i) at the end of the blocks that are sources of back edges
+ Dictionary<Block/*!*/, string/*!*/>/*!*/ loopHeaderToName = new Dictionary<Block/*!*/, string/*!*/>();
+ Dictionary<Block/*!*/, VariableSeq/*!*/>/*!*/ loopHeaderToInputs = new Dictionary<Block/*!*/, VariableSeq/*!*/>();
+ Dictionary<Block/*!*/, VariableSeq/*!*/>/*!*/ loopHeaderToOutputs = new Dictionary<Block/*!*/, VariableSeq/*!*/>();
+ Dictionary<Block/*!*/, Hashtable/*!*/>/*!*/ loopHeaderToSubstMap = new Dictionary<Block/*!*/, Hashtable/*!*/>();
+ Dictionary<Block/*!*/, Procedure/*!*/>/*!*/ loopHeaderToLoopProc = new Dictionary<Block/*!*/, Procedure/*!*/>();
+ Dictionary<Block/*!*/, CallCmd/*!*/>/*!*/ loopHeaderToCallCmd = new Dictionary<Block/*!*/, CallCmd/*!*/>();
+ foreach (Block/*!*/ header in g.Headers) {
+ Contract.Assert(header != null);
+ Contract.Assert(header != null);
+ string name = header.ToString();
+ loopHeaderToName[header] = name;
+ VariableSeq inputs = new VariableSeq();
+ VariableSeq outputs = new VariableSeq();
+ ExprSeq callInputs = new ExprSeq();
+ IdentifierExprSeq callOutputs = new IdentifierExprSeq();
+ Hashtable substMap = new Hashtable(); // Variable -> IdentifierExpr
+
+ foreach (Variable/*!*/ v in impl.InParams) {
+ Contract.Assert(v != null);
+ callInputs.Add(new IdentifierExpr(Token.NoToken, v));
+ Formal f = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "in_" + v.Name, v.TypedIdent.Type), true);
+ inputs.Add(f);
+ substMap[v] = new IdentifierExpr(Token.NoToken, f);
+ }
+ foreach (Variable/*!*/ v in impl.OutParams) {
+ Contract.Assert(v != null);
+ callInputs.Add(new IdentifierExpr(Token.NoToken, v));
+ inputs.Add(new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "in_" + v.Name, v.TypedIdent.Type), true));
+ callOutputs.Add(new IdentifierExpr(Token.NoToken, v));
+ Formal f = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "out_" + v.Name, v.TypedIdent.Type), false);
+ outputs.Add(f);
+ substMap[v] = new IdentifierExpr(Token.NoToken, f);
+ }
+ foreach (Variable/*!*/ v in impl.LocVars) {
+ Contract.Assert(v != null);
+ callInputs.Add(new IdentifierExpr(Token.NoToken, v));
+ inputs.Add(new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "in_" + v.Name, v.TypedIdent.Type), true));
+ callOutputs.Add(new IdentifierExpr(Token.NoToken, v));
+ Formal f = new Formal(Token.NoToken, new TypedIdent(Token.NoToken, "out_" + v.Name, v.TypedIdent.Type), false);
+ outputs.Add(f);
+ substMap[v] = new IdentifierExpr(Token.NoToken, f);
+ }
+ VariableSeq/*!*/ targets = new VariableSeq();
+ foreach (Block/*!*/ b in g.BackEdgeNodes(header)) {
+ Contract.Assert(b != null);
+ foreach (Block/*!*/ block in g.NaturalLoops(header, b)) {
+ Contract.Assert(block != null);
+ foreach (Cmd/*!*/ cmd in block.Cmds) {
+ Contract.Assert(cmd != null);
+ cmd.AddAssignedVariables(targets);
}
- VariableSeq! targets = new VariableSeq();
- foreach (Block! b in g.BackEdgeNodes(header))
- {
- foreach (Block! block in g.NaturalLoops(header, b))
- {
- foreach (Cmd! cmd in block.Cmds)
- {
- cmd.AddAssignedVariables(targets);
- }
+ }
+ }
+ IdentifierExprSeq/*!*/ globalMods = new IdentifierExprSeq();
+ Set globalModsSet = new Set();
+ foreach (Variable/*!*/ v in targets) {
+ Contract.Assert(v != null);
+ if (!(v is GlobalVariable))
+ continue;
+ if (globalModsSet.Contains(v))
+ continue;
+ globalModsSet.Add(v);
+ globalMods.Add(new IdentifierExpr(Token.NoToken, v));
+ }
+ loopHeaderToInputs[header] = inputs;
+ loopHeaderToOutputs[header] = outputs;
+ loopHeaderToSubstMap[header] = substMap;
+ Procedure/*!*/ proc =
+ new Procedure(Token.NoToken, "loop_" + header.ToString(),
+ new TypeVariableSeq(), inputs, outputs,
+ new RequiresSeq(), globalMods, new EnsuresSeq());
+ if (CommandLineOptions.Clo.LazyInlining > 0 || CommandLineOptions.Clo.StratifiedInlining > 0) {
+ proc.AddAttribute("inline", Expr.Literal(1));
+ }
+ loopHeaderToLoopProc[header] = proc;
+ CallCmd callCmd = new CallCmd(Token.NoToken, name, callInputs, callOutputs);
+ callCmd.Proc = proc;
+ loopHeaderToCallCmd[header] = callCmd;
+ }
+
+ foreach (Block/*!*/ header in g.Headers) {
+ Contract.Assert(header != null);
+ Procedure loopProc = loopHeaderToLoopProc[header];
+ Dictionary<Block, Block> blockMap = new Dictionary<Block, Block>();
+ CodeCopier codeCopier = new CodeCopier(loopHeaderToSubstMap[header]); // fix me
+ VariableSeq inputs = loopHeaderToInputs[header];
+ VariableSeq outputs = loopHeaderToOutputs[header];
+ foreach (Block/*!*/ source in g.BackEdgeNodes(header)) {
+ Contract.Assert(source != null);
+ foreach (Block/*!*/ block in g.NaturalLoops(header, source)) {
+ Contract.Assert(block != null);
+ if (blockMap.ContainsKey(block))
+ continue;
+ Block newBlock = new Block();
+ newBlock.Label = block.Label;
+ newBlock.Cmds = codeCopier.CopyCmdSeq(block.Cmds);
+ blockMap[block] = newBlock;
+ }
+ string callee = loopHeaderToName[header];
+ ExprSeq ins = new ExprSeq();
+ IdentifierExprSeq outs = new IdentifierExprSeq();
+ for (int i = 0; i < impl.InParams.Length; i++) {
+ ins.Add(new IdentifierExpr(Token.NoToken, cce.NonNull(inputs[i])));
+ }
+ foreach (Variable/*!*/ v in outputs) {
+ Contract.Assert(v != null);
+ ins.Add(new IdentifierExpr(Token.NoToken, v));
+ outs.Add(new IdentifierExpr(Token.NoToken, v));
+ }
+ CallCmd callCmd = new CallCmd(Token.NoToken, callee, ins, outs);
+ callCmd.Proc = loopProc;
+ Block/*!*/ block1 = new Block(Token.NoToken, source.Label + "_dummy",
+ new CmdSeq(new AssumeCmd(Token.NoToken, Expr.False)), new ReturnCmd(Token.NoToken));
+ Block/*!*/ block2 = new Block(Token.NoToken, block1.Label,
+ new CmdSeq(callCmd), new ReturnCmd(Token.NoToken));
+ impl.Blocks.Add(block1);
+
+ GotoCmd gotoCmd = source.TransferCmd as GotoCmd;
+ Contract.Assert(gotoCmd != null && gotoCmd.labelNames != null && gotoCmd.labelTargets != null && gotoCmd.labelTargets.Length >= 1);
+ StringSeq/*!*/ newLabels = new StringSeq();
+ BlockSeq/*!*/ newTargets = new BlockSeq();
+ for (int i = 0; i < gotoCmd.labelTargets.Length; i++) {
+ if (gotoCmd.labelTargets[i] == header)
+ continue;
+ newTargets.Add(gotoCmd.labelTargets[i]);
+ newLabels.Add(gotoCmd.labelNames[i]);
+ }
+ newTargets.Add(block1);
+ newLabels.Add(block1.Label);
+ gotoCmd.labelNames = newLabels;
+ gotoCmd.labelTargets = newTargets;
+
+ blockMap[block1] = block2;
+ }
+ List<Block/*!*/>/*!*/ blocks = new List<Block/*!*/>();
+ Block exit = new Block(Token.NoToken, "exit", new CmdSeq(), new ReturnCmd(Token.NoToken));
+ GotoCmd cmd = new GotoCmd(Token.NoToken,
+ new StringSeq(cce.NonNull(blockMap[header]).Label, exit.Label),
+ new BlockSeq(blockMap[header], exit));
+
+ Debug.Assert(outputs.Length + impl.InParams.Length == inputs.Length);
+ List<AssignLhs/*!*/>/*!*/ lhss = new List<AssignLhs/*!*/>();
+ List<Expr/*!*/>/*!*/ rhss = new List<Expr/*!*/>();
+ for (int i = impl.InParams.Length; i < inputs.Length; i++) {
+ Variable/*!*/ inv = cce.NonNull(inputs[i]);
+ Variable/*!*/ outv = cce.NonNull(outputs[i - impl.InParams.Length]);
+ AssignLhs lhs = new SimpleAssignLhs(Token.NoToken, new IdentifierExpr(Token.NoToken, outv));
+ Expr rhs = new IdentifierExpr(Token.NoToken, inv);
+ lhss.Add(lhs);
+ rhss.Add(rhs);
+ }
+ AssignCmd assignCmd = new AssignCmd(Token.NoToken, lhss, rhss);
+ Block entry = new Block(Token.NoToken, "entry", new CmdSeq(assignCmd), cmd);
+ blocks.Add(entry);
+ foreach (Block/*!*/ block in blockMap.Keys) {
+ Contract.Assert(block != null);
+ Block/*!*/ newBlock = cce.NonNull(blockMap[block]);
+ GotoCmd gotoCmd = block.TransferCmd as GotoCmd;
+ if (gotoCmd == null) {
+ newBlock.TransferCmd = new ReturnCmd(Token.NoToken);
+ } else {
+ Contract.Assume(gotoCmd.labelNames != null && gotoCmd.labelTargets != null);
+ StringSeq newLabels = new StringSeq();
+ BlockSeq newTargets = new BlockSeq();
+ for (int i = 0; i < gotoCmd.labelTargets.Length; i++) {
+ Block target = gotoCmd.labelTargets[i];
+ if (blockMap.ContainsKey(target)) {
+ newLabels.Add(gotoCmd.labelNames[i]);
+ newTargets.Add(blockMap[target]);
}
}
- IdentifierExprSeq! globalMods = new IdentifierExprSeq();
- Set globalModsSet = new Set();
- foreach (Variable! v in targets)
- {
- if (!(v is GlobalVariable)) continue;
- if (globalModsSet.Contains(v)) continue;
- globalModsSet.Add(v);
- globalMods.Add(new IdentifierExpr(Token.NoToken, v));
- }
- loopHeaderToInputs[header] = inputs;
- loopHeaderToOutputs[header] = outputs;
- loopHeaderToSubstMap[header] = substMap;
- Procedure! proc =
- new Procedure(Token.NoToken, "loop_" + header.ToString(),
- new TypeVariableSeq(), inputs, outputs,
- new RequiresSeq(), globalMods, new EnsuresSeq());
- if (CommandLineOptions.Clo.LazyInlining > 0 || CommandLineOptions.Clo.StratifiedInlining > 0)
- {
- proc.AddAttribute("inline", Expr.Literal(1));
+ if (newTargets.Length == 0) {
+ newBlock.Cmds.Add(new AssumeCmd(Token.NoToken, Expr.False));
+ newBlock.TransferCmd = new ReturnCmd(Token.NoToken);
+ } else {
+ newBlock.TransferCmd = new GotoCmd(Token.NoToken, newLabels, newTargets);
}
- loopHeaderToLoopProc[header] = proc;
- CallCmd callCmd = new CallCmd(Token.NoToken, name, callInputs, callOutputs);
- callCmd.Proc = proc;
- loopHeaderToCallCmd[header] = callCmd;
+ }
+ blocks.Add(newBlock);
}
+ blocks.Add(exit);
+ Implementation loopImpl =
+ new Implementation(Token.NoToken, loopProc.Name,
+ new TypeVariableSeq(), inputs, outputs, new VariableSeq(), blocks);
+ loopImpl.Proc = loopProc;
+ loopImpls.Add(loopImpl);
- foreach (Block! header in g.Headers)
- {
- Procedure loopProc = loopHeaderToLoopProc[header];
- Dictionary<Block, Block> blockMap = new Dictionary<Block, Block>();
- CodeCopier codeCopier = new CodeCopier(loopHeaderToSubstMap[header]); // fix me
- VariableSeq inputs = loopHeaderToInputs[header];
- VariableSeq outputs = loopHeaderToOutputs[header];
- foreach (Block! source in g.BackEdgeNodes(header))
- {
- foreach (Block! block in g.NaturalLoops(header, source))
- {
- if (blockMap.ContainsKey(block)) continue;
- Block newBlock = new Block();
- newBlock.Label = block.Label;
- newBlock.Cmds = codeCopier.CopyCmdSeq(block.Cmds);
- blockMap[block] = newBlock;
- }
- string callee = loopHeaderToName[header];
- ExprSeq ins = new ExprSeq();
- IdentifierExprSeq outs = new IdentifierExprSeq();
- for (int i = 0; i < impl.InParams.Length; i++)
- {
- ins.Add(new IdentifierExpr(Token.NoToken, (!) inputs[i]));
- }
- foreach (Variable! v in outputs)
- {
- ins.Add(new IdentifierExpr(Token.NoToken, v));
- outs.Add(new IdentifierExpr(Token.NoToken, v));
- }
- CallCmd callCmd = new CallCmd(Token.NoToken, callee, ins, outs);
- callCmd.Proc = loopProc;
- Block! block1 = new Block(Token.NoToken, source.Label + "_dummy",
- new CmdSeq(new AssumeCmd(Token.NoToken, Expr.False)), new ReturnCmd(Token.NoToken));
- Block! block2 = new Block(Token.NoToken, block1.Label,
- new CmdSeq(callCmd), new ReturnCmd(Token.NoToken));
- impl.Blocks.Add(block1);
-
- GotoCmd gotoCmd = source.TransferCmd as GotoCmd;
- assert gotoCmd != null && gotoCmd.labelNames != null && gotoCmd.labelTargets != null && gotoCmd.labelTargets.Length >= 1;
- StringSeq! newLabels = new StringSeq();
- BlockSeq! newTargets = new BlockSeq();
- for (int i = 0; i < gotoCmd.labelTargets.Length; i++)
- {
- if (gotoCmd.labelTargets[i] == header) continue;
- newTargets.Add(gotoCmd.labelTargets[i]);
- newLabels.Add(gotoCmd.labelNames[i]);
- }
- newTargets.Add(block1);
- newLabels.Add(block1.Label);
- gotoCmd.labelNames = newLabels;
- gotoCmd.labelTargets = newTargets;
-
- blockMap[block1] = block2;
- }
- List<Block!>! blocks = new List<Block!>();
- Block exit = new Block(Token.NoToken, "exit", new CmdSeq(), new ReturnCmd(Token.NoToken));
- GotoCmd cmd = new GotoCmd(Token.NoToken,
- new StringSeq(((!)blockMap[header]).Label, exit.Label),
- new BlockSeq(blockMap[header], exit));
-
- Debug.Assert(outputs.Length + impl.InParams.Length == inputs.Length);
- List<AssignLhs!>! lhss = new List<AssignLhs!>();
- List<Expr!>! rhss = new List<Expr!>();
- for (int i = impl.InParams.Length; i < inputs.Length; i++)
- {
- Variable! inv = (!)inputs[i];
- Variable! outv = (!)outputs[i - impl.InParams.Length];
- AssignLhs lhs = new SimpleAssignLhs(Token.NoToken, new IdentifierExpr(Token.NoToken, outv));
- Expr rhs = new IdentifierExpr(Token.NoToken, inv);
- lhss.Add(lhs);
- rhss.Add(rhs);
- }
- AssignCmd assignCmd = new AssignCmd(Token.NoToken, lhss, rhss);
- Block entry = new Block(Token.NoToken, "entry", new CmdSeq(assignCmd), cmd);
- blocks.Add(entry);
- foreach (Block! block in blockMap.Keys)
- {
- Block! newBlock = (!) blockMap[block];
- GotoCmd gotoCmd = block.TransferCmd as GotoCmd;
- if (gotoCmd == null)
- {
- newBlock.TransferCmd = new ReturnCmd(Token.NoToken);
- }
- else
- {
- assume gotoCmd.labelNames != null && gotoCmd.labelTargets != null;
- StringSeq newLabels = new StringSeq();
- BlockSeq newTargets = new BlockSeq();
- for (int i = 0; i < gotoCmd.labelTargets.Length; i++)
- {
- Block target = gotoCmd.labelTargets[i];
- if (blockMap.ContainsKey(target))
- {
- newLabels.Add(gotoCmd.labelNames[i]);
- newTargets.Add(blockMap[target]);
- }
- }
- if (newTargets.Length == 0)
- {
- newBlock.Cmds.Add(new AssumeCmd(Token.NoToken, Expr.False));
- newBlock.TransferCmd = new ReturnCmd(Token.NoToken);
- }
- else
- {
- newBlock.TransferCmd = new GotoCmd(Token.NoToken, newLabels, newTargets);
- }
- }
- blocks.Add(newBlock);
- }
- blocks.Add(exit);
- Implementation loopImpl =
- new Implementation(Token.NoToken, loopProc.Name,
- new TypeVariableSeq(), inputs, outputs, new VariableSeq(), blocks);
- loopImpl.Proc = loopProc;
- loopImpls.Add(loopImpl);
-
- // Finally, add call to the loop in the containing procedure
- CmdSeq cmdSeq = new CmdSeq();
- cmdSeq.Add(loopHeaderToCallCmd[header]);
- cmdSeq.AddRange(header.Cmds);
- header.Cmds = cmdSeq;
- }
- }
-
- public static Graph<Block!>! GraphFromImpl(Implementation! impl) {
+ // Finally, add call to the loop in the containing procedure
+ CmdSeq cmdSeq = new CmdSeq();
+ cmdSeq.Add(loopHeaderToCallCmd[header]);
+ cmdSeq.AddRange(header.Cmds);
+ header.Cmds = cmdSeq;
+ }
+ }
+
+ public static Graph<Block/*!*/>/*!*/ GraphFromImpl(Implementation impl) {
+ Contract.Requires(impl != null);
+ Contract.Ensures(cce.NonNullElements(Contract.Result<Graph<Block>>().TopologicalSort()));
Contract.Ensures(Contract.Result<Graph<Block>>() != null);
- Graph<Block!> g = new Graph<Block!>();
+ Graph<Block/*!*/> g = new Graph<Block/*!*/>();
g.AddSource(impl.Blocks[0]); // there is always at least one node in the graph
foreach (Block b in impl.Blocks) {
Contract.Assert(b != null);
GotoCmd gtc = b.TransferCmd as GotoCmd;
if (gtc != null) {
- foreach (Block! dest in (!)gtc.labelTargets) {
+ foreach (Block/*!*/ dest in cce.NonNull(gtc.labelTargets)) {
+ Contract.Assert(dest != null);
g.AddEdge(b, dest);
}
}
}
return g;
}
-
- public void ExtractLoops()
- {
- List<Implementation!>! loopImpls = new List<Implementation!>();
+
+ public void ExtractLoops() {
+ List<Implementation/*!*/>/*!*/ loopImpls = new List<Implementation/*!*/>();
foreach (Declaration d in this.TopLevelDeclarations) {
Implementation impl = d as Implementation;
if (impl != null && impl.Blocks != null && impl.Blocks.Count > 0) {
- Graph<Block!>! g = GraphFromImpl(impl);
- g.ComputeLoops();
- if (!g.Reducible)
- {
- throw new Exception("Irreducible flow graphs are unsupported.");
- }
- CreateProceduresForLoops(impl, g, loopImpls);
+ Graph<Block/*!*/>/*!*/ g = GraphFromImpl(impl);
+ Contract.Assert(cce.NonNullElements(g.TopologicalSort()));
+ g.ComputeLoops();
+ if (!g.Reducible) {
+ throw new Exception("Irreducible flow graphs are unsupported.");
+ }
+ CreateProceduresForLoops(impl, g, loopImpls);
}
}
- foreach (Implementation! loopImpl in loopImpls)
- {
+ foreach (Implementation/*!*/ loopImpl in loopImpls) {
+ Contract.Assert(loopImpl != null);
TopLevelDeclarations.Add(loopImpl);
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitProgram(this);
}
-
- private List<GlobalVariable!> globals = null;
- public List<GlobalVariable!>! GlobalVariables()
- {
- if (globals != null) return globals;
- globals = new List<GlobalVariable!>();
+
+ private List<GlobalVariable/*!*/> globals = null;
+ public List<GlobalVariable/*!*/>/*!*/ GlobalVariables() {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<GlobalVariable>>()));
+ if (globals != null)
+ return globals;
+ globals = new List<GlobalVariable/*!*/>();
foreach (Declaration d in TopLevelDeclarations) {
GlobalVariable gvar = d as GlobalVariable;
- if (gvar != null) globals.Add(gvar);
+ if (gvar != null)
+ globals.Add(gvar);
}
return globals;
}
@@ -585,32 +638,32 @@ namespace Microsoft.Boogie
//---------------------------------------------------------------------
// Declarations
- public abstract class Declaration : Absy
- {
+ [ContractClass(typeof(DeclarationContracts))]
+ public abstract class Declaration : Absy {
public QKeyValue Attributes;
- public Declaration(IToken! tok)
- : base(tok)
- {
+ public Declaration(IToken tok)
+ : base(tok) {
+ Contract.Requires(tok != null);
}
- protected void EmitAttributes(TokenTextWriter! stream)
- {
+ protected void EmitAttributes(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
for (QKeyValue kv = this.Attributes; kv != null; kv = kv.Next) {
kv.Emit(stream);
stream.Write(" ");
}
}
- protected void ResolveAttributes(ResolutionContext! rc)
- {
+ protected void ResolveAttributes(ResolutionContext rc) {
+ Contract.Requires(rc != null);
for (QKeyValue kv = this.Attributes; kv != null; kv = kv.Next) {
kv.Resolve(rc);
}
}
- protected void TypecheckAttributes(TypecheckingContext! rc)
- {
+ protected void TypecheckAttributes(TypecheckingContext rc) {
+ Contract.Requires(rc != null);
for (QKeyValue kv = this.Attributes; kv != null; kv = kv.Next) {
kv.Typecheck(rc);
}
@@ -620,9 +673,9 @@ namespace Microsoft.Boogie
// (which is not touched if there is no attribute specified).
//
// Returns false is there was an error processing the flag, true otherwise.
- public bool CheckBooleanAttribute(string! name, ref bool result)
- {
- Expr? expr = FindExprAttribute(name);
+ public bool CheckBooleanAttribute(string name, ref bool result) {
+ Contract.Requires(name != null);
+ Expr expr = FindExprAttribute(name);
if (expr != null) {
if (expr is LiteralExpr && ((LiteralExpr)expr).isBool) {
result = ((LiteralExpr)expr).asBool;
@@ -634,9 +687,9 @@ namespace Microsoft.Boogie
}
// Look for {:name expr} in list of attributes.
- public Expr? FindExprAttribute(string! name)
- {
- Expr? res = null;
+ public Expr FindExprAttribute(string name) {
+ Contract.Requires(name != null);
+ Expr res = null;
for (QKeyValue kv = this.Attributes; kv != null; kv = kv.Next) {
if (kv.Key == name) {
if (kv.Params.Count == 1 && kv.Params[0] is Expr) {
@@ -648,8 +701,8 @@ namespace Microsoft.Boogie
}
// Look for {:name string} in list of attributes.
- public string? FindStringAttribute(string! name)
- {
+ public string FindStringAttribute(string name) {
+ Contract.Requires(name != null);
return QKeyValue.FindStringAttribute(this.Attributes, name);
}
@@ -657,9 +710,9 @@ namespace Microsoft.Boogie
// (which is not touched if there is no attribute specified).
//
// Returns false is there was an error processing the flag, true otherwise.
- public bool CheckIntAttribute(string! name, ref int result)
- {
- Expr? expr = FindExprAttribute(name);
+ public bool CheckIntAttribute(string name, ref int result) {
+ Contract.Requires(name != null);
+ Expr expr = FindExprAttribute(name);
if (expr != null) {
if (expr is LiteralExpr && ((LiteralExpr)expr).isBigNum) {
result = ((LiteralExpr)expr).asBigNum.ToInt;
@@ -670,8 +723,9 @@ namespace Microsoft.Boogie
return true;
}
- public void AddAttribute(string! name, object! val)
- {
+ public void AddAttribute(string name, object val) {
+ Contract.Requires(val != null);
+ Contract.Requires(name != null);
QKeyValue kv;
for (kv = this.Attributes; kv != null; kv = kv.Next) {
if (kv.Key == name) {
@@ -680,58 +734,83 @@ namespace Microsoft.Boogie
}
}
if (kv == null) {
- Attributes = new QKeyValue(tok, name, new List<object!>(new object![] { val }), Attributes);
+ Attributes = new QKeyValue(tok, name, new List<object/*!*/>(new object/*!*/[] { val }), Attributes);
}
- }
-
- public abstract void Emit(TokenTextWriter! stream, int level);
- public abstract void Register(ResolutionContext! rc);
+ }
+
+ public abstract void Emit(TokenTextWriter/*!*/ stream, int level);
+ public abstract void Register(ResolutionContext/*!*/ rc);
/// <summary>
/// Compute the strongly connected components of the declaration.
/// By default, it does nothing
/// </summary>
- public virtual void ComputeStronglyConnectedComponents() { /* Does nothing */}
+ public virtual void ComputeStronglyConnectedComponents() { /* Does nothing */
+ }
/// <summary>
/// This method inserts the abstract-interpretation-inferred invariants
/// as assume (or possibly assert) statements in the statement sequences of
/// each block.
/// </summary>
- public virtual void InstrumentWithInvariants () {}
+ public virtual void InstrumentWithInvariants() {
+ }
/// <summary>
/// Reset the abstract stated computed before
/// </summary>
- public virtual void ResetAbstractInterpretationState() { /* does nothing */ }
+ public virtual void ResetAbstractInterpretationState() { /* does nothing */
+ }
+ }
+ [ContractClassFor(typeof(Declaration))]
+ public abstract class DeclarationContracts : Declaration {
+ public DeclarationContracts() :base(null){
+ }
+ public override void Register(ResolutionContext rc) {
+ Contract.Requires(rc != null);
+ throw new NotImplementedException();
+ }
+ public override void Emit(TokenTextWriter stream, int level) {
+ Contract.Requires(stream != null);
+ throw new NotImplementedException();
+ }
}
- public class Axiom : Declaration
- {
- public Expr! Expr;
- public string? Comment;
+ public class Axiom : Declaration {
+ public Expr/*!*/ Expr;
+ [ContractInvariantMethod]
+ void ExprInvariant() {
+ Contract.Invariant(Expr != null);
+ }
- public Axiom(IToken! tok, Expr! expr)
- {
- this(tok, expr, null);
+ public string Comment;
+
+ public Axiom(IToken tok, Expr expr)
+ : this(tok, expr, null) {
+ Contract.Requires(expr != null);
+ Contract.Requires(tok != null);
+ //:this(tok, expr, null);//BASEMOVEA
}
- public Axiom(IToken! tok, Expr! expr, string? comment)
- : base(tok)
- {
+ public Axiom(IToken/*!*/ tok, Expr/*!*/ expr, string comment)
+ : base(tok) {//BASEMOVE DANGER
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
Expr = expr;
Comment = comment;
- // base(tok);
+ // :base(tok);
}
- public Axiom(IToken! tok, Expr! expr, string? comment, QKeyValue kv)
- {
- this(tok, expr, comment);
+ public Axiom(IToken tok, Expr expr, string comment, QKeyValue kv)
+ : this(tok, expr, comment) {//BASEMOVEA
+ Contract.Requires(expr != null);
+ Contract.Requires(tok != null);
+ //:this(tok, expr, comment);
this.Attributes = kv;
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
if (Comment != null) {
stream.WriteLine(this, level, "// " + Comment);
}
@@ -740,80 +819,86 @@ namespace Microsoft.Boogie
this.Expr.Emit(stream);
stream.WriteLine(";");
}
- public override void Register(ResolutionContext! rc)
- {
+ public override void Register(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
// nothing to register
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
ResolveAttributes(rc);
rc.StateMode = ResolutionContext.State.StateLess;
Expr.Resolve(rc);
rc.StateMode = ResolutionContext.State.Single;
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
TypecheckAttributes(tc);
Expr.Typecheck(tc);
- assert Expr.Type != null; // follows from postcondition of Expr.Typecheck
- if (! Expr.Type.Unify(Type.Bool))
- {
+ Contract.Assert(Expr.Type != null); // follows from postcondition of Expr.Typecheck
+ if (!Expr.Type.Unify(Type.Bool)) {
tc.Error(this, "axioms must be of type bool");
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitAxiom(this);
}
}
- public abstract class NamedDeclaration : Declaration
- {
- private string! name;
- public string! Name
- {
- get
- {
+ public abstract class NamedDeclaration : Declaration {
+ private string/*!*/ name;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(name != null);
+ }
+
+ public string/*!*/ Name {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+
return this.name;
}
- set
- {
+ set {
+ Contract.Requires(value != null);
this.name = value;
}
}
- public NamedDeclaration(IToken! tok, string! name)
- : base(tok)
- {
+ public NamedDeclaration(IToken/*!*/ tok, string/*!*/ name)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
this.name = name;
// base(tok);
}
[Pure]
- public override string! ToString()
- {
- return (!) Name;
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return cce.NonNull(Name);
}
- }
+ }
- public class TypeCtorDecl : NamedDeclaration
- {
+ public class TypeCtorDecl : NamedDeclaration {
public readonly int Arity;
- public TypeCtorDecl(IToken! tok, string! name, int Arity)
- : base(tok, name)
- {
- this.Arity = Arity;
- }
- public TypeCtorDecl(IToken! tok, string! name, int Arity, QKeyValue kv)
- : base(tok, name)
- {
- this.Arity = Arity;
- this.Attributes = kv;
+ public TypeCtorDecl(IToken/*!*/ tok, string/*!*/ name, int Arity)
+ : base(tok, name) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ this.Arity = Arity;
+ }
+ public TypeCtorDecl(IToken/*!*/ tok, string/*!*/ name, int Arity, QKeyValue kv)
+ : base(tok, name) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ this.Arity = Arity;
+ this.Attributes = kv;
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.Write(this, level, "type ");
EmitAttributes(stream);
stream.Write("{0}", TokenTextWriter.SanitizeIdentifier(Name));
@@ -821,48 +906,59 @@ namespace Microsoft.Boogie
stream.Write(" _");
stream.WriteLine(";");
}
- public override void Register(ResolutionContext! rc)
- {
+ public override void Register(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.AddType(this);
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
ResolveAttributes(rc);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
TypecheckAttributes(tc);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitTypeCtorDecl(this);
}
}
+ public class TypeSynonymDecl : NamedDeclaration {
+ public TypeVariableSeq/*!*/ TypeParameters;
+ public Type/*!*/ Body;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(TypeParameters != null);
+ Contract.Invariant(Body != null);
+ }
- public class TypeSynonymDecl : NamedDeclaration
- {
- public TypeVariableSeq! TypeParameters;
- public Type! Body;
- public TypeSynonymDecl(IToken! tok, string! name,
- TypeVariableSeq! typeParams, Type! body)
- : base(tok, name)
- {
+ public TypeSynonymDecl(IToken/*!*/ tok, string/*!*/ name,
+ TypeVariableSeq/*!*/ typeParams, Type/*!*/ body)
+ : base(tok, name) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(body != null);
this.TypeParameters = typeParams;
this.Body = body;
}
- public TypeSynonymDecl(IToken! tok, string! name,
- TypeVariableSeq! typeParams, Type! body, QKeyValue kv)
- : base(tok, name)
- {
+ public TypeSynonymDecl(IToken/*!*/ tok, string/*!*/ name,
+ TypeVariableSeq/*!*/ typeParams, Type/*!*/ body, QKeyValue kv)
+ : base(tok, name) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(body != null);
this.TypeParameters = typeParams;
this.Body = body;
this.Attributes = kv;
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.Write(this, level, "type ");
EmitAttributes(stream);
stream.Write("{0}", TokenTextWriter.SanitizeIdentifier(Name));
@@ -873,46 +969,51 @@ namespace Microsoft.Boogie
Body.Emit(stream);
stream.WriteLine(";");
}
- public override void Register(ResolutionContext! rc)
- {
+ public override void Register(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.AddType(this);
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
ResolveAttributes(rc);
int previousState = rc.TypeBinderState;
try {
- foreach (TypeVariable! v in TypeParameters)
+ foreach (TypeVariable/*!*/ v in TypeParameters) {
+ Contract.Assert(v != null);
rc.AddTypeBinder(v);
+ }
Body = Body.ResolveType(rc);
} finally {
rc.TypeBinderState = previousState;
}
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
TypecheckAttributes(tc);
}
- public static void ResolveTypeSynonyms(List<TypeSynonymDecl!>! synonymDecls,
- ResolutionContext! rc) {
+ public static void ResolveTypeSynonyms(List<TypeSynonymDecl/*!*/>/*!*/ synonymDecls, ResolutionContext/*!*/ rc) {
+ Contract.Requires(cce.NonNullElements(synonymDecls));
+ Contract.Requires(rc != null);
// then discover all dependencies between type synonyms
- IDictionary<TypeSynonymDecl!, List<TypeSynonymDecl!>!>! deps =
- new Dictionary<TypeSynonymDecl!, List<TypeSynonymDecl!>!> ();
- foreach (TypeSynonymDecl! decl in synonymDecls) {
- List<TypeSynonymDecl!>! declDeps = new List<TypeSynonymDecl!> ();
+ IDictionary<TypeSynonymDecl/*!*/, List<TypeSynonymDecl/*!*/>/*!*/>/*!*/ deps =
+ new Dictionary<TypeSynonymDecl/*!*/, List<TypeSynonymDecl/*!*/>/*!*/>();
+ foreach (TypeSynonymDecl/*!*/ decl in synonymDecls) {
+ Contract.Assert(decl != null);
+ List<TypeSynonymDecl/*!*/>/*!*/ declDeps = new List<TypeSynonymDecl/*!*/>();
FindDependencies(decl.Body, declDeps, rc);
deps.Add(decl, declDeps);
}
- List<TypeSynonymDecl!>! resolved = new List<TypeSynonymDecl!> ();
+ List<TypeSynonymDecl/*!*/>/*!*/ resolved = new List<TypeSynonymDecl/*!*/>();
int unresolved = synonymDecls.Count - resolved.Count;
while (unresolved > 0) {
- foreach (TypeSynonymDecl! decl in synonymDecls) {
+ foreach (TypeSynonymDecl/*!*/ decl in synonymDecls) {
+ Contract.Assert(decl != null);
if (!resolved.Contains(decl) &&
- forall{TypeSynonymDecl! d in deps[decl]; resolved.Contains(d)}) {
+ Contract.ForAll(deps[decl], d => resolved.Contains(d))) {
decl.Resolve(rc);
resolved.Add(decl);
}
@@ -924,12 +1025,13 @@ namespace Microsoft.Boogie
unresolved = newUnresolved;
} else {
// there have to be cycles in the definitions
- foreach (TypeSynonymDecl! decl in synonymDecls) {
+ foreach (TypeSynonymDecl/*!*/ decl in synonymDecls) {
+ Contract.Assert(decl != null);
if (!resolved.Contains(decl)) {
- rc.Error(decl,
- "type synonym could not be resolved because of cycles: {0}" +
- " (replacing body with \"bool\" to continue resolving)",
- decl.Name);
+ rc.Error(decl,
+ "type synonym could not be resolved because of cycles: {0}" +
+ " (replacing body with \"bool\" to continue resolving)",
+ decl.Name);
// we simply replace the bodies of all remaining type
// synonyms with "bool" so that resolution can continue
@@ -944,129 +1046,148 @@ namespace Microsoft.Boogie
}
// determine a list of all type synonyms that occur in "type"
- private static void FindDependencies(Type! type, List<TypeSynonymDecl!>! deps,
- ResolutionContext! rc) {
+ private static void FindDependencies(Type/*!*/ type, List<TypeSynonymDecl/*!*/>/*!*/ deps, ResolutionContext/*!*/ rc) {
+ Contract.Requires(type != null);
+ Contract.Requires(cce.NonNullElements(deps));
+ Contract.Requires(rc != null);
if (type.IsVariable || type.IsBasic) {
// nothing
} else if (type.IsUnresolved) {
- UnresolvedTypeIdentifier! unresType = type.AsUnresolved;
+ UnresolvedTypeIdentifier/*!*/ unresType = type.AsUnresolved;
+ Contract.Assert(unresType != null);
TypeSynonymDecl dep = rc.LookUpTypeSynonym(unresType.Name);
if (dep != null)
deps.Add(dep);
- foreach (Type! subtype in unresType.Arguments)
+ foreach (Type/*!*/ subtype in unresType.Arguments) {
+ Contract.Assert(subtype != null);
FindDependencies(subtype, deps, rc);
+ }
} else if (type.IsMap) {
- MapType! mapType = type.AsMap;
- foreach (Type! subtype in mapType.Arguments)
+ MapType/*!*/ mapType = type.AsMap;
+ Contract.Assert(mapType != null);
+ foreach (Type/*!*/ subtype in mapType.Arguments) {
+ Contract.Assert(subtype != null);
FindDependencies(subtype, deps, rc);
+ }
FindDependencies(mapType.Result, deps, rc);
} else if (type.IsCtor) {
// this can happen because we allow types to be resolved multiple times
- CtorType! ctorType = type.AsCtor;
- foreach (Type! subtype in ctorType.Arguments)
+ CtorType/*!*/ ctorType = type.AsCtor;
+ Contract.Assert(ctorType != null);
+ foreach (Type/*!*/ subtype in ctorType.Arguments) {
+ Contract.Assert(subtype != null);
FindDependencies(subtype, deps, rc);
+ }
} else {
System.Diagnostics.Debug.Fail("Did not expect this type during resolution: "
+ type);
}
}
-
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitTypeSynonymDecl(this);
}
}
+ public abstract class Variable : NamedDeclaration, AI.IVariable {
+ public TypedIdent/*!*/ TypedIdent;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(TypedIdent != null);
+ }
- public abstract class Variable : NamedDeclaration, AI.IVariable
- {
- public TypedIdent! TypedIdent;
- public Variable(IToken! tok, TypedIdent! typedIdent)
- : base(tok, typedIdent.Name)
- {
+ public Variable(IToken/*!*/ tok, TypedIdent/*!*/ typedIdent)
+ : base(tok, typedIdent.Name) {
+ Contract.Requires(tok != null);
+ Contract.Requires(typedIdent != null);
this.TypedIdent = typedIdent;
// base(tok, typedIdent.Name);
}
- public Variable(IToken! tok, TypedIdent! typedIdent, QKeyValue kv)
- : base(tok, typedIdent.Name)
- {
+ public Variable(IToken/*!*/ tok, TypedIdent/*!*/ typedIdent, QKeyValue kv)
+ : base(tok, typedIdent.Name) {
+ Contract.Requires(tok != null);
+ Contract.Requires(typedIdent != null);
this.TypedIdent = typedIdent;
// base(tok, typedIdent.Name);
this.Attributes = kv;
}
- public abstract bool IsMutable
- {
+ public abstract bool IsMutable {
get;
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ Contract.Requires(stream != null);
stream.Write(this, level, "var ");
EmitAttributes(stream);
EmitVitals(stream, level);
stream.WriteLine(";");
}
- public void EmitVitals(TokenTextWriter! stream, int level)
- {
- if (CommandLineOptions.Clo.PrintWithUniqueASTIds && this.TypedIdent.HasName)
- {
+ public void EmitVitals(TokenTextWriter stream, int level) {
+ Contract.Requires(stream != null);
+ if (CommandLineOptions.Clo.PrintWithUniqueASTIds && this.TypedIdent.HasName) {
stream.Write("h{0}^^", this.GetHashCode()); // the idea is that this will prepend the name printed by TypedIdent.Emit
}
this.TypedIdent.Emit(stream);
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ Contract.Requires(rc != null);
this.TypedIdent.Resolve(rc);
}
- public void ResolveWhere(ResolutionContext! rc)
- {
+ public void ResolveWhere(ResolutionContext rc) {
+ Contract.Requires(rc != null);
if (this.TypedIdent.WhereExpr != null) {
this.TypedIdent.WhereExpr.Resolve(rc);
}
ResolveAttributes(rc);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ Contract.Requires(tc != null);
TypecheckAttributes(tc);
this.TypedIdent.Typecheck(tc);
}
[Pure]
- public object DoVisit(AI.ExprVisitor! visitor)
- {
+ public object DoVisit(AI.ExprVisitor visitor) {
+ Contract.Requires(visitor != null);
return visitor.VisitVariable(this);
}
}
- public class VariableComparer : IComparer
- {
+ public class VariableComparer : IComparer {
public int Compare(object a, object b) {
- Variable A = a as Variable;
- Variable B = b as Variable;
- if (A == null || B == null) {
- throw new ArgumentException("VariableComparer works only on objects of type Variable");
- }
- return ((!)A.Name).CompareTo(B.Name);
+ Variable A = a as Variable;
+ Variable B = b as Variable;
+ if (A == null || B == null) {
+ throw new ArgumentException("VariableComparer works only on objects of type Variable");
+ }
+ return cce.NonNull(A.Name).CompareTo(B.Name);
}
}
// class to specify the <:-parents of the values of constants
public class ConstantParent {
- public readonly IdentifierExpr! Parent;
+ public readonly IdentifierExpr/*!*/ Parent;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Parent != null);
+ }
+
// if true, the sub-dag underneath this constant-parent edge is
// disjoint from all other unique sub-dags
public readonly bool Unique;
- public ConstantParent(IdentifierExpr! parent, bool unique) {
+ public ConstantParent(IdentifierExpr parent, bool unique) {
+ Contract.Requires(parent != null);
Parent = parent;
Unique = unique;
}
}
- public class Constant : Variable
- {
+ public class Constant : Variable {
// when true, the value of this constant is meant to be distinct
// from all other constants.
public readonly bool Unique;
@@ -1074,65 +1195,73 @@ namespace Microsoft.Boogie
// the <:-parents of the value of this constant. If the field is
// null, no information about the parents is provided, which means
// that the parental situation is unconstrained.
- public readonly List<ConstantParent!> Parents;
+ public readonly List<ConstantParent/*!*/> Parents;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(Parents, true));
+ }
+
// if true, it is assumed that the immediate <:-children of the
// value of this constant are completely specified
public readonly bool ChildrenComplete;
- public Constant(IToken! tok, TypedIdent! typedIdent)
- : base(tok, typedIdent)
- requires typedIdent.Name != null && typedIdent.Name.Length > 0;
- requires typedIdent.WhereExpr == null;
- {
+ public Constant(IToken/*!*/ tok, TypedIdent/*!*/ typedIdent)
+ : base(tok, typedIdent) {
+ Contract.Requires(tok != null);
+ Contract.Requires(typedIdent != null);
+ Contract.Requires(typedIdent.Name != null && typedIdent.Name.Length > 0);
+ Contract.Requires(typedIdent.WhereExpr == null);
// base(tok, typedIdent);
this.Unique = true;
this.Parents = null;
this.ChildrenComplete = false;
}
- public Constant(IToken! tok, TypedIdent! typedIdent, bool unique)
- : base(tok, typedIdent)
- requires typedIdent.Name != null && typedIdent.Name.Length > 0;
- requires typedIdent.WhereExpr == null;
- {
+ public Constant(IToken/*!*/ tok, TypedIdent/*!*/ typedIdent, bool unique)
+ : base(tok, typedIdent) {
+ Contract.Requires(tok != null);
+ Contract.Requires(typedIdent != null);
+ Contract.Requires(typedIdent.Name != null && typedIdent.Name.Length > 0);
+ Contract.Requires(typedIdent.WhereExpr == null);
// base(tok, typedIdent);
this.Unique = unique;
this.Parents = null;
this.ChildrenComplete = false;
}
- public Constant(IToken! tok, TypedIdent! typedIdent,
+ public Constant(IToken/*!*/ tok, TypedIdent/*!*/ typedIdent,
bool unique,
- List<ConstantParent!> parents, bool childrenComplete,
+ List<ConstantParent/*!*/> parents, bool childrenComplete,
QKeyValue kv)
- : base(tok, typedIdent, kv)
- requires typedIdent.Name != null && typedIdent.Name.Length > 0;
- requires typedIdent.WhereExpr == null;
- {
+ : base(tok, typedIdent, kv) {
+ Contract.Requires(tok != null);
+ Contract.Requires(typedIdent != null);
+ Contract.Requires(parents == null || cce.NonNullElements(parents));
+ Contract.Requires(typedIdent.Name != null && typedIdent.Name.Length > 0);
+ Contract.Requires(typedIdent.WhereExpr == null);
// base(tok, typedIdent);
this.Unique = unique;
this.Parents = parents;
this.ChildrenComplete = childrenComplete;
}
- public override bool IsMutable
- {
- get
- {
+ public override bool IsMutable {
+ get {
return false;
}
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.Write(this, level, "const ");
EmitAttributes(stream);
- if (this.Unique){
+ if (this.Unique) {
stream.Write(this, level, "unique ");
}
EmitVitals(stream, level);
if (Parents != null || ChildrenComplete) {
stream.Write(this, level, " extends");
- string! sep = " ";
- foreach (ConstantParent! p in (!)Parents) {
+ string/*!*/ sep = " ";
+ foreach (ConstantParent/*!*/ p in cce.NonNull(Parents)) {
+ Contract.Assert(p != null);
stream.Write(this, level, sep);
sep = ", ";
if (p.Unique)
@@ -1142,18 +1271,19 @@ namespace Microsoft.Boogie
if (ChildrenComplete)
stream.Write(this, level, " complete");
}
-
+
stream.WriteLine(";");
}
- public override void Register(ResolutionContext! rc)
- {
+ public override void Register(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.AddVariable(this, true);
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
base.Resolve(rc);
if (Parents != null) {
- foreach (ConstantParent! p in Parents) {
+ foreach (ConstantParent/*!*/ p in Parents) {
+ Contract.Assert(p != null);
p.Parent.Resolve(rc);
if (p.Parent.Decl != null && !(p.Parent.Decl is Constant))
rc.Error(p.Parent, "the parent of a constant has to be a constant");
@@ -1169,7 +1299,7 @@ namespace Microsoft.Boogie
if (Parents[i].Parent.Decl != null) {
for (int j = i + 1; j < Parents.Count; ++j) {
if (Parents[j].Parent.Decl != null &&
- ((!)Parents[i].Parent.Decl).Equals(Parents[j].Parent.Decl))
+ cce.NonNull(Parents[i].Parent.Decl).Equals(Parents[j].Parent.Decl))
rc.Error(Parents[j].Parent,
"{0} occurs more than once as parent",
Parents[j].Parent.Decl);
@@ -1178,14 +1308,15 @@ namespace Microsoft.Boogie
}
}
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
base.Typecheck(tc);
if (Parents != null) {
- foreach (ConstantParent! p in Parents) {
+ foreach (ConstantParent/*!*/ p in Parents) {
+ Contract.Assert(p != null);
p.Parent.Typecheck(tc);
- if (!((!)p.Parent.Decl).TypedIdent.Type.Unify(this.TypedIdent.Type))
+ if (!cce.NonNull(p.Parent.Decl).TypedIdent.Type.Unify(this.TypedIdent.Type))
tc.Error(p.Parent,
"parent of constant has incompatible type ({0} instead of {1})",
p.Parent.Decl.TypedIdent.Type, this.TypedIdent.Type);
@@ -1193,55 +1324,54 @@ namespace Microsoft.Boogie
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitConstant(this);
}
}
- public class GlobalVariable : Variable
- {
- public GlobalVariable(IToken! tok, TypedIdent! typedIdent)
- : base(tok, typedIdent)
- {
- }
- public GlobalVariable(IToken! tok, TypedIdent! typedIdent, QKeyValue kv)
- : base(tok, typedIdent, kv)
- {
- }
- public override bool IsMutable
- {
- get
- {
+ public class GlobalVariable : Variable {
+ public GlobalVariable(IToken/*!*/ tok, TypedIdent/*!*/ typedIdent)
+ : base(tok, typedIdent) {
+ Contract.Requires(tok != null);
+ Contract.Requires(typedIdent != null);
+ }
+ public GlobalVariable(IToken/*!*/ tok, TypedIdent/*!*/ typedIdent, QKeyValue kv)
+ : base(tok, typedIdent, kv) {
+ Contract.Requires(tok != null);
+ Contract.Requires(typedIdent != null);
+ }
+ public override bool IsMutable {
+ get {
return true;
}
}
- public override void Register(ResolutionContext! rc)
- {
+ public override void Register(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.AddVariable(this, true);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitGlobalVariable(this);
}
}
- public class Formal : Variable
- {
+ public class Formal : Variable {
public bool InComing;
- public Formal(IToken! tok, TypedIdent! typedIdent, bool incoming)
- : base(tok, typedIdent)
- {
+ public Formal(IToken tok, TypedIdent typedIdent, bool incoming)
+ : base(tok, typedIdent) {
+ Contract.Requires(typedIdent != null);
+ Contract.Requires(tok != null);
InComing = incoming;
}
- public override bool IsMutable
- {
- get
- {
+ public override bool IsMutable {
+ get {
return !InComing;
}
}
- public override void Register(ResolutionContext! rc)
- {
+ public override void Register(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.AddVariable(this, false);
}
@@ -1249,10 +1379,12 @@ namespace Microsoft.Boogie
/// Given a sequence of Formal declarations, returns sequence of Formals like the given one but without where clauses.
/// The Type of each Formal is cloned.
/// </summary>
- public static VariableSeq! StripWhereClauses(VariableSeq! w)
- {
+ public static VariableSeq StripWhereClauses(VariableSeq w) {
+ Contract.Requires(w != null);
+ Contract.Ensures(Contract.Result<VariableSeq>() != null);
VariableSeq s = new VariableSeq();
- foreach (Variable! v in w) {
+ foreach (Variable/*!*/ v in w) {
+ Contract.Assert(v != null);
Formal f = (Formal)v;
TypedIdent ti = f.TypedIdent;
s.Add(new Formal(f.tok, new TypedIdent(ti.tok, ti.Name, ti.Type.CloneUnresolved()), f.InComing));
@@ -1260,115 +1392,124 @@ namespace Microsoft.Boogie
return s;
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitFormal(this);
}
}
- public class LocalVariable : Variable
- {
- public LocalVariable(IToken! tok, TypedIdent! typedIdent, QKeyValue kv)
- {
- base(tok, typedIdent, kv);
- }
- public LocalVariable(IToken! tok, TypedIdent! typedIdent)
- {
- base(tok, typedIdent, null);
- }
- public override bool IsMutable
- {
- get
- {
+ public class LocalVariable : Variable {
+ public LocalVariable(IToken tok, TypedIdent typedIdent, QKeyValue kv)
+ : base(tok, typedIdent, kv) {//BASEMOVEA
+ Contract.Requires(typedIdent != null);
+ Contract.Requires(tok != null);
+ //:base(tok, typedIdent, kv);
+ }
+ public LocalVariable(IToken tok, TypedIdent typedIdent)
+ : base(tok, typedIdent, null) {//BASEMOVEA
+ Contract.Requires(typedIdent != null);
+ Contract.Requires(tok != null);
+ //:base(tok, typedIdent, null);
+ }
+ public override bool IsMutable {
+ get {
return true;
}
}
- public override void Register(ResolutionContext! rc)
- {
+ public override void Register(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.AddVariable(this, false);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitLocalVariable(this);
}
}
- public class Incarnation : LocalVariable
- {
+ public class Incarnation : LocalVariable {
public int incarnationNumber;
- public Incarnation(Variable! var, int i) :
+ public Incarnation(Variable/*!*/ var, int i) :
base(
var.tok,
- new TypedIdent(var.TypedIdent.tok,var.TypedIdent.Name + "@" + i,var.TypedIdent.Type)
- )
- {
+ new TypedIdent(var.TypedIdent.tok, var.TypedIdent.Name + "@" + i, var.TypedIdent.Type)
+ ) {
+ Contract.Requires(var != null);
incarnationNumber = i;
}
}
- public class BoundVariable : Variable
- {
- public BoundVariable(IToken! tok, TypedIdent! typedIdent)
- requires typedIdent.WhereExpr == null;
- {
- base(tok, typedIdent); // here for aesthetic reasons
- }
- public override bool IsMutable
- {
- get
- {
+ public class BoundVariable : Variable {
+ public BoundVariable(IToken tok, TypedIdent typedIdent)
+ : base(tok, typedIdent) {//BASEMOVEA
+ Contract.Requires(typedIdent != null);
+ Contract.Requires(tok != null);
+ Contract.Requires(typedIdent.WhereExpr == null);
+ //:base(tok, typedIdent); // here for aesthetic reasons
+ }
+ public override bool IsMutable {
+ get {
return false;
}
}
- public override void Register(ResolutionContext! rc)
- {
+ public override void Register(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.AddVariable(this, false);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitBoundVariable(this);
}
}
- public abstract class DeclWithFormals : NamedDeclaration
- {
- public TypeVariableSeq! TypeParameters;
- public /*readonly--except in StandardVisitor*/ VariableSeq! InParams, OutParams;
-
- public DeclWithFormals (IToken! tok, string! name, TypeVariableSeq! typeParams,
- VariableSeq! inParams, VariableSeq! outParams)
- : base(tok, name)
- {
+ public abstract class DeclWithFormals : NamedDeclaration {
+ public TypeVariableSeq/*!*/ TypeParameters;
+ public /*readonly--except in StandardVisitor*/ VariableSeq/*!*/ InParams, OutParams;
+
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(TypeParameters != null);
+ Contract.Invariant(InParams != null);
+ Contract.Invariant(OutParams != null);
+ }
+
+ public DeclWithFormals(IToken tok, string name, TypeVariableSeq typeParams,
+ VariableSeq inParams, VariableSeq outParams)
+ : base(tok, name) {
+ Contract.Requires(inParams != null);
+ Contract.Requires(outParams != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(name != null);
+ Contract.Requires(tok != null);
this.TypeParameters = typeParams;
this.InParams = inParams;
this.OutParams = outParams;
// base(tok, name);
}
- protected DeclWithFormals (DeclWithFormals! that)
- : base(that.tok, (!) that.Name)
- {
+ protected DeclWithFormals(DeclWithFormals that)
+ : base(that.tok, cce.NonNull(that.Name)) {
+ Contract.Requires(that != null);
this.TypeParameters = that.TypeParameters;
this.InParams = that.InParams;
this.OutParams = that.OutParams;
// base(that.tok, (!) that.Name);
}
- protected void EmitSignature (TokenTextWriter! stream, bool shortRet)
- {
+ protected void EmitSignature(TokenTextWriter stream, bool shortRet) {
+ Contract.Requires(stream != null);
Type.EmitOptionalTypeParams(stream, TypeParameters);
stream.Write("(");
InParams.Emit(stream);
stream.Write(")");
- if (shortRet)
- {
- assert OutParams.Length == 1;
+ if (shortRet) {
+ Contract.Assert(OutParams.Length == 1);
stream.Write(" : ");
- ((!)OutParams[0]).TypedIdent.Type.Emit(stream);
- }
- else if (OutParams.Length > 0)
- {
+ cce.NonNull(OutParams[0]).TypedIdent.Type.Emit(stream);
+ } else if (OutParams.Length > 0) {
stream.Write(" returns (");
OutParams.Emit(stream);
stream.Write(")");
@@ -1376,13 +1517,17 @@ namespace Microsoft.Boogie
}
// Register all type parameters at the resolution context
- protected void RegisterTypeParameters(ResolutionContext! rc) {
- foreach (TypeVariable! v in TypeParameters)
+ protected void RegisterTypeParameters(ResolutionContext rc) {
+ Contract.Requires(rc != null);
+ foreach (TypeVariable/*!*/ v in TypeParameters) {
+ Contract.Assert(v != null);
rc.AddTypeBinder(v);
+ }
}
protected void SortTypeParams() {
- TypeSeq! allTypes = InParams.ToTypeSeq;
+ TypeSeq/*!*/ allTypes = InParams.ToTypeSeq;
+ Contract.Assert(allTypes != null);
allTypes.AddRange(OutParams.ToTypeSeq);
TypeParameters = Type.SortTypeParams(TypeParameters, allTypes, null);
}
@@ -1395,12 +1540,12 @@ namespace Microsoft.Boogie
/// context.
/// </summary>
/// <param name="rc"></param>
- protected void RegisterFormals(VariableSeq! formals, ResolutionContext! rc)
- {
- foreach (Formal! f in formals)
- {
- if (f.Name != TypedIdent.NoName)
- {
+ protected void RegisterFormals(VariableSeq formals, ResolutionContext rc) {
+ Contract.Requires(rc != null);
+ Contract.Requires(formals != null);
+ foreach (Formal/*!*/ f in formals) {
+ Contract.Assert(f != null);
+ if (f.Name != TypedIdent.NoName) {
rc.AddVariable(f, false);
}
f.Resolve(rc);
@@ -1411,34 +1556,47 @@ namespace Microsoft.Boogie
/// Resolves the where clauses (and attributes) of the formals.
/// </summary>
/// <param name="rc"></param>
- protected void ResolveFormals(VariableSeq! formals, ResolutionContext! rc)
- {
- foreach (Formal! f in formals)
- {
+ protected void ResolveFormals(VariableSeq formals, ResolutionContext rc) {
+ Contract.Requires(rc != null);
+ Contract.Requires(formals != null);
+ foreach (Formal/*!*/ f in formals) {
+ Contract.Assert(f != null);
f.ResolveWhere(rc);
}
}
- public override void Typecheck(TypecheckingContext! tc) {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
TypecheckAttributes(tc);
- foreach (Formal! p in InParams) {
+ foreach (Formal/*!*/ p in InParams) {
+ Contract.Assert(p != null);
p.Typecheck(tc);
}
- foreach (Formal! p in OutParams) {
+ foreach (Formal/*!*/ p in OutParams) {
+ Contract.Assert(p != null);
p.Typecheck(tc);
}
}
}
public class Expansion {
- public string? ignore; // when to ignore
- public Expr! body;
- public TypeVariableSeq! TypeParameters;
- public Variable[]! formals;
-
- public Expansion(string? ignore, Expr! body,
- TypeVariableSeq! typeParams, Variable[]! formals)
- {
+ public string ignore; // when to ignore
+ public Expr/*!*/ body;
+ public TypeVariableSeq/*!*/ TypeParameters;
+ public Variable[]/*!*/ formals;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(body != null);
+ Contract.Invariant(TypeParameters != null);
+ Contract.Invariant(formals != null);
+ }
+
+
+ public Expansion(string ignore, Expr body,
+ TypeVariableSeq/*!*/ typeParams, Variable[] formals) {
+ Contract.Requires(typeParams != null);
+ Contract.Requires(formals != null);
+ Contract.Requires(body != null);
this.ignore = ignore;
this.body = body;
this.TypeParameters = typeParams;
@@ -1446,46 +1604,70 @@ namespace Microsoft.Boogie
}
}
- public class Function : DeclWithFormals
- {
- public string? Comment;
+ public class Function : DeclWithFormals {
+ public string Comment;
// the body is only set if the function is declared with {:expand true}
public Expr Body;
- public List<Expansion!>? expansions;
+ public List<Expansion/*!*/> expansions;
public bool doingExpansion;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(expansions, true));
+ }
+
private bool neverTrigger;
private bool neverTriggerComputed;
- public Function(IToken! tok, string! name, VariableSeq! args, Variable! result)
- {
- this(tok, name, new TypeVariableSeq(), args, result, null);
- }
- public Function(IToken! tok, string! name, TypeVariableSeq! typeParams, VariableSeq! args, Variable! result)
- {
- this(tok, name, typeParams, args, result, null);
- }
- public Function(IToken! tok, string! name, VariableSeq! args, Variable! result,
- string? comment)
- {
- this(tok, name, new TypeVariableSeq(), args, result, comment);
- }
- public Function(IToken! tok, string! name, TypeVariableSeq! typeParams, VariableSeq! args, Variable! result,
- string? comment)
- : base(tok, name, typeParams, args, new VariableSeq(result))
- {
+ public Function(IToken tok, string name, VariableSeq args, Variable result)
+ : this(tok, name, new TypeVariableSeq(), args, result, null) {
+ Contract.Requires(result != null);
+ Contract.Requires(args != null);
+ Contract.Requires(name != null);
+ Contract.Requires(tok != null);
+ //:this(tok, name, new TypeVariableSeq(), args, result, null);
+ }
+ public Function(IToken tok, string name, TypeVariableSeq typeParams, VariableSeq args, Variable result)
+ : this(tok, name, typeParams, args, result, null) {
+ Contract.Requires(result != null);
+ Contract.Requires(args != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(name != null);
+ Contract.Requires(tok != null);
+ //:this(tok, name, typeParams, args, result, null);
+ }
+ public Function(IToken tok, string name, VariableSeq args, Variable result, string comment)
+ : this(tok, name, new TypeVariableSeq(), args, result, comment) {
+ Contract.Requires(result != null);
+ Contract.Requires(args != null);
+ Contract.Requires(name != null);
+ Contract.Requires(tok != null);
+ //:this(tok, name, new TypeVariableSeq(), args, result, comment);
+ }
+ public Function(IToken tok, string name, TypeVariableSeq typeParams, VariableSeq args, Variable/*!*/ result, string comment)
+ : base(tok, name, typeParams, args, new VariableSeq(result)) {
+ Contract.Requires(result != null);
+ Contract.Requires(args != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(name != null);
+ Contract.Requires(tok != null);
Comment = comment;
// base(tok, name, args, new VariableSeq(result));
}
- public Function(IToken! tok, string! name, TypeVariableSeq! typeParams, VariableSeq! args, Variable! result,
- string? comment, QKeyValue kv)
- {
- this(tok, name, typeParams, args, result, comment);
+ public Function(IToken tok, string name, TypeVariableSeq typeParams, VariableSeq args, Variable result,
+ string comment, QKeyValue kv)
+ : this(tok, name, typeParams, args, result, comment) {
+ Contract.Requires(args != null);
+ Contract.Requires(result != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(name != null);
+ Contract.Requires(tok != null);
+ //:this(tok, name, typeParams, args, result, comment);
this.Attributes = kv;
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
if (Comment != null) {
stream.WriteLine(this, level, "// " + Comment);
}
@@ -1500,7 +1682,7 @@ namespace Microsoft.Boogie
if (Body != null) {
stream.WriteLine();
stream.WriteLine("{");
- stream.Write(level+1, "");
+ stream.Write(level + 1, "");
Body.Emit(stream);
stream.WriteLine();
stream.WriteLine("}");
@@ -1508,12 +1690,12 @@ namespace Microsoft.Boogie
stream.WriteLine(";");
}
}
- public override void Register(ResolutionContext! rc)
- {
+ public override void Register(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.AddProcedure(this);
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
int previousTypeBinderState = rc.TypeBinderState;
try {
RegisterTypeParameters(rc);
@@ -1533,22 +1715,21 @@ namespace Microsoft.Boogie
}
SortTypeParams();
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
// PR: why was the base call left out previously?
base.Typecheck(tc);
// TypecheckAttributes(tc);
if (Body != null) {
Body.Typecheck(tc);
- if (!((!)Body.Type).Unify(((!)OutParams[0]).TypedIdent.Type))
+ if (!cce.NonNull(Body.Type).Unify(cce.NonNull(OutParams[0]).TypedIdent.Type))
tc.Error(Body,
"function body with invalid type: {0} (expected: {1})",
- Body.Type, ((!)OutParams[0]).TypedIdent.Type);
+ Body.Type, cce.NonNull(OutParams[0]).TypedIdent.Type);
}
}
- public bool NeverTrigger
- {
+ public bool NeverTrigger {
get {
if (!neverTriggerComputed) {
this.CheckBooleanAttribute("never_pattern", ref neverTrigger);
@@ -1558,30 +1739,44 @@ namespace Microsoft.Boogie
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitFunction(this);
}
}
- public class Requires : Absy, IPotentialErrorNode
- {
+ public class Requires : Absy, IPotentialErrorNode {
public readonly bool Free;
- public Expr! Condition;
- public string? Comment;
+ public Expr/*!*/ Condition;
+ public string Comment;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Condition != null);
+ Contract.Invariant(errorData == null || errorData is string);
+ }
+
// TODO: convert to use generics
private object errorData;
public object ErrorData {
- get { return errorData; }
- set { errorData = value; }
+ get {
+ return errorData;
+ }
+ set {
+ errorData = value;
+ }
}
- invariant errorData != null ==> errorData is string;
+
private MiningStrategy errorDataEnhanced;
public MiningStrategy ErrorDataEnhanced {
- get { return errorDataEnhanced; }
- set { errorDataEnhanced = value; }
+ get {
+ return errorDataEnhanced;
+ }
+ set {
+ errorDataEnhanced = value;
+ }
}
public QKeyValue Attributes;
@@ -1592,9 +1787,10 @@ namespace Microsoft.Boogie
}
}
- public Requires(IToken! token, bool free, Expr! condition, string? comment, QKeyValue kv)
- : base(token)
- {
+ public Requires(IToken token, bool free, Expr condition, string comment, QKeyValue kv)
+ : base(token) {
+ Contract.Requires(condition != null);
+ Contract.Requires(token != null);
this.Free = free;
this.Condition = condition;
this.Comment = comment;
@@ -1602,23 +1798,27 @@ namespace Microsoft.Boogie
// base(token);
}
- public Requires(IToken! token, bool free, Expr! condition, string? comment)
- {
- this(token, free, condition, comment, null);
+ public Requires(IToken token, bool free, Expr condition, string comment)
+ : this(token, free, condition, comment, null) {
+ Contract.Requires(condition != null);
+ Contract.Requires(token != null);
+ //:this(token, free, condition, comment, null);
}
- public Requires(bool free, Expr! condition)
- {
- this(Token.NoToken, free, condition, null);
+ public Requires(bool free, Expr condition)
+ : this(Token.NoToken, free, condition, null) {
+ Contract.Requires(condition != null);
+ //:this(Token.NoToken, free, condition, null);
}
- public Requires(bool free, Expr! condition, string? comment)
- {
- this(Token.NoToken, free, condition, comment);
+ public Requires(bool free, Expr condition, string comment)
+ : this(Token.NoToken, free, condition, comment) {
+ Contract.Requires(condition != null);
+ //:this(Token.NoToken, free, condition, comment);
}
- public void Emit(TokenTextWriter! stream, int level)
- {
+ public void Emit(TokenTextWriter stream, int level) {
+ Contract.Requires(stream != null);
if (Comment != null) {
stream.WriteLine(this, level, "// " + Comment);
}
@@ -1627,40 +1827,51 @@ namespace Microsoft.Boogie
stream.WriteLine(";");
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
this.Condition.Resolve(rc);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
this.Condition.Typecheck(tc);
- assert this.Condition.Type != null; // follows from postcondition of Expr.Typecheck
- if (!this.Condition.Type.Unify(Type.Bool))
- {
+ Contract.Assert(this.Condition.Type != null); // follows from postcondition of Expr.Typecheck
+ if (!this.Condition.Type.Unify(Type.Bool)) {
tc.Error(this, "preconditions must be of type bool");
}
}
}
- public class Ensures : Absy, IPotentialErrorNode
- {
+ public class Ensures : Absy, IPotentialErrorNode {
public readonly bool Free;
- public Expr! Condition;
- public string? Comment;
+ public Expr/*!*/ Condition;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Condition != null);
+ Contract.Invariant(errorData == null || errorData is string);
+ }
+
+ public string Comment;
// TODO: convert to use generics
private object errorData;
public object ErrorData {
- get { return errorData; }
- set { errorData = value; }
+ get {
+ return errorData;
+ }
+ set {
+ errorData = value;
+ }
}
- invariant errorData != null ==> errorData is string;
private MiningStrategy errorDataEnhanced;
public MiningStrategy ErrorDataEnhanced {
- get { return errorDataEnhanced; }
- set { errorDataEnhanced = value; }
+ get {
+ return errorDataEnhanced;
+ }
+ set {
+ errorDataEnhanced = value;
+ }
}
public String ErrorMessage {
@@ -1671,9 +1882,10 @@ namespace Microsoft.Boogie
public QKeyValue Attributes;
- public Ensures(IToken! token, bool free, Expr! condition, string? comment, QKeyValue kv)
- : base(token)
- {
+ public Ensures(IToken token, bool free, Expr/*!*/ condition, string comment, QKeyValue kv)
+ : base(token) {
+ Contract.Requires(condition != null);
+ Contract.Requires(token != null);
this.Free = free;
this.Condition = condition;
this.Comment = comment;
@@ -1681,23 +1893,27 @@ namespace Microsoft.Boogie
// base(token);
}
- public Ensures(IToken! token, bool free, Expr! condition, string? comment)
- {
- this(token, free, condition, comment, null);
+ public Ensures(IToken token, bool free, Expr condition, string comment)
+ : this(token, free, condition, comment, null) {
+ Contract.Requires(condition != null);
+ Contract.Requires(token != null);
+ //:this(token, free, condition, comment, null);
}
- public Ensures(bool free, Expr! condition)
- {
- this(Token.NoToken, free, condition, null);
+ public Ensures(bool free, Expr condition)
+ : this(Token.NoToken, free, condition, null) {
+ Contract.Requires(condition != null);
+ //:this(Token.NoToken, free, condition, null);
}
- public Ensures(bool free, Expr! condition, string? comment)
- {
- this(Token.NoToken, free, condition, comment);
+ public Ensures(bool free, Expr condition, string comment)
+ : this(Token.NoToken, free, condition, comment) {
+ Contract.Requires(condition != null);
+ //:this(Token.NoToken, free, condition, comment);
}
- public void Emit(TokenTextWriter! stream, int level)
- {
+ public void Emit(TokenTextWriter stream, int level) {
+ Contract.Requires(stream != null);
if (Comment != null) {
stream.WriteLine(this, level, "// " + Comment);
}
@@ -1706,68 +1922,73 @@ namespace Microsoft.Boogie
stream.WriteLine(";");
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
this.Condition.Resolve(rc);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
this.Condition.Typecheck(tc);
- assert this.Condition.Type != null; // follows from postcondition of Expr.Typecheck
- if (!this.Condition.Type.Unify(Type.Bool))
- {
+ Contract.Assert(this.Condition.Type != null); // follows from postcondition of Expr.Typecheck
+ if (!this.Condition.Type.Unify(Type.Bool)) {
tc.Error(this, "postconditions must be of type bool");
}
}
}
- public class Procedure : DeclWithFormals
- {
- public RequiresSeq! Requires;
- public IdentifierExprSeq! Modifies;
- public EnsuresSeq! Ensures;
+ public class Procedure : DeclWithFormals {
+ public RequiresSeq/*!*/ Requires;
+ public IdentifierExprSeq/*!*/ Modifies;
+ public EnsuresSeq/*!*/ Ensures;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Requires != null);
+ Contract.Invariant(Modifies != null);
+ Contract.Invariant(Ensures != null);
+ Contract.Invariant(Summary != null);
+ }
+
// Abstract interpretation: Procedure-specific invariants...
[Rep]
- public readonly ProcedureSummary! Summary;
-
- public Procedure (
- IToken! tok,
- string! name,
- TypeVariableSeq! typeParams,
- VariableSeq! inParams,
- VariableSeq! outParams,
- RequiresSeq! @requires,
- IdentifierExprSeq! @modifies,
- EnsuresSeq! @ensures
- )
- {
- this(tok, name, typeParams, inParams, outParams, @requires, @modifies, @ensures, null);
- }
-
- public Procedure (
- IToken! tok,
- string! name,
- TypeVariableSeq! typeParams,
- VariableSeq! inParams,
- VariableSeq! outParams,
- RequiresSeq! @requires,
- IdentifierExprSeq! @modifies,
- EnsuresSeq! @ensures,
- QKeyValue kv
+ public readonly ProcedureSummary/*!*/ Summary;
+
+ public Procedure(IToken/*!*/ tok, string/*!*/ name, TypeVariableSeq/*!*/ typeParams, VariableSeq/*!*/ inParams, VariableSeq/*!*/ outParams,
+ RequiresSeq/*!*/ requires, IdentifierExprSeq/*!*/ modifies, EnsuresSeq/*!*/ ensures)
+ : this(tok, name, typeParams, inParams, outParams, requires, modifies, ensures, null) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(inParams != null);
+ Contract.Requires(outParams != null);
+ Contract.Requires(requires != null);
+ Contract.Requires(modifies != null);
+ Contract.Requires(ensures != null);
+ //:this(tok, name, typeParams, inParams, outParams, requires, modifies, ensures, null);
+ }
+
+ public Procedure(IToken/*!*/ tok, string/*!*/ name, TypeVariableSeq/*!*/ typeParams, VariableSeq/*!*/ inParams, VariableSeq/*!*/ outParams,
+ RequiresSeq/*!*/ @requires, IdentifierExprSeq/*!*/ @modifies, EnsuresSeq/*!*/ @ensures, QKeyValue kv
)
- : base(tok, name, typeParams, inParams, outParams)
- {
+ : base(tok, name, typeParams, inParams, outParams) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(inParams != null);
+ Contract.Requires(outParams != null);
+ Contract.Requires(@requires != null);
+ Contract.Requires(@modifies != null);
+ Contract.Requires(@ensures != null);
this.Requires = @requires;
this.Modifies = @modifies;
this.Ensures = @ensures;
this.Summary = new ProcedureSummary();
this.Attributes = kv;
}
-
- public override void Emit(TokenTextWriter! stream, int level)
- {
+
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.Write(this, level, "procedure ");
EmitAttributes(stream);
stream.Write(this, level, "{0}", TokenTextWriter.SanitizeIdentifier(this.Name));
@@ -1776,28 +1997,25 @@ namespace Microsoft.Boogie
level++;
- foreach (Requires! e in this.Requires)
- {
+ foreach (Requires/*!*/ e in this.Requires) {
+ Contract.Assert(e != null);
e.Emit(stream, level);
}
- if (this.Modifies.Length > 0)
- {
+ if (this.Modifies.Length > 0) {
stream.Write(level, "modifies ");
this.Modifies.Emit(stream, false);
stream.WriteLine(";");
}
- foreach (Ensures! e in this.Ensures)
- {
+ foreach (Ensures/*!*/ e in this.Ensures) {
+ Contract.Assert(e != null);
e.Emit(stream, level);
}
- if (!CommandLineOptions.Clo.IntraproceduralInfer)
- {
- for (int s=0; s < this.Summary.Count; s++)
- {
- ProcedureSummaryEntry! entry = (!) this.Summary[s];
+ if (!CommandLineOptions.Clo.IntraproceduralInfer) {
+ for (int s = 0; s < this.Summary.Count; s++) {
+ ProcedureSummaryEntry/*!*/ entry = cce.NonNull(this.Summary[s]);
stream.Write(level + 1, "// ");
Expr e;
e = (Expr)entry.Lattice.ToPredicate(entry.OnEntry);
@@ -1813,16 +2031,16 @@ namespace Microsoft.Boogie
stream.WriteLine();
}
- public override void Register(ResolutionContext! rc)
- {
+ public override void Register(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.AddProcedure(this);
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.PushVarContext();
- foreach (IdentifierExpr! ide in Modifies)
- {
+ foreach (IdentifierExpr/*!*/ ide in Modifies) {
+ Contract.Assert(ide != null);
ide.Resolve(rc);
}
@@ -1832,16 +2050,16 @@ namespace Microsoft.Boogie
RegisterFormals(InParams, rc);
ResolveFormals(InParams, rc); // "where" clauses of in-parameters are resolved without the out-parameters in scope
- foreach (Requires! e in Requires)
- {
+ foreach (Requires/*!*/ e in Requires) {
+ Contract.Assert(e != null);
e.Resolve(rc);
}
RegisterFormals(OutParams, rc);
ResolveFormals(OutParams, rc); // "where" clauses of out-parameters are resolved with both in- and out-parametes in scope
-
+
rc.StateMode = ResolutionContext.State.Two;
- foreach (Ensures! e in Ensures)
- {
+ foreach (Ensures/*!*/ e in Ensures) {
+ Contract.Assert(e != null);
e.Resolve(rc);
}
rc.StateMode = ResolutionContext.State.Single;
@@ -1860,63 +2078,68 @@ namespace Microsoft.Boogie
SortTypeParams();
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
base.Typecheck(tc);
- foreach (IdentifierExpr! ide in Modifies)
- {
- assume ide.Decl != null;
- if (!ide.Decl.IsMutable)
- {
+ foreach (IdentifierExpr/*!*/ ide in Modifies) {
+ Contract.Assert(ide != null);
+ Contract.Assume(ide.Decl != null);
+ if (!ide.Decl.IsMutable) {
tc.Error(this, "modifies list contains constant: {0}", ide.Name);
}
ide.Typecheck(tc);
}
- foreach (Requires! e in Requires)
- {
+ foreach (Requires/*!*/ e in Requires) {
+ Contract.Assert(e != null);
e.Typecheck(tc);
}
- foreach (Ensures! e in Ensures)
- {
+ foreach (Ensures/*!*/ e in Ensures) {
+ Contract.Assert(e != null);
e.Typecheck(tc);
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitProcedure(this);
}
}
- public class Implementation : DeclWithFormals
- {
- public VariableSeq! LocVars;
- [Rep] public StmtList StructuredStmts;
- [Rep] public List<Block!>! Blocks;
+ public class Implementation : DeclWithFormals {
+ public VariableSeq/*!*/ LocVars;
+ [Rep]
+ public StmtList StructuredStmts;
+ [Rep]
+ public List<Block/*!*/>/*!*/ Blocks;
public Procedure Proc;
// Blocks before applying passification etc.
// Both are used only when /inline is set.
- public List<Block!>? OriginalBlocks;
- public VariableSeq? OriginalLocVars;
+ public List<Block/*!*/> OriginalBlocks;
+ public VariableSeq OriginalLocVars;
// Strongly connected components
- private StronglyConnectedComponents<Block!> scc;
+ private StronglyConnectedComponents<Block/*!*/> scc;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(LocVars != null);
+ Contract.Invariant(cce.NonNullElements(Blocks));
+ Contract.Invariant(cce.NonNullElements(OriginalBlocks, true));
+ Contract.Invariant(cce.NonNullElements(scc, true));
+
+ }
private bool BlockPredecessorsComputed;
- public bool StronglyConnectedComponentsComputed
- {
- get
- {
+ public bool StronglyConnectedComponentsComputed {
+ get {
return this.scc != null;
}
}
- public bool SkipVerification
- {
- get
- {
+ public bool SkipVerification {
+ get {
bool verify = true;
- ((!)this.Proc).CheckBooleanAttribute("verify", ref verify);
+ cce.NonNull(this.Proc).CheckBooleanAttribute("verify", ref verify);
this.CheckBooleanAttribute("verify", ref verify);
if (!verify) {
return true;
@@ -1924,8 +2147,9 @@ namespace Microsoft.Boogie
if (CommandLineOptions.Clo.ProcedureInlining == CommandLineOptions.Inlining.Assert ||
CommandLineOptions.Clo.ProcedureInlining == CommandLineOptions.Inlining.Assume) {
- Expr? inl = this.FindExprAttribute("inline");
- if (inl == null) inl = this.Proc.FindExprAttribute("inline");
+ Expr inl = this.FindExprAttribute("inline");
+ if (inl == null)
+ inl = this.Proc.FindExprAttribute("inline");
if (inl != null && inl is LiteralExpr && ((LiteralExpr)inl).isBigNum && ((LiteralExpr)inl).asBigNum.Signum > 0) {
return true;
}
@@ -1935,27 +2159,49 @@ namespace Microsoft.Boogie
}
}
- public Implementation(IToken! tok, string! name, TypeVariableSeq! typeParams,
- VariableSeq! inParams, VariableSeq! outParams,
- VariableSeq! localVariables, [Captured] StmtList! structuredStmts)
- {
- this(tok, name, typeParams, inParams, outParams, localVariables, structuredStmts, null, new Errors());
- }
-
- public Implementation(IToken! tok, string! name, TypeVariableSeq! typeParams,
- VariableSeq! inParams, VariableSeq! outParams,
- VariableSeq! localVariables, [Captured] StmtList! structuredStmts,
- Errors! errorHandler)
- {
- this(tok, name, typeParams, inParams, outParams, localVariables, structuredStmts, null, errorHandler);
- }
-
- public Implementation(IToken! tok, string! name, TypeVariableSeq! typeParams,
- VariableSeq! inParams, VariableSeq! outParams,
- VariableSeq! localVariables, [Captured] StmtList! structuredStmts, QKeyValue kv,
- Errors! errorHandler)
- : base(tok, name, typeParams, inParams, outParams)
- {
+ public Implementation(IToken tok, string name, TypeVariableSeq typeParams, VariableSeq inParams, VariableSeq outParams, VariableSeq localVariables, [Captured] StmtList structuredStmts)
+ : this(tok, name, typeParams, inParams, outParams, localVariables, structuredStmts, null, new Errors()) {
+ Contract.Requires(structuredStmts != null);
+ Contract.Requires(localVariables != null);
+ Contract.Requires(outParams != null);
+ Contract.Requires(inParams != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(name != null);
+ Contract.Requires(tok != null);
+ //:this(tok, name, typeParams, inParams, outParams, localVariables, structuredStmts, null, new Errors());
+ }
+
+ public Implementation(IToken tok, string name, TypeVariableSeq typeParams, VariableSeq inParams, VariableSeq outParams, VariableSeq localVariables, [Captured] StmtList structuredStmts, Errors errorHandler)
+ : this(tok, name, typeParams, inParams, outParams, localVariables, structuredStmts, null, errorHandler) {
+ Contract.Requires(errorHandler != null);
+ Contract.Requires(structuredStmts != null);
+ Contract.Requires(localVariables != null);
+ Contract.Requires(outParams != null);
+ Contract.Requires(inParams != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(name != null);
+ Contract.Requires(tok != null);
+ //:this(tok, name, typeParams, inParams, outParams, localVariables, structuredStmts, null, errorHandler);
+ }
+
+ public Implementation(IToken/*!*/ tok,
+ string/*!*/ name,
+ TypeVariableSeq/*!*/ typeParams,
+ VariableSeq/*!*/ inParams,
+ VariableSeq/*!*/ outParams,
+ VariableSeq/*!*/ localVariables,
+ [Captured] StmtList/*!*/ structuredStmts,
+ QKeyValue kv,
+ Errors/*!*/ errorHandler)
+ : base(tok, name, typeParams, inParams, outParams) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(inParams != null);
+ Contract.Requires(outParams != null);
+ Contract.Requires(localVariables != null);
+ Contract.Requires(structuredStmts != null);
+ Contract.Requires(errorHandler != null);
LocVars = localVariables;
StructuredStmts = structuredStmts;
BigBlocksResolutionContext ctx = new BigBlocksResolutionContext(structuredStmts, errorHandler);
@@ -1967,18 +2213,32 @@ namespace Microsoft.Boogie
// base(tok, name, inParams, outParams);
}
- public Implementation(IToken! tok, string! name, TypeVariableSeq! typeParams,
- VariableSeq! inParams, VariableSeq! outParams,
- VariableSeq! localVariables, [Captured] List<Block!>! block)
- {
- this(tok, name, typeParams, inParams, outParams, localVariables, block, null);
- }
-
- public Implementation(IToken! tok, string! name, TypeVariableSeq! typeParams,
- VariableSeq! inParams, VariableSeq! outParams,
- VariableSeq! localVariables, [Captured] List<Block!>! blocks, QKeyValue kv)
- : base(tok, name, typeParams, inParams, outParams)
- {
+ public Implementation(IToken tok, string name, TypeVariableSeq typeParams, VariableSeq inParams, VariableSeq outParams, VariableSeq localVariables, [Captured] List<Block/*!*/> block)
+ : this(tok, name, typeParams, inParams, outParams, localVariables, block, null) {
+ Contract.Requires(cce.NonNullElements(block));
+ Contract.Requires(localVariables != null);
+ Contract.Requires(outParams != null);
+ Contract.Requires(inParams != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(name != null);
+ Contract.Requires(tok != null);
+ //:this(tok, name, typeParams, inParams, outParams, localVariables, block, null);
+ }
+
+ public Implementation(IToken/*!*/ tok,
+ string/*!*/ name,
+ TypeVariableSeq/*!*/ typeParams,
+ VariableSeq/*!*/ inParams,
+ VariableSeq/*!*/ outParams,
+ VariableSeq/*!*/ localVariables,
+ [Captured] List<Block/*!*/>/*!*/ blocks,
+ QKeyValue kv)
+ : base(tok, name, typeParams, inParams, outParams) {
+ Contract.Requires(name != null);
+ Contract.Requires(inParams != null);
+ Contract.Requires(outParams != null);
+ Contract.Requires(localVariables != null);
+ Contract.Requires(cce.NonNullElements(blocks));
LocVars = localVariables;
Blocks = blocks;
BlockPredecessorsComputed = false;
@@ -1988,8 +2248,8 @@ namespace Microsoft.Boogie
//base(tok, name, inParams, outParams);
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.Write(this, level, "implementation ");
EmitAttributes(stream);
stream.Write(this, level, "{0}", TokenTextWriter.SanitizeIdentifier(this.Name));
@@ -1998,7 +2258,8 @@ namespace Microsoft.Boogie
stream.WriteLine(level, "{0}", '{');
- foreach (Variable! v in this.LocVars) {
+ foreach (Variable/*!*/ v in this.LocVars) {
+ Contract.Assert(v != null);
v.Emit(stream, level + 1);
}
@@ -2008,21 +2269,19 @@ namespace Microsoft.Boogie
}
if (CommandLineOptions.Clo.PrintUnstructured < 2) {
if (CommandLineOptions.Clo.PrintUnstructured == 1) {
- stream.WriteLine(this, level+1, "/*** structured program:");
+ stream.WriteLine(this, level + 1, "/*** structured program:");
}
- this.StructuredStmts.Emit(stream, level+1);
+ this.StructuredStmts.Emit(stream, level + 1);
if (CommandLineOptions.Clo.PrintUnstructured == 1) {
- stream.WriteLine(level+1, "**** end structured program */");
+ stream.WriteLine(level + 1, "**** end structured program */");
}
}
}
if (this.StructuredStmts == null || 1 <= CommandLineOptions.Clo.PrintUnstructured ||
- CommandLineOptions.Clo.PrintInstrumented || CommandLineOptions.Clo.PrintInlined)
- {
- foreach (Block b in this.Blocks)
- {
- b.Emit(stream, level+1);
+ CommandLineOptions.Clo.PrintInstrumented || CommandLineOptions.Clo.PrintInlined) {
+ foreach (Block b in this.Blocks) {
+ b.Emit(stream, level + 1);
}
}
@@ -2031,25 +2290,21 @@ namespace Microsoft.Boogie
stream.WriteLine();
stream.WriteLine();
}
- public override void Register(ResolutionContext! rc)
- {
+ public override void Register(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
// nothing to register
}
- public override void Resolve(ResolutionContext! rc)
- {
- if (Proc != null)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ if (Proc != null) {
// already resolved
return;
}
- DeclWithFormals dwf = rc.LookUpProcedure((!) this.Name);
+ DeclWithFormals dwf = rc.LookUpProcedure(cce.NonNull(this.Name));
Proc = dwf as Procedure;
- if (dwf == null)
- {
+ if (dwf == null) {
rc.Error(this, "implementation given for undeclared procedure: {0}", this.Name);
- }
- else if (Proc == null)
- {
+ } else if (Proc == null) {
rc.Error(this, "implementations given for function, not procedure: {0}", this.Name);
}
@@ -2061,31 +2316,29 @@ namespace Microsoft.Boogie
RegisterFormals(InParams, rc);
RegisterFormals(OutParams, rc);
- foreach (Variable! v in LocVars)
- {
+ foreach (Variable/*!*/ v in LocVars) {
+ Contract.Assert(v != null);
v.Register(rc);
v.Resolve(rc);
}
- foreach (Variable! v in LocVars)
- {
+ foreach (Variable/*!*/ v in LocVars) {
+ Contract.Assert(v != null);
v.ResolveWhere(rc);
}
rc.PushProcedureContext();
- foreach (Block b in Blocks)
- {
+ foreach (Block b in Blocks) {
b.Register(rc);
}
-
+
ResolveAttributes(rc);
rc.StateMode = ResolutionContext.State.Two;
- foreach (Block b in Blocks)
- {
+ foreach (Block b in Blocks) {
b.Resolve(rc);
}
rc.StateMode = ResolutionContext.State.Single;
-
+
rc.PopProcedureContext();
rc.PopVarContext();
@@ -2098,11 +2351,11 @@ namespace Microsoft.Boogie
}
SortTypeParams();
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
base.Typecheck(tc);
- assume this.Proc != null;
+ Contract.Assume(this.Proc != null);
if (this.TypeParameters.Length != Proc.TypeParameters.Length) {
tc.Error(this, "mismatched number of type parameters in procedure implementation: {0}",
@@ -2114,57 +2367,56 @@ namespace Microsoft.Boogie
MatchFormals(this.OutParams, Proc.OutParams, "out", tc);
}
- foreach (Variable! v in LocVars)
- {
+ foreach (Variable/*!*/ v in LocVars) {
+ Contract.Assert(v != null);
v.Typecheck(tc);
}
IdentifierExprSeq oldFrame = tc.Frame;
tc.Frame = Proc.Modifies;
- foreach (Block b in Blocks)
- {
+ foreach (Block b in Blocks) {
b.Typecheck(tc);
}
- assert tc.Frame == Proc.Modifies;
+ Contract.Assert(tc.Frame == Proc.Modifies);
tc.Frame = oldFrame;
}
- void MatchFormals(VariableSeq! implFormals, VariableSeq! procFormals,
- string! inout, TypecheckingContext! tc)
- {
- if (implFormals.Length != procFormals.Length)
- {
+ void MatchFormals(VariableSeq/*!*/ implFormals, VariableSeq/*!*/ procFormals, string/*!*/ inout, TypecheckingContext/*!*/ tc) {
+ Contract.Requires(implFormals != null);
+ Contract.Requires(procFormals != null);
+ Contract.Requires(inout != null);
+ Contract.Requires(tc != null);
+ if (implFormals.Length != procFormals.Length) {
tc.Error(this, "mismatched number of {0}-parameters in procedure implementation: {1}",
inout, this.Name);
- }
- else
- {
+ } else {
// unify the type parameters so that types can be compared
- assert Proc != null;
- assert this.TypeParameters.Length == Proc.TypeParameters.Length;
-
- IDictionary<TypeVariable!, Type!>! subst1 =
- new Dictionary<TypeVariable!, Type!> ();
- IDictionary<TypeVariable!, Type!>! subst2 =
- new Dictionary<TypeVariable!, Type!> ();
+ Contract.Assert(Proc != null);
+ Contract.Assert(this.TypeParameters.Length == Proc.TypeParameters.Length);
+
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst1 =
+ new Dictionary<TypeVariable/*!*/, Type/*!*/>();
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst2 =
+ new Dictionary<TypeVariable/*!*/, Type/*!*/>();
for (int i = 0; i < this.TypeParameters.Length; ++i) {
- TypeVariable! newVar =
- new TypeVariable (Token.NoToken, Proc.TypeParameters[i].Name);
+ TypeVariable/*!*/ newVar =
+ new TypeVariable(Token.NoToken, Proc.TypeParameters[i].Name);
+ Contract.Assert(newVar != null);
subst1.Add(Proc.TypeParameters[i], newVar);
subst2.Add(this.TypeParameters[i], newVar);
}
- for (int i = 0; i < implFormals.Length; i++)
- {
+ for (int i = 0; i < implFormals.Length; i++) {
// the names of the formals are allowed to change from the proc to the impl
// but types must be identical
- Type t = ((Variable!)implFormals[i]).TypedIdent.Type.Substitute(subst2);
- Type u = ((Variable!)procFormals[i]).TypedIdent.Type.Substitute(subst1);
- if (!t.Equals(u))
- {
- string! a = (!) ((Variable!)implFormals[i]).Name;
- string! b = (!) ((Variable!)procFormals[i]).Name;
- string! c;
+ Type t = cce.NonNull((Variable)implFormals[i]).TypedIdent.Type.Substitute(subst2);
+ Type u = cce.NonNull((Variable)procFormals[i]).TypedIdent.Type.Substitute(subst1);
+ if (!t.Equals(u)) {
+ string/*!*/ a = cce.NonNull((Variable)implFormals[i]).Name;
+ Contract.Assert(a != null);
+ string/*!*/ b = cce.NonNull((Variable)procFormals[i]).Name;
+ Contract.Assert(b != null);
+ string/*!*/ c;
if (a == b) {
c = a;
} else {
@@ -2180,44 +2432,41 @@ namespace Microsoft.Boogie
public void ResetImplFormalMap() {
this.formalMap = null;
}
- public Hashtable /*Variable->Expr*/! GetImplFormalMap()
- {
+ public Hashtable /*Variable->Expr*//*!*/ GetImplFormalMap() {
+ Contract.Ensures(Contract.Result<Hashtable>() != null);
+
if (this.formalMap != null)
return this.formalMap;
- else
- {
- Hashtable /*Variable->Expr*/! map = new Hashtable /*Variable->Expr*/ (InParams.Length + OutParams.Length);
+ else {
+ Hashtable /*Variable->Expr*//*!*/ map = new Hashtable /*Variable->Expr*/ (InParams.Length + OutParams.Length);
- assume this.Proc != null;
- assume InParams.Length == Proc.InParams.Length;
- for (int i = 0; i < InParams.Length; i++)
- {
- Variable! v = (!) InParams[i];
+ Contract.Assume(this.Proc != null);
+ Contract.Assume(InParams.Length == Proc.InParams.Length);
+ for (int i = 0; i < InParams.Length; i++) {
+ Variable/*!*/ v = InParams[i];
+ Contract.Assert(v != null);
IdentifierExpr ie = new IdentifierExpr(v.tok, v);
- Variable! pv = (!) Proc.InParams[i];
+ Variable/*!*/ pv = Proc.InParams[i];
+ Contract.Assert(pv != null);
map.Add(pv, ie);
}
System.Diagnostics.Debug.Assert(OutParams.Length == Proc.OutParams.Length);
- for (int i = 0; i < OutParams.Length; i++)
- {
- Variable! v = (!) OutParams[i];
+ for (int i = 0; i < OutParams.Length; i++) {
+ Variable/*!*/ v = cce.NonNull(OutParams[i]);
IdentifierExpr ie = new IdentifierExpr(v.tok, v);
- Variable! pv = (!) Proc.OutParams[i];
+ Variable pv = cce.NonNull(Proc.OutParams[i]);
map.Add(pv, ie);
}
this.formalMap = map;
- if (CommandLineOptions.Clo.PrintWithUniqueASTIds)
- {
+ if (CommandLineOptions.Clo.PrintWithUniqueASTIds) {
Console.WriteLine("Implementation.GetImplFormalMap on {0}:", this.Name);
- using (TokenTextWriter stream = new TokenTextWriter("<console>", Console.Out, false))
- {
- foreach (DictionaryEntry e in map)
- {
+ using (TokenTextWriter stream = new TokenTextWriter("<console>", Console.Out, false)) {
+ foreach (DictionaryEntry e in map) {
Console.Write(" ");
- ((Variable!)e.Key).Emit(stream, 0);
+ cce.NonNull((Variable/*!*/)e.Key).Emit(stream, 0);
Console.Write(" --> ");
- ((Expr!)e.Value).Emit(stream);
+ cce.NonNull((Expr)e.Value).Emit(stream);
Console.WriteLine();
}
}
@@ -2230,14 +2479,11 @@ namespace Microsoft.Boogie
/// <summary>
/// Instrument the blocks with the inferred invariants
/// </summary>
- public override void InstrumentWithInvariants()
- {
- foreach (Block b in this.Blocks)
- {
- if (b.Lattice != null)
- {
- assert b.PreInvariant != null; /* If the pre-abstract state is null, then something is wrong */
- assert b.PostInvariant != null; /* If the post-state is null, then something is wrong */
+ public override void InstrumentWithInvariants() {
+ foreach (Block b in this.Blocks) {
+ if (b.Lattice != null) {
+ Contract.Assert(b.PreInvariant != null); /* If the pre-abstract state is null, then something is wrong */
+ Contract.Assert(b.PostInvariant != null); /* If the post-state is null, then something is wrong */
bool instrumentEntry;
bool instrumentExit;
@@ -2250,21 +2496,23 @@ namespace Microsoft.Boogie
instrumentEntry = b.widenBlock;
instrumentExit = false;
break;
- default:
- assert false; // unexpected InstrumentationPlaces value
+ default: {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // unexpected InstrumentationPlaces value
}
-
+
if (instrumentEntry || instrumentExit) {
CmdSeq newCommands = new CmdSeq();
if (instrumentEntry) {
- Expr inv = (Expr) b.Lattice.ToPredicate(b.PreInvariant); /*b.PreInvariantBuckets.GetDisjunction(b.Lattice);*/
- PredicateCmd cmd = CommandLineOptions.Clo.InstrumentWithAsserts ? (PredicateCmd)new AssertCmd(Token.NoToken,inv) : (PredicateCmd)new AssumeCmd(Token.NoToken, inv);
+ Expr inv = (Expr)b.Lattice.ToPredicate(b.PreInvariant); /*b.PreInvariantBuckets.GetDisjunction(b.Lattice);*/
+ PredicateCmd cmd = CommandLineOptions.Clo.InstrumentWithAsserts ? (PredicateCmd)new AssertCmd(Token.NoToken, inv) : (PredicateCmd)new AssumeCmd(Token.NoToken, inv);
newCommands.Add(cmd);
}
newCommands.AddRange(b.Cmds);
if (instrumentExit) {
- Expr inv = (Expr) b.Lattice.ToPredicate(b.PostInvariant);
- PredicateCmd cmd = CommandLineOptions.Clo.InstrumentWithAsserts ? (PredicateCmd)new AssertCmd(Token.NoToken,inv) : (PredicateCmd)new AssumeCmd(Token.NoToken, inv);
+ Expr inv = (Expr)b.Lattice.ToPredicate(b.PostInvariant);
+ PredicateCmd cmd = CommandLineOptions.Clo.InstrumentWithAsserts ? (PredicateCmd)new AssertCmd(Token.NoToken, inv) : (PredicateCmd)new AssumeCmd(Token.NoToken, inv);
newCommands.Add(cmd);
}
b.Cmds = newCommands;
@@ -2277,48 +2525,50 @@ namespace Microsoft.Boogie
/// Return a collection of blocks that are reachable from the block passed as a parameter.
/// The block must be defined in the current implementation
/// </summary>
- public ICollection<Block!> GetConnectedComponents(Block! startingBlock)
- {
- assert this.Blocks.Contains(startingBlock);
+ public ICollection<Block/*!*/> GetConnectedComponents(Block startingBlock) {
+ Contract.Requires(startingBlock != null);
+ Contract.Ensures(cce.NonNullElements(Contract.Result<ICollection<Block>>(), true));
+ Contract.Assert(this.Blocks.Contains(startingBlock));
- if(!this.BlockPredecessorsComputed)
+ if (!this.BlockPredecessorsComputed)
ComputeStronglyConnectedComponents();
#if DEBUG_PRINT
System.Console.WriteLine("* Strongly connected components * \n{0} \n ** ", scc);
#endif
- foreach(ICollection<Block!> component in (!) this.scc)
- {
- foreach(Block! b in component)
- {
- if(b == startingBlock) // We found the compontent that owns the startingblock
+ foreach (ICollection<Block/*!*/> component in cce.NonNull(this.scc)) {
+ foreach (Block/*!*/ b in component) {
+ Contract.Assert(b != null);
+ if (b == startingBlock) // We found the compontent that owns the startingblock
{
return component;
}
}
}
- assert false; // if we are here, it means that the block is not in one of the components. This is an error.
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // if we are here, it means that the block is not in one of the components. This is an error.
}
/// <summary>
/// Compute the strongly connected compontents of the blocks in the implementation.
/// As a side effect, it also computes the "predecessor" relation for the block in the implementation
/// </summary>
- override public void ComputeStronglyConnectedComponents()
- {
- if(!this.BlockPredecessorsComputed)
- ComputedPredecessorsForBlocks();
+ override public void ComputeStronglyConnectedComponents() {
+ if (!this.BlockPredecessorsComputed)
+ ComputedPredecessorsForBlocks();
- Adjacency<Block!> next = new Adjacency<Block!>(Successors);
- Adjacency<Block!> prev = new Adjacency<Block!>(Predecessors);
+ Adjacency<Block/*!*/> next = new Adjacency<Block/*!*/>(Successors);
+ Adjacency<Block/*!*/> prev = new Adjacency<Block/*!*/>(Predecessors);
- this.scc = new StronglyConnectedComponents<Block!>(this.Blocks, next, prev);
+ this.scc = new StronglyConnectedComponents<Block/*!*/>(this.Blocks, next, prev);
scc.Compute();
- foreach(Block! block in this.Blocks)
- {
+ foreach (Block/*!*/ block in this.Blocks) {
+ Contract.Assert(block != null);
block.Predecessors = new BlockSeq();
}
@@ -2327,10 +2577,9 @@ namespace Microsoft.Boogie
/// <summary>
/// Reset the abstract stated computed before
/// </summary>
- override public void ResetAbstractInterpretationState()
- {
- foreach(Block! b in this.Blocks)
- {
+ override public void ResetAbstractInterpretationState() {
+ foreach (Block/*!*/ b in this.Blocks) {
+ Contract.Assert(b != null);
b.ResetAbstractInterpretationState();
}
}
@@ -2339,21 +2588,20 @@ namespace Microsoft.Boogie
/// A private method used as delegate for the strongly connected components.
/// It return, given a node, the set of its successors
/// </summary>
- private IEnumerable/*<Block!>*/! Successors(Block! node)
- {
+ private IEnumerable/*<Block!>*//*!*/ Successors(Block node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<IEnumerable>() != null);
+
GotoCmd gotoCmd = node.TransferCmd as GotoCmd;
- if(gotoCmd != null)
- { // If it is a gotoCmd
- assert gotoCmd.labelTargets != null;
+ if (gotoCmd != null) { // If it is a gotoCmd
+ Contract.Assert(gotoCmd.labelTargets != null);
return gotoCmd.labelTargets;
- }
- else
- { // otherwise must be a ReturnCmd
- assert node.TransferCmd is ReturnCmd;
+ } else { // otherwise must be a ReturnCmd
+ Contract.Assert(node.TransferCmd is ReturnCmd);
- return new List<Block!>();
+ return new List<Block/*!*/>();
}
}
@@ -2361,26 +2609,25 @@ namespace Microsoft.Boogie
/// A private method used as delegate for the strongly connected components.
/// It return, given a node, the set of its predecessors
/// </summary>
- private IEnumerable/*<Block!>*/! Predecessors(Block! node)
- {
- assert this.BlockPredecessorsComputed;
+ private IEnumerable/*<Block!>*//*!*/ Predecessors(Block node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<IEnumerable>() != null);
+
+ Contract.Assert(this.BlockPredecessorsComputed);
- return node.Predecessors;
+ return node.Predecessors;
}
/// <summary>
/// Compute the predecessor informations for the blocks
/// </summary>
- private void ComputedPredecessorsForBlocks()
- {
- foreach (Block b in this.Blocks)
- {
+ private void ComputedPredecessorsForBlocks() {
+ foreach (Block b in this.Blocks) {
GotoCmd gtc = b.TransferCmd as GotoCmd;
- if (gtc != null)
- {
- assert gtc.labelTargets != null;
- foreach (Block! dest in gtc.labelTargets)
- {
+ if (gtc != null) {
+ Contract.Assert(gtc.labelTargets != null);
+ foreach (Block/*!*/ dest in gtc.labelTargets) {
+ Contract.Assert(dest != null);
dest.Predecessors.Add(b);
}
}
@@ -2390,64 +2637,78 @@ namespace Microsoft.Boogie
public void PruneUnreachableBlocks() {
ArrayList /*Block!*/ visitNext = new ArrayList /*Block!*/ ();
- List<Block!> reachableBlocks = new List<Block!>();
+ List<Block/*!*/> reachableBlocks = new List<Block/*!*/>();
System.Compiler.IMutableSet /*Block!*/ reachable = new System.Compiler.HashSet /*Block!*/ (); // the set of elements in "reachableBlocks"
visitNext.Add(this.Blocks[0]);
while (visitNext.Count != 0) {
- Block! b = (Block!)visitNext[visitNext.Count-1];
- visitNext.RemoveAt(visitNext.Count-1);
+ Block b = cce.NonNull((Block)visitNext[visitNext.Count - 1]);
+ visitNext.RemoveAt(visitNext.Count - 1);
if (!reachable.Contains(b)) {
- reachableBlocks.Add(b);
- reachable.Add(b);
- if (b.TransferCmd is GotoCmd) {
- foreach (Cmd! s in b.Cmds) {
- if (s is PredicateCmd) {
- LiteralExpr e = ((PredicateCmd)s).Expr as LiteralExpr;
- if (e != null && e.IsFalse) {
- // This statement sequence will never reach the end, because of this "assume false" or "assert false".
- // Hence, it does not reach its successors.
- b.TransferCmd = new ReturnCmd(b.TransferCmd.tok);
- goto NEXT_BLOCK;
- }
- }
- }
- // it seems that the goto statement at the end may be reached
- foreach (Block! succ in (!)((GotoCmd)b.TransferCmd).labelTargets) {
- visitNext.Add(succ);
+ reachableBlocks.Add(b);
+ reachable.Add(b);
+ if (b.TransferCmd is GotoCmd) {
+ foreach (Cmd/*!*/ s in b.Cmds) {
+ Contract.Assert(s != null);
+ if (s is PredicateCmd) {
+ LiteralExpr e = ((PredicateCmd)s).Expr as LiteralExpr;
+ if (e != null && e.IsFalse) {
+ // This statement sequence will never reach the end, because of this "assume false" or "assert false".
+ // Hence, it does not reach its successors.
+ b.TransferCmd = new ReturnCmd(b.TransferCmd.tok);
+ goto NEXT_BLOCK;
}
+ }
+ }
+ // it seems that the goto statement at the end may be reached
+ foreach (Block succ in cce.NonNull((GotoCmd)b.TransferCmd).labelTargets) {
+ Contract.Assume(succ != null);
+ visitNext.Add(succ);
}
+ }
+ }
+ NEXT_BLOCK: {
}
- NEXT_BLOCK: {}
}
this.Blocks = reachableBlocks;
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitImplementation(this);
}
}
- public class TypedIdent : Absy
- {
+ public class TypedIdent : Absy {
public const string NoName = "";
- public string! Name;
- public Type! Type;
+ public string/*!*/ Name;
+ public Type/*!*/ Type;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Name != null);
+ Contract.Invariant(Type != null);
+ }
+
public Expr WhereExpr;
- // [NotDelayed]
- public TypedIdent (IToken! tok, string! name, Type! type)
- ensures this.WhereExpr == null; //PM: needed to verify BoogiePropFactory.FreshBoundVariable
- {
- this(tok, name, type, null); // here for aesthetic reasons
+ // [NotDelayed]
+ public TypedIdent(IToken/*!*/ tok, string/*!*/ name, Type/*!*/ type)
+ : this(tok, name, type, null) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(type != null);
+ Contract.Ensures(this.WhereExpr == null); //PM: needed to verify BoogiePropFactory.FreshBoundVariable
+ //:this(tok, name, type, null); // here for aesthetic reasons
}
// [NotDelayed]
- public TypedIdent (IToken! tok, string! name, Type! type, Expr whereExpr)
- : base(tok)
- ensures this.WhereExpr == whereExpr;
- {
+ public TypedIdent(IToken/*!*/ tok, string/*!*/ name, Type/*!*/ type, Expr whereExpr)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(type != null);
+ Contract.Ensures(this.WhereExpr == whereExpr);
this.Name = name;
this.Type = type;
this.WhereExpr = whereExpr;
@@ -2458,43 +2719,41 @@ namespace Microsoft.Boogie
return this.Name != NoName;
}
}
- public void Emit(TokenTextWriter! stream)
- {
+ public void Emit(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
stream.SetToken(this);
- if (this.Name != NoName)
- {
+ if (this.Name != NoName) {
stream.Write("{0}: ", TokenTextWriter.SanitizeIdentifier(this.Name));
}
this.Type.Emit(stream);
- if (this.WhereExpr != null)
- {
+ if (this.WhereExpr != null) {
stream.Write(" where ");
this.WhereExpr.Emit(stream);
}
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
// NOTE: WhereExpr needs to be resolved by the caller, because the caller must provide a modified ResolutionContext
this.Type = this.Type.ResolveType(rc);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
-// type variables can occur when working with polymorphic functions/procedures
-// if (!this.Type.IsClosed)
-// tc.Error(this, "free variables in type of an identifier: {0}",
-// this.Type.FreeVariables);
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ // type variables can occur when working with polymorphic functions/procedures
+ // if (!this.Type.IsClosed)
+ // tc.Error(this, "free variables in type of an identifier: {0}",
+ // this.Type.FreeVariables);
if (this.WhereExpr != null) {
this.WhereExpr.Typecheck(tc);
- assert this.WhereExpr.Type != null; // follows from postcondition of Expr.Typecheck
- if (!this.WhereExpr.Type.Unify(Type.Bool))
- {
+ Contract.Assert(this.WhereExpr.Type != null); // follows from postcondition of Expr.Typecheck
+ if (!this.WhereExpr.Type.Unify(Type.Bool)) {
tc.Error(this, "where clauses must be of type bool");
}
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitTypedIdent(this);
}
}
@@ -2513,26 +2772,18 @@ namespace Microsoft.Boogie
/// The right-hand value of the setter is not allowed to be null; that is,
/// null can occur in the list only as an "unused" element.
/// </summary>
- public class LatticeElementList : ArrayList
- {
- public new /*Maybe null*/ AI.Lattice.Element this [ int i ]
- {
- get
- {
- if (i < Count)
- {
+ public class LatticeElementList : ArrayList {
+ public new /*Maybe null*/ AI.Lattice.Element this[int i] {
+ get {
+ if (i < Count) {
return (AI.Lattice.Element)base[i];
- }
- else
- {
+ } else {
return null;
}
}
- set
- {
+ set {
System.Diagnostics.Debug.Assert(value != null);
- while (Count <= i)
- {
+ while (Count <= i) {
Add(null);
}
base[i] = value;
@@ -2546,60 +2797,51 @@ namespace Microsoft.Boogie
/// </summary>
/// <param name="lattice"></param>
/// <returns></returns>
- public Expr GetDisjunction(AI.Lattice! lattice)
- {
+ public Expr GetDisjunction(AI.Lattice lattice) {
+ Contract.Requires(lattice != null);
Expr disjunction = null;
- foreach (AI.Lattice.Element el in this)
- {
- if (el != null)
- {
- Expr e = (Expr) lattice.ToPredicate(el);
- if (disjunction == null)
- {
+ foreach (AI.Lattice.Element el in this) {
+ if (el != null) {
+ Expr e = (Expr)lattice.ToPredicate(el);
+ if (disjunction == null) {
disjunction = e;
- }
- else
- {
+ } else {
disjunction = Expr.Or(disjunction, e);
}
}
}
- if (disjunction == null)
- {
+ if (disjunction == null) {
return Expr.False;
- }
- else
- {
+ } else {
return disjunction;
}
}
}
-
-
public abstract class BoogieFactory {
- public static Expr! IExpr2Expr(AI.IExpr! e) {
+ public static Expr IExpr2Expr(AI.IExpr e) {
+ Contract.Requires(e != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
Variable v = e as Variable;
if (v != null) {
return new IdentifierExpr(Token.NoToken, v);
- }
- else if (e is AI.IVariable) { // but not a Variable
+ } else if (e is AI.IVariable) { // but not a Variable
return new AIVariableExpr(Token.NoToken, (AI.IVariable)e);
- }
- else if (e is IdentifierExpr.ConstantFunApp) {
+ } else if (e is IdentifierExpr.ConstantFunApp) {
return ((IdentifierExpr.ConstantFunApp)e).IdentifierExpr;
- }
- else if (e is QuantifierExpr.AIQuantifier) {
+ } else if (e is QuantifierExpr.AIQuantifier) {
return ((QuantifierExpr.AIQuantifier)e).arg.RealQuantifier;
- }
- else {
+ } else {
return (Expr)e;
}
}
- public static ExprSeq! IExprArray2ExprSeq(IList/*<AI.IExpr!>*/! a) {
+ public static ExprSeq IExprArray2ExprSeq(IList/*<AI.IExpr!>*/ a) {
+ Contract.Requires(a != null);
+ Contract.Ensures(Contract.Result<ExprSeq>() != null);
Expr[] e = new Expr[a.Count];
int i = 0;
- foreach (AI.IExpr! aei in a) {
+ foreach (AI.IExpr/*!*/ aei in a) {
+ Contract.Assert(aei != null);
e[i] = IExpr2Expr(aei);
i++;
}
@@ -2608,15 +2850,16 @@ namespace Microsoft.Boogie
// Convert a Boogie type into an AIType if possible. This should be
// extended when AIFramework gets more types.
- public static AI.AIType! Type2AIType(Type! t)
- {
-// if (t.IsRef)
-// return AI.Ref.Type;
-// else
+ public static AI.AIType Type2AIType(Type t) {
+ Contract.Requires(t != null);
+ Contract.Ensures(Contract.Result<AI.AIType>() != null);
+ // if (t.IsRef)
+ // return AI.Ref.Type;
+ // else
if (t.IsInt)
return AI.Int.Type;
-// else if (t.IsName) PR: how to handle this case?
-// return AI.FieldName.Type;
+ // else if (t.IsName) PR: how to handle this case?
+ // return AI.FieldName.Type;
else
return AI.Value.Type;
}
@@ -2627,125 +2870,129 @@ namespace Microsoft.Boogie
// Generic Sequences
//---------------------------------------------------------------------
- public sealed class TypedIdentSeq : PureCollections.Sequence
- {
- public TypedIdentSeq(params Type[]! args) : base(args) { }
- public new TypedIdent this[int index]
- {
- get
- {
+ public sealed class TypedIdentSeq : PureCollections.Sequence {
+ public TypedIdentSeq(params Type[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
+ }
+ public new TypedIdent this[int index] {
+ get {
return (TypedIdent)base[index];
}
- set
- {
+ set {
base[index] = value;
}
}
}
- public sealed class RequiresSeq : PureCollections.Sequence
- {
- public RequiresSeq(params Requires[]! args) : base(args) { }
- public new Requires! this[int index]
- {
- get
- {
- return (Requires!) base[index];
+ public sealed class RequiresSeq : PureCollections.Sequence {
+ public RequiresSeq(params Requires[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
+ }
+ public new Requires/*!*/ this[int index] {
+ get {
+ Contract.Ensures(Contract.Result<Requires>() != null);
+
+ return cce.NonNull((Requires/*!*/)base[index]);
}
- set
- {
+ set {
base[index] = value;
}
}
}
- public sealed class EnsuresSeq : PureCollections.Sequence
- {
- public EnsuresSeq(params Ensures[]! args) : base(args) { }
- public new Ensures! this[int index]
- {
- get
- {
- return (Ensures!) base[index];
+ public sealed class EnsuresSeq : PureCollections.Sequence {
+ public EnsuresSeq(params Ensures[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
+ }
+ public new Ensures/*!*/ this[int index] {
+ get {
+ Contract.Ensures(Contract.Result<Ensures>() != null);
+ return cce.NonNull((Ensures/*!*/)base[index]);
}
- set
- {
+ set {
base[index] = value;
}
}
}
- public sealed class VariableSeq : PureCollections.Sequence
- {
- public VariableSeq(params Variable[]! args)
- : base(args)
- {
+ public sealed class VariableSeq : PureCollections.Sequence {
+ public VariableSeq(params Variable[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
}
- public VariableSeq(VariableSeq! varSeq)
- : base(varSeq)
- {
+ public VariableSeq(VariableSeq/*!*/ varSeq)
+ : base(varSeq) {
+ Contract.Requires(varSeq != null);
}
- public new Variable this[int index]
- {
- get
- {
+ public new Variable this[int index] {
+ get {
return (Variable)base[index];
}
- set
- {
+ set {
base[index] = value;
}
}
- public void Emit(TokenTextWriter! stream)
- {
+ public void Emit(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
string sep = "";
- foreach (Variable! v in this)
- {
+ foreach (Variable/*!*/ v in this) {
+ Contract.Assert(v != null);
stream.Write(sep);
sep = ", ";
v.EmitVitals(stream, 0);
}
}
- public TypeSeq! ToTypeSeq { get {
- TypeSeq! res = new TypeSeq ();
- foreach(Variable! v in this)
- res.Add(v.TypedIdent.Type);
- return res;
- } }
+ public TypeSeq/*!*/ ToTypeSeq {
+ get {
+ Contract.Ensures(Contract.Result<TypeSeq>() != null);
+
+ TypeSeq/*!*/ res = new TypeSeq();
+ foreach (Variable/*!*/ v in this) {
+ Contract.Assert(v != null);
+ res.Add(v.TypedIdent.Type);
+ }
+ return res;
+ }
+ }
}
- public sealed class TypeSeq : PureCollections.Sequence
- {
- public TypeSeq(params Type[]! args)
- : base(args)
- {
+ public sealed class TypeSeq : PureCollections.Sequence {
+ public TypeSeq(params Type[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
}
- public TypeSeq(TypeSeq! varSeq)
- : base(varSeq)
- {
+ public TypeSeq(TypeSeq/*!*/ varSeq)
+ : base(varSeq) {
+ Contract.Requires(varSeq != null);
}
- public new Type! this[int index]
- {
- get
- {
- return (Type!)base[index];
+ public new Type/*!*/ this[int index] {
+ get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ return cce.NonNull((Type/*!*/)base[index]);
}
- set
- {
+ set {
base[index] = value;
}
}
- public List<Type!>! ToList() {
- List<Type!>! res = new List<Type!> (Length);
- foreach (Type! t in this)
+ public List<Type/*!*/>/*!*/ ToList() {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Type>>()));
+ List<Type/*!*/>/*!*/ res = new List<Type/*!*/>(Length);
+ foreach (Type/*!*/ t in this) {
+ Contract.Assert(t != null);
res.Add(t);
+ }
return res;
}
- public void Emit(TokenTextWriter! stream, string! separator)
- {
+ public void Emit(TokenTextWriter stream, string separator) {
+ Contract.Requires(separator != null);
+ Contract.Requires(stream != null);
string sep = "";
- foreach (Type! v in this)
- {
+ foreach (Type/*!*/ v in this) {
+ Contract.Assert(v != null);
stream.Write(sep);
sep = separator;
v.Emit(stream);
@@ -2753,94 +3000,100 @@ namespace Microsoft.Boogie
}
}
- public sealed class TypeVariableSeq : PureCollections.Sequence
- {
- public TypeVariableSeq(params TypeVariable[]! args)
- : base(args)
- {
- }
- public TypeVariableSeq(TypeVariableSeq! varSeq)
- : base(varSeq)
- {
- }
-/* PR: the following two constructors cause Spec# crashes
- public TypeVariableSeq(TypeVariable! var)
- : base(new TypeVariable! [] { var })
- {
- }
- public TypeVariableSeq()
- : base(new TypeVariable![0])
- {
- } */
- public new TypeVariable! this[int index]
- {
- get
- {
- return (TypeVariable!)base[index];
+ public sealed class TypeVariableSeq : PureCollections.Sequence {
+ public TypeVariableSeq(params TypeVariable[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
+ }
+ public TypeVariableSeq(TypeVariableSeq/*!*/ varSeq)
+ : base(varSeq) {
+ Contract.Requires(varSeq != null);
+ }
+ /* PR: the following two constructors cause Spec# crashes
+ public TypeVariableSeq(TypeVariable! var)
+ : base(new TypeVariable! [] { var })
+ {
+ }
+ public TypeVariableSeq()
+ : base(new TypeVariable![0])
+ {
+ } */
+ public new TypeVariable/*!*/ this[int index] {
+ get {
+ Contract.Ensures(Contract.Result<TypeVariable>() != null);
+
+ return cce.NonNull((TypeVariable)base[index]);
}
- set
- {
+ set {
base[index] = value;
}
}
- public void AppendWithoutDups(TypeVariableSeq! s1) {
+ public void AppendWithoutDups(TypeVariableSeq s1) {
+ Contract.Requires(s1 != null);
for (int i = 0; i < s1.card; i++) {
- TypeVariable! next = s1[i];
- if (!this.Has(next)) this.Add(next);
+ TypeVariable/*!*/ next = s1[i];
+ Contract.Assert(next != null);
+ if (!this.Has(next))
+ this.Add(next);
}
}
- public void Emit(TokenTextWriter! stream, string! separator)
- {
+ public void Emit(TokenTextWriter stream, string separator) {
+ Contract.Requires(separator != null);
+ Contract.Requires(stream != null);
string sep = "";
- foreach (TypeVariable! v in this)
- {
+ foreach (TypeVariable/*!*/ v in this) {
+ Contract.Assert(v != null);
stream.Write(sep);
sep = separator;
v.Emit(stream);
}
}
- public new TypeVariable[]! ToArray() {
- TypeVariable[]! n = new TypeVariable[Length];
+ public new TypeVariable[] ToArray() {
+ Contract.Ensures(Contract.Result<TypeVariable[]>() != null);
+ TypeVariable[]/*!*/ n = new TypeVariable[Length];
int ct = 0;
- foreach (TypeVariable! var in this)
+ foreach (TypeVariable/*!*/ var in this) {
+ Contract.Assert(var != null);
n[ct++] = var;
+ }
return n;
}
- public List<TypeVariable!>! ToList() {
- List<TypeVariable!>! res = new List<TypeVariable!> (Length);
- foreach (TypeVariable! var in this)
+ public List<TypeVariable/*!*/>/*!*/ ToList() {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<TypeVariable>>()));
+ List<TypeVariable/*!*/>/*!*/ res = new List<TypeVariable/*!*/>(Length);
+ foreach (TypeVariable/*!*/ var in this) {
+ Contract.Assert(var != null);
res.Add(var);
+ }
return res;
}
}
- public sealed class IdentifierExprSeq : PureCollections.Sequence
- {
- public IdentifierExprSeq(params IdentifierExpr[]! args)
- : base(args)
- {
+ public sealed class IdentifierExprSeq : PureCollections.Sequence {
+ public IdentifierExprSeq(params IdentifierExpr[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
}
- public IdentifierExprSeq(IdentifierExprSeq! ideSeq)
- : base(ideSeq)
- {
+ public IdentifierExprSeq(IdentifierExprSeq/*!*/ ideSeq)
+ : base(ideSeq) {
+ Contract.Requires(ideSeq != null);
}
- public new IdentifierExpr! this[int index]
- {
- get
- {
- return (IdentifierExpr!)base[index];
+ public new IdentifierExpr/*!*/ this[int index] {
+ get {
+ Contract.Ensures(Contract.Result<IdentifierExpr>() != null);
+
+ return cce.NonNull((IdentifierExpr)base[index]);
}
- set
- {
- base[index] = value;
+ set {
+ base[index] = value;
}
}
- public void Emit(TokenTextWriter! stream, bool printWhereComments)
- {
+ public void Emit(TokenTextWriter stream, bool printWhereComments) {
+ Contract.Requires(stream != null);
string sep = "";
- foreach (IdentifierExpr! e in this)
- {
+ foreach (IdentifierExpr/*!*/ e in this) {
+ Contract.Assert(e != null);
stream.Write(sep);
sep = ", ";
e.Emit(stream);
@@ -2855,123 +3108,122 @@ namespace Microsoft.Boogie
}
- public sealed class CmdSeq : PureCollections.Sequence
- {
- public CmdSeq(params Cmd[]! args) : base(args){}
- public CmdSeq(CmdSeq! cmdSeq)
- : base(cmdSeq)
- {
- }
- public new Cmd! this[int index]
- {
- get
- {
- return (Cmd!)base[index];
+ public sealed class CmdSeq : PureCollections.Sequence {
+ public CmdSeq(params Cmd[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
+ }
+ public CmdSeq(CmdSeq/*!*/ cmdSeq)
+ : base(cmdSeq) {
+ Contract.Requires(cmdSeq != null);
+ }
+ public new Cmd/*!*/ this[int index] {
+ get {
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+
+ return cce.NonNull((Cmd)base[index]);
}
- set
- {
+ set {
base[index] = value;
}
}
}
- public sealed class ExprSeq : PureCollections.Sequence
- {
- public ExprSeq(params Expr[]! args)
- : base(args)
- {
+ public sealed class ExprSeq : PureCollections.Sequence {
+ public ExprSeq(params Expr[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
}
- public ExprSeq(ExprSeq! exprSeq)
- : base(exprSeq)
- {
+ public ExprSeq(ExprSeq/*!*/ exprSeq)
+ : base(exprSeq) {
+ Contract.Requires(exprSeq != null);
}
- public new Expr this[int index]
- {
- get
- {
+ public new Expr this[int index] {
+ get {
return (Expr)base[index];
}
- set
- {
+ set {
base[index] = value;
}
}
-
- public new Expr Last() { return (Expr)base.Last(); }
- public static ExprSeq operator +(ExprSeq a, ExprSeq b)
- {
- if (a==null) throw new ArgumentNullException("a");
- if (b==null) throw new ArgumentNullException("b");
- return Append(a,b);
+ public new Expr Last() {
+ return (Expr)base.Last();
}
- public static ExprSeq Append(ExprSeq! s, ExprSeq! t)
- {
- Expr[] n = new Expr[s.card+t.card];
- for (int i = 0; i< s.card; i++) n[i] = s[i];
- for (int i = 0; i< t.card; i++) n[s.card+i] = t[i];
+ public static ExprSeq operator +(ExprSeq a, ExprSeq b) {
+ if (a == null)
+ throw new ArgumentNullException("a");
+ if (b == null)
+ throw new ArgumentNullException("b");
+ return Append(a, b);
+ }
+
+ public static ExprSeq Append(ExprSeq s, ExprSeq t) {
+ Contract.Requires(t != null);
+ Contract.Requires(s != null);
+ Expr[] n = new Expr[s.card + t.card];
+ for (int i = 0; i < s.card; i++)
+ n[i] = s[i];
+ for (int i = 0; i < t.card; i++)
+ n[s.card + i] = t[i];
return new ExprSeq(n);
}
- public void Emit(TokenTextWriter! stream)
- {
+ public void Emit(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
string sep = "";
- foreach (Expr! e in this)
- {
+ foreach (Expr/*!*/ e in this) {
+ Contract.Assert(e != null);
stream.Write(sep);
sep = ", ";
e.Emit(stream);
}
}
- public TypeSeq! ToTypeSeq { get {
- TypeSeq! res = new TypeSeq ();
- foreach(Expr e in this)
- res.Add(((!)e).Type);
- return res;
- } }
+ public TypeSeq/*!*/ ToTypeSeq {
+ get {
+ Contract.Ensures(Contract.Result<TypeSeq>() != null);
+
+ TypeSeq res = new TypeSeq();
+ foreach (Expr e in this)
+ res.Add(cce.NonNull(e).Type);
+ return res;
+ }
+ }
}
- public sealed class TokenSeq : PureCollections.Sequence
- {
- public TokenSeq(params Token[]! args)
- : base(args)
- {
+ public sealed class TokenSeq : PureCollections.Sequence {
+ public TokenSeq(params Token[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
}
- public new Token this[int index]
- {
- get
- {
+ public new Token this[int index] {
+ get {
return (Token)base[index];
}
- set
- {
+ set {
base[index] = value;
}
}
}
- public sealed class StringSeq : PureCollections.Sequence
- {
- public StringSeq(params string[]! args)
- : base(args)
- {
+ public sealed class StringSeq : PureCollections.Sequence {
+ public StringSeq(params string[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
}
- public new String this[int index]
- {
- get
- {
+ public new String this[int index] {
+ get {
return (String)base[index];
}
- set
- {
+ set {
base[index] = value;
}
}
- public void Emit(TokenTextWriter! stream)
- {
+ public void Emit(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
string sep = "";
- foreach (string! s in this)
- {
+ foreach (string/*!*/ s in this) {
+ Contract.Assert(s != null);
stream.Write(sep);
sep = ", ";
stream.Write(s);
@@ -2979,87 +3231,73 @@ namespace Microsoft.Boogie
}
}
- public sealed class BlockSeq : PureCollections.Sequence
- {
- public BlockSeq(params Block[]! args)
- : base(args)
- {
+ public sealed class BlockSeq : PureCollections.Sequence {
+ public BlockSeq(params Block[]/*!*/ args)
+ : base(args) {
+ Contract.Requires(args != null);
}
- public BlockSeq(BlockSeq! blockSeq)
- : base(blockSeq)
- {
+ public BlockSeq(BlockSeq blockSeq)
+ : base(blockSeq) {
+ Contract.Requires(blockSeq != null);
}
- public new Block this[int index]
- {
- get
- {
+ public new Block this[int index] {
+ get {
return (Block)base[index];
}
- set
- {
+ set {
base[index] = value;
}
}
}
public static class Emitter {
- public static void Declarations(List<Declaration!>! decls, TokenTextWriter! stream)
- {
+ public static void Declarations(List<Declaration/*!*/>/*!*/ decls, TokenTextWriter stream) {
+ Contract.Requires(stream != null);
+ Contract.Requires(cce.NonNullElements(decls));
bool first = true;
- foreach (Declaration d in decls)
- {
- if (d == null) continue;
- if (first)
- {
+ foreach (Declaration d in decls) {
+ if (d == null)
+ continue;
+ if (first) {
first = false;
- }
- else
- {
+ } else {
stream.WriteLine();
}
d.Emit(stream, 0);
}
}
}
- public sealed class DeclarationSeq : PureCollections.Sequence
- {
- public DeclarationSeq(params string[]! args)
- : base(args)
- {
+ public sealed class DeclarationSeq : PureCollections.Sequence {
+ public DeclarationSeq(params string[] args)
+ : base(args) {
+ Contract.Requires(args != null);
}
- public new Declaration this[int index]
- {
- get
- {
+ public new Declaration this[int index] {
+ get {
return (Declaration)base[index];
}
- set
- {
+ set {
base[index] = value;
}
}
- public void Emit(TokenTextWriter! stream)
- {
+ public void Emit(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
bool first = true;
- foreach (Declaration d in this)
- {
- if (d == null) continue;
- if (first)
- {
+ foreach (Declaration d in this) {
+ if (d == null)
+ continue;
+ if (first) {
first = false;
- }
- else
- {
+ } else {
stream.WriteLine();
}
d.Emit(stream, 0);
}
}
- public void InstrumentWithInvariants ()
- {
- foreach (Declaration! d in this)
- {
+ public void InstrumentWithInvariants() {
+ foreach (Declaration/*!*/ d in this) {
+ Contract.Assert(d != null);
d.InstrumentWithInvariants();
}
}
@@ -3069,24 +3307,20 @@ namespace Microsoft.Boogie
#region Regular Expressions
// a data structure to recover the "program structure" from the flow graph
- public sealed class RESeq : PureCollections.Sequence
- {
- public RESeq(params RE[]! args)
- : base (args)
- {
+ public sealed class RESeq : PureCollections.Sequence {
+ public RESeq(params RE[] args)
+ : base(args) {
+ Contract.Requires(args != null);
}
- public RESeq(RESeq! reSeq)
- : base(reSeq)
- {
+ public RESeq(RESeq reSeq)
+ : base(reSeq) {
+ Contract.Requires(reSeq != null);
}
- public new RE this[int index]
- {
- get
- {
+ public new RE this[int index] {
+ get {
return (RE)base[index];
}
- set
- {
+ set {
base[index] = value;
}
}
@@ -3101,119 +3335,140 @@ namespace Microsoft.Boogie
// }
// }
}
- public abstract class RE : Cmd
- {
- public RE() : base(Token.NoToken) {}
- public override void AddAssignedVariables(VariableSeq! vars) { throw new NotImplementedException(); }
+ public abstract class RE : Cmd {
+ public RE()
+ : base(Token.NoToken) {
+ }
+ public override void AddAssignedVariables(VariableSeq vars) {
+ //Contract.Requires(vars != null);
+ throw new NotImplementedException();
+ }
}
- public class AtomicRE : RE
- {
- public Block! b;
- public AtomicRE(Block! block) { b = block; }
- public override void Resolve(ResolutionContext! rc)
- {
+ public class AtomicRE : RE {
+ public Block/*!*/ b;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(b != null);
+ }
+
+ public AtomicRE(Block block) {
+ Contract.Requires(block != null);
+ b = block;
+ }
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
b.Resolve(rc);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
b.Typecheck(tc);
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
- b.Emit(stream,level);
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
+ b.Emit(stream, level);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitAtomicRE(this);
}
}
- public abstract class CompoundRE : RE
- {
- public override void Resolve(ResolutionContext! rc)
- {
+ public abstract class CompoundRE : RE {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
return;
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
return;
}
}
- public class Sequential : CompoundRE
- {
- public RE! first;
- public RE! second;
- public Sequential(RE! a, RE! b)
- {
+ public class Sequential : CompoundRE {
+ public RE/*!*/ first;
+ public RE/*!*/ second;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(first != null);
+ Contract.Invariant(second != null);
+ }
+
+ public Sequential(RE a, RE b) {
+ Contract.Requires(b != null);
+ Contract.Requires(a != null);
first = a;
second = b;
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.WriteLine();
stream.WriteLine("{0};", Indent(level));
- first.Emit(stream,level+1);
- second.Emit(stream,level+1);
+ first.Emit(stream, level + 1);
+ second.Emit(stream, level + 1);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitSequential(this);
}
}
- public class Choice : CompoundRE
- {
- public RESeq! rs;
- public Choice(RESeq! operands)
- {
+ public class Choice : CompoundRE {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(rs != null);
+ }
+
+ public RESeq/*!*/ rs;
+ public Choice(RESeq operands) {
+ Contract.Requires(operands != null);
rs = operands;
// base();
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.WriteLine();
stream.WriteLine("{0}[]", Indent(level));
- foreach (RE! r in rs )
- r.Emit(stream,level+1);
+ foreach (RE/*!*/ r in rs) {
+ Contract.Assert(r != null);
+ r.Emit(stream, level + 1);
+ }
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitChoice(this);
}
}
- public class DAG2RE
- {
- public static RE! Transform(Block! b)
- {
+ public class DAG2RE {
+ public static RE Transform(Block b) {
+ Contract.Requires(b != null);
+ Contract.Ensures(Contract.Result<RE>() != null);
TransferCmd tc = b.TransferCmd;
- if ( tc is ReturnCmd )
- {
+ if (tc is ReturnCmd) {
return new AtomicRE(b);
- }
- else if ( tc is GotoCmd )
- {
- GotoCmd! g = (GotoCmd) tc ;
- assume g.labelTargets != null;
- if ( g.labelTargets.Length == 1 )
- {
- return new Sequential(new AtomicRE(b),Transform( (!) g.labelTargets[0]));
- }
- else
- {
+ } else if (tc is GotoCmd) {
+ GotoCmd/*!*/ g = (GotoCmd)tc;
+ Contract.Assert(g != null);
+ Contract.Assume(g.labelTargets != null);
+ if (g.labelTargets.Length == 1) {
+ return new Sequential(new AtomicRE(b), Transform(cce.NonNull(g.labelTargets[0])));
+ } else {
RESeq rs = new RESeq();
- foreach (Block! target in g.labelTargets )
- {
+ foreach (Block/*!*/ target in g.labelTargets) {
+ Contract.Assert(target != null);
RE r = Transform(target);
rs.Add(r);
}
RE second = new Choice(rs);
- return new Sequential(new AtomicRE(b),second);
+ return new Sequential(new AtomicRE(b), second);
+ }
+ } else {
+ {
+ Contract.Assume(false);
+ throw new cce.UnreachableException();
}
- }
- else
- {
- assume false;
return new AtomicRE(b);
}
}
@@ -3224,21 +3479,29 @@ namespace Microsoft.Boogie
// NOTE: This class is here for convenience, since this file's
// classes are used pretty much everywhere.
- public class BoogieDebug
- {
+ public class BoogieDebug {
public static bool DoPrinting = false;
- public static void Write (string! format, params object[]! args)
- {
- if (DoPrinting) { Console.Error.Write(format, args); }
+ public static void Write(string format, params object[] args) {
+ Contract.Requires(args != null);
+ Contract.Requires(format != null);
+ if (DoPrinting) {
+ Console.Error.Write(format, args);
+ }
}
- public static void WriteLine (string! format, params object[]! args)
- {
- if (DoPrinting) { Console.Error.WriteLine(format, args); }
+ public static void WriteLine(string format, params object[] args) {
+ Contract.Requires(args != null);
+ Contract.Requires(format != null);
+ if (DoPrinting) {
+ Console.Error.WriteLine(format, args);
+ }
}
- public static void WriteLine () { if (DoPrinting) { Console.Error.WriteLine(); } }
+ public static void WriteLine() {
+ if (DoPrinting) {
+ Console.Error.WriteLine();
+ }
+ }
}
-
-}
+} \ No newline at end of file
diff --git a/Source/Core/AbsyCmd.cs b/Source/Core/AbsyCmd.cs
index 7aa3e1fc..e31348a1 100644
--- a/Source/Core/AbsyCmd.cs
+++ b/Source/Core/AbsyCmd.cs
@@ -7,34 +7,42 @@
// BoogiePL - Absy.cs
//---------------------------------------------------------------------------------------------
-namespace Microsoft.Boogie
-{
+namespace Microsoft.Boogie {
using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Boogie.AbstractInterpretation;
using AI = Microsoft.AbstractInterpretationFramework;
- using Microsoft.Contracts;
+ using System.Diagnostics.Contracts;
//---------------------------------------------------------------------
// BigBlock
- public class BigBlock
- {
- public readonly IToken! tok;
+ public class BigBlock {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ Contract.Invariant(Anonymous || LabelName != null);
+ Contract.Invariant(ec == null || tc == null);
+ Contract.Invariant(simpleCmds != null);
+ }
+
+ public readonly IToken/*!*/ tok;
public string LabelName;
public readonly bool Anonymous;
- invariant !Anonymous ==> LabelName != null;
- [Rep] public CmdSeq! simpleCmds;
+
+ [Rep]
+ public CmdSeq/*!*/ simpleCmds;
public StructuredCmd ec;
public TransferCmd tc;
- invariant ec == null || tc == null;
+
public BigBlock successorBigBlock; // null if successor is end of proceduure body (or if field has not yet been initialized)
- public BigBlock(IToken! tok, string? labelName, [Captured] CmdSeq! simpleCmds, StructuredCmd? ec, TransferCmd? tc)
- requires ec == null || tc == null;
- {
+ public BigBlock(IToken tok, string labelName, [Captured] CmdSeq simpleCmds, StructuredCmd ec, TransferCmd tc) {
+ Contract.Requires(simpleCmds != null);
+ Contract.Requires(tok != null);
+ Contract.Requires(ec == null || tc == null);
this.tok = tok;
this.LabelName = labelName;
this.Anonymous = labelName == null;
@@ -43,45 +51,57 @@ namespace Microsoft.Boogie
this.tc = tc;
}
- public void Emit(TokenTextWriter! stream, int level) {
+ public void Emit(TokenTextWriter stream, int level) {
+ Contract.Requires(stream != null);
if (!Anonymous) {
- stream.WriteLine(level, "{0}:",
+ stream.WriteLine(level, "{0}:",
CommandLineOptions.Clo.PrintWithUniqueASTIds ? String.Format("h{0}^^{1}", this.GetHashCode(), this.LabelName) : this.LabelName);
}
- foreach (Cmd! c in this.simpleCmds) {
- c.Emit(stream, level+1);
+ foreach (Cmd/*!*/ c in this.simpleCmds) {
+ Contract.Assert(c != null);
+ c.Emit(stream, level + 1);
}
if (this.ec != null) {
- this.ec.Emit(stream, level+1);
+ this.ec.Emit(stream, level + 1);
} else if (this.tc != null) {
- this.tc.Emit(stream, level+1);
+ this.tc.Emit(stream, level + 1);
}
}
}
- public class StmtList
- {
- [Rep] public readonly List<BigBlock!>! BigBlocks;
+ public class StmtList {
+ [Rep]
+ public readonly List<BigBlock/*!*/>/*!*/ BigBlocks;
public CmdSeq PrefixCommands;
- public readonly IToken! EndCurly;
+ public readonly IToken/*!*/ EndCurly;
public StmtList ParentContext;
public BigBlock ParentBigBlock;
- public Set<string!>! Labels = new Set<string!>();
+ public Set<string/*!*/>/*!*/ Labels = new Set<string/*!*/>();
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(EndCurly != null);
+ Contract.Invariant(cce.NonNullElements(BigBlocks));
+ Contract.Invariant(cce.NonNullElements(Labels));
+ }
- public StmtList([Captured] List<BigBlock!>! bigblocks, IToken! endCurly)
- requires bigblocks.Count > 0;
- {
+
+ public StmtList([Captured] List<BigBlock/*!*/>/*!*/ bigblocks, IToken endCurly) {
+ Contract.Requires(endCurly != null);
+ Contract.Requires(cce.NonNullElements(bigblocks));
+ Contract.Requires(bigblocks.Count > 0);
this.BigBlocks = bigblocks;
this.EndCurly = endCurly;
}
// prints the list of statements, not the surrounding curly braces
- public void Emit(TokenTextWriter! stream, int level) {
+ public void Emit(TokenTextWriter stream, int level) {
+ Contract.Requires(stream != null);
bool needSeperator = false;
foreach (BigBlock b in BigBlocks) {
- assume b.IsPeerConsistent;
+ Contract.Assert(b != null);
+ Contract.Assume(cce.IsPeerConsistent(b));
if (needSeperator) {
stream.WriteLine();
}
@@ -101,10 +121,11 @@ namespace Microsoft.Boogie
/// Note, to be conservative (that is, ignoring the possible optimization that this
/// method enables), this method can do nothing and return false.
/// </summary>
- public bool PrefixFirstBlock([Captured] CmdSeq! prefixCmds, ref string! suggestedLabel)
- ensures !result ==> Owner.None(prefixCmds); // "prefixCmds" is captured only on success
- {
- assume PrefixCommands == null; // prefix has not been used
+ public bool PrefixFirstBlock([Captured] CmdSeq prefixCmds, ref string suggestedLabel) {
+ Contract.Requires(suggestedLabel != null);
+ Contract.Requires(prefixCmds != null);
+ Contract.Ensures(Contract.Result<bool>() || cce.Owner.None(prefixCmds)); // "prefixCmds" is captured only on success
+ Contract.Assume(PrefixCommands == null); // prefix has not been used
BigBlock bb0 = BigBlocks[0];
if (prefixCmds.Length == 0) {
@@ -113,7 +134,7 @@ namespace Microsoft.Boogie
if (bb0.Anonymous) {
bb0.LabelName = suggestedLabel;
} else {
- assert bb0.LabelName != null;
+ Contract.Assert(bb0.LabelName != null);
suggestedLabel = bb0.LabelName;
}
return true;
@@ -138,14 +159,17 @@ namespace Microsoft.Boogie
/// The StmtListBuilder class makes it easier to build structured commands.
/// </summary>
public class StmtListBuilder {
- List<BigBlock!>! bigBlocks = new List<BigBlock!>();
+ List<BigBlock/*!*/>/*!*/ bigBlocks = new List<BigBlock/*!*/>();
string label;
CmdSeq simpleCmds;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(bigBlocks));
+ }
- void Dump(StructuredCmd scmd, TransferCmd tcmd)
- requires scmd == null || tcmd == null;
- ensures label == null && simpleCmds == null;
- {
+ void Dump(StructuredCmd scmd, TransferCmd tcmd) {
+ Contract.Requires(scmd == null || tcmd == null);
+ Contract.Ensures(label == null && simpleCmds == null);
if (label == null && simpleCmds == null && scmd == null && tcmd == null) {
// nothing to do
} else {
@@ -162,7 +186,9 @@ namespace Microsoft.Boogie
/// Collects the StmtList built so far and returns it. The StmtListBuilder should no longer
/// be used once this method has been invoked.
/// </summary>
- public StmtList! Collect(IToken! endCurlyBrace) {
+ public StmtList Collect(IToken endCurlyBrace) {
+ Contract.Requires(endCurlyBrace != null);
+ Contract.Ensures(Contract.Result<StmtList>() != null);
Dump(null, null);
if (bigBlocks.Count == 0) {
simpleCmds = new CmdSeq(); // the StmtList constructor doesn't like an empty list of BigBlock's
@@ -171,48 +197,66 @@ namespace Microsoft.Boogie
return new StmtList(bigBlocks, endCurlyBrace);
}
- public void Add(Cmd! cmd) {
+ public void Add(Cmd cmd) {
+ Contract.Requires(cmd != null);
if (simpleCmds == null) {
simpleCmds = new CmdSeq();
}
simpleCmds.Add(cmd);
}
- public void Add(StructuredCmd! scmd) {
+ public void Add(StructuredCmd scmd) {
+ Contract.Requires(scmd != null);
Dump(scmd, null);
}
- public void Add(TransferCmd! tcmd) {
+ public void Add(TransferCmd tcmd) {
+ Contract.Requires(tcmd != null);
Dump(null, tcmd);
}
- public void AddLabelCmd(string! label) {
+ public void AddLabelCmd(string label) {
+ Contract.Requires(label != null);
Dump(null, null);
this.label = label;
}
- public void AddLocalVariable(string! name) {
+ public void AddLocalVariable(string name) {
+ Contract.Requires(name != null);
// TODO
}
}
class BigBlocksResolutionContext {
- StmtList! stmtList;
- [Peer] List<Block!> blocks;
- string! prefix = "anon";
+ StmtList/*!*/ stmtList;
+ [Peer]
+ List<Block/*!*/> blocks;
+ string/*!*/ prefix = "anon";
int anon = 0;
- Set<string!> allLabels = new Set<string!>();
- Errors! errorHandler;
+ Set<string/*!*/> allLabels = new Set<string/*!*/>();
+ Errors/*!*/ errorHandler;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(stmtList != null);
+ Contract.Invariant(cce.NonNullElements(blocks, true));
+ Contract.Invariant(prefix != null);
+ Contract.Invariant(cce.NonNullElements(allLabels, true));
+ Contract.Invariant(errorHandler != null);
+ }
- public BigBlocksResolutionContext(StmtList! stmtList, Errors! errorHandler) {
+
+ public BigBlocksResolutionContext(StmtList stmtList, Errors errorHandler) {
+ Contract.Requires(errorHandler != null);
+ Contract.Requires(stmtList != null);
this.stmtList = stmtList;
this.errorHandler = errorHandler;
}
- public List<Block!>! Blocks {
+ public List<Block/*!*/>/*!*/ Blocks {
get {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Block>>()));
if (blocks == null) {
- blocks = new List<Block!>();
+ blocks = new List<Block/*!*/>();
int startErrorCount = this.errorHandler.count;
// Check that there are no goto's into the middle of a block, and no break statement to a non-enclosing loop.
@@ -234,12 +278,12 @@ namespace Microsoft.Boogie
}
}
- void CheckLegalLabels(StmtList! stmtList, StmtList parentContext, BigBlock parentBigBlock)
- requires parentContext == null <==> parentBigBlock == null;
- requires stmtList.ParentContext == null; // it hasn't been set yet
- modifies stmtList.*;
- ensures stmtList.ParentContext == parentContext;
- {
+ void CheckLegalLabels(StmtList stmtList, StmtList parentContext, BigBlock parentBigBlock) {
+ Contract.Requires(stmtList != null);
+ Contract.Requires((parentContext == null) == (parentBigBlock == null));
+ Contract.Requires(stmtList.ParentContext == null); // it hasn't been set yet
+ //modifies stmtList.*;
+ Contract.Ensures(stmtList.ParentContext == parentContext);
stmtList.ParentContext = parentContext;
stmtList.ParentBigBlock = parentBigBlock;
@@ -263,7 +307,8 @@ namespace Microsoft.Boogie
// goto's must reference blocks in enclosing blocks
if (b.tc is GotoCmd) {
GotoCmd g = (GotoCmd)b.tc;
- foreach (string! lbl in (!)g.labelNames) {
+ foreach (string/*!*/ lbl in cce.NonNull(g.labelNames)) {
+ Contract.Assert(lbl != null);
bool found = false;
for (StmtList sl = stmtList; sl != null; sl = sl.ParentContext) {
if (sl.Labels.Contains(lbl)) {
@@ -280,11 +325,10 @@ namespace Microsoft.Boogie
// break labels must refer to an enclosing while statement
else if (b.ec is BreakCmd) {
BreakCmd bcmd = (BreakCmd)b.ec;
- assert bcmd.BreakEnclosure == null; // it hasn't been initialized yet
+ Contract.Assert(bcmd.BreakEnclosure == null); // it hasn't been initialized yet
bool found = false;
- for (StmtList sl = stmtList; sl.ParentBigBlock != null; sl = sl.ParentContext)
- invariant sl != null;
- {
+ for (StmtList sl = stmtList; sl.ParentBigBlock != null; sl = sl.ParentContext) {
+ cce.LoopInvariant(sl != null);
BigBlock bb = sl.ParentBigBlock;
if (bcmd.Label == null) {
@@ -331,7 +375,8 @@ namespace Microsoft.Boogie
}
}
- void NameAnonymousBlocks(StmtList! stmtList) {
+ void NameAnonymousBlocks(StmtList stmtList) {
+ Contract.Requires(stmtList != null);
foreach (BigBlock b in stmtList.BigBlocks) {
if (b.LabelName == null) {
b.LabelName = prefix + anon;
@@ -351,7 +396,8 @@ namespace Microsoft.Boogie
}
}
- void RecordSuccessors(StmtList! stmtList, BigBlock successor) {
+ void RecordSuccessors(StmtList stmtList, BigBlock successor) {
+ Contract.Requires(stmtList != null);
for (int i = stmtList.BigBlocks.Count; 0 <= --i; ) {
BigBlock big = stmtList.BigBlocks[i];
big.successorBigBlock = successor;
@@ -374,15 +420,15 @@ namespace Microsoft.Boogie
// If the enclosing context is a loop, then "runOffTheEndLabel" is the loop head label;
// otherwise, it is null.
- void CreateBlocks(StmtList! stmtList, string runOffTheEndLabel)
- requires blocks != null;
- {
+ void CreateBlocks(StmtList stmtList, string runOffTheEndLabel) {
+ Contract.Requires(stmtList != null);
+ Contract.Requires(blocks != null);
CmdSeq cmdPrefixToApply = stmtList.PrefixCommands;
int n = stmtList.BigBlocks.Count;
foreach (BigBlock b in stmtList.BigBlocks) {
n--;
- assert b.LabelName != null;
+ Contract.Assert(b.LabelName != null);
CmdSeq theSimpleCmds;
if (cmdPrefixToApply == null) {
theSimpleCmds = b.simpleCmds;
@@ -395,7 +441,7 @@ namespace Microsoft.Boogie
if (b.tc != null) {
// this BigBlock has the very same components as a Block
- assert b.ec == null;
+ Contract.Assert(b.ec == null);
Block block = new Block(b.tok, b.LabelName, theSimpleCmds, b.tc);
blocks.Add(block);
@@ -412,14 +458,14 @@ namespace Microsoft.Boogie
} else if (b.ec is BreakCmd) {
BreakCmd bcmd = (BreakCmd)b.ec;
- assert bcmd.BreakEnclosure != null;
+ Contract.Assert(bcmd.BreakEnclosure != null);
Block block = new Block(b.tok, b.LabelName, theSimpleCmds, GotoSuccessor(b.ec.tok, bcmd.BreakEnclosure));
blocks.Add(block);
} else if (b.ec is WhileCmd) {
WhileCmd wcmd = (WhileCmd)b.ec;
string loopHeadLabel = prefix + anon + "_LoopHead";
- string! loopBodyLabel = prefix + anon + "_LoopBody";
+ string/*!*/ loopBodyLabel = prefix + anon + "_LoopBody";
string loopDoneLabel = prefix + anon + "_LoopDone";
anon++;
@@ -471,8 +517,10 @@ namespace Microsoft.Boogie
CmdSeq predCmds = theSimpleCmds;
for (; ifcmd != null; ifcmd = ifcmd.elseIf) {
- string! thenLabel = prefix + anon + "_Then";
- string! elseLabel = prefix + anon + "_Else";
+ string thenLabel = prefix + anon + "_Then";
+ Contract.Assert(thenLabel != null);
+ string elseLabel = prefix + anon + "_Else";
+ Contract.Assert(elseLabel != null);
anon++;
CmdSeq ssThen = new CmdSeq();
@@ -504,7 +552,7 @@ namespace Microsoft.Boogie
CreateBlocks(ifcmd.thn, n == 0 ? runOffTheEndLabel : null);
if (ifcmd.elseBlock != null) {
- assert ifcmd.elseIf == null;
+ Contract.Assert(ifcmd.elseIf == null);
if (!elseGuardTakenCareOf) {
// Else: assume !guard; goto firstElseBlock;
block = new Block(ifcmd.tok, elseLabel, ssElse, new GotoCmd(ifcmd.tok, new StringSeq(ifcmd.elseBlock.BigBlocks[0].LabelName)));
@@ -540,7 +588,10 @@ namespace Microsoft.Boogie
}
}
- TransferCmd! GotoSuccessor(IToken! tok, BigBlock! b) {
+ TransferCmd GotoSuccessor(IToken tok, BigBlock b) {
+ Contract.Requires(b != null);
+ Contract.Requires(tok != null);
+ Contract.Ensures(Contract.Result<TransferCmd>() != null);
if (b.successorBigBlock != null) {
return new GotoCmd(tok, new StringSeq(b.successorBigBlock.LabelName));
} else {
@@ -549,29 +600,50 @@ namespace Microsoft.Boogie
}
}
- public abstract class StructuredCmd
- {
- public IToken! tok;
- public StructuredCmd(IToken! tok)
- {
+ [ContractClass(typeof(StructuredCmdContracts))]
+ public abstract class StructuredCmd {
+ public IToken/*!*/ tok;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ }
+
+ public StructuredCmd(IToken tok) {
+ Contract.Requires(tok != null);
this.tok = tok;
}
- public abstract void Emit(TokenTextWriter! stream, int level);
+ public abstract void Emit(TokenTextWriter/*!*/ stream, int level);
}
+ [ContractClassFor(typeof(StructuredCmd))]
+ public abstract class StructuredCmdContracts : StructuredCmd {
+ public override void Emit(TokenTextWriter stream, int level) {
+ Contract.Requires(stream != null);
+ throw new NotImplementedException();
+ }
+ public StructuredCmdContracts() :base(null){
- public class IfCmd : StructuredCmd
- {
- public Expr? Guard;
- public StmtList! thn;
- public IfCmd? elseIf;
+ }
+ }
+
+ public class IfCmd : StructuredCmd {
+ public Expr Guard;
+ public StmtList/*!*/ thn;
+ public IfCmd elseIf;
public StmtList elseBlock;
- invariant elseIf == null || elseBlock == null;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(thn != null);
+ Contract.Invariant(elseIf == null || elseBlock == null);
+ }
+
- public IfCmd(IToken! tok, Expr? guard, StmtList! thn, IfCmd? elseIf, StmtList elseBlock)
- : base(tok)
- requires elseIf == null || elseBlock == null;
- {
+
+ public IfCmd(IToken/*!*/ tok, Expr guard, StmtList/*!*/ thn, IfCmd elseIf, StmtList elseBlock)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(thn != null);
+ Contract.Requires(elseIf == null || elseBlock == null);
this.Guard = guard;
this.thn = thn;
this.elseIf = elseIf;
@@ -579,9 +651,9 @@ namespace Microsoft.Boogie
// base(tok);
}
- public override void Emit(TokenTextWriter! stream, int level) {
+ public override void Emit(TokenTextWriter stream, int level) {
stream.Write(level, "if (");
- IfCmd! ifcmd = this;
+ IfCmd/*!*/ ifcmd = this;
while (true) {
if (ifcmd.Guard == null) {
stream.Write("*");
@@ -609,22 +681,30 @@ namespace Microsoft.Boogie
}
}
- public class WhileCmd : StructuredCmd
- {
- [Peer] public Expr? Guard;
- public List<PredicateCmd!>! Invariants;
- public StmtList! Body;
+ public class WhileCmd : StructuredCmd {
+ [Peer]
+ public Expr Guard;
+ public List<PredicateCmd/*!*/>/*!*/ Invariants;
+ public StmtList/*!*/ Body;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Body != null);
+ Contract.Invariant(cce.NonNullElements(Invariants));
+ }
+
- public WhileCmd(IToken! tok, [Captured] Expr? guard, List<PredicateCmd!>! invariants, StmtList! body)
- : base(tok)
- {
+ public WhileCmd(IToken tok, [Captured] Expr guard, List<PredicateCmd/*!*/>/*!*/ invariants, StmtList/*!*/ body)
+ : base(tok) {
+ Contract.Requires(cce.NonNullElements(invariants));
+ Contract.Requires(body != null);
+ Contract.Requires(tok != null);
this.Guard = guard;
this.Invariants = invariants;
this.Body = body;
/// base(tok);
}
- public override void Emit(TokenTextWriter! stream, int level) {
+ public override void Emit(TokenTextWriter stream, int level) {
stream.Write(level, "while (");
if (Guard == null) {
stream.Write("*");
@@ -649,19 +729,19 @@ namespace Microsoft.Boogie
}
}
- public class BreakCmd : StructuredCmd
- {
+ public class BreakCmd : StructuredCmd {
public string Label;
public BigBlock BreakEnclosure;
- public BreakCmd(IToken! tok, string? label)
- : base(tok)
- {
+ public BreakCmd(IToken tok, string label)
+ : base(tok) {
+ Contract.Requires(tok != null);
this.Label = label;
// base(tok);
}
- public override void Emit(TokenTextWriter! stream, int level) {
+ public override void Emit(TokenTextWriter stream, int level) {
+
if (Label == null) {
stream.WriteLine(level, "break;");
} else {
@@ -672,10 +752,11 @@ namespace Microsoft.Boogie
//---------------------------------------------------------------------
// Block
- public sealed class Block : Absy
- {
- public string! Label; // Note, Label is mostly readonly, but it can change to the name of a nearby block during block coalescing and empty-block removal
- [Rep] [ElementsPeer] public CmdSeq! Cmds;
+ public sealed class Block : Absy {
+ public string/*!*/ Label; // Note, Label is mostly readonly, but it can change to the name of a nearby block during block coalescing and empty-block removal
+ [Rep]
+ [ElementsPeer]
+ public CmdSeq/*!*/ Cmds;
[Rep] //PM: needed to verify Traverse.Visit
public TransferCmd TransferCmd; // maybe null only because we allow deferred initialization (necessary for cyclic structures)
@@ -683,7 +764,11 @@ namespace Microsoft.Boogie
// public bool currentlyTraversed;
- public enum VisitState {ToVisit, BeingVisited, AlreadyVisited}; // used by WidenPoints.Compute
+ public enum VisitState {
+ ToVisit,
+ BeingVisited,
+ AlreadyVisited
+ }; // used by WidenPoints.Compute
public VisitState TraversingStatus;
public bool widenBlock;
@@ -693,22 +778,38 @@ namespace Microsoft.Boogie
public AI.Lattice Lattice; // The lattice used for the analysis of this block
public AI.Lattice.Element PreInvariant; // The initial abstract states for this block
public AI.Lattice.Element PostInvariant; // The exit abstract states for this block
- // KRML: We want to include the following invariant, but at the moment, doing so causes a run-time error (something about committed): invariant PreInvariant != null <==> PostInvariant != null;
+ // KRML: We want to include the following invariant, but at the moment, doing so causes a run-time error (something about committed):
+ //invariant ;
// VC generation and SCC computation
- public BlockSeq! Predecessors;
+ public BlockSeq/*!*/ Predecessors;
- public Set<Variable!> liveVarsBefore;
- public bool IsLive(Variable! v) {
- if (liveVarsBefore == null) return true;
+ public Set<Variable/*!*/> liveVarsBefore;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Label != null);
+ Contract.Invariant(Cmds != null);
+ Contract.Invariant(cce.NonNullElements(liveVarsBefore, true));
+ Contract.Invariant((PreInvariant != null) == (PostInvariant != null));
+ }
+
+ public bool IsLive(Variable v) {
+ Contract.Requires(v != null);
+ if (liveVarsBefore == null)
+ return true;
return liveVarsBefore.Contains(v);
}
-
- public Block() { this(Token.NoToken, "", new CmdSeq(), new ReturnCmd(Token.NoToken));}
- public Block (IToken! tok, string! label, CmdSeq! cmds, TransferCmd transferCmd)
- : base(tok)
- {
+ public Block()
+ : this(Token.NoToken, "", new CmdSeq(), new ReturnCmd(Token.NoToken)) {
+
+ }
+
+ public Block(IToken tok, string/*!*/ label, CmdSeq/*!*/ cmds, TransferCmd transferCmd)
+ : base(tok) {
+ Contract.Requires(label != null);
+ Contract.Requires(cmds != null);
+ Contract.Requires(tok != null);
this.Label = label;
this.Cmds = cmds;
this.TransferCmd = transferCmd;
@@ -721,8 +822,8 @@ namespace Microsoft.Boogie
// base(tok);
}
- public void Emit (TokenTextWriter! stream, int level)
- {
+ public void Emit(TokenTextWriter stream, int level) {
+ Contract.Requires(stream != null);
stream.WriteLine();
stream.WriteLine(
this,
@@ -731,45 +832,45 @@ namespace Microsoft.Boogie
CommandLineOptions.Clo.PrintWithUniqueASTIds ? String.Format("h{0}^^{1}", this.GetHashCode(), this.Label) : this.Label,
this.widenBlock ? " // cut point" : "");
- foreach (Cmd! c in this.Cmds)
- {
+ foreach (Cmd/*!*/ c in this.Cmds) {
+ Contract.Assert(c != null);
c.Emit(stream, level + 1);
}
- assume this.TransferCmd != null;
+ Contract.Assume(this.TransferCmd != null);
this.TransferCmd.Emit(stream, level + 1);
}
- public void Register (ResolutionContext! rc)
- {
+ public void Register(ResolutionContext rc) {
+ Contract.Requires(rc != null);
rc.AddBlock(this);
}
- public override void Resolve (ResolutionContext! rc)
- {
- foreach (Cmd! c in Cmds)
- {
+ public override void Resolve(ResolutionContext rc) {
+
+
+ foreach (Cmd/*!*/ c in Cmds) {
+ Contract.Assert(c != null);
c.Resolve(rc);
}
- assume this.TransferCmd != null;
+ Contract.Assume(this.TransferCmd != null);
TransferCmd.Resolve(rc);
}
- public override void Typecheck (TypecheckingContext! tc)
- {
- foreach (Cmd! c in Cmds)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+
+ foreach (Cmd/*!*/ c in Cmds) {
+ Contract.Assert(c != null);
c.Typecheck(tc);
}
- assume this.TransferCmd != null;
+ Contract.Assume(this.TransferCmd != null);
TransferCmd.Typecheck(tc);
}
/// <summary>
/// Reset the abstract intepretation state of this block. It does this by putting the iterations to 0 and the pre and post states to null
/// </summary>
- public void ResetAbstractInterpretationState()
- {
-// this.currentlyTraversed = false;
+ public void ResetAbstractInterpretationState() {
+ // this.currentlyTraversed = false;
this.TraversingStatus = VisitState.ToVisit;
this.iterations = 0;
this.Lattice = null;
@@ -778,89 +879,119 @@ namespace Microsoft.Boogie
}
[Pure]
- public override string! ToString()
- {
- return this.Label + (this.widenBlock? "[w]" : "");
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return this.Label + (this.widenBlock ? "[w]" : "");
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitBlock(this);
}
}
//---------------------------------------------------------------------
// Commands
+ [ContractClassFor(typeof(Cmd))]
+ public abstract class CmdContracts : Cmd {
+ public CmdContracts() :base(null){
- public abstract class Cmd : Absy
- {
- public Cmd(IToken! tok) : base(tok) { }
- public abstract void Emit(TokenTextWriter! stream, int level);
- public abstract void AddAssignedVariables(VariableSeq! vars);
- public void CheckAssignments(TypecheckingContext! tc)
- {
- VariableSeq! vars = new VariableSeq();
+ }
+ public override void Emit(TokenTextWriter stream, int level) {
+ Contract.Requires(stream != null);
+ throw new NotImplementedException();
+ }
+ public override void AddAssignedVariables(VariableSeq vars) {
+ Contract.Requires(vars != null);
+ throw new NotImplementedException();
+ }
+ }
+ [ContractClass(typeof(CmdContracts))]
+ public abstract class Cmd : Absy {
+ public Cmd(IToken/*!*/ tok)
+ : base(tok) {
+ Contract.Assert(tok != null);
+ }
+ public abstract void Emit(TokenTextWriter/*!*/ stream, int level);
+ public abstract void AddAssignedVariables(VariableSeq/*!*/ vars);
+ public void CheckAssignments(TypecheckingContext tc) {
+ Contract.Requires(tc != null);
+ VariableSeq/*!*/ vars = new VariableSeq();
this.AddAssignedVariables(vars);
- foreach (Variable! v in vars)
- {
- if (!v.IsMutable)
- {
+ foreach (Variable/*!*/ v in vars) {
+ Contract.Assert(v != null);
+ if (!v.IsMutable) {
tc.Error(this, "command assigns to an immutable variable: {0}", v.Name);
- }
- else if (v is GlobalVariable && !tc.InFrame(v))
- {
+ } else if (v is GlobalVariable && !tc.InFrame(v)) {
tc.Error(this, "command assigns to a global variable that is not in the enclosing method's modifies clause: {0}", v.Name);
}
}
}
// Methods to simulate the old SimpleAssignCmd and MapAssignCmd
- public static AssignCmd! SimpleAssign(IToken! tok, IdentifierExpr! lhs, Expr! rhs) {
- List<AssignLhs!>! lhss = new List<AssignLhs!> ();
- List<Expr!>! rhss = new List<Expr!> ();
-
- lhss.Add(new SimpleAssignLhs (lhs.tok, lhs));
+ public static AssignCmd SimpleAssign(IToken tok, IdentifierExpr lhs, Expr rhs) {
+ Contract.Requires(rhs != null);
+ Contract.Requires(lhs != null);
+ Contract.Requires(tok != null);
+ Contract.Ensures(Contract.Result<AssignCmd>() != null);
+ List<AssignLhs/*!*/>/*!*/ lhss = new List<AssignLhs/*!*/>();
+ List<Expr/*!*/>/*!*/ rhss = new List<Expr/*!*/>();
+
+ lhss.Add(new SimpleAssignLhs(lhs.tok, lhs));
rhss.Add(rhs);
return new AssignCmd(tok, lhss, rhss);
}
- public static AssignCmd! MapAssign(IToken! tok,
- IdentifierExpr! map,
- ExprSeq! indexes, Expr! rhs) {
- List<AssignLhs!>! lhss = new List<AssignLhs!> ();
- List<Expr!>! rhss = new List<Expr!> ();
- List<Expr!>! indexesList = new List<Expr!> ();
+ public static AssignCmd/*!*/ MapAssign(IToken tok,
+ IdentifierExpr/*!*/ map,
+ ExprSeq/*!*/ indexes, Expr/*!*/ rhs) {
+
+ Contract.Requires(tok != null);
+ Contract.Requires(map != null);
+ Contract.Requires(indexes != null);
+ Contract.Requires(rhs != null);
+ Contract.Ensures(Contract.Result<AssignCmd>() != null);
+ List<AssignLhs/*!*/>/*!*/ lhss = new List<AssignLhs/*!*/>();
+ List<Expr/*!*/>/*!*/ rhss = new List<Expr/*!*/>();
+ List<Expr/*!*/>/*!*/ indexesList = new List<Expr/*!*/>();
+
+
foreach (Expr e in indexes)
- indexesList.Add((!)e);
+ indexesList.Add(cce.NonNull(e));
- lhss.Add(new MapAssignLhs (map.tok,
- new SimpleAssignLhs (map.tok, map),
+ lhss.Add(new MapAssignLhs(map.tok,
+ new SimpleAssignLhs(map.tok, map),
indexesList));
rhss.Add(rhs);
return new AssignCmd(tok, lhss, rhss);
}
- public static AssignCmd! MapAssign(IToken! tok,
- IdentifierExpr! map,
- params Expr[]! args)
- requires args.Length > 0; // at least the rhs
- requires forall{int i in (0:args.Length); args[i] != null};
- {
- List<AssignLhs!>! lhss = new List<AssignLhs!> ();
- List<Expr!>! rhss = new List<Expr!> ();
- List<Expr!>! indexesList = new List<Expr!> ();
+ public static AssignCmd/*!*/ MapAssign(IToken tok,
+ IdentifierExpr/*!*/ map,
+ params Expr[]/*!*/ args) {
+ Contract.Requires(tok != null);
+ Contract.Requires(map != null);
+ Contract.Requires(args != null);
+ Contract.Requires(args.Length > 0); // at least the rhs
+ Contract.Requires(Contract.ForAll(args, i => i != null));
+ Contract.Ensures(Contract.Result<AssignCmd>() != null);
+
+ List<AssignLhs/*!*/>/*!*/ lhss = new List<AssignLhs/*!*/>();
+ List<Expr/*!*/>/*!*/ rhss = new List<Expr/*!*/>();
+ List<Expr/*!*/>/*!*/ indexesList = new List<Expr/*!*/>();
for (int i = 0; i < args.Length - 1; ++i)
- indexesList.Add((!)args[i]);
+ indexesList.Add(cce.NonNull(args[i]));
- lhss.Add(new MapAssignLhs (map.tok,
- new SimpleAssignLhs (map.tok, map),
+ lhss.Add(new MapAssignLhs(map.tok,
+ new SimpleAssignLhs(map.tok, map),
indexesList));
- rhss.Add((!)args[args.Length - 1]);
-
+ rhss.Add(cce.NonNull(args[args.Length - 1]));
+
return new AssignCmd(tok, lhss, rhss);
}
@@ -868,21 +999,21 @@ namespace Microsoft.Boogie
/// This is a helper routine for printing a linked list of attributes. Each attribute
/// is terminated by a space.
/// </summary>
- public static void EmitAttributes(TokenTextWriter! stream, QKeyValue attributes)
- {
+ public static void EmitAttributes(TokenTextWriter stream, QKeyValue attributes) {
+ Contract.Requires(stream != null);
for (QKeyValue kv = attributes; kv != null; kv = kv.Next) {
kv.Emit(stream);
stream.Write(" ");
}
}
- public static void ResolveAttributes(QKeyValue attributes, ResolutionContext! rc)
- {
+ public static void ResolveAttributes(QKeyValue attributes, ResolutionContext rc) {
+ Contract.Requires(rc != null);
for (QKeyValue kv = attributes; kv != null; kv = kv.Next) {
kv.Resolve(rc);
}
}
- public static void TypecheckAttributes(QKeyValue attributes, TypecheckingContext! tc)
- {
+ public static void TypecheckAttributes(QKeyValue attributes, TypecheckingContext tc) {
+ Contract.Requires(tc != null);
for (QKeyValue kv = attributes; kv != null; kv = kv.Next) {
kv.Typecheck(tc);
}
@@ -891,27 +1022,39 @@ namespace Microsoft.Boogie
public class CommentCmd : Cmd // just a convenience for debugging
{
- public readonly string! Comment;
- public CommentCmd (string! c)
- : base(Token.NoToken)
- {
+ public readonly string/*!*/ Comment;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Comment != null);
+ }
+
+ public CommentCmd(string c)
+ : base(Token.NoToken) {
+ Contract.Requires(c != null);
Comment = c;
// base(Token.NoToken);
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+
if (this.Comment.Contains("\n")) {
stream.WriteLine(this, level, "/* {0} */", this.Comment);
} else {
stream.WriteLine(this, level, "// {0}", this.Comment);
}
}
- public override void Resolve(ResolutionContext! rc) { }
- public override void AddAssignedVariables(VariableSeq! vars) { }
- public override void Typecheck(TypecheckingContext! tc) { }
+ public override void Resolve(ResolutionContext rc) {
+
+ }
+ public override void AddAssignedVariables(VariableSeq vars) {
+
+ }
+ public override void Typecheck(TypecheckingContext tc) {
+
+ }
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+
+
return visitor.VisitCommentCmd(this);
}
}
@@ -919,21 +1062,32 @@ namespace Microsoft.Boogie
// class for parallel assignments, which subsumes both the old
// SimpleAssignCmd and the old MapAssignCmd
public class AssignCmd : Cmd {
- public List<AssignLhs!>! Lhss;
- public List<Expr!>! Rhss;
+ public List<AssignLhs/*!*/>/*!*/ Lhss;
+ public List<Expr/*!*/>/*!*/ Rhss;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(Lhss));
+ Contract.Invariant(cce.NonNullElements(Rhss));
+ }
- public AssignCmd(IToken! tok, List<AssignLhs!>! lhss, List<Expr!>! rhss) {
- base(tok);
+
+ public AssignCmd(IToken tok, List<AssignLhs/*!*/>/*!*/ lhss, List<Expr/*!*/>/*!*/ rhss)
+ : base(tok) {//BASEMOVEA
+ Contract.Requires(tok != null);
+ Contract.Requires(cce.NonNullElements(rhss));
+ Contract.Requires(cce.NonNullElements(lhss));
+ //base(tok);
Lhss = lhss;
Rhss = rhss;
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+
stream.Write(this, level, "");
- string! sep = "";
- foreach (AssignLhs! l in Lhss) {
+ string/*!*/ sep = "";
+ foreach (AssignLhs/*!*/ l in Lhss) {
+ Contract.Assert(l != null);
stream.Write(sep);
sep = ", ";
l.Emit(stream);
@@ -942,7 +1096,8 @@ namespace Microsoft.Boogie
stream.Write(" := ");
sep = "";
- foreach (Expr! e in Rhss) {
+ foreach (Expr/*!*/ e in Rhss) {
+ Contract.Assert(e != null);
stream.Write(sep);
sep = ", ";
e.Emit(stream);
@@ -951,22 +1106,26 @@ namespace Microsoft.Boogie
stream.WriteLine(";");
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+
if (Lhss.Count != Rhss.Count)
rc.Error(this,
"number of left-hand sides does not match number of right-hand sides");
- foreach (AssignLhs! e in Lhss)
+ foreach (AssignLhs/*!*/ e in Lhss) {
+ Contract.Assert(e != null);
e.Resolve(rc);
- foreach (Expr! e in Rhss)
+ }
+ foreach (Expr/*!*/ e in Rhss) {
+ Contract.Assert(e != null);
e.Resolve(rc);
+ }
// check for double occurrences of assigned variables
// (could be optimised)
for (int i = 0; i < Lhss.Count; ++i) {
for (int j = i + 1; j < Lhss.Count; ++j) {
- if (((!)Lhss[i].DeepAssignedVariable).Equals(
+ if (cce.NonNull(Lhss[i].DeepAssignedVariable).Equals(
Lhss[j].DeepAssignedVariable))
rc.Error(Lhss[j],
"variable {0} is assigned more than once in parallel assignment",
@@ -975,11 +1134,16 @@ namespace Microsoft.Boogie
}
}
- public override void Typecheck(TypecheckingContext! tc) {
- foreach (AssignLhs! e in Lhss)
+ public override void Typecheck(TypecheckingContext tc) {
+
+ foreach (AssignLhs/*!*/ e in Lhss) {
+ Contract.Assert(e != null);
e.Typecheck(tc);
- foreach (Expr! e in Rhss)
+ }
+ foreach (Expr/*!*/ e in Rhss) {
+ Contract.Assert(e != null);
e.Typecheck(tc);
+ }
this.CheckAssignments(tc);
@@ -997,97 +1161,169 @@ namespace Microsoft.Boogie
}
}
- public override void AddAssignedVariables(VariableSeq! vars)
- {
- foreach (AssignLhs! l in Lhss)
+ public override void AddAssignedVariables(VariableSeq vars) {
+
+ foreach (AssignLhs/*!*/ l in Lhss) {
+ Contract.Assert(l != null);
vars.Add(l.DeepAssignedVariable);
+ }
}
// transform away the syntactic sugar of map assignments and
// determine an equivalent assignment in which all rhs are simple
// variables
- public AssignCmd! AsSimpleAssignCmd { get {
- List<AssignLhs!>! newLhss = new List<AssignLhs!> ();
- List<Expr!>! newRhss = new List<Expr!> ();
-
- for (int i = 0; i < Lhss.Count; ++i) {
- IdentifierExpr! newLhs;
- Expr! newRhs;
- Lhss[i].AsSimpleAssignment(Rhss[i], out newLhs, out newRhs);
- newLhss.Add(new SimpleAssignLhs(Token.NoToken, newLhs));
- newRhss.Add(newRhs);
+ public AssignCmd/*!*/ AsSimpleAssignCmd {
+ get {
+ Contract.Ensures(Contract.Result<AssignCmd>() != null);
+
+ List<AssignLhs/*!*/>/*!*/ newLhss = new List<AssignLhs/*!*/>();
+ List<Expr/*!*/>/*!*/ newRhss = new List<Expr/*!*/>();
+
+ for (int i = 0; i < Lhss.Count; ++i) {
+ IdentifierExpr/*!*/ newLhs;
+ Expr/*!*/ newRhs;
+ Lhss[i].AsSimpleAssignment(Rhss[i], out newLhs, out newRhs);
+ newLhss.Add(new SimpleAssignLhs(Token.NoToken, newLhs));
+ newRhss.Add(newRhs);
+ }
+
+ return new AssignCmd(Token.NoToken, newLhss, newRhss);
}
+ }
- return new AssignCmd(Token.NoToken, newLhss, newRhss);
- } }
+ public override Absy StdDispatch(StandardVisitor visitor) {
+
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
return visitor.VisitAssignCmd(this);
}
}
// There are two different kinds of left-hand sides in assignments:
// simple variables (identifiers), or locations of a map
+ [ContractClass(typeof(AssignLhsContracts))]
public abstract class AssignLhs : Absy {
// The type of the lhs is determined during typechecking
- public abstract Type Type { get; }
+ public abstract Type Type {
+ get;
+ }
// Determine the variable that is actually assigned in this lhs
- public abstract IdentifierExpr! DeepAssignedIdentifier { get; }
- public abstract Variable DeepAssignedVariable { get; }
+ public abstract IdentifierExpr/*!*/ DeepAssignedIdentifier {
+ get;
+ }
+ public abstract Variable DeepAssignedVariable {
+ get;
+ }
- public AssignLhs(IToken! tok) : base(tok) {}
- public abstract void Emit(TokenTextWriter! stream);
+ public AssignLhs(IToken/*!*/ tok)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ }
+ public abstract void Emit(TokenTextWriter/*!*/ stream);
- public abstract Expr! AsExpr { get; }
+ public abstract Expr/*!*/ AsExpr {
+ get;
+ }
// transform away the syntactic sugar of map assignments and
// determine an equivalent simple assignment
- internal abstract void AsSimpleAssignment(Expr! rhs,
- out IdentifierExpr! simpleLhs,
- out Expr! simpleRhs);
+ internal abstract void AsSimpleAssignment(Expr/*!*/ rhs,
+ out IdentifierExpr/*!*/ simpleLhs,
+ out Expr/*!*/ simpleRhs);
+ }
+ [ContractClassFor(typeof(AssignLhs))]
+ public abstract class AssignLhsContracts : AssignLhs {
+ public AssignLhsContracts():base(null)
+ {
+
+ }public override IdentifierExpr DeepAssignedIdentifier {
+
+ get {
+ Contract.Ensures(Contract.Result<IdentifierExpr>() != null);
+ throw new NotImplementedException();
+ }
+ }
+ public override Expr AsExpr {
+ get {
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ throw new NotImplementedException();
+ }
+
+ }
+ internal override void AsSimpleAssignment(Expr rhs, out IdentifierExpr simpleLhs, out Expr simpleRhs) {
+ Contract.Requires(rhs != null);
+ Contract.Ensures(Contract.ValueAtReturn(out simpleLhs) != null);
+ Contract.Ensures(Contract.ValueAtReturn(out simpleRhs) != null);
+
+ throw new NotImplementedException();
+ }
}
public class SimpleAssignLhs : AssignLhs {
- public IdentifierExpr! AssignedVariable;
+ public IdentifierExpr/*!*/ AssignedVariable;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(AssignedVariable != null);
+ }
- public override Type Type { get {
- return AssignedVariable.Type;
- } }
- public override IdentifierExpr! DeepAssignedIdentifier { get {
- return AssignedVariable;
- } }
+ public override Type Type {
+ get {
+ return AssignedVariable.Type;
+ }
+ }
+
+ public override IdentifierExpr/*!*/ DeepAssignedIdentifier {
+ get {
+ Contract.Ensures(Contract.Result<IdentifierExpr>() != null);
+ return AssignedVariable;
+ }
+ }
- public override Variable DeepAssignedVariable { get {
- return AssignedVariable.Decl;
- } }
+ public override Variable DeepAssignedVariable {
+ get {
+ return AssignedVariable.Decl;
+ }
+ }
- public SimpleAssignLhs(IToken! tok, IdentifierExpr! assignedVariable) {
- base(tok);
+ public SimpleAssignLhs(IToken tok, IdentifierExpr assignedVariable)
+ : base(tok) {
+ Contract.Requires(assignedVariable != null);
+ Contract.Requires(tok != null);
+ //base(tok);
AssignedVariable = assignedVariable;
}
- public override void Resolve(ResolutionContext! rc) {
+ public override void Resolve(ResolutionContext rc) {
+
AssignedVariable.Resolve(rc);
}
- public override void Typecheck(TypecheckingContext! tc) {
+ public override void Typecheck(TypecheckingContext tc) {
+
AssignedVariable.Typecheck(tc);
}
- public override void Emit(TokenTextWriter! stream) {
+ public override void Emit(TokenTextWriter stream) {
+
AssignedVariable.Emit(stream);
}
- public override Expr! AsExpr { get {
- return AssignedVariable;
- } }
- internal override void AsSimpleAssignment(Expr! rhs,
- out IdentifierExpr! simpleLhs,
- out Expr! simpleRhs) {
+ public override Expr/*!*/ AsExpr {
+ get {
+ Contract.Ensures(Contract.Result<Expr>() != null);
+
+ return AssignedVariable;
+ }
+ }
+ internal override void AsSimpleAssignment(Expr rhs,
+ out IdentifierExpr/*!*/ simpleLhs,
+ out Expr/*!*/ simpleRhs) {
+
+
+
simpleLhs = AssignedVariable;
simpleRhs = rhs;
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+
+
return visitor.VisitSimpleAssignLhs(this);
}
}
@@ -1096,9 +1332,15 @@ namespace Microsoft.Boogie
// a map select expression, but it is cleaner to keep those two
// things separate
public class MapAssignLhs : AssignLhs {
- public AssignLhs! Map;
+ public AssignLhs/*!*/ Map;
+
+ public List<Expr/*!*/>/*!*/ Indexes;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Map != null);
+ Contract.Invariant(cce.NonNullElements(Indexes));
+ }
- public List<Expr!>! Indexes;
// The instantiation of type parameters of the map that is
// determined during type checking.
@@ -1106,69 +1348,102 @@ namespace Microsoft.Boogie
private Type TypeAttr = null;
- public override Type Type { get {
- return TypeAttr;
- } }
+ public override Type Type {
+ get {
+ return TypeAttr;
+ }
+ }
+
+ public override IdentifierExpr/*!*/ DeepAssignedIdentifier {
+ get {
+ Contract.Ensures(Contract.Result<IdentifierExpr>() != null);
- public override IdentifierExpr! DeepAssignedIdentifier { get {
- return Map.DeepAssignedIdentifier;
- } }
+ return Map.DeepAssignedIdentifier;
+ }
+ }
+
+ public override Variable DeepAssignedVariable {
+ get {
+ return Map.DeepAssignedVariable;
+ }
+ }
- public override Variable DeepAssignedVariable { get {
- return Map.DeepAssignedVariable;
- } }
+ public MapAssignLhs(IToken tok, AssignLhs map, List<Expr/*!*/>/*!*/ indexes)
+ : base(tok) {//BASEMOVEA
+ //:base(tok);
+ Contract.Requires(map != null);
+ Contract.Requires(tok != null);
+ Contract.Requires(cce.NonNullElements(indexes));
- public MapAssignLhs(IToken! tok, AssignLhs! map, List<Expr!>! indexes) {
- base(tok);
Map = map;
Indexes = indexes;
}
- public override void Resolve(ResolutionContext! rc) {
+ public override void Resolve(ResolutionContext rc) {
+
Map.Resolve(rc);
- foreach (Expr! e in Indexes)
+ foreach (Expr/*!*/ e in Indexes) {
+ Contract.Assert(e != null);
e.Resolve(rc);
+ }
}
- public override void Typecheck(TypecheckingContext! tc) {
+ public override void Typecheck(TypecheckingContext tc) {
+
Map.Typecheck(tc);
- foreach (Expr! e in Indexes)
+ foreach (Expr/*!*/ e in Indexes) {
+ Contract.Assert(e != null);
e.Typecheck(tc);
+ }
// we use the same typechecking code as in MapSelect
- ExprSeq! selectArgs = new ExprSeq ();
- foreach (Expr! e in Indexes)
+ ExprSeq/*!*/ selectArgs = new ExprSeq();
+ foreach (Expr/*!*/ e in Indexes) {
+ Contract.Assert(e != null);
selectArgs.Add(e);
- TypeParamInstantiation! tpInsts;
+ }
+ TypeParamInstantiation/*!*/ tpInsts;
TypeAttr =
- MapSelect.Typecheck((!)Map.Type, Map,
+ MapSelect.Typecheck(cce.NonNull(Map.Type), Map,
selectArgs, out tpInsts, tc, tok, "map assignment");
TypeParameters = tpInsts;
}
- public override void Emit(TokenTextWriter! stream) {
+ public override void Emit(TokenTextWriter stream) {
+
Map.Emit(stream);
stream.Write("[");
- string! sep = "";
- foreach (Expr! e in Indexes) {
+ string/*!*/ sep = "";
+ foreach (Expr/*!*/ e in Indexes) {
+ Contract.Assert(e != null);
stream.Write(sep);
sep = ", ";
e.Emit(stream);
}
stream.Write("]");
}
- public override Expr! AsExpr { get {
- NAryExpr! res = Expr.Select(Map.AsExpr, Indexes);
- res.TypeParameters = this.TypeParameters;
- return res;
- } }
- internal override void AsSimpleAssignment(Expr! rhs,
- out IdentifierExpr! simpleLhs,
- out Expr! simpleRhs) {
- NAryExpr! newRhs = Expr.Store(Map.AsExpr, Indexes, rhs);
+ public override Expr/*!*/ AsExpr {
+ get {
+ Contract.Ensures(Contract.Result<Expr>() != null);
+
+ NAryExpr/*!*/ res = Expr.Select(Map.AsExpr, Indexes);
+ Contract.Assert(res != null);
+ res.TypeParameters = this.TypeParameters;
+ return res;
+ }
+ }
+ internal override void AsSimpleAssignment(Expr rhs,
+ out IdentifierExpr/*!*/ simpleLhs,
+ out Expr/*!*/ simpleRhs) { //Contract.Requires(rhs != null);
+ Contract.Ensures(Contract.ValueAtReturn(out simpleLhs) != null);
+ Contract.Ensures(Contract.ValueAtReturn(out simpleRhs) != null);
+
+ NAryExpr/*!*/ newRhs = Expr.Store(Map.AsExpr, Indexes, rhs);
+ Contract.Assert(newRhs != null);
newRhs.TypeParameters = this.TypeParameters;
Map.AsSimpleAssignment(newRhs, out simpleLhs, out simpleRhs);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitMapAssignLhs(this);
}
}
@@ -1178,90 +1453,111 @@ namespace Microsoft.Boogie
/// There is no user syntax for a StateCmd. Instead, a StateCmd is only used
/// temporarily during the desugaring phase inside the VC generator.
/// </summary>
- public class StateCmd : Cmd
- {
- public /*readonly, except for the StandardVisitor*/ VariableSeq! Locals;
- public /*readonly, except for the StandardVisitor*/ CmdSeq! Cmds;
-
- public StateCmd(IToken! tok, VariableSeq! locals, CmdSeq! cmds)
- : base(tok)
- {
- this.Locals = locals;
- this.Cmds = cmds;
- // base(tok);
+ public class StateCmd : Cmd {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Locals != null);
+ Contract.Invariant(Cmds != null);
+ }
+
+ public /*readonly, except for the StandardVisitor*/ VariableSeq/*!*/ Locals;
+ public /*readonly, except for the StandardVisitor*/ CmdSeq/*!*/ Cmds;
+
+ public StateCmd(IToken tok, VariableSeq/*!*/ locals, CmdSeq/*!*/ cmds)
+ : base(tok) {
+ Contract.Requires(locals != null);
+ Contract.Requires(cmds != null);
+ Contract.Requires(tok != null);
+ this.Locals = locals;
+ this.Cmds = cmds;
+ // base(tok);
}
- public override void Resolve(ResolutionContext! rc) {
- rc.PushVarContext();
- foreach (Variable! v in Locals) {
- rc.AddVariable(v, false);
- }
- foreach (Cmd! cmd in Cmds) {
- cmd.Resolve(rc);
- }
- rc.PopVarContext();
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ rc.PushVarContext();
+ foreach (Variable/*!*/ v in Locals) {
+ Contract.Assert(v != null);
+ rc.AddVariable(v, false);
+ }
+ foreach (Cmd/*!*/ cmd in Cmds) {
+ Contract.Assert(cmd != null);
+ cmd.Resolve(rc);
+ }
+ rc.PopVarContext();
}
- public override void AddAssignedVariables(VariableSeq! vars) {
- VariableSeq! vs = new VariableSeq();
- foreach (Cmd! cmd in this.Cmds)
- {
- cmd.AddAssignedVariables(vs);
- }
- System.Collections.Hashtable! localsSet = new System.Collections.Hashtable();
- foreach (Variable! local in this.Locals)
- {
- localsSet[local] = bool.TrueString;
- }
- foreach (Variable! v in vs)
- {
- if (!localsSet.ContainsKey(v))
- {
- vars.Add(v);
- }
+ public override void AddAssignedVariables(VariableSeq vars) {
+ //Contract.Requires(vars != null);
+ VariableSeq/*!*/ vs = new VariableSeq();
+ foreach (Cmd/*!*/ cmd in this.Cmds) {
+ Contract.Assert(cmd != null);
+ cmd.AddAssignedVariables(vs);
+ }
+ System.Collections.Hashtable/*!*/ localsSet = new System.Collections.Hashtable();
+ foreach (Variable/*!*/ local in this.Locals) {
+ Contract.Assert(local != null);
+ localsSet[local] = bool.TrueString;
+ }
+ foreach (Variable/*!*/ v in vs) {
+ Contract.Assert(v != null);
+ if (!localsSet.ContainsKey(v)) {
+ vars.Add(v);
}
+ }
}
- public override void Typecheck(TypecheckingContext! tc) {
- foreach (Cmd! cmd in Cmds) {
- cmd.Typecheck(tc);
- }
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ foreach (Cmd/*!*/ cmd in Cmds) {
+ Contract.Assert(cmd != null);
+ cmd.Typecheck(tc);
+ }
}
- public override void Emit(TokenTextWriter! stream, int level) {
- stream.WriteLine(this, level, "{");
- foreach (Variable! v in Locals) {
- v.Emit(stream, level+1);
- }
- foreach (Cmd! c in Cmds) {
- c.Emit(stream, level+1);
- }
- stream.WriteLine(level, "}");
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
+ stream.WriteLine(this, level, "{");
+ foreach (Variable/*!*/ v in Locals) {
+ Contract.Assert(v != null);
+ v.Emit(stream, level + 1);
+ }
+ foreach (Cmd/*!*/ c in Cmds) {
+ Contract.Assert(c != null);
+ c.Emit(stream, level + 1);
+ }
+ stream.WriteLine(level, "}");
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitStateCmd(this);
}
}
-
- abstract public class SugaredCmd : Cmd
- {
+ [ContractClass(typeof(SugaredCmdContracts))]
+ abstract public class SugaredCmd : Cmd {
private Cmd desugaring; // null until desugared
- public SugaredCmd(IToken! tok) : base(tok) {}
+ public SugaredCmd(IToken/*!*/ tok)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ }
+
+ public Cmd/*!*/ Desugaring {
+ get {
+ Contract.Ensures(Contract.Result<Cmd>() != null);
- public Cmd! Desugaring {
- get {
- if (desugaring == null) {
- desugaring = ComputeDesugaring();
- }
- return desugaring;
+ if (desugaring == null) {
+ desugaring = ComputeDesugaring();
}
+ return desugaring;
+ }
}
- protected abstract Cmd! ComputeDesugaring();
+ protected abstract Cmd/*!*/ ComputeDesugaring();
- public override void Emit(TokenTextWriter! stream, int level) {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
if (CommandLineOptions.Clo.PrintDesugarings) {
stream.WriteLine(this, level, "/*** desugaring:");
Desugaring.Emit(stream, level);
@@ -1269,21 +1565,41 @@ namespace Microsoft.Boogie
}
}
}
+ [ContractClassFor(typeof(SugaredCmd))]
+ public abstract class SugaredCmdContracts : SugaredCmd {
+ public SugaredCmdContracts() :base(null){
- public abstract class CallCommonality : SugaredCmd
- {
+ }
+ protected override Cmd ComputeDesugaring() {
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+
+ throw new NotImplementedException();
+ }
+ }
+
+ public abstract class CallCommonality : SugaredCmd {
public QKeyValue Attributes;
-
- protected CallCommonality(IToken! tok, QKeyValue kv) {
- base(tok);
+
+ protected CallCommonality(IToken tok, QKeyValue kv)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ //base(tok);
Attributes = kv;
}
- protected enum TempVarKind { Formal, Old, Bound }
-
+ protected enum TempVarKind {
+ Formal,
+ Old,
+ Bound
+ }
+
// We have to give the type explicitly, because the type of the formal "likeThisOne" can contain type variables
- protected Variable! CreateTemporaryVariable(VariableSeq! tempVars, Variable! likeThisOne, Type! ty, TempVarKind kind) {
- string! tempNamePrefix;
+ protected Variable CreateTemporaryVariable(VariableSeq tempVars, Variable likeThisOne, Type ty, TempVarKind kind) {
+ Contract.Requires(ty != null);
+ Contract.Requires(likeThisOne != null);
+ Contract.Requires(tempVars != null);
+ Contract.Ensures(Contract.Result<Variable>() != null);
+ string/*!*/ tempNamePrefix;
switch (kind) {
case TempVarKind.Formal:
tempNamePrefix = "formal@";
@@ -1294,31 +1610,39 @@ namespace Microsoft.Boogie
case TempVarKind.Bound:
tempNamePrefix = "forall@";
break;
- default:
- assert false; // unexpected kind
+ default: {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // unexpected kind
}
TypedIdent ti = likeThisOne.TypedIdent;
TypedIdent newTi = new TypedIdent(ti.tok, "call" + UniqueId + tempNamePrefix + ti.Name, ty);
- Variable! v;
+ Variable/*!*/ v;
if (kind == TempVarKind.Bound) {
v = new BoundVariable(likeThisOne.tok, newTi);
} else {
v = new LocalVariable(likeThisOne.tok, newTi);
tempVars.Add(v);
- }
+ }
return v;
}
}
- public class CallCmd : CallCommonality, IPotentialErrorNode
- {
- string! callee;
+ public class CallCmd : CallCommonality, IPotentialErrorNode {
+ string/*!*/ callee;
public Procedure Proc;
// Element of the following lists can be null, which means that
// the call happens with * as these parameters
- public List<Expr>! Ins;
- public List<IdentifierExpr>! Outs;
+ public List<Expr>/*!*/ Ins;
+ public List<IdentifierExpr>/*!*/ Outs;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(callee != null);
+ Contract.Invariant(Ins != null);
+ Contract.Invariant(Outs != null);
+ }
+
//public Lattice.Element StateAfterCall;
// The instantiation of type parameters that is determined during
@@ -1328,52 +1652,70 @@ namespace Microsoft.Boogie
// TODO: convert to use generics
private object errorData;
public object ErrorData {
- get { return errorData; }
- set { errorData = value; }
- }
-
- public CallCmd(IToken! tok, string! callee, ExprSeq! ins, IdentifierExprSeq! outs)
- {
- List<Expr>! insList = new List<Expr> ();
- List<IdentifierExpr>! outsList = new List<IdentifierExpr> ();
- foreach (Expr e in ins)
- insList.Add(e);
- foreach (IdentifierExpr e in outs)
- outsList.Add(e);
-
- this(tok, callee, insList, outsList);
- }
- public CallCmd(IToken! tok, string! callee, List<Expr>! ins, List<IdentifierExpr>! outs)
- {
- base(tok, null);
+ get {
+ return errorData;
+ }
+ set {
+ errorData = value;
+ }
+ }
+
+ public CallCmd(IToken tok, string callee, ExprSeq ins, IdentifierExprSeq outs)
+ : this(tok, callee, cce.toList<Expr>(ins), cce.toList<IdentifierExpr>(outs)) {
+ Contract.Requires(outs != null);
+ Contract.Requires(ins != null);
+ Contract.Requires(callee != null);
+ Contract.Requires(tok != null);
+ //List<Expr>/*!*/ insList = new List<Expr>();
+ //List<IdentifierExpr>/*!*/ outsList = new List<IdentifierExpr>();
+ //foreach (Expr e in ins)
+ // if(e!=null)
+ // insList.Add(e);
+ //foreach (IdentifierExpr e in outs)
+ // if(e!=null)
+ // outsList.Add(e);
+ //this(tok, callee, insList, outsList);
+
+ }
+ public CallCmd(IToken tok, string callee, List<Expr> ins, List<IdentifierExpr> outs)
+ : base(tok, null) {//BASEMOVE DANGER
+ Contract.Requires(outs != null);
+ Contract.Requires(ins != null);
+ Contract.Requires(callee != null);
+ Contract.Requires(tok != null);
+ //base(tok, null);
this.callee = callee;
this.Ins = ins;
this.Outs = outs;
}
- public CallCmd(IToken! tok, string! callee, List<Expr>! ins, List<IdentifierExpr>! outs, QKeyValue kv)
- {
- base(tok, kv);
+ public CallCmd(IToken tok, string callee, List<Expr> ins, List<IdentifierExpr> outs, QKeyValue kv)
+ : base(tok, kv) {//BASEMOVE DANGER
+ Contract.Requires(outs != null);
+ Contract.Requires(ins != null);
+ Contract.Requires(callee != null);
+ Contract.Requires(tok != null);
+ //base(tok, kv);
this.callee = callee;
this.Ins = ins;
this.Outs = outs;
}
-
- public override void Emit(TokenTextWriter! stream, int level)
- {
+
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.Write(this, level, "call ");
EmitAttributes(stream, Attributes);
string sep = "";
if (Outs.Count > 0) {
- foreach (Expr arg in Outs) {
- stream.Write(sep);
- sep = ", ";
- if (arg == null) {
- stream.Write("*");
- } else {
- arg.Emit(stream);
- }
- }
- stream.Write(" := ");
+ foreach (Expr arg in Outs) {
+ stream.Write(sep);
+ sep = ", ";
+ if (arg == null) {
+ stream.Write("*");
+ } else {
+ arg.Emit(stream);
+ }
+ }
+ stream.Write(" := ");
}
stream.Write(TokenTextWriter.SanitizeIdentifier(callee));
stream.Write("(");
@@ -1390,10 +1732,9 @@ namespace Microsoft.Boogie
stream.WriteLine(");");
base.Emit(stream, level);
}
- public override void Resolve(ResolutionContext! rc)
- {
- if (Proc != null)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ if (Proc != null) {
// already resolved
return;
}
@@ -1402,15 +1743,13 @@ namespace Microsoft.Boogie
if (Proc == null) {
rc.Error(this, "call to undeclared procedure: {0}", callee);
}
- foreach (Expr e in Ins)
- {
- if (e!=null) {
+ foreach (Expr e in Ins) {
+ if (e != null) {
e.Resolve(rc);
}
}
Set/*<Variable>*/ actualOuts = new Set/*<Variable>*/ (Outs.Count);
- foreach (IdentifierExpr ide in Outs)
- {
+ foreach (IdentifierExpr ide in Outs) {
if (ide != null) {
ide.Resolve(rc);
if (ide.Decl != null) {
@@ -1447,27 +1786,29 @@ namespace Microsoft.Boogie
rc.Error(this.tok, "a procedure called asynchronously can have at most one output parameter");
return;
}
- }
-
+ }
+
// Check that type parameters can be determined using the given
// actual i/o arguments. This is done already during resolution
// because CheckBoundVariableOccurrences needs a resolution
// context
- TypeSeq! formalInTypes = new TypeSeq();
- TypeSeq! formalOutTypes = new TypeSeq();
+ TypeSeq/*!*/ formalInTypes = new TypeSeq();
+ TypeSeq/*!*/ formalOutTypes = new TypeSeq();
for (int i = 0; i < Ins.Count; ++i)
if (Ins[i] != null)
- formalInTypes.Add(((!)Proc.InParams[i]).TypedIdent.Type);
+ formalInTypes.Add(cce.NonNull(Proc.InParams[i]).TypedIdent.Type);
for (int i = 0; i < Outs.Count; ++i)
if (Outs[i] != null)
- formalOutTypes.Add(((!)Proc.OutParams[i]).TypedIdent.Type);
-
+ formalOutTypes.Add(cce.NonNull(Proc.OutParams[i]).TypedIdent.Type);
+
// we need to bind the type parameters for this
// (this is expected by CheckBoundVariableOccurrences)
int previousTypeBinderState = rc.TypeBinderState;
try {
- foreach (TypeVariable! v in Proc.TypeParameters)
+ foreach (TypeVariable/*!*/ v in Proc.TypeParameters) {
+ Contract.Assert(v != null);
rc.AddTypeBinder(v);
+ }
Type.CheckBoundVariableOccurrences(Proc.TypeParameters,
formalInTypes, formalOutTypes,
this.tok, "types of given arguments",
@@ -1477,66 +1818,62 @@ namespace Microsoft.Boogie
}
}
- public override void AddAssignedVariables(VariableSeq! vars)
- {
- foreach (IdentifierExpr e in Outs)
- {
- if (e!=null) {
+ public override void AddAssignedVariables(VariableSeq vars) {
+ //Contract.Requires(vars != null);
+ foreach (IdentifierExpr e in Outs) {
+ if (e != null) {
vars.Add(e.Decl);
}
}
- assume this.Proc != null;
- foreach (IdentifierExpr! e in this.Proc.Modifies)
- {
+ Contract.Assume(this.Proc != null);
+ foreach (IdentifierExpr/*!*/ e in this.Proc.Modifies) {
+ Contract.Assert(e != null);
vars.Add(e.Decl);
}
}
- public override void Typecheck(TypecheckingContext! tc)
- {
- assume this.Proc != null; // we assume the CallCmd has been successfully resolved before calling this Typecheck method
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ Contract.Assume(this.Proc != null); // we assume the CallCmd has been successfully resolved before calling this Typecheck method
TypecheckAttributes(Attributes, tc);
// typecheck in-parameters
foreach (Expr e in Ins)
- if (e!=null)
+ if (e != null)
e.Typecheck(tc);
foreach (Expr e in Outs)
- if (e!=null)
+ if (e != null)
e.Typecheck(tc);
this.CheckAssignments(tc);
- TypeSeq! formalInTypes = new TypeSeq();
- TypeSeq! formalOutTypes = new TypeSeq();
- ExprSeq! actualIns = new ExprSeq();
- IdentifierExprSeq! actualOuts = new IdentifierExprSeq();
- for (int i = 0; i < Ins.Count; ++i)
- {
+ TypeSeq/*!*/ formalInTypes = new TypeSeq();
+ TypeSeq/*!*/ formalOutTypes = new TypeSeq();
+ ExprSeq/*!*/ actualIns = new ExprSeq();
+ IdentifierExprSeq/*!*/ actualOuts = new IdentifierExprSeq();
+ for (int i = 0; i < Ins.Count; ++i) {
if (Ins[i] != null) {
- formalInTypes.Add(((!)Proc.InParams[i]).TypedIdent.Type);
+ formalInTypes.Add(cce.NonNull(Proc.InParams[i]).TypedIdent.Type);
actualIns.Add(Ins[i]);
}
- }
- for (int i = 0; i < Outs.Count; ++i)
- {
+ }
+ for (int i = 0; i < Outs.Count; ++i) {
if (Outs[i] != null) {
- formalOutTypes.Add(((!)Proc.OutParams[i]).TypedIdent.Type);
+ formalOutTypes.Add(cce.NonNull(Proc.OutParams[i]).TypedIdent.Type);
actualOuts.Add(Outs[i]);
}
}
-
+
if (QKeyValue.FindBoolAttribute(this.Attributes, "async") && Outs.Count > 0) {
- Type returnType = ((!)Outs[0]).ShallowType;
- if (!returnType.Equals(Type.Int))
- {
+ Type returnType = cce.NonNull(Outs[0]).ShallowType;
+ if (!returnType.Equals(Type.Int)) {
tc.Error(this.tok, "the return from an asynchronous call should be an integer");
return;
}
}
-
+
// match actuals with formals
- List<Type!>! actualTypeParams;
+ List<Type/*!*/>/*!*/ actualTypeParams;
Type.CheckArgumentTypes(Proc.TypeParameters,
out actualTypeParams,
formalInTypes, actualIns,
@@ -1544,28 +1881,33 @@ namespace Microsoft.Boogie
this.tok,
"call to " + callee,
tc);
+ Contract.Assert(cce.NonNullElements(actualTypeParams));
TypeParameters = SimpleTypeParamInstantiation.From(Proc.TypeParameters,
actualTypeParams);
}
- private IDictionary<TypeVariable!, Type!>! TypeParamSubstitution() {
- assume TypeParameters != null;
- IDictionary<TypeVariable!, Type!>! res = new Dictionary<TypeVariable!, Type!> ();
- foreach (TypeVariable! v in TypeParameters.FormalTypeParams)
+ private IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ TypeParamSubstitution() {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<IDictionary<TypeVariable, Type>>()));
+ Contract.Assume(TypeParameters != null);
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ res = new Dictionary<TypeVariable/*!*/, Type/*!*/>();
+ foreach (TypeVariable/*!*/ v in TypeParameters.FormalTypeParams) {
+ Contract.Assert(v != null);
res.Add(v, TypeParameters[v]);
+ }
return res;
}
- protected override Cmd! ComputeDesugaring() {
+ protected override Cmd ComputeDesugaring() {
+ Contract.Ensures(Contract.Result<Cmd>() != null);
CmdSeq newBlockBody = new CmdSeq();
Hashtable /*Variable -> Expr*/ substMap = new Hashtable/*Variable -> Expr*/();
Hashtable /*Variable -> Expr*/ substMapOld = new Hashtable/*Variable -> Expr*/();
Hashtable /*Variable -> Expr*/ substMapBound = new Hashtable/*Variable -> Expr*/();
- VariableSeq! tempVars = new VariableSeq();
+ VariableSeq/*!*/ tempVars = new VariableSeq();
// proc P(ins) returns (outs)
// requires Pre
- // modifies frame
+ // //modifies frame
// ensures Post
//
// call aouts := P(ains)
@@ -1579,23 +1921,22 @@ namespace Microsoft.Boogie
// cframe : new variables created just for this call, to keep track of OLD values
// couts : new variables created just for this call, one per aouts
// WildcardVars : new variables created just for this call, one per null in ains
-
+
#region Create cins; each one is an incarnation of the corresponding in parameter
- VariableSeq! cins = new VariableSeq();
+ VariableSeq/*!*/ cins = new VariableSeq();
VariableSeq wildcardVars = new VariableSeq();
- assume this.Proc != null;
- for (int i = 0; i < this.Proc.InParams.Length; ++i)
- {
- Variable! param = (!)this.Proc.InParams[i];
+ Contract.Assume(this.Proc != null);
+ for (int i = 0; i < this.Proc.InParams.Length; ++i) {
+ Variable/*!*/ param = cce.NonNull(this.Proc.InParams[i]);
bool isWildcard = this.Ins[i] == null;
- Type! actualType;
+ Type/*!*/ actualType;
if (isWildcard)
actualType = param.TypedIdent.Type.Substitute(TypeParamSubstitution());
else
// during type checking, we have ensured that the type of the actual
// parameter Ins[i] is correct, so we can use it here
- actualType = (!)((!)Ins[i]).Type;
+ actualType = cce.NonNull(cce.NonNull(Ins[i]).Type);
Variable cin = CreateTemporaryVariable(tempVars, param, actualType,
TempVarKind.Formal);
@@ -1613,14 +1954,14 @@ namespace Microsoft.Boogie
#endregion
#region call aouts := P(ains) becomes: (open outlining one level to see)
#region cins := ains (or havoc cin when ain is null)
- for (int i = 0, n = this.Ins.Count; i < n; i++)
- {
- IdentifierExpr! cin_exp = new IdentifierExpr(((!)cins[i]).tok, (!) cins[i]);
+ for (int i = 0, n = this.Ins.Count; i < n; i++) {
+ IdentifierExpr/*!*/ cin_exp = new IdentifierExpr(cce.NonNull(cins[i]).tok, cce.NonNull(cins[i]));
+ Contract.Assert(cin_exp != null);
if (this.Ins[i] != null) {
- AssignCmd assign = Cmd.SimpleAssign(Token.NoToken, cin_exp, (!) this.Ins[i]);
+ AssignCmd assign = Cmd.SimpleAssign(Token.NoToken, cin_exp, cce.NonNull(this.Ins[i]));
newBlockBody.Add(assign);
} else {
- IdentifierExprSeq! ies = new IdentifierExprSeq();
+ IdentifierExprSeq/*!*/ ies = new IdentifierExprSeq();
ies.Add(cin_exp);
HavocCmd havoc = new HavocCmd(Token.NoToken, ies);
newBlockBody.Add(havoc);
@@ -1632,60 +1973,62 @@ namespace Microsoft.Boogie
Substitution s = Substituter.SubstitutionFromHashtable(substMapBound);
bool hasWildcard = (wildcardVars.Length != 0);
Expr preConjunction = null;
- for (int i = 0; i < this.Proc.Requires.Length; i++)
- {
- Requires! req = (!) this.Proc.Requires[i];
+ for (int i = 0; i < this.Proc.Requires.Length; i++) {
+ Requires/*!*/ req = cce.NonNull(this.Proc.Requires[i]);
if (!req.Free) {
if (hasWildcard) {
- Expr pre = Substituter.Apply(s, req.Condition);
- if (preConjunction == null) {
- preConjunction = pre;
- } else {
- preConjunction = Expr.And(preConjunction, pre);
- }
+ Expr pre = Substituter.Apply(s, req.Condition);
+ if (preConjunction == null) {
+ preConjunction = pre;
+ } else {
+ preConjunction = Expr.And(preConjunction, pre);
+ }
} else {
- Requires! reqCopy = (Requires!) req.Clone();
- reqCopy.Condition = Substituter.Apply(s, req.Condition);
- AssertCmd! a = new AssertRequiresCmd(this, reqCopy);
- a.ErrorDataEnhanced = reqCopy.ErrorDataEnhanced;
- newBlockBody.Add(a);
+ Requires/*!*/ reqCopy = (Requires/*!*/)cce.NonNull(req.Clone());
+ reqCopy.Condition = Substituter.Apply(s, req.Condition);
+ AssertCmd/*!*/ a = new AssertRequiresCmd(this, reqCopy);
+ Contract.Assert(a != null);
+ a.ErrorDataEnhanced = reqCopy.ErrorDataEnhanced;
+ newBlockBody.Add(a);
}
}
}
if (hasWildcard) {
- if (preConjunction == null) {
- preConjunction = Expr.True;
- }
- Expr! expr = new ExistsExpr(tok, wildcardVars, preConjunction);
- AssertCmd! a = new AssertCmd(tok, expr);
- a.ErrorDataEnhanced = AssertCmd.GenerateBoundVarMiningStrategy(expr);
- newBlockBody.Add(a);
+ if (preConjunction == null) {
+ preConjunction = Expr.True;
+ }
+ Expr/*!*/ expr = new ExistsExpr(tok, wildcardVars, preConjunction);
+ Contract.Assert(expr != null);
+ AssertCmd/*!*/ a = new AssertCmd(tok, expr);
+ Contract.Assert(a != null);
+ a.ErrorDataEnhanced = AssertCmd.GenerateBoundVarMiningStrategy(expr);
+ newBlockBody.Add(a);
}
#endregion
#region assume Pre[ins := cins] with formal paramters
if (hasWildcard) {
- s = Substituter.SubstitutionFromHashtable(substMap);
- for (int i = 0; i < this.Proc.Requires.Length; i++)
- {
- Requires! req = (!) this.Proc.Requires[i];
- if (!req.Free) {
- Requires! reqCopy = (Requires!) req.Clone();
- reqCopy.Condition = Substituter.Apply(s, req.Condition);
- AssumeCmd! a = new AssumeCmd(tok, reqCopy.Condition);
- newBlockBody.Add(a);
- }
+ s = Substituter.SubstitutionFromHashtable(substMap);
+ for (int i = 0; i < this.Proc.Requires.Length; i++) {
+ Requires/*!*/ req = cce.NonNull(this.Proc.Requires[i]);
+ if (!req.Free) {
+ Requires/*!*/ reqCopy = (Requires/*!*/)cce.NonNull(req.Clone());
+ reqCopy.Condition = Substituter.Apply(s, req.Condition);
+ AssumeCmd/*!*/ a = new AssumeCmd(tok, reqCopy.Condition);
+ Contract.Assert(a != null);
+ newBlockBody.Add(a);
}
+ }
}
#endregion
#region cframe := frame (to hold onto frame values in case they are referred to in the postcondition)
IdentifierExprSeq havocVarExprs = new IdentifierExprSeq();
- foreach (IdentifierExpr! f in this.Proc.Modifies)
- {
- assume f.Decl != null;
- assert f.Type != null;
+ foreach (IdentifierExpr/*!*/ f in this.Proc.Modifies) {
+ Contract.Assert(f != null);
+ Contract.Assume(f.Decl != null);
+ Contract.Assert(f.Type != null);
Variable v = CreateTemporaryVariable(tempVars, f.Decl, f.Type, TempVarKind.Old);
IdentifierExpr v_exp = new IdentifierExpr(v.tok, v);
substMapOld.Add(f.Decl, v_exp); // this assumes no duplicates in this.Proc.Modifies
@@ -1693,24 +2036,23 @@ namespace Microsoft.Boogie
newBlockBody.Add(assign);
// fra
- if(!havocVarExprs.Has(f))
+ if (!havocVarExprs.Has(f))
havocVarExprs.Add(f);
}
#endregion
#region Create couts
- VariableSeq! couts = new VariableSeq();
- for (int i = 0; i < this.Proc.OutParams.Length; ++i)
- {
- Variable! param = (!)this.Proc.OutParams[i];
+ VariableSeq/*!*/ couts = new VariableSeq();
+ for (int i = 0; i < this.Proc.OutParams.Length; ++i) {
+ Variable/*!*/ param = cce.NonNull(this.Proc.OutParams[i]);
bool isWildcard = this.Outs[i] == null;
- Type! actualType;
+ Type/*!*/ actualType;
if (isWildcard)
actualType = param.TypedIdent.Type.Substitute(TypeParamSubstitution());
else
// during type checking, we have ensured that the type of the actual
// out parameter Outs[i] is correct, so we can use it here
- actualType = (!)((!)Outs[i]).Type;
+ actualType = cce.NonNull(cce.NonNull(Outs[i]).Type);
Variable cout = CreateTemporaryVariable(tempVars, param, actualType,
TempVarKind.Formal);
@@ -1718,15 +2060,16 @@ namespace Microsoft.Boogie
IdentifierExpr ie = new IdentifierExpr(cout.tok, cout);
substMap.Add(param, ie);
- if(!havocVarExprs.Has(ie))
+ if (!havocVarExprs.Has(ie))
havocVarExprs.Add(ie);
}
// add the where clauses, now that we have the entire substitution map
- foreach (Variable! param in this.Proc.OutParams) {
+ foreach (Variable/*!*/ param in this.Proc.OutParams) {
+ Contract.Assert(param != null);
Expr w = param.TypedIdent.WhereExpr;
if (w != null) {
- IdentifierExpr ie = (IdentifierExpr!)substMap[param];
- assert ie.Decl != null;
+ IdentifierExpr ie = (IdentifierExpr/*!*/)cce.NonNull(substMap[param]);
+ Contract.Assert(ie.Decl != null);
ie.Decl.TypedIdent.WhereExpr = Substituter.Apply(Substituter.SubstitutionFromHashtable(substMap), w);
}
}
@@ -1741,8 +2084,8 @@ namespace Microsoft.Boogie
#region assume Post[ins, outs, old(frame) := cins, couts, cframe]
Substitution s2 = Substituter.SubstitutionFromHashtable(substMap);
Substitution s2old = Substituter.SubstitutionFromHashtable(substMapOld);
- foreach (Ensures! e in this.Proc.Ensures)
- {
+ foreach (Ensures/*!*/ e in this.Proc.Ensures) {
+ Contract.Assert(e != null);
Expr copy = Substituter.ApplyReplacingOldExprs(s2, s2old, e.Condition);
AssumeCmd assume = new AssumeCmd(this.tok, copy);
newBlockBody.Add(assume);
@@ -1750,12 +2093,12 @@ namespace Microsoft.Boogie
#endregion
#region aouts := couts
- for (int i = 0, n = this.Outs.Count; i < n; i++)
- {
- if (this.Outs[i]!=null) {
- Variable! param_i = (!) this.Proc.OutParams[i];
- Expr! cout_exp = new IdentifierExpr(((!)couts[i]).tok, (!) couts[i]);
- AssignCmd assign = Cmd.SimpleAssign(param_i.tok, (!) this.Outs[i], cout_exp);
+ for (int i = 0, n = this.Outs.Count; i < n; i++) {
+ if (this.Outs[i] != null) {
+ Variable/*!*/ param_i = cce.NonNull(this.Proc.OutParams[i]);
+ Expr/*!*/ cout_exp = new IdentifierExpr(cce.NonNull(couts[i]).tok, cce.NonNull(couts[i]));
+ Contract.Assert(cout_exp != null);
+ AssignCmd assign = Cmd.SimpleAssign(param_i.tok, cce.NonNull(this.Outs[i]), cout_exp);
newBlockBody.Add(assign);
}
}
@@ -1765,37 +2108,49 @@ namespace Microsoft.Boogie
return new StateCmd(this.tok, tempVars, newBlockBody);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitCallCmd(this);
}
}
- public class CallForallCmd : CallCommonality
- {
- string! callee;
+ public class CallForallCmd : CallCommonality {
+ string/*!*/ callee;
public Procedure Proc;
- public List<Expr>! Ins;
+ public List<Expr>/*!*/ Ins;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(callee != null);
+ Contract.Invariant(Ins != null);
+ }
+
// the types of the formal in-parameters after instantiating all
// type variables whose value could be inferred using the given
// actual non-wildcard arguments
public TypeSeq InstantiatedTypes;
- public CallForallCmd(IToken! tok, string! callee, List<Expr>! ins)
- {
- base(tok, null);
+ public CallForallCmd(IToken tok, string callee, List<Expr> ins)
+ : base(tok, null) {//BASEMOVEA
+ Contract.Requires(ins != null);
+ Contract.Requires(callee != null);
+ Contract.Requires(tok != null);
+ //:base(tok, null);
this.callee = callee;
this.Ins = ins;
}
- public CallForallCmd(IToken! tok, string! callee, List<Expr>! ins, QKeyValue kv)
- {
- base(tok, kv);
+ public CallForallCmd(IToken tok, string callee, List<Expr> ins, QKeyValue kv)
+ : base(tok, kv) {//BASEMOVEA
+ Contract.Requires(ins != null);
+ Contract.Requires(callee != null);
+ Contract.Requires(tok != null);
+ //:base(tok, kv);
this.callee = callee;
this.Ins = ins;
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.Write(this, level, "call ");
EmitAttributes(stream, Attributes);
stream.Write("forall ");
@@ -1814,8 +2169,8 @@ namespace Microsoft.Boogie
stream.WriteLine(");");
base.Emit(stream, level);
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
if (Proc != null) {
// already resolved
return;
@@ -1831,9 +2186,11 @@ namespace Microsoft.Boogie
}
}
}
- public override void AddAssignedVariables(VariableSeq! vars) { }
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void AddAssignedVariables(VariableSeq vars) {
+ //Contract.Requires(vars != null);
+ }
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
TypecheckAttributes(Attributes, tc);
// typecheck in-parameters
foreach (Expr e in Ins) {
@@ -1842,58 +2199,56 @@ namespace Microsoft.Boogie
}
}
- if (this.Proc == null)
- {
+ if (this.Proc == null) {
// called procedure didn't resolve, so bug out
return;
}
// match actuals with formals
- if (Ins.Count != Proc.InParams.Length)
- {
+ if (Ins.Count != Proc.InParams.Length) {
tc.Error(this, "wrong number of in-parameters in call: {0}", callee);
- }
- else
- {
+ } else {
// determine the lists of formal and actual arguments that need
// to be matched (stars are left out)
- TypeSeq! formalTypes = new TypeSeq ();
- ExprSeq! actualArgs = new ExprSeq ();
- for (int i = 0; i < Ins.Count; i++)
+ TypeSeq/*!*/ formalTypes = new TypeSeq();
+ ExprSeq/*!*/ actualArgs = new ExprSeq();
+ for (int i = 0; i < Ins.Count; i++)
if (Ins[i] != null) {
- formalTypes.Add(((!)Proc.InParams[i]).TypedIdent.Type);
+ formalTypes.Add(cce.NonNull(Proc.InParams[i]).TypedIdent.Type);
actualArgs.Add(Ins[i]);
}
- IDictionary<TypeVariable!, Type!>! subst =
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst =
Type.MatchArgumentTypes(Proc.TypeParameters,
formalTypes, actualArgs, null, null,
"call forall to " + callee, tc);
+ Contract.Assert(cce.NonNullElements(subst));
- InstantiatedTypes = new TypeSeq ();
- foreach (Variable! var in Proc.InParams) {
+ InstantiatedTypes = new TypeSeq();
+ foreach (Variable/*!*/ var in Proc.InParams) {
+ Contract.Assert(var != null);
InstantiatedTypes.Add(var.TypedIdent.Type.Substitute(subst));
}
}
-// if (Proc.OutParams.Length != 0)
-// {
-// tc.Error(this, "call forall is allowed only on procedures with no out-parameters: {0}", callee);
-// }
+ // if (Proc.OutParams.Length != 0)
+ // {
+ // tc.Error(this, "call forall is allowed only on procedures with no out-parameters: {0}", callee);
+ // }
- if (Proc.Modifies.Length != 0)
- {
+ if (Proc.Modifies.Length != 0) {
tc.Error(this, "call forall is allowed only on procedures with no modifies clause: {0}", callee);
}
}
- protected override Cmd! ComputeDesugaring() {
+ protected override Cmd ComputeDesugaring() {
+ Contract.Ensures(Contract.Result<Cmd>() != null);
CmdSeq newBlockBody = new CmdSeq();
Hashtable /*Variable -> Expr*/ substMap = new Hashtable/*Variable -> Expr*/();
- VariableSeq! tempVars = new VariableSeq();
+ VariableSeq/*!*/ tempVars = new VariableSeq();
// proc P(ins) returns ()
// requires Pre;
- // modifies ;
+ // //modifies ;
// ensures Post;
//
// call forall P(ains);
@@ -1904,12 +2259,12 @@ namespace Microsoft.Boogie
// wildcardVars : the bound variables to be wrapped up in a quantification
#region Create cins; each one is an incarnation of the corresponding in parameter
- VariableSeq! cins = new VariableSeq();
+ VariableSeq cins = new VariableSeq();
VariableSeq wildcardVars = new VariableSeq();
- assume this.Proc != null;
+ Contract.Assume(this.Proc != null);
for (int i = 0, n = this.Proc.InParams.Length; i < n; i++) {
- Variable param = (!)this.Proc.InParams[i];
- Type! paramType = ((!)this.InstantiatedTypes)[i]; // might contain type variables
+ Variable param = cce.NonNull(this.Proc.InParams[i]);
+ Type/*!*/ paramType = cce.NonNull(this.InstantiatedTypes)[i]; // might contain type variables
bool isWildcard = this.Ins[i] == null;
Variable cin = CreateTemporaryVariable(tempVars, param, paramType,
isWildcard ? TempVarKind.Bound : TempVarKind.Formal);
@@ -1926,11 +2281,10 @@ namespace Microsoft.Boogie
#region call forall P(ains) becomes: (open outlining one level to see)
#region cins := ains
- for (int i = 0, n = this.Ins.Count; i < n; i++)
- {
+ for (int i = 0, n = this.Ins.Count; i < n; i++) {
if (this.Ins[i] != null) {
- IdentifierExpr! cin_exp = new IdentifierExpr(((!)cins[i]).tok, (!) cins[i]);
- AssignCmd assign = Cmd.SimpleAssign(Token.NoToken, cin_exp, (!) this.Ins[i]);
+ IdentifierExpr/*!*/ cin_exp = new IdentifierExpr(cce.NonNull(cins[i]).tok, cce.NonNull(cins[i]));
+ AssignCmd assign = Cmd.SimpleAssign(Token.NoToken, cin_exp, cce.NonNull(this.Ins[i]));
newBlockBody.Add(assign);
}
}
@@ -1939,9 +2293,8 @@ namespace Microsoft.Boogie
#region assert Pre[ins := cins]
Substitution s = Substituter.SubstitutionFromHashtable(substMap);
Expr preConjunction = null;
- for (int i = 0; i < this.Proc.Requires.Length; i++)
- {
- Requires! req = (!) this.Proc.Requires[i];
+ for (int i = 0; i < this.Proc.Requires.Length; i++) {
+ Requires/*!*/ req = cce.NonNull(this.Proc.Requires[i]);
if (!req.Free) {
Expr pre = Substituter.Apply(s, req.Condition);
if (preConjunction == null) {
@@ -1957,9 +2310,9 @@ namespace Microsoft.Boogie
#endregion
#region Create couts
- VariableSeq! couts = new VariableSeq();
- foreach ( Variable! param in this.Proc.OutParams )
- {
+ VariableSeq/*!*/ couts = new VariableSeq();
+ foreach (Variable/*!*/ param in this.Proc.OutParams) {
+ Contract.Assert(param != null);
Variable cout = CreateTemporaryVariable(tempVars, param,
param.TypedIdent.Type, TempVarKind.Bound);
couts.Add(cout);
@@ -1967,11 +2320,12 @@ namespace Microsoft.Boogie
substMap.Add(param, ie);
}
// add the where clauses, now that we have the entire substitution map
- foreach (Variable! param in this.Proc.OutParams) {
+ foreach (Variable/*!*/ param in this.Proc.OutParams) {
+ Contract.Assert(param != null);
Expr w = param.TypedIdent.WhereExpr;
if (w != null) {
- IdentifierExpr ie = (IdentifierExpr!)substMap[param];
- assert ie.Decl != null;
+ IdentifierExpr ie = (IdentifierExpr)cce.NonNull(substMap[param]);
+ Contract.Assert(ie.Decl != null);
ie.Decl.TypedIdent.WhereExpr = Substituter.Apply(Substituter.SubstitutionFromHashtable(substMap), w);
}
}
@@ -1980,8 +2334,8 @@ namespace Microsoft.Boogie
#region assume Post[ins := cins]
s = Substituter.SubstitutionFromHashtable(substMap);
Expr postConjunction = null;
- foreach (Ensures! e in this.Proc.Ensures)
- {
+ foreach (Ensures/*!*/ e in this.Proc.Ensures) {
+ Contract.Assert(e != null);
Expr post = Substituter.Apply(s, e.Condition);
if (postConjunction == null) {
postConjunction = post;
@@ -1997,11 +2351,11 @@ namespace Microsoft.Boogie
#region assume (forall wildcardVars :: Pre ==> Post);
Expr body = postConjunction;
if (couts.Length > 0) {
- body = new ExistsExpr(tok, couts, body);
+ body = new ExistsExpr(tok, couts, body);
}
body = Expr.Imp(preConjunction, body);
if (wildcardVars.Length != 0) {
- TypeVariableSeq! typeParams = Type.FreeVariablesIn((!)InstantiatedTypes);
+ TypeVariableSeq/*!*/ typeParams = Type.FreeVariablesIn(cce.NonNull(InstantiatedTypes));
body = new ForallExpr(tok, typeParams, wildcardVars, body);
}
newBlockBody.Add(new AssumeCmd(tok, body));
@@ -2011,25 +2365,33 @@ namespace Microsoft.Boogie
return new StateCmd(this.tok, tempVars, newBlockBody);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitCallForallCmd(this);
}
}
- public abstract class PredicateCmd : Cmd
- {
- public /*readonly--except in StandardVisitor*/ Expr! Expr;
- public PredicateCmd(IToken! tok, Expr! expr)
- : base(tok)
- {
+ public abstract class PredicateCmd : Cmd {
+ public /*readonly--except in StandardVisitor*/ Expr/*!*/ Expr;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Expr != null);
+ }
+
+ public PredicateCmd(IToken/*!*/ tok, Expr/*!*/ expr)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
Expr = expr;
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
Expr.Resolve(rc);
}
- public override void AddAssignedVariables(VariableSeq! vars) { }
+ public override void AddAssignedVariables(VariableSeq vars) {
+ //Contract.Requires(vars != null);
+ }
}
public abstract class MiningStrategy {
@@ -2038,33 +2400,50 @@ namespace Microsoft.Boogie
}
public class ListOfMiningStrategies : MiningStrategy {
- public List<MiningStrategy>! msList;
+ public List<MiningStrategy>/*!*/ msList;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(msList != null);
+ }
- public ListOfMiningStrategies (List<MiningStrategy>! l) {
+
+ public ListOfMiningStrategies(List<MiningStrategy> l) {
+ Contract.Requires(l != null);
this.msList = l;
}
}
public class EEDTemplate : MiningStrategy {
- public string! reason;
- public List<Expr!>! exprList;
+ public string/*!*/ reason;
+ public List<Expr/*!*/>/*!*/ exprList;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(reason != null);
+ Contract.Invariant(cce.NonNullElements(exprList));
+ }
- public EEDTemplate (string! reason, List<Expr!>! exprList) {
+
+ public EEDTemplate(string reason, List<Expr/*!*/>/*!*/ exprList) {
+ Contract.Requires(reason != null);
+ Contract.Requires(cce.NonNullElements(exprList));
this.reason = reason;
this.exprList = exprList;
}
}
- public class AssertCmd : PredicateCmd, IPotentialErrorNode
- {
+ public class AssertCmd : PredicateCmd, IPotentialErrorNode {
public Expr OrigExpr;
public Hashtable /*Variable -> Expr*/ IncarnationMap;
// TODO: convert to use generics
private object errorData;
public object ErrorData {
- get { return errorData; }
- set { errorData = value; }
+ get {
+ return errorData;
+ }
+ set {
+ errorData = value;
+ }
}
public string ErrorMessage {
@@ -2077,48 +2456,54 @@ namespace Microsoft.Boogie
private MiningStrategy errorDataEnhanced;
public MiningStrategy ErrorDataEnhanced {
- get { return errorDataEnhanced; }
- set { errorDataEnhanced = value; }
+ get {
+ return errorDataEnhanced;
+ }
+ set {
+ errorDataEnhanced = value;
+ }
}
- public AssertCmd(IToken! tok, Expr! expr)
- : base(tok, expr)
- {
+ public AssertCmd(IToken/*!*/ tok, Expr/*!*/ expr)
+ : base(tok, expr) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
errorDataEnhanced = GenerateBoundVarMiningStrategy(expr);
}
- public AssertCmd(IToken! tok, Expr! expr, QKeyValue kv)
- : base(tok, expr)
- {
+ public AssertCmd(IToken/*!*/ tok, Expr/*!*/ expr, QKeyValue kv)
+ : base(tok, expr) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
errorDataEnhanced = GenerateBoundVarMiningStrategy(expr);
Attributes = kv;
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.Write(this, level, "assert ");
EmitAttributes(stream, Attributes);
this.Expr.Emit(stream);
stream.WriteLine(";");
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
ResolveAttributes(Attributes, rc);
base.Resolve(rc);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
TypecheckAttributes(Attributes, tc);
Expr.Typecheck(tc);
- assert Expr.Type != null; // follows from Expr.Typecheck postcondition
- if (!Expr.Type.Unify(Type.Bool))
- {
+ Contract.Assert(Expr.Type != null); // follows from Expr.Typecheck postcondition
+ if (!Expr.Type.Unify(Type.Bool)) {
tc.Error(this, "an asserted expression must be of type bool (got: {0})", Expr.Type);
}
}
- public static MiningStrategy GenerateBoundVarMiningStrategy (Expr! expr) {
+ public static MiningStrategy GenerateBoundVarMiningStrategy(Expr expr) {
+ Contract.Requires(expr != null);
List<MiningStrategy> l = new List<MiningStrategy>();
if (expr != null) {
l = GenerateBoundVarListForMining(expr, l);
@@ -2126,29 +2511,32 @@ namespace Microsoft.Boogie
return new ListOfMiningStrategies(l);
}
- public static List<MiningStrategy>! GenerateBoundVarListForMining (Expr! expr, List<MiningStrategy>! l) {
+ public static List<MiningStrategy>/*!*/ GenerateBoundVarListForMining(Expr expr, List<MiningStrategy> l) {
+ Contract.Requires(l != null);
+ Contract.Requires(expr != null);
+ Contract.Ensures(Contract.Result<List<MiningStrategy>>() != null);
+
// go through the origExpr and identify all bound variables in the AST.
if (expr is LiteralExpr || expr is IdentifierExpr) {
//end recursion
- }
- else if (expr is NAryExpr) {
+ } else if (expr is NAryExpr) {
NAryExpr e = (NAryExpr)expr;
- foreach (Expr! arg in e.Args) {
+ foreach (Expr/*!*/ arg in e.Args) {
+ Contract.Assert(arg != null);
l = GenerateBoundVarListForMining(arg, l);
}
- }
- else if (expr is OldExpr) {
+ } else if (expr is OldExpr) {
OldExpr e = (OldExpr)expr;
l = GenerateBoundVarListForMining(e.Expr, l);
- }
- else if (expr is QuantifierExpr) {
- QuantifierExpr qe = (QuantifierExpr) expr;
+ } else if (expr is QuantifierExpr) {
+ QuantifierExpr qe = (QuantifierExpr)expr;
VariableSeq vs = qe.Dummies;
- foreach (Variable! x in vs) {
+ foreach (Variable/*!*/ x in vs) {
+ Contract.Assert(x != null);
string name = x.Name;
if (name.StartsWith("^")) {
name = name.Substring(1);
- List<Expr!> exprList = new List<Expr!>();
+ List<Expr> exprList = new List<Expr>();
exprList.Add(new IdentifierExpr(Token.NoToken, x.ToString(), x.TypedIdent.Type));
MiningStrategy eed = new EEDTemplate("The bound variable " + name + " has the value {0}.", exprList);
l.Add(eed);
@@ -2160,48 +2548,56 @@ namespace Microsoft.Boogie
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitAssertCmd(this);
}
}
// An AssertCmd that is a loop invariant check before the loop iteration starts
- public class LoopInitAssertCmd : AssertCmd
- {
- public LoopInitAssertCmd(IToken! tok, Expr! expr)
- : base(tok, expr)
- {
+ public class LoopInitAssertCmd : AssertCmd {
+ public LoopInitAssertCmd(IToken/*!*/ tok, Expr/*!*/ expr)
+ : base(tok, expr) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
}
}
// An AssertCmd that is a loop invariant check to maintain the invariant after iteration
- public class LoopInvMaintainedAssertCmd : AssertCmd
- {
- public LoopInvMaintainedAssertCmd(IToken! tok, Expr! expr)
- : base(tok, expr)
- {
+ public class LoopInvMaintainedAssertCmd : AssertCmd {
+ public LoopInvMaintainedAssertCmd(IToken/*!*/ tok, Expr/*!*/ expr)
+ : base(tok, expr) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
}
}
/// <summary>
/// An AssertCmd that is introduced in translation from the requires on a call.
/// </summary>
- public class AssertRequiresCmd : AssertCmd
- {
- public CallCmd! Call;
- public Requires! Requires;
+ public class AssertRequiresCmd : AssertCmd {
+ public CallCmd/*!*/ Call;
+ public Requires/*!*/ Requires;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Call != null);
+ Contract.Invariant(Requires != null);
+ }
- public AssertRequiresCmd(CallCmd! call, Requires! @requires)
- : base(call.tok, @requires.Condition)
- {
+
+ public AssertRequiresCmd(CallCmd/*!*/ call, Requires/*!*/ requires)
+ : base(call.tok, requires.Condition) {
+ Contract.Requires(call != null);
+ Contract.Requires(requires != null);
this.Call = call;
- this.Requires = @requires;
+ this.Requires = requires;
// base(call.tok, @requires.Condition);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitAssertRequiresCmd(this);
}
}
@@ -2210,263 +2606,284 @@ namespace Microsoft.Boogie
/// An AssertCmd that is introduced in translation from an ensures
/// declaration.
/// </summary>
- public class AssertEnsuresCmd : AssertCmd
- {
- public Ensures! Ensures;
- public AssertEnsuresCmd(Ensures! ens)
- : base(ens.tok, ens.Condition)
- {
+ public class AssertEnsuresCmd : AssertCmd {
+ public Ensures/*!*/ Ensures;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Ensures != null);
+ }
+
+ public AssertEnsuresCmd(Ensures/*!*/ ens)
+ : base(ens.tok, ens.Condition) {
+ Contract.Requires(ens != null);
this.Ensures = ens;
// base(ens.tok, ens.Condition);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitAssertEnsuresCmd(this);
}
}
- public class AssumeCmd : PredicateCmd
- {
- public AssumeCmd(IToken! tok, Expr! expr)
- : base(tok, expr)
- {
- //Debug.Assert(expr != null);
+ public class AssumeCmd : PredicateCmd {
+ public AssumeCmd(IToken/*!*/ tok, Expr/*!*/ expr)
+ : base(tok, expr) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.Write(this, level, "assume ");
this.Expr.Emit(stream);
stream.WriteLine(";");
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
Expr.Typecheck(tc);
- assert Expr.Type != null; // follows from Expr.Typecheck postcondition
- if (!Expr.Type.Unify(Type.Bool))
- {
+ Contract.Assert(Expr.Type != null); // follows from Expr.Typecheck postcondition
+ if (!Expr.Type.Unify(Type.Bool)) {
tc.Error(this, "an assumed expression must be of type bool (got: {0})", Expr.Type);
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitAssumeCmd(this);
}
}
- public class ReturnExprCmd : ReturnCmd
- {
- public Expr! Expr;
- public ReturnExprCmd(IToken! tok, Expr! expr)
- : base(tok)
- {
+ public class ReturnExprCmd : ReturnCmd {
+ public Expr/*!*/ Expr;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Expr != null);
+ }
+
+ public ReturnExprCmd(IToken/*!*/ tok, Expr/*!*/ expr)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
Expr = expr;
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.Write(this, level, "return ");
this.Expr.Emit(stream);
stream.WriteLine(";");
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
Expr.Typecheck(tc);
- assert Expr.Type != null; // follows from Expr.Typecheck postcondition
- if (!Expr.Type.Unify(Type.Bool))
- {
+ Contract.Assert(Expr.Type != null); // follows from Expr.Typecheck postcondition
+ if (!Expr.Type.Unify(Type.Bool)) {
tc.Error(this, "a return expression must be of type bool (got: {0})", Expr.Type);
}
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
Expr.Resolve(rc);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitReturnExprCmd(this);
}
}
- public class HavocCmd : Cmd
- {
- public IdentifierExprSeq! Vars;
- public HavocCmd(IToken! tok, IdentifierExprSeq! vars)
- : base(tok)
- {
+ public class HavocCmd : Cmd {
+ public IdentifierExprSeq/*!*/ Vars;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Vars != null);
+ }
+
+ public HavocCmd(IToken/*!*/ tok, IdentifierExprSeq/*!*/ vars)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(vars != null);
Vars = vars;
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.Write(this, level, "havoc ");
Vars.Emit(stream, true);
stream.WriteLine(";");
}
- public override void Resolve(ResolutionContext! rc)
- {
- foreach (IdentifierExpr! ide in Vars)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ foreach (IdentifierExpr/*!*/ ide in Vars) {
+ Contract.Assert(ide != null);
ide.Resolve(rc);
}
}
- public override void AddAssignedVariables(VariableSeq! vars)
- {
- foreach (IdentifierExpr! e in this.Vars)
- {
+ public override void AddAssignedVariables(VariableSeq vars) {
+ //Contract.Requires(vars != null);
+ foreach (IdentifierExpr/*!*/ e in this.Vars) {
+ Contract.Assert(e != null);
vars.Add(e.Decl);
}
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
this.CheckAssignments(tc);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitHavocCmd(this);
}
}
//---------------------------------------------------------------------
// Transfer commands
+ [ContractClass(typeof(TransferCmdContracts))]
+ public abstract class TransferCmd : Absy {
+ internal TransferCmd(IToken/*!*/ tok)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ }
+ public abstract void Emit(TokenTextWriter/*!*/ stream, int level);
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ // nothing to typecheck
+ }
+ }
+ [ContractClassFor(typeof(TransferCmd))]
+ public abstract class TransferCmdContracts : TransferCmd {
+ public TransferCmdContracts() :base(null){
- public abstract class TransferCmd : Absy
- {
- internal TransferCmd(IToken! tok)
- : base(tok)
- {
}
- public abstract void Emit(TokenTextWriter! stream, int level);
- public override void Typecheck(TypecheckingContext! tc)
- {
- // nothing to typecheck
+ public override void Emit(TokenTextWriter stream, int level) {
+ Contract.Requires(stream != null);
+ throw new NotImplementedException();
}
}
- public class ReturnCmd : TransferCmd
- {
- public ReturnCmd(IToken! tok)
- : base(tok)
- {
+ public class ReturnCmd : TransferCmd {
+ public ReturnCmd(IToken/*!*/ tok)
+ : base(tok) {
+ Contract.Requires(tok != null);
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
stream.WriteLine(this, level, "return;");
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
// nothing to resolve
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitReturnCmd(this);
}
}
- public class GotoCmd : TransferCmd
- {
+ public class GotoCmd : TransferCmd {
[Rep]
public StringSeq labelNames;
[Rep]
public BlockSeq labelTargets;
- invariant labelNames != null && labelTargets != null ==> labelNames.Length == labelTargets.Length;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(labelNames == null || labelTargets == null || labelNames.Length == labelTargets.Length);
+ }
[NotDelayed]
- public GotoCmd(IToken! tok, StringSeq! labelSeq)
- : base (tok)
- {
+ public GotoCmd(IToken/*!*/ tok, StringSeq/*!*/ labelSeq)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(labelSeq != null);
this.labelNames = labelSeq;
}
- public GotoCmd(IToken! tok, StringSeq! labelSeq, BlockSeq! blockSeq)
- : base (tok)
- {
+ public GotoCmd(IToken/*!*/ tok, StringSeq/*!*/ labelSeq, BlockSeq/*!*/ blockSeq)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(labelSeq != null);
+ Contract.Requires(blockSeq != null);
Debug.Assert(labelSeq.Length == blockSeq.Length);
- for (int i=0; i<labelSeq.Length; i++) { Debug.Assert(Equals(labelSeq[i], ((!)blockSeq[i]).Label)); }
+ for (int i = 0; i < labelSeq.Length; i++) {
+ Debug.Assert(Equals(labelSeq[i], cce.NonNull(blockSeq[i]).Label));
+ }
this.labelNames = labelSeq;
this.labelTargets = blockSeq;
}
- public GotoCmd(IToken! tok, BlockSeq! blockSeq)
- : base (tok)
- { //requires blockSeq[i] != null ==> blockSeq[i].Label != null;
+ public GotoCmd(IToken/*!*/ tok, BlockSeq/*!*/ blockSeq)
+ : base(tok) { //requires (blockSeq[i] != null ==> blockSeq[i].Label != null);
+ Contract.Requires(tok != null);
+ Contract.Requires(blockSeq != null);
StringSeq labelSeq = new StringSeq();
- for (int i=0; i<blockSeq.Length; i++)
- labelSeq.Add(((!)blockSeq[i]).Label);
+ for (int i = 0; i < blockSeq.Length; i++)
+ labelSeq.Add(cce.NonNull(blockSeq[i]).Label);
this.labelNames = labelSeq;
this.labelTargets = blockSeq;
}
- public void AddTarget(Block! b)
- requires b.Label != null;
- requires this.labelTargets != null;
- requires this.labelNames != null;
- {
+ public void AddTarget(Block b) {
+ Contract.Requires(b != null);
+ Contract.Requires(b.Label != null);
+ Contract.Requires(this.labelTargets != null);
+ Contract.Requires(this.labelNames != null);
this.labelTargets.Add(b);
this.labelNames.Add(b.Label);
}
- public override void Emit(TokenTextWriter! stream, int level)
- {
- assume this.labelNames != null;
+ public override void Emit(TokenTextWriter stream, int level) {
+ //Contract.Requires(stream != null);
+ Contract.Assume(this.labelNames != null);
stream.Write(this, level, "goto ");
- if (CommandLineOptions.Clo.PrintWithUniqueASTIds)
- {
- if (labelTargets == null)
- {
+ if (CommandLineOptions.Clo.PrintWithUniqueASTIds) {
+ if (labelTargets == null) {
string sep = "";
- foreach (string name in labelNames)
- {
+ foreach (string name in labelNames) {
stream.Write("{0}{1}^^{2}", sep, "NoDecl", name);
sep = ", ";
}
- }
- else
- {
+ } else {
string sep = "";
- foreach (Block! b in labelTargets)
- {
+ foreach (Block/*!*/ b in labelTargets) {
+ Contract.Assert(b != null);
stream.Write("{0}h{1}^^{2}", sep, b.GetHashCode(), b.Label);
sep = ", ";
}
}
- }
- else
- {
+ } else {
labelNames.Emit(stream);
}
stream.WriteLine(";");
}
- public override void Resolve(ResolutionContext! rc)
- ensures labelTargets != null;
- {
- if (labelTargets != null)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ Contract.Ensures(labelTargets != null);
+ if (labelTargets != null) {
// already resolved
return;
}
- assume this.labelNames != null;
+ Contract.Assume(this.labelNames != null);
labelTargets = new BlockSeq();
- foreach (string! lbl in labelNames)
- {
+ foreach (string/*!*/ lbl in labelNames) {
+ Contract.Assert(lbl != null);
Block b = rc.LookUpBlock(lbl);
- if (b == null)
- {
+ if (b == null) {
rc.Error(this, "goto to unknown block: {0}", lbl);
- }
- else
- {
+ } else {
labelTargets.Add(b);
}
}
Debug.Assert(rc.ErrorCount > 0 || labelTargets.Length == labelNames.Length);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitGotoCmd(this);
}
}
-
-}
+} \ No newline at end of file
diff --git a/Source/Core/AbsyExpr.cs b/Source/Core/AbsyExpr.cs
index 250820ed..f5771f7f 100644
--- a/Source/Core/AbsyExpr.cs
+++ b/Source/Core/AbsyExpr.cs
@@ -7,17 +7,17 @@
// BoogiePL - Absy.cs
//---------------------------------------------------------------------------------------------
-namespace Microsoft.Boogie
-{
+namespace Microsoft.Boogie {
using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Boogie.AbstractInterpretation;
using AI = Microsoft.AbstractInterpretationFramework;
- using Microsoft.Contracts;
+ using Microsoft.AbstractInterpretationFramework;//DANGER: Added?
+ using System.Diagnostics.Contracts;
using Microsoft.Basetypes;
-
+
//---------------------------------------------------------------------
// Expressions
@@ -28,26 +28,25 @@ namespace Microsoft.Boogie
//---------------------------------------------------------------------
- public abstract class Expr : Absy
- {
- public Expr(IToken! tok)
- : base(tok)
- {
+ [ContractClass(typeof(ExprContracts))]
+ public abstract class Expr : Absy {
+ public Expr(IToken/*!*/ tok)
+ : base(tok) {
+ Contract.Requires(tok != null);
}
- public void Emit (TokenTextWriter! stream)
- {
+ public void Emit(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
Emit(stream, 0, false);
}
- public abstract void Emit (TokenTextWriter! wr, int contextBindingStrength, bool fragileContext);
-
+ public abstract void Emit(TokenTextWriter/*!*/ wr, int contextBindingStrength, bool fragileContext);
+
[Pure]
- public override string! ToString ()
- {
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
System.IO.StringWriter buffer = new System.IO.StringWriter();
- using (TokenTextWriter stream = new TokenTextWriter("<buffer>", buffer, false))
- {
+ using (TokenTextWriter stream = new TokenTextWriter("<buffer>", buffer, false)) {
this.Emit(stream, 0, false);
}
return buffer.ToString();
@@ -56,7 +55,7 @@ namespace Microsoft.Boogie
/// <summary>
/// Add to "freeVars" the free variables in the expression.
/// </summary>
- public abstract void ComputeFreeVariables(Set /*Variable*/! freeVars);
+ public abstract void ComputeFreeVariables(Set /*Variable*//*!*/ freeVars);
/// <summary>
/// Filled in by the Typecheck method. A value of "null" means a succeeding
@@ -66,138 +65,285 @@ namespace Microsoft.Boogie
/// </summary>
public Type Type;
- public override void Typecheck (TypecheckingContext! tc)
- ensures Type != null;
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ Contract.Ensures(Type != null);
// This body is added only because C# insists on it. It should really be left out, as if TypeCheck still were abstract.
// The reason for mentioning the method here at all is to give TypeCheck a postcondition for all expressions.
- assert false;
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ }
}
/// <summary>
/// Returns the type of the expression, supposing that all its subexpressions are well typed.
/// </summary>
- public abstract Type! ShallowType { get; }
+ public abstract Type/*!*/ ShallowType {
+ get;
+ }
// Handy syntactic sugar follows:
- public static NAryExpr! Unary (IToken! x, UnaryOperator.Opcode op, Expr! e1)
- {
+ public static NAryExpr Unary(IToken x, UnaryOperator.Opcode op, Expr e1) {
+ Contract.Requires(e1 != null);
+ Contract.Requires(x != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
return new NAryExpr(x, new UnaryOperator(x, op), new ExprSeq(e1));
}
- public static NAryExpr! Binary (IToken! x, BinaryOperator.Opcode op, Expr! e0, Expr! e1)
- {
+ public static NAryExpr Binary(IToken x, BinaryOperator.Opcode op, Expr e0, Expr e1) {
+ Contract.Requires(e1 != null);
+ Contract.Requires(e0 != null);
+ Contract.Requires(x != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
return new NAryExpr(x, new BinaryOperator(x, op), new ExprSeq(e0, e1));
}
- public static NAryExpr! Binary (BinaryOperator.Opcode op, Expr! e0, Expr! e1)
- {
+ public static NAryExpr Binary(BinaryOperator.Opcode op, Expr e0, Expr e1) {
+ Contract.Requires(e1 != null);
+ Contract.Requires(e0 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
return Binary(Token.NoToken, op, e0, e1);
}
- public static NAryExpr! Eq (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Eq, e1, e2); }
- public static NAryExpr! Neq (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Neq, e1, e2); }
- public static NAryExpr! Le (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Le, e1, e2); }
- public static NAryExpr! Ge (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Ge, e1, e2); }
- public static NAryExpr! Lt (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Lt, e1, e2); }
- public static NAryExpr! Gt (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Gt, e1, e2); }
- public static Expr! And (Expr! e1, Expr! e2) {
- if (e1 == true_) { return e2; }
- else if (e2 == true_) { return e1; }
- else if (e1 == false_ || e2 == false_) { return false_; }
- else { return Binary(BinaryOperator.Opcode.And, e1, e2); }
- }
- public static Expr! Or (Expr! e1, Expr! e2) {
- if (e1 == false_) { return e2; }
- else if (e2 == false_) { return e1; }
- else if (e1 == true_ || e2 == true_) { return true_; }
- else { return Binary(BinaryOperator.Opcode.Or, e1, e2); }
- }
- public static Expr! Not (Expr! e1) {
- NAryExpr nary = e1 as NAryExpr;
-
- if (e1 == true_) { return false_; }
- else if (e1 == false_) { return true_; }
- else if (nary != null)
- {
- if (nary.Fun is UnaryOperator)
- {
- UnaryOperator op = (UnaryOperator)nary.Fun;
- if (op.Op == UnaryOperator.Opcode.Not) { return (!) nary.Args[0]; }
- }
- else if (nary.Fun is BinaryOperator)
- {
- BinaryOperator op = (BinaryOperator)nary.Fun;
- Expr arg0 = (!)nary.Args[0];
- Expr arg1 = (!)nary.Args[1];
- if (op.Op == BinaryOperator.Opcode.Eq) { return Neq(arg0, arg1); }
- else if (op.Op == BinaryOperator.Opcode.Neq) { return Eq(arg0, arg1); }
- else if (op.Op == BinaryOperator.Opcode.Lt) { return Ge(arg0, arg1); }
- else if (op.Op == BinaryOperator.Opcode.Le) { return Gt(arg0, arg1); }
- else if (op.Op == BinaryOperator.Opcode.Ge) { return Lt(arg0, arg1); }
- else if (op.Op == BinaryOperator.Opcode.Gt) { return Le(arg0, arg1); }
- }
+ public static NAryExpr Eq(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Eq, e1, e2);
+ }
+ public static NAryExpr Neq(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Neq, e1, e2);
+ }
+ public static NAryExpr Le(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Le, e1, e2);
+ }
+ public static NAryExpr Ge(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Ge, e1, e2);
+ }
+ public static NAryExpr Lt(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Lt, e1, e2);
+ }
+ public static NAryExpr Gt(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Gt, e1, e2);
+ }
+ public static Expr And(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ if (e1 == true_) {
+ return e2;
+ } else if (e2 == true_) {
+ return e1;
+ } else if (e1 == false_ || e2 == false_) {
+ return false_;
+ } else {
+ return Binary(BinaryOperator.Opcode.And, e1, e2);
+ }
+ }
+ public static Expr Or(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ if (e1 == false_) {
+ return e2;
+ } else if (e2 == false_) {
+ return e1;
+ } else if (e1 == true_ || e2 == true_) {
+ return true_;
+ } else {
+ return Binary(BinaryOperator.Opcode.Or, e1, e2);
+ }
+ }
+ public static Expr Not(Expr e1) {
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ NAryExpr nary = e1 as NAryExpr;
+
+ if (e1 == true_) {
+ return false_;
+ } else if (e1 == false_) {
+ return true_;
+ } else if (nary != null) {
+ if (nary.Fun is UnaryOperator) {
+ UnaryOperator op = (UnaryOperator)nary.Fun;
+ if (op.Op == UnaryOperator.Opcode.Not) {
+ return cce.NonNull(nary.Args[0]);
+ }
+ } else if (nary.Fun is BinaryOperator) {
+ BinaryOperator op = (BinaryOperator)nary.Fun;
+ Expr arg0 = cce.NonNull(nary.Args[0]);
+ Expr arg1 = cce.NonNull(nary.Args[1]);
+ if (op.Op == BinaryOperator.Opcode.Eq) {
+ return Neq(arg0, arg1);
+ } else if (op.Op == BinaryOperator.Opcode.Neq) {
+ return Eq(arg0, arg1);
+ } else if (op.Op == BinaryOperator.Opcode.Lt) {
+ return Ge(arg0, arg1);
+ } else if (op.Op == BinaryOperator.Opcode.Le) {
+ return Gt(arg0, arg1);
+ } else if (op.Op == BinaryOperator.Opcode.Ge) {
+ return Lt(arg0, arg1);
+ } else if (op.Op == BinaryOperator.Opcode.Gt) {
+ return Le(arg0, arg1);
+ }
}
+ }
- return Unary(Token.NoToken, UnaryOperator.Opcode.Not, e1);
- }
- public static NAryExpr! Imp (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Imp, e1, e2); }
- public static NAryExpr! Iff (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Iff, e1, e2); }
- public static NAryExpr! Add (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Add, e1, e2); }
- public static NAryExpr! Sub (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Sub, e1, e2); }
- public static NAryExpr! Mul (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Mul, e1, e2); }
- public static NAryExpr! Div (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Div, e1, e2); }
- public static NAryExpr! Mod (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Mod, e1, e2); }
- public static NAryExpr! Subtype (Expr! e1, Expr! e2) { return Binary(BinaryOperator.Opcode.Subtype, e1, e2); }
-
- public static IdentifierExpr! Ident (string! name, Type! type)
- {
+ return Unary(Token.NoToken, UnaryOperator.Opcode.Not, e1);
+ }
+ public static NAryExpr Imp(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Imp, e1, e2);
+ }
+ public static NAryExpr Iff(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Iff, e1, e2);
+ }
+ public static NAryExpr Add(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Add, e1, e2);
+ }
+ public static NAryExpr Sub(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Sub, e1, e2);
+ }
+ public static NAryExpr Mul(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Mul, e1, e2);
+ }
+ public static NAryExpr Div(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Div, e1, e2);
+ }
+ public static NAryExpr Mod(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Mod, e1, e2);
+ }
+ public static NAryExpr Subtype(Expr e1, Expr e2) {
+ Contract.Requires(e2 != null);
+ Contract.Requires(e1 != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ return Binary(BinaryOperator.Opcode.Subtype, e1, e2);
+ }
+
+ public static IdentifierExpr Ident(string name, Type type) {
+ Contract.Requires(type != null);
+ Contract.Requires(name != null);
+ Contract.Ensures(Contract.Result<IdentifierExpr>() != null);
return new IdentifierExpr(Token.NoToken, name, type);
}
- public static IdentifierExpr! Ident (Variable! decl)
- {
+ public static IdentifierExpr Ident(Variable decl) {
+ Contract.Requires(decl != null);
+ Contract.Ensures(Contract.Result<IdentifierExpr>() != null);
IdentifierExpr result = new IdentifierExpr(Token.NoToken, decl);
return result;
}
- public static LiteralExpr! Literal (bool value) { return new LiteralExpr(Token.NoToken, value); }
- public static LiteralExpr! Literal (int value) { return new LiteralExpr(Token.NoToken, BigNum.FromInt(value)); }
- public static LiteralExpr! Literal (BigNum value) { return new LiteralExpr(Token.NoToken, value); }
+ public static LiteralExpr Literal(bool value) {
+ Contract.Ensures(Contract.Result<LiteralExpr>() != null);
+ return new LiteralExpr(Token.NoToken, value);
+ }
+ public static LiteralExpr Literal(int value) {
+ Contract.Ensures(Contract.Result<LiteralExpr>() != null);
+ return new LiteralExpr(Token.NoToken, BigNum.FromInt(value));
+ }
+ public static LiteralExpr Literal(BigNum value) {
+ Contract.Ensures(Contract.Result<LiteralExpr>() != null);
+ return new LiteralExpr(Token.NoToken, value);
+ }
- private static LiteralExpr! true_ = Literal(true);
- public static LiteralExpr! True { get { return true_; } }
+ private static LiteralExpr/*!*/ true_ = Literal(true);
+ public static LiteralExpr/*!*/ True {
+ get {
+ Contract.Ensures(Contract.Result<LiteralExpr>() != null);
+ return true_;
+ }
+ }
- private static LiteralExpr! false_ = Literal(false);
- public static LiteralExpr! False { get { return false_; } }
+ private static LiteralExpr/*!*/ false_ = Literal(false);
+ public static LiteralExpr/*!*/ False {
+ get {
+ Contract.Ensures(Contract.Result<LiteralExpr>() != null);
+ return false_;
+ }
+ }
- public static NAryExpr! Select(Expr! map, params Expr[]! args) {
+ public static NAryExpr Select(Expr map, params Expr[] args) {
+ Contract.Requires(args != null);
+ Contract.Requires(map != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
return SelectTok(Token.NoToken, map, args);
}
- public static NAryExpr! Select(Expr! map, List<Expr!>! args) {
+ public static NAryExpr Select(Expr map, List<Expr/*!*/>/*!*/ args) {
+ Contract.Requires(map != null);
+ Contract.Requires(cce.NonNullElements(args));
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
return Select(map, args.ToArray());
}
// use a different name for this variant of the method
// (-> some bug prevents overloading in this case)
- public static NAryExpr! SelectTok(IToken! x, Expr! map, params Expr[]! args)
- {
- ExprSeq! allArgs = new ExprSeq ();
+ public static NAryExpr SelectTok(IToken x, Expr map, params Expr[] args) {
+ Contract.Requires(args != null);
+ Contract.Requires(map != null);
+ Contract.Requires(x != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ ExprSeq/*!*/ allArgs = new ExprSeq();
allArgs.Add(map);
- foreach (Expr! a in args)
+ foreach (Expr/*!*/ a in args) {
+ Contract.Assert(a != null);
allArgs.Add(a);
+ }
return new NAryExpr(x, new MapSelect(Token.NoToken, args.Length), allArgs);
}
-
- public static NAryExpr! Store(Expr! map, params Expr[]! args) {
+
+ public static NAryExpr Store(Expr map, params Expr[] args) {
+ Contract.Requires(args != null);
+ Contract.Requires(map != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
return StoreTok(Token.NoToken, map, args);
}
- public static NAryExpr! Store(Expr! map, List<Expr!>! indexes, Expr! rhs) {
- Expr[]! allArgs = new Expr [indexes.Count + 1];
+ public static NAryExpr Store(Expr map, List<Expr/*!*/>/*!*/ indexes, Expr rhs) {
+ Contract.Requires(rhs != null);
+ Contract.Requires(map != null);
+ Contract.Requires(cce.NonNullElements(indexes));
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ Expr[]/*!*/ allArgs = new Expr[indexes.Count + 1];
for (int i = 0; i < indexes.Count; ++i)
allArgs[i] = indexes[i];
allArgs[indexes.Count] = rhs;
@@ -206,18 +352,28 @@ namespace Microsoft.Boogie
// use a different name for this variant of the method
// (-> some bug prevents overloading in this case)
- public static NAryExpr! StoreTok(IToken! x, Expr! map, params Expr[]! args)
- requires args.Length > 0; // zero or more indices, plus the value
- {
- ExprSeq! allArgs = new ExprSeq ();
+ public static NAryExpr/*!*/ StoreTok(IToken x, Expr map, params Expr[] args) {
+ Contract.Requires(args != null);
+ Contract.Requires(map != null);
+ Contract.Requires(x != null);
+ Contract.Requires(args.Length > 0); // zero or more indices, plus the value
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+
+ ExprSeq/*!*/ allArgs = new ExprSeq();
allArgs.Add(map);
- foreach (Expr! a in args)
+ foreach (Expr/*!*/ a in args) {
+ Contract.Assert(a != null);
allArgs.Add(a);
+ }
return new NAryExpr(x, new MapStore(Token.NoToken, args.Length - 1), allArgs);
}
-
- public static NAryExpr! CoerceType(IToken! x, Expr! subexpr, Type! type) {
- ExprSeq! args = new ExprSeq ();
+
+ public static NAryExpr CoerceType(IToken x, Expr subexpr, Type type) {
+ Contract.Requires(type != null);
+ Contract.Requires(subexpr != null);
+ Contract.Requires(x != null);
+ Contract.Ensures(Contract.Result<NAryExpr>() != null);
+ ExprSeq/*!*/ args = new ExprSeq();
args.Add(subexpr);
return new NAryExpr(x, new TypeCoercion(x, type), args);
}
@@ -231,23 +387,56 @@ namespace Microsoft.Boogie
/// implement some proper subinterface of AI.IExpr).
/// The converse operations of this property are found in AbsInt\ExprFactories.ssc.
/// </summary>
- public abstract AI.IExpr! IExpr {
- [Peer] get;
+ public abstract AI.IExpr/*!*/ IExpr {
+ [Peer]
+ get;
}
}
-
- public class LiteralExpr : Expr, AI.IFunApp
- {
- public readonly object! Val; // false, true, a BigNum, or a BvConst
+ [ContractClassFor(typeof(Expr))]
+ public abstract class ExprContracts : Expr {
+ public ExprContracts() :base(null){
+
+ }
+ public override void Emit(TokenTextWriter wr, int contextBindingStrength, bool fragileContext) {
+ Contract.Requires(wr != null);
+ throw new NotImplementedException();
+ }
+ public override void ComputeFreeVariables(Set freeVars) {
+ Contract.Requires(freeVars != null);
+ throw new NotImplementedException();
+ }
+ public override Type ShallowType {
+ get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ throw new NotImplementedException();
+ }
+ }
+ public override Microsoft.AbstractInterpretationFramework.IExpr IExpr {
+ get {
+ Contract.Ensures(Contract.Result<Microsoft.AbstractInterpretationFramework.IExpr>() != null);
+
+ throw new NotImplementedException();
+ }
+ }
+ }
+
+ public class LiteralExpr : Expr, AI.IFunApp {
+ public readonly object/*!*/ Val; // false, true, a BigNum, or a BvConst
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Val != null);
+ }
+
/// <summary>
/// Creates a literal expression for the boolean value "b".
/// </summary>
/// <param name="tok"></param>
/// <param name="b"></param>
- public LiteralExpr(IToken! tok, bool b)
- : base(tok)
- {
+ public LiteralExpr(IToken/*!*/ tok, bool b)
+ : base(tok) {
+ Contract.Requires(tok != null);
Val = b;
}
/// <summary>
@@ -255,79 +444,76 @@ namespace Microsoft.Boogie
/// </summary>
/// <param name="tok"></param>
/// <param name="v"></param>
- public LiteralExpr(IToken! tok, BigNum v)
- : base(tok)
- {
+ public LiteralExpr(IToken/*!*/ tok, BigNum v)
+ : base(tok) {
+ Contract.Requires(tok != null);
Val = v;
}
-
+
/// <summary>
/// Creates a literal expression for the bitvector value "v".
/// </summary>
- public LiteralExpr(IToken! tok, BigNum v, int b)
- : base(tok)
- {
+ public LiteralExpr(IToken/*!*/ tok, BigNum v, int b)
+ : base(tok) {
+ Contract.Requires(tok != null);
Val = new BvConst(v, b);
}
-
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- if (!(obj is LiteralExpr)) return false;
+
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj is LiteralExpr))
+ return false;
LiteralExpr other = (LiteralExpr)obj;
return object.Equals(this.Val, other.Val);
}
[Pure]
- public override int GetHashCode()
- {
+ public override int GetHashCode() {
return this.Val.GetHashCode();
}
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
stream.SetToken(this);
- if (this.Val is bool)
- {
+ if (this.Val is bool) {
stream.Write((bool)this.Val ? "true" : "false"); // correct capitalization
- }
- else
- {
- stream.Write((!) this.Val.ToString());
+ } else {
+ stream.Write(cce.NonNull(this.Val.ToString()));
}
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
// nothing to resolve
}
- public override void ComputeFreeVariables(Set /*Variable*/! freeVars) {
+ public override void ComputeFreeVariables(Set /*Variable*/ freeVars) {
+ //Contract.Requires(freeVars != null);
// no free variables to add
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
if (Val is BvConst && CommandLineOptions.Clo.Verify && CommandLineOptions.Clo.Bitvectors == CommandLineOptions.BvHandling.None)
tc.Error(this, "no bitvector handling specified, please use /bv:i or /bv:z flag");
this.Type = ShallowType;
}
- public override Type! ShallowType {
+ public override Type/*!*/ ShallowType {
get {
- if (Val is bool)
- {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ if (Val is bool) {
return Type.Bool;
- }
- else if (Val is BigNum)
- {
+ } else if (Val is BigNum) {
return Type.Int;
- }
- else if (Val is BvConst)
- {
+ } else if (Val is BvConst) {
return Type.GetBvType(((BvConst)Val).Bits);
- }
- else
- {
- assert false; // like, where did this value come from?!
+ } else {
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // like, where did this value come from?!
}
}
}
@@ -342,231 +528,250 @@ namespace Microsoft.Boogie
return Val is bool && ((bool)Val) == true;
}
}
- public override AI.IExpr! IExpr {
- get {
- return this;
- }
+ public override AI.IExpr/*!*/ IExpr {
+ get {
+ Contract.Ensures(Contract.Result<AI.IExpr>() != null);
+ return this;
+ }
}
// should be eliminated after converting everything to BigNums
private int asInt {
- get {
- return asBigNum.ToIntSafe;
- }
- }
+ get {
+ return asBigNum.ToIntSafe;
+ }
+ }
public bool isBigNum {
- get {
- return Val is BigNum;
- }
- }
+ get {
+ return Val is BigNum;
+ }
+ }
public BigNum asBigNum {
- get {
- assert isBigNum;
- return (BigNum)(!)Val;
- }
+ get {
+ Contract.Assert(isBigNum);
+ return (BigNum)cce.NonNull(Val);
+ }
}
public bool isBool {
- get {
- return Val is bool;
- }
- }
+ get {
+ return Val is bool;
+ }
+ }
public bool asBool {
- get {
- assert isBool;
- return (bool)(!)Val;
- }
+ get {
+ Contract.Assert(isBool);
+ return (bool)cce.NonNull(Val);
+ }
}
- public AI.IFunctionSymbol! FunctionSymbol {
- get {
- if (Val is bool)
- {
- if ((bool)Val)
- {
- return AI.Prop.True;
- }
- else
- {
- return AI.Prop.False;
- }
- }
- else if (Val is BigNum)
- {
- return AI.Int.Const((BigNum)Val);
- }
- else if (Val is BvConst)
- {
- return AI.Bv.Const(((BvConst)Val).Value, ((BvConst)Val).Bits);
- }
- else
- {
- assert false; // like, where did this value come from?!
- }
+ public AI.IFunctionSymbol/*!*/ FunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+
+ if (Val is bool) {
+ if ((bool)Val) {
+ return AI.Prop.True;
+ } else {
+ return AI.Prop.False;
+ }
+ } else if (Val is BigNum) {
+ return AI.Int.Const((BigNum)Val);
+ } else if (Val is BvConst) {
+ return AI.Bv.Const(((BvConst)Val).Value, ((BvConst)Val).Bits);
+ } else {
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // like, where did this value come from?!
}
+ }
}
- public IList/*<AI.IExpr!>*/! Arguments {
- get {
- return ArrayList.ReadOnly(new AI.IExpr[0]);
- }
+ public IList/*<AI.IExpr!>*//*!*/ Arguments {
+ get {
+ Contract.Ensures(Contract.Result<IList>() != null);
+
+ return ArrayList.ReadOnly(new AI.IExpr[0]);
+ }
}
- public Microsoft.AbstractInterpretationFramework.IFunApp! CloneWithArguments(IList/*<AI.IExpr!>*/! args) {
- assert args.Count == 0;
- return this;
+ public Microsoft.AbstractInterpretationFramework.IFunApp CloneWithArguments(IList/*<AI.IExpr!>*/ args) {
+ Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<Microsoft.AbstractInterpretationFramework.IFunApp>() != null);
+ Contract.Assert(args.Count == 0);
+ return this;
}
- public AI.AIType! AIType {
- get {
- if (Val is bool) {
- return AI.Prop.Type;
- } else if (Val is BigNum) {
- return AI.Int.Type;
- } else if (Val is BvConst) {
- return AI.Bv.Type;
- } else {
- assert false; // like, where did this value come from?!
- }
+ public AI.AIType/*!*/ AIType {
+ get {
+ Contract.Requires(AIType != null);
+ if (Val is bool) {
+ return AI.Prop.Type;
+ } else if (Val is BigNum) {
+ return AI.Int.Type;
+ } else if (Val is BvConst) {
+ return AI.Bv.Type;
+ } else {
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // like, where did this value come from?!
}
+ }
}
[Pure]
- public object DoVisit(AI.ExprVisitor! visitor)
- {
+ public object DoVisit(AI.ExprVisitor visitor) {
+ Contract.Requires(visitor != null);
return visitor.VisitFunApp(this);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitLiteralExpr(this);
}
}
- public class BvConst
- {
+ public class BvConst {
public BigNum Value;
public int Bits;
-
- public BvConst(BigNum v, int b)
- {
- assert v.Signum >= 0;
- Value = v;
- Bits = b;
- }
-
+
+ public BvConst(BigNum v, int b) {
+ Contract.Assert(v.Signum >= 0);
+ Value = v;
+ Bits = b;
+ }
+
[Pure]
- public override string! ToString()
- {
- return Value + "bv" + Bits;
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return Value + "bv" + Bits;
}
-
+
[Pure]
- public string! ToReadableString()
- {
- if (Value > BigNum.FromInt(10000)) {
- string! val = (!)Value.ToString("x");
- int pos = val.Length % 4;
- string! res = "0x" + val.Substring(0, pos);
- while (pos < val.Length) {
- res += "." + val.Substring(pos, 4);
- pos += 4;
- }
- return res + ".bv" + Bits;
- } else
- return ToString();
- }
-
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
+ public string ToReadableString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ if (Value > BigNum.FromInt(10000)) {
+ string val = cce.NonNull(Value.ToString("x"));
+ int pos = val.Length % 4;
+ string res = "0x" + val.Substring(0, pos);
+ Contract.Assert(res != null);
+ while (pos < val.Length) {
+ res += "." + val.Substring(pos, 4);
+ pos += 4;
+ }
+ return res + ".bv" + Bits;
+ } else
+ return ToString();
+ }
+
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
BvConst other = obj as BvConst;
- if (other == null) return false;
+ if (other == null)
+ return false;
return Bits == other.Bits && Value == other.Value;
}
-
- [Pure]
- public override int GetHashCode()
- {
+
+ [Pure]
+ public override int GetHashCode() {
unchecked {
return Value.GetHashCode() ^ Bits;
}
}
}
- public class AIVariableExpr : Expr
- {
-
+ public class AIVariableExpr : Expr {
+
public string Name; // identifier symbol
- public AI.IVariable! Decl; // identifier declaration
+ public AI.IVariable/*!*/ Decl; // identifier declaration
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Decl != null);
+ }
+
/// <summary>
/// Creates an unresolved identifier expression.
/// </summary>
/// <param name="tok"></param>
/// <param name="name"></param>
- public AIVariableExpr(IToken! tok, AI.IVariable! var)
- : base(tok)
- {
+ public AIVariableExpr(IToken/*!*/ tok, AI.IVariable/*!*/ var)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(var != null);
Name = var.ToString();
Decl = var;
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- if (!(obj is AIVariableExpr)) return false;
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj is AIVariableExpr))
+ return false;
AIVariableExpr other = (AIVariableExpr)obj;
return object.Equals(this.Name, other.Name) && object.Equals(this.Decl, other.Decl);
}
- [Pure]
- public override int GetHashCode()
- {
- int h = this.Name == null ? 0 : this.Name.GetHashCode();
- h ^= this.Decl == null ? 0 : this.Decl.GetHashCode();
+ [Pure]
+ public override int GetHashCode() {
+ int h = this.Name == null ? 0 : this.Name.GetHashCode();
+ h ^= this.Decl == null ? 0 : this.Decl.GetHashCode();
return h;
}
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
- if (CommandLineOptions.Clo.PrintWithUniqueASTIds)
- {
- stream.Write("{0}^^", this.Decl == null ? "NoDecl" : "h"+this.Decl.GetHashCode());
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
+ if (CommandLineOptions.Clo.PrintWithUniqueASTIds) {
+ stream.Write("{0}^^", this.Decl == null ? "NoDecl" : "h" + this.Decl.GetHashCode());
}
stream.Write(this, "{0}", this.Name);
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
}
- public override void ComputeFreeVariables(Set /*Variable*/! freeVars) {
+ public override void ComputeFreeVariables(Set /*Variable*/ freeVars) {
+ //Contract.Requires(freeVars != null);
if (Decl is Variable) {
freeVars.Add((Variable)Decl);
}
}
- public override void Typecheck(TypecheckingContext! tc)
- {
- throw new System.NotImplementedException();
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ throw new System.NotImplementedException();
}
- public override Type! ShallowType
- {
- get { throw new System.NotImplementedException(); }
+ public override Type/*!*/ ShallowType {
+ get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+ throw new System.NotImplementedException();
+ }
}
- public override AI.IExpr! IExpr {
- get {
- return Decl;
- }
+ public override AI.IExpr/*!*/ IExpr {
+ get {
+ Contract.Ensures(Contract.Result<AI.IExpr>() != null);
+
+ return Decl;
+ }
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitAIVariableExpr(this);
}
}
-
- public class IdentifierExpr : Expr
- {
- public string! Name; // identifier symbol
+
+ public class IdentifierExpr : Expr {
+ public string/*!*/ Name; // identifier symbol
public Variable Decl; // identifier declaration
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Name != null);
+ }
+
/// <summary>
/// Creates an unresolved identifier expression. This constructor is intended to be called
@@ -575,9 +780,10 @@ namespace Microsoft.Boogie
/// </summary>
/// <param name="tok"></param>
/// <param name="name"></param>
- internal IdentifierExpr(IToken! tok, string! name)
- : base(tok)
- {
+ internal IdentifierExpr(IToken/*!*/ tok, string/*!*/ name)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
Name = name;
// base(tok);
}
@@ -587,55 +793,57 @@ namespace Microsoft.Boogie
/// <param name="tok"></param>
/// <param name="name"></param>
/// <param name="type"></param>
- public IdentifierExpr(IToken! tok, string! name, Type! type)
- : base(tok)
- {
+ public IdentifierExpr(IToken/*!*/ tok, string/*!*/ name, Type/*!*/ type)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(name != null);
+ Contract.Requires(type != null);
Name = name;
Type = type;
// base(tok);
}
-
+
/// <summary>
/// Creates a resolved identifier expression.
/// </summary>
/// <param name="tok"></param>
/// <param name="d"></param>
- public IdentifierExpr(IToken! tok, Variable! d)
- : base(tok)
- {
- Name = (!) d.Name;
+ public IdentifierExpr(IToken/*!*/ tok, Variable/*!*/ d)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(d != null);
+ Name = cce.NonNull(d.Name);
Decl = d;
Type = d.TypedIdent.Type;
// base(tok);
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- if (!(obj is IdentifierExpr)) return false;
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj is IdentifierExpr))
+ return false;
IdentifierExpr other = (IdentifierExpr)obj;
return object.Equals(this.Name, other.Name) && object.Equals(this.Decl, other.Decl);
}
- [Pure]
- public override int GetHashCode()
- {
- int h = this.Name == null ? 0 : this.Name.GetHashCode();
- h ^= this.Decl == null ? 0 : this.Decl.GetHashCode();
+ [Pure]
+ public override int GetHashCode() {
+ int h = this.Name == null ? 0 : this.Name.GetHashCode();
+ h ^= this.Decl == null ? 0 : this.Decl.GetHashCode();
return h;
}
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
- if (CommandLineOptions.Clo.PrintWithUniqueASTIds)
- {
- stream.Write("{0}^^", this.Decl == null ? "NoDecl" : "h"+this.Decl.GetHashCode());
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
+ if (CommandLineOptions.Clo.PrintWithUniqueASTIds) {
+ stream.Write("{0}^^", this.Decl == null ? "NoDecl" : "h" + this.Decl.GetHashCode());
}
stream.Write(this, "{0}", TokenTextWriter.SanitizeIdentifier(this.Name));
}
- public override void Resolve(ResolutionContext! rc)
- {
- if (Decl != null)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ if (Decl != null) {
// already resolved, but re-resolve type just in case it came from an unresolved type
if (Type != null) {
Type = Type.ResolveType(rc);
@@ -652,155 +860,201 @@ namespace Microsoft.Boogie
Type = Type.ResolveType(rc);
}
}
- public override void ComputeFreeVariables(Set /*Variable*/! freeVars) {
- assume this.Decl != null;
+ public override void ComputeFreeVariables(Set /*Variable*/ freeVars) {
+ //Contract.Requires(freeVars != null);
+ Contract.Assume(this.Decl != null);
freeVars.Add(Decl);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
- if (this.Decl != null)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ if (this.Decl != null) {
// sanity check
if (Type != null && !Type.Equals(Decl.TypedIdent.Type)) {
- tc.Error(this, "internal error, shallow-type assignment was done incorrectly, {0}:{1} != {2}",
+ tc.Error(this, "internal error, shallow-type assignment was done incorrectly, {0}:{1} != {2}",
Name, Type, Decl.TypedIdent.Type);
- assert false;
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ }
}
Type = Decl.TypedIdent.Type;
}
}
- public override Type! ShallowType {
+ public override Type/*!*/ ShallowType {
get {
- assert Type != null;
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ Contract.Assert(Type != null);
return Type;
}
}
-
- public sealed class ConstantFunApp : AI.IFunApp
- {
- private IdentifierExpr! identifierExpr;
- public IdentifierExpr! IdentifierExpr { get { return identifierExpr; } }
-
- private AI.IFunctionSymbol! symbol;
- public AI.IFunctionSymbol! FunctionSymbol { get { return symbol; } }
-
- private static IList! emptyArgs = ArrayList.ReadOnly((IList!)new ArrayList());
- public IList! Arguments { get { return emptyArgs; } }
-
- public AI.IFunApp! CloneWithArguments(IList! newargs) { return this; }
-
- [Pure]
- public object DoVisit(AI.ExprVisitor! visitor) { return visitor.VisitFunApp(this); }
-
- public ConstantFunApp(IdentifierExpr! ie, Constant! c)
- {
- this.identifierExpr = ie;
- this.symbol =
- new AI.NamedSymbol(c.TypedIdent.Name, BoogieFactory.Type2AIType(c.TypedIdent.Type));
- // base();
+
+ public sealed class ConstantFunApp : AI.IFunApp {
+ private IdentifierExpr/*!*/ identifierExpr;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(identifierExpr != null);
+ Contract.Invariant(symbol != null);
+ Contract.Invariant(emptyArgs != null);
+ }
+
+ public IdentifierExpr/*!*/ IdentifierExpr {
+ get {
+ Contract.Requires(IdentifierExpr != null);
+ return identifierExpr;
+ }
+ }
+
+ private AI.IFunctionSymbol/*!*/ symbol;
+ public AI.IFunctionSymbol/*!*/ FunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+ return symbol;
+ }
+ }
+
+ private static IList/*!*/ emptyArgs = ArrayList.ReadOnly(cce.NonNull((IList/*!*/)new ArrayList()));
+ public IList/*!*/ Arguments {
+ get {
+ Contract.Ensures(Contract.Result<IList>() != null);
+ return emptyArgs;
}
-
+ }
+
+ public AI.IFunApp CloneWithArguments(IList newargs) {
+ Contract.Requires(newargs != null);
+ Contract.Ensures(Contract.Result<AI.IFunApp>() != null);
+ return this;
+ }
+
+ [Pure]
+ public object DoVisit(AI.ExprVisitor visitor) {
+ Contract.Requires(visitor != null);
+ return visitor.VisitFunApp(this);
+ }
+
+ public ConstantFunApp(IdentifierExpr ie, Constant c) {
+ Contract.Requires(c != null);
+ Contract.Requires(ie != null);
+ this.identifierExpr = ie;
+ this.symbol =
+ new AI.NamedSymbol(c.TypedIdent.Name, BoogieFactory.Type2AIType(c.TypedIdent.Type));
+ // base();
+ }
+
}
private AI.IExpr iexprCache = null;
- public override AI.IExpr! IExpr {
- get
- {
- if (iexprCache == null)
- {
- if (Decl is Constant)
- iexprCache = new ConstantFunApp(this, (Constant)Decl);
- else{
- assume this.Decl != null;
- iexprCache = Decl;
- }
- }
- return iexprCache;
+ public override AI.IExpr/*!*/ IExpr {
+ get {
+ Contract.Ensures(Contract.Result<IExpr>() != null);
+
+ if (iexprCache == null) {
+ if (Decl is Constant)
+ iexprCache = new ConstantFunApp(this, (Constant)Decl);
+ else {
+ Contract.Assume(this.Decl != null);
+ iexprCache = Decl;
+ }
}
+ return iexprCache;
+ }
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitIdentifierExpr(this);
}
}
- public class OldExpr : Expr
- , AI.IFunApp // HACK
+ public class OldExpr : Expr, AI.IFunApp // HACK
{
- public Expr! Expr;
- public OldExpr(IToken! tok, Expr! expr)
- : base(tok)
- {
+ public Expr/*!*/ Expr;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Expr != null);
+ }
+
+ public OldExpr(IToken/*!*/ tok, Expr/*!*/ expr)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(expr != null);
Expr = expr;
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- if (!(obj is OldExpr)) return false;
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj is OldExpr))
+ return false;
OldExpr other = (OldExpr)obj;
return object.Equals(this.Expr, other.Expr);
}
- [Pure]
- public override int GetHashCode()
- {
+ [Pure]
+ public override int GetHashCode() {
return this.Expr == null ? 0 : this.Expr.GetHashCode();
}
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
stream.Write(this, "old(");
this.Expr.Emit(stream);
stream.Write(")");
}
- public override void Resolve(ResolutionContext! rc)
- {
- if (rc.StateMode != ResolutionContext.State.Two)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ if (rc.StateMode != ResolutionContext.State.Two) {
rc.Error(this, "old expressions allowed only in two-state contexts");
}
Expr.Resolve(rc);
}
- public override void ComputeFreeVariables(Set /*Variable*/! freeVars) {
+ public override void ComputeFreeVariables(Set /*Variable*/ freeVars) {
+ //Contract.Requires(freeVars != null);
Expr.ComputeFreeVariables(freeVars);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
Expr.Typecheck(tc);
Type = Expr.Type;
}
- public override Type! ShallowType {
+ public override Type/*!*/ ShallowType {
get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
return Expr.ShallowType;
}
}
- public override AI.IExpr! IExpr {
- get {
-// Put back these lines when "HACK" removed
-// // An Old expression has no AI.IExpr representation
-// assert false;
-// throw new System.Exception(); // make compiler shut up
- return this; // HACK
- }
+ public override AI.IExpr/*!*/ IExpr {
+ get {
+ Contract.Ensures(Contract.Result<IExpr>() != null);
+
+ // Put back these lines when "HACK" removed
+ // // An Old expression has no AI.IExpr representation
+ // {Contract.Assert(false);throw new cce.UnreachableException();}
+ return this; // HACK
+ }
}
[Pure]
- public object DoVisit(AI.ExprVisitor! visitor)
- {
+ public object DoVisit(AI.ExprVisitor visitor) {
+ Contract.Requires(visitor != null);
return visitor.VisitFunApp(this);
}
- public AI.IFunApp! CloneWithArguments(IList/*<IExpr!>*/! args)
- {
- assume args.Count == 1;
- AI.IExpr! iexpr = (AI.IExpr!)args[0];
+ public AI.IFunApp CloneWithArguments(IList/*<IExpr!>*/ args) {
+ Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<AI.IFunApp>() != null);
+ Contract.Assume(args.Count == 1);
+ AI.IExpr/*!*/ iexpr = (AI.IExpr)cce.NonNull(args[0]);
return new OldExpr(Token.NoToken, BoogieFactory.IExpr2Expr(iexpr));
}
private IList/*?*/ argCache = null;
- public IList/*<IExpr!*/! Arguments
- {
+ public IList/*<IExpr!*//*!*/ Arguments {
+
get {
- if (argCache == null)
- {
+ Contract.Ensures(Contract.Result<IList>() != null);
+
+ if (argCache == null) {
IList l = new ArrayList(1);
l.Add(Expr.IExpr);
argCache = ArrayList.ReadOnly(l);
@@ -808,46 +1062,101 @@ namespace Microsoft.Boogie
return argCache;
}
}
- private sealed class OldFunctionSymbol : AI.IFunctionSymbol
- {
- private static AI.AIType! aitype = new AI.FunctionType(AI.Value.Type, AI.Value.Type);
- public AI.AIType! AIType { get { return aitype; } }
- private OldFunctionSymbol() { }
- internal static OldFunctionSymbol! Sym = new OldFunctionSymbol();
+ private sealed class OldFunctionSymbol : AI.IFunctionSymbol {
+ private static AI.AIType/*!*/ aitype = new AI.FunctionType(AI.Value.Type, AI.Value.Type);
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(aitype != null);
+ Contract.Invariant(Sym != null);
+ }
+
+ public AI.AIType/*!*/ AIType {
+ get {
+ Contract.Ensures(Contract.Result<AIType>() != null);
+ return aitype;
+ }
+ }
+ private OldFunctionSymbol() {
+ }
+ internal static OldFunctionSymbol/*!*/ Sym = new OldFunctionSymbol();
+
[Pure]
- public override string! ToString() { return "old"; }
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return "old";
+ }
}
- public AI.IFunctionSymbol! FunctionSymbol
- {
- get { return OldFunctionSymbol.Sym; }
+ public AI.IFunctionSymbol/*!*/ FunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+ return OldFunctionSymbol.Sym;
+ }
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitOldExpr(this);
}
}
-
+ [ContractClass(typeof(IAppliableVisitorContracts<>))]
public interface IAppliableVisitor<T> {
-
- T Visit(UnaryOperator! unaryOperator);
-
- T Visit(BinaryOperator! binaryOperator);
-
- T Visit(FunctionCall! functionCall);
-
- T Visit(MapSelect! mapSelect);
-
- T Visit(MapStore! mapStore);
-
- T Visit(TypeCoercion! typeCoercion);
-
- T Visit(IfThenElse! ifThenElse);
+ T Visit(UnaryOperator/*!*/ unaryOperator);
+ T Visit(BinaryOperator/*!*/ binaryOperator);
+ T Visit(FunctionCall/*!*/ functionCall);
+ T Visit(MapSelect/*!*/ mapSelect);
+ T Visit(MapStore/*!*/ mapStore);
+ T Visit(TypeCoercion/*!*/ typeCoercion);
+ T Visit(IfThenElse/*!*/ ifThenElse);
}
+ [ContractClassFor(typeof(IAppliableVisitor<>))]
+ public abstract class IAppliableVisitorContracts<T> : IAppliableVisitor<T> {
- public interface IAppliable
- {
- string! FunctionName { get; }
+ #region IAppliableVisitor<T> Members
+
+ public T Visit(UnaryOperator unaryOperator) {
+ Contract.Requires(unaryOperator != null);
+ throw new NotImplementedException();
+ }
+
+ public T Visit(BinaryOperator binaryOperator) {
+ Contract.Requires(binaryOperator != null);
+ throw new NotImplementedException();
+ }
+
+ public T Visit(FunctionCall functionCall) {
+ Contract.Requires(functionCall != null);
+ throw new NotImplementedException();
+ }
+
+ public T Visit(MapSelect mapSelect) {
+ Contract.Requires(mapSelect != null);
+ throw new NotImplementedException();
+ }
+
+ public T Visit(MapStore mapStore) {
+ Contract.Requires(mapStore != null);
+ throw new NotImplementedException();
+ }
+
+ public T Visit(TypeCoercion typeCoercion) {
+ Contract.Requires(typeCoercion != null);
+ throw new NotImplementedException();
+ }
+
+ public T Visit(IfThenElse ifThenElse) {
+ Contract.Requires(ifThenElse != null);
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+
+ [ContractClass(typeof(IAppliableContracts))]
+ public interface IAppliable {
+ string/*!*/ FunctionName {
+ get;
+ }
/// <summary>
/// Emits to "stream" the operator applied to the given arguments.
@@ -858,14 +1167,16 @@ namespace Microsoft.Boogie
/// <param name="stream"></param>
/// <param name="contextBindingStrength"></param>
/// <param name="fragileContext"></param>
- void Emit(ExprSeq! args, TokenTextWriter! stream, int contextBindingStrength, bool fragileContext);
+ void Emit(ExprSeq/*!*/ args, TokenTextWriter/*!*/ stream, int contextBindingStrength, bool fragileContext);
- void Resolve(ResolutionContext! rc, Expr! subjectForErrorReporting);
+ void Resolve(ResolutionContext/*!*/ rc, Expr/*!*/ subjectForErrorReporting);
/// <summary>
/// Requires the object to have been properly resolved.
/// </summary>
- int ArgumentCount { get; }
+ int ArgumentCount {
+ get;
+ }
/// <summary>
/// Typechecks the arguments "args" for the Appliable. If the arguments are
@@ -879,251 +1190,426 @@ namespace Microsoft.Boogie
/// </summary>
/// <param name="args"></param>
/// <param name="tc"></param>
- Type Typecheck(ref ExprSeq! args, out TypeParamInstantiation! tpInstantiation, TypecheckingContext! tc);
- ensures args.Length == old(args.Length);
- // requires Microsoft.SpecSharp.Collections.Reductions.Forall{Expr! arg in args; arg.Type != null};
-
+ Type Typecheck(ref ExprSeq/*!*/ args, out TypeParamInstantiation/*!*/ tpInstantiation, TypecheckingContext/*!*/ tc);
+
+ // Contract.Requires( Microsoft.SpecSharp.Collections.Reductions.Forall{Expr! arg in args; arg.Type != null});
+
/// <summary>
/// Returns the result type of the IAppliable, supposing the argument are of the correct types.
/// </summary>
- Type! ShallowType(ExprSeq! args);
-
- AI.IFunctionSymbol! AIFunctionSymbol { get; }
-
- T Dispatch<T>(IAppliableVisitor<T>! visitor);
+ Type/*!*/ ShallowType(ExprSeq/*!*/ args);
+
+ AI.IFunctionSymbol/*!*/ AIFunctionSymbol {
+ get;
+ }
+
+ T Dispatch<T>(IAppliableVisitor<T>/*!*/ visitor);
}
-
- public interface IOverloadedAppliable
- {
- void ResolveOverloading(NAryExpr! expr);
+ [ContractClassFor(typeof(IAppliable))]
+ abstract class IAppliableContracts : IAppliable {
+
+ #region IAppliable Members
+
+ public string FunctionName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ throw new NotImplementedException();
+ }
+ }
+
+ public void Emit(ExprSeq args, TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ Contract.Requires(args != null);
+ Contract.Requires(stream != null);
+ throw new NotImplementedException();
+ }
+
+ public void Resolve(ResolutionContext rc, Expr subjectForErrorReporting) {
+ Contract.Requires(rc != null);
+ Contract.Requires(subjectForErrorReporting != null);
+ throw new NotImplementedException();
+ }
+
+ public int ArgumentCount {
+ get {
+ throw new NotImplementedException();
+ }
+ }
+
+ public Type Typecheck(ref ExprSeq args, out TypeParamInstantiation tpInstantiation, TypecheckingContext tc) {
+ Contract.Requires(args != null);
+ Contract.Requires(tc != null);
+ Contract.Ensures(Contract.ValueAtReturn(out args) != null);
+ Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+ Contract.Ensures(args.Length == Contract.OldValue(args.Length));
+ throw new NotImplementedException();
+ }
+
+ public Type ShallowType(ExprSeq args) {
+ Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ throw new NotImplementedException();
+ }
+
+ public IFunctionSymbol AIFunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+ throw new NotImplementedException();
+ }
+ }
+
+ public T Dispatch<T>(IAppliableVisitor<T> visitor) {
+ Contract.Requires(visitor != null);
+ throw new NotImplementedException();
+ }
+
+ #endregion
}
-
- public class UnaryOperator : IAppliable
- {
- private IToken! tok;
- public enum Opcode { Not };
+
+
+ [ContractClass(typeof(IOverloadedAppliableContracts))]
+ public interface IOverloadedAppliable {
+ void ResolveOverloading(NAryExpr/*!*/ expr);
+ }
+ [ContractClassFor(typeof(IOverloadedAppliable))]
+ public abstract class IOverloadedAppliableContracts : IOverloadedAppliable {
+
+ #region IOverloadedAppliable Members
+
+ void IOverloadedAppliable.ResolveOverloading(NAryExpr expr) {
+ Contract.Requires(expr != null);
+ throw new NotImplementedException();
+ }
+
+ #endregion
+ }
+
+ public class UnaryOperator : IAppliable {
+ private IToken/*!*/ tok;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ }
+
+ public enum Opcode {
+ Not
+ };
private Opcode op;
- public Opcode Op { get { return op; } }
- public UnaryOperator (IToken! tok, Opcode op) { this.tok = tok; this.op = op; }
+ public Opcode Op {
+ get {
+ return op;
+ }
+ }
+ public UnaryOperator(IToken tok, Opcode op) {
+ Contract.Requires(tok != null);
+ this.tok = tok;
+ this.op = op;
+ }
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- if (!(obj is UnaryOperator)) return false;
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj is UnaryOperator))
+ return false;
UnaryOperator other = (UnaryOperator)obj;
return object.Equals(this.op, other.op);
}
- [Pure]
- public override int GetHashCode()
- {
- return (int) this.op;
+ [Pure]
+ public override int GetHashCode() {
+ return (int)this.op;
}
- public string! FunctionName
- {
- get
- {
- switch (this.op)
- {
- case Opcode.Not: return "!";
+ public string/*!*/ FunctionName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+
+ switch (this.op) {
+ case Opcode.Not:
+ return "!";
}
System.Diagnostics.Debug.Fail("unknown unary operator: " + op.ToString());
throw new Exception();
}
}
- public AI.IFunctionSymbol! AIFunctionSymbol {
- get {
- switch (this.op) {
- case Opcode.Not: return AI.Prop.Not;
- }
- System.Diagnostics.Debug.Fail("unknown unary operator: " + op.ToString());
- throw new Exception();
+ public AI.IFunctionSymbol/*!*/ AIFunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+
+ switch (this.op) {
+ case Opcode.Not:
+ return AI.Prop.Not;
}
+ System.Diagnostics.Debug.Fail("unknown unary operator: " + op.ToString());
+ throw new Exception();
+ }
}
- public void Emit(ExprSeq! args, TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
+ public void Emit(ExprSeq args, TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
+ //Contract.Requires(args != null);
stream.SetToken(ref this.tok);
- assert args.Length == 1;
+ Contract.Assert(args.Length == 1);
// determine if parens are needed
int opBindingStrength = 0x60;
bool parensNeeded = opBindingStrength < contextBindingStrength ||
(fragileContext && opBindingStrength == contextBindingStrength);
- if (parensNeeded)
- {
+ if (parensNeeded) {
stream.Write("(");
}
stream.Write(FunctionName);
- ((!)args[0]).Emit(stream, opBindingStrength, false);
- if (parensNeeded)
- {
+ cce.NonNull(args[0]).Emit(stream, opBindingStrength, false);
+ if (parensNeeded) {
stream.Write(")");
}
}
- public void Resolve(ResolutionContext! rc, Expr! subjectForErrorReporting)
- {
+ public void Resolve(ResolutionContext rc, Expr subjectForErrorReporting) {
+ //Contract.Requires(subjectForErrorReporting != null);
+ //Contract.Requires(rc != null);
if (rc.TriggerMode && this.op == Opcode.Not) {
rc.Error(subjectForErrorReporting, "boolean operators are not allowed in triggers");
}
}
- public int ArgumentCount
- {
- get
- {
+ public int ArgumentCount {
+ get {
return 1;
}
}
- public Type Typecheck(ref ExprSeq! args, out TypeParamInstantiation! tpInstantiation, TypecheckingContext! tc)
- {
- assume args.Length == 1;
+ public Type Typecheck(ref ExprSeq args, out TypeParamInstantiation tpInstantiation, TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ //Contract.Requires(args != null);
+ Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+ Contract.Ensures(Contract.ValueAtReturn(out args) != null);
+
+ Contract.Assume(args.Length == 1);
tpInstantiation = SimpleTypeParamInstantiation.EMPTY;
- Type arg0type = (!)((!)args[0]).Type;
- switch (this.op)
- {
+ Type arg0type = cce.NonNull(cce.NonNull(args[0]).Type);
+ switch (this.op) {
case Opcode.Not:
- if (arg0type.Unify(Type.Bool))
- {
+ if (arg0type.Unify(Type.Bool)) {
return Type.Bool;
}
goto BAD_TYPE;
}
System.Diagnostics.Debug.Fail("unknown unary operator: " + op.ToString());
- assert false;
- BAD_TYPE:
- tc.Error(this.tok, "invalid argument type ({1}) to unary operator {0}",
- this.FunctionName, arg0type);
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ }
+ BAD_TYPE:
+ tc.Error(this.tok, "invalid argument type ({1}) to unary operator {0}",
+ this.FunctionName, arg0type);
return null;
}
- public Type! ShallowType(ExprSeq! args) {
+ public Type ShallowType(ExprSeq args) {
+ //Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
switch (this.op) {
case Opcode.Not:
return Type.Bool;
- default:
- assert false; // unexpected unary operator
+ default: {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // unexpected unary operator
}
}
- public object Evaluate (object argument)
- {
- if (argument == null) { return null; }
- switch (this.op)
- {
+ public object Evaluate(object argument) {
+ if (argument == null) {
+ return null;
+ }
+ switch (this.op) {
case Opcode.Not:
- if (argument is bool) { return ! ((bool)argument); }
+ if (argument is bool) {
+ return !((bool)argument);
+ }
throw new System.InvalidOperationException("unary Not only applies to bool");
}
return null; // unreachable
}
-
- public T Dispatch<T>(IAppliableVisitor<T>! visitor) {
+
+ public T Dispatch<T>(IAppliableVisitor<T> visitor) {
+ //Contract.Requires(visitor != null);
return visitor.Visit(this);
}
}
- public class BinaryOperator : IAppliable, IOverloadedAppliable
- {
- private IToken! tok;
- public enum Opcode { Add, Sub, Mul, Div, Mod, Eq, Neq, Gt, Ge, Lt, Le, And, Or, Imp, Iff, Subtype };
+ public class BinaryOperator : IAppliable, IOverloadedAppliable {
+ private IToken/*!*/ tok;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ }
+
+ public enum Opcode {
+ Add,
+ Sub,
+ Mul,
+ Div,
+ Mod,
+ Eq,
+ Neq,
+ Gt,
+ Ge,
+ Lt,
+ Le,
+ And,
+ Or,
+ Imp,
+ Iff,
+ Subtype
+ };
private Opcode op;
- public Opcode Op { get { return op; } }
- public BinaryOperator (IToken! tok, Opcode op) { this.tok = tok; this.op = op; }
+ public Opcode Op {
+ get {
+ return op;
+ }
+ }
+ public BinaryOperator(IToken tok, Opcode op) {
+ Contract.Requires(tok != null);
+ this.tok = tok;
+ this.op = op;
+ }
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- if (!(obj is BinaryOperator)) return false;
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj is BinaryOperator))
+ return false;
BinaryOperator other = (BinaryOperator)obj;
return object.Equals(this.op, other.op);
}
- [Pure]
- public override int GetHashCode()
- {
- return (int) this.op << 1;
+ [Pure]
+ public override int GetHashCode() {
+ return (int)this.op << 1;
}
- public string! FunctionName
- {
- get
- {
- switch (this.op)
- {
- case Opcode.Add: return "+";
- case Opcode.Sub: return "-";
- case Opcode.Mul: return "*";
- case Opcode.Div: return "/";
- case Opcode.Mod: return "%";
- case Opcode.Eq: return "==";
- case Opcode.Neq: return "!=";
- case Opcode.Gt: return ">";
- case Opcode.Ge: return ">=";
- case Opcode.Lt: return "<";
- case Opcode.Le: return "<=";
- case Opcode.And: return "&&";
- case Opcode.Or: return "||";
- case Opcode.Imp: return "==>";
- case Opcode.Iff: return "<==>";
- case Opcode.Subtype: return "<:";
+ public string/*!*/ FunctionName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+
+ switch (this.op) {
+ case Opcode.Add:
+ return "+";
+ case Opcode.Sub:
+ return "-";
+ case Opcode.Mul:
+ return "*";
+ case Opcode.Div:
+ return "/";
+ case Opcode.Mod:
+ return "%";
+ case Opcode.Eq:
+ return "==";
+ case Opcode.Neq:
+ return "!=";
+ case Opcode.Gt:
+ return ">";
+ case Opcode.Ge:
+ return ">=";
+ case Opcode.Lt:
+ return "<";
+ case Opcode.Le:
+ return "<=";
+ case Opcode.And:
+ return "&&";
+ case Opcode.Or:
+ return "||";
+ case Opcode.Imp:
+ return "==>";
+ case Opcode.Iff:
+ return "<==>";
+ case Opcode.Subtype:
+ return "<:";
}
System.Diagnostics.Debug.Fail("unknown binary operator: " + op.ToString());
throw new Exception();
}
}
- public AI.IFunctionSymbol! AIFunctionSymbol {
- get {
- switch (this.op) {
- case Opcode.Add: return AI.Int.Add;
- case Opcode.Sub: return AI.Int.Sub;
- case Opcode.Mul: return AI.Int.Mul;
- case Opcode.Div: return AI.Int.Div;
- case Opcode.Mod: return AI.Int.Mod;
- case Opcode.Eq: return AI.Value.Eq;
- case Opcode.Neq: return AI.Value.Neq;
- case Opcode.Gt: return AI.Int.Greater;
- case Opcode.Ge: return AI.Int.AtLeast;
- case Opcode.Lt: return AI.Int.Less;
- case Opcode.Le: return AI.Int.AtMost;
- case Opcode.And: return AI.Prop.And;
- case Opcode.Or: return AI.Prop.Or;
- case Opcode.Imp: return AI.Prop.Implies;
- case Opcode.Iff: return AI.Value.Eq;
- case Opcode.Subtype: return AI.Value.Subtype;
- }
- System.Diagnostics.Debug.Fail("unknown binary operator: " + op.ToString());
- throw new Exception();
+ public AI.IFunctionSymbol/*!*/ AIFunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+
+ switch (this.op) {
+
+ case Opcode.Add:
+ return AI.Int.Add;
+ case Opcode.Sub:
+ return AI.Int.Sub;
+ case Opcode.Mul:
+ return AI.Int.Mul;
+ case Opcode.Div:
+ return AI.Int.Div;
+ case Opcode.Mod:
+ return AI.Int.Mod;
+ case Opcode.Eq:
+ return AI.Value.Eq;
+ case Opcode.Neq:
+ return AI.Value.Neq;
+ case Opcode.Gt:
+ return AI.Int.Greater;
+ case Opcode.Ge:
+ return AI.Int.AtLeast;
+ case Opcode.Lt:
+ return AI.Int.Less;
+ case Opcode.Le:
+ return AI.Int.AtMost;
+ case Opcode.And:
+ return AI.Prop.And;
+ case Opcode.Or:
+ return AI.Prop.Or;
+ case Opcode.Imp:
+ return AI.Prop.Implies;
+ case Opcode.Iff:
+ return AI.Value.Eq;
+ case Opcode.Subtype:
+ return AI.Value.Subtype;
}
+ System.Diagnostics.Debug.Fail("unknown binary operator: " + op.ToString());
+ throw new Exception();
+ }
}
- public void Emit(ExprSeq! args, TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
+ public void Emit(ExprSeq args, TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
+ //Contract.Requires(args != null);
stream.SetToken(ref this.tok);
- assert args.Length == 2;
+ Contract.Assert(args.Length == 2);
// determine if parens are needed
int opBindingStrength;
bool fragileLeftContext = false; // false means "allow same binding power on left without parens"
bool fragileRightContext = false; // false means "allow same binding power on right without parens"
- switch (this.op)
- {
+ switch (this.op) {
case Opcode.Add:
- opBindingStrength = 0x40; break;
+ opBindingStrength = 0x40;
+ break;
case Opcode.Sub:
- opBindingStrength = 0x40; fragileRightContext = true; break;
+ opBindingStrength = 0x40;
+ fragileRightContext = true;
+ break;
case Opcode.Mul:
- opBindingStrength = 0x50; break;
+ opBindingStrength = 0x50;
+ break;
case Opcode.Div:
- opBindingStrength = 0x50; fragileRightContext = true; break;
+ opBindingStrength = 0x50;
+ fragileRightContext = true;
+ break;
case Opcode.Mod:
- opBindingStrength = 0x50; fragileRightContext = true; break;
+ opBindingStrength = 0x50;
+ fragileRightContext = true;
+ break;
case Opcode.Eq:
case Opcode.Neq:
case Opcode.Gt:
@@ -1135,13 +1621,18 @@ namespace Microsoft.Boogie
fragileLeftContext = fragileRightContext = true;
break;
case Opcode.And:
- opBindingStrength = 0x20; break;
+ opBindingStrength = 0x20;
+ break;
case Opcode.Or:
- opBindingStrength = 0x21; break;
+ opBindingStrength = 0x21;
+ break;
case Opcode.Imp:
- opBindingStrength = 0x10; fragileLeftContext = true; break;
+ opBindingStrength = 0x10;
+ fragileLeftContext = true;
+ break;
case Opcode.Iff:
- opBindingStrength = 0x00; break;
+ opBindingStrength = 0x00;
+ break;
default:
System.Diagnostics.Debug.Fail("unknown binary operator: " + op.ToString());
opBindingStrength = -1; // to please compiler, which refuses to consider whether or not all enumeration cases have been considered!
@@ -1152,23 +1643,21 @@ namespace Microsoft.Boogie
bool parensNeeded = opBS < ctxtBS ||
(opBS == ctxtBS && (opBindingStrength != contextBindingStrength || fragileContext));
- if (parensNeeded)
- {
+ if (parensNeeded) {
stream.Write("(");
}
- ((!)args[0]).Emit(stream, opBindingStrength, fragileLeftContext);
+ cce.NonNull(args[0]).Emit(stream, opBindingStrength, fragileLeftContext);
stream.Write(" {0} ", FunctionName);
- ((!)args[1]).Emit(stream, opBindingStrength, fragileRightContext);
- if (parensNeeded)
- {
+ cce.NonNull(args[1]).Emit(stream, opBindingStrength, fragileRightContext);
+ if (parensNeeded) {
stream.Write(")");
}
}
- public void Resolve(ResolutionContext! rc, Expr! subjectForErrorReporting)
- {
+ public void Resolve(ResolutionContext rc, Expr subjectForErrorReporting) {
+ //Contract.Requires(subjectForErrorReporting != null);
+ //Contract.Requires(rc != null);
if (rc.TriggerMode) {
- switch (this.op)
- {
+ switch (this.op) {
case Opcode.Add:
case Opcode.Sub:
case Opcode.Mul:
@@ -1203,25 +1692,25 @@ namespace Microsoft.Boogie
}
}
}
- public int ArgumentCount
- {
- get
- {
+ public int ArgumentCount {
+ get {
return 2;
}
}
- public Type Typecheck(ref ExprSeq! args, out TypeParamInstantiation! tpInstantiation, TypecheckingContext! tc)
- {
- assert args.Length == 2;
+ public Type Typecheck(ref ExprSeq args, out TypeParamInstantiation tpInstantiation, TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ //Contract.Requires(args != null);
+ Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+ Contract.Ensures(args != null);
+ Contract.Assert(args.Length == 2);
// the default; the only binary operator with a type parameter is equality, but right
// we don't store this parameter because it does not appear necessary
tpInstantiation = SimpleTypeParamInstantiation.EMPTY;
- Expr arg0 = (!)args[0];
- Expr arg1 = (!)args[1];
- Type arg0type = (!)arg0.Type;
- Type arg1type = (!)arg1.Type;
- switch (this.op)
- {
+ Expr arg0 = cce.NonNull(args[0]);
+ Expr arg1 = cce.NonNull(args[1]);
+ Type arg0type = cce.NonNull(arg0.Type);
+ Type arg1type = cce.NonNull(arg1.Type);
+ switch (this.op) {
case Opcode.Add:
case Opcode.Sub:
case Opcode.Mul:
@@ -1229,7 +1718,7 @@ namespace Microsoft.Boogie
case Opcode.Mod:
if (arg0type.Unify(Type.Int) && arg1type.Unify(Type.Int)) {
return Type.Int;
- }
+ }
goto BAD_TYPE;
case Opcode.Eq:
case Opcode.Neq:
@@ -1240,11 +1729,11 @@ namespace Microsoft.Boogie
// quick path
return Type.Bool;
}
- TypeVariableSeq! unifiable = new TypeVariableSeq ();
+ TypeVariableSeq/*!*/ unifiable = new TypeVariableSeq();
unifiable.AddRange(arg0type.FreeVariables);
unifiable.AddRange(arg1type.FreeVariables);
- if (arg0type.Unify(arg1type, unifiable, new Dictionary<TypeVariable!, Type!> ()))
+ if (arg0type.Unify(arg1type, unifiable, new Dictionary<TypeVariable/*!*/, Type/*!*/>()))
return Type.Bool;
goto BAD_TYPE;
case Opcode.Gt:
@@ -1253,7 +1742,7 @@ namespace Microsoft.Boogie
case Opcode.Le:
if (arg0type.Unify(Type.Int) && arg1type.Unify(Type.Int)) {
return Type.Bool;
- }
+ }
goto BAD_TYPE;
case Opcode.And:
case Opcode.Or:
@@ -1261,27 +1750,30 @@ namespace Microsoft.Boogie
case Opcode.Iff:
if (arg0type.Unify(Type.Bool) && arg1type.Unify(Type.Bool)) {
return Type.Bool;
- }
+ }
goto BAD_TYPE;
case Opcode.Subtype:
// Subtype is polymorphically typed and can compare things of
// arbitrary types (but both arguments must have the same type)
- if (arg0type.Unify(arg1type))
- {
+ if (arg0type.Unify(arg1type)) {
return Type.Bool;
}
goto BAD_TYPE;
}
System.Diagnostics.Debug.Fail("unknown binary operator: " + op.ToString());
- assert false;
- BAD_TYPE:
- tc.Error(this.tok, "invalid argument types ({1} and {2}) to binary operator {0}", this.FunctionName, arg0type, arg1type);
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ }
+ BAD_TYPE:
+ tc.Error(this.tok, "invalid argument types ({1} and {2}) to binary operator {0}", this.FunctionName, arg0type, arg1type);
return null;
}
-
- public Type! ShallowType(ExprSeq! args) {
- switch (this.op)
- {
+
+ public Type ShallowType(ExprSeq args) {
+ //Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+ switch (this.op) {
case Opcode.Add:
case Opcode.Sub:
case Opcode.Mul:
@@ -1302,26 +1794,25 @@ namespace Microsoft.Boogie
case Opcode.Subtype:
return Type.Bool;
- default:
- assert false; // unexpected binary operator
+ default: {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // unexpected binary operator
}
}
- public void ResolveOverloading(NAryExpr! expr)
- {
- Expr arg0 = (!) expr.Args[0];
- Expr arg1 = (!) expr.Args[1];
- switch (op)
- {
+ public void ResolveOverloading(NAryExpr expr) {
+ //Contract.Requires(expr != null);
+ Expr arg0 = cce.NonNull(expr.Args[0]);
+ Expr arg1 = cce.NonNull(expr.Args[1]);
+ switch (op) {
case Opcode.Eq:
- if (arg0.Type != null && arg0.Type.IsBool && arg1.Type != null && arg1.Type.IsBool)
- {
+ if (arg0.Type != null && arg0.Type.IsBool && arg1.Type != null && arg1.Type.IsBool) {
expr.Fun = new BinaryOperator(tok, Opcode.Iff);
}
break;
case Opcode.Neq:
- if (arg0.Type != null && arg0.Type.IsBool && arg1.Type != null && arg1.Type.IsBool)
- {
+ if (arg0.Type != null && arg0.Type.IsBool && arg1.Type != null && arg1.Type.IsBool) {
expr.Fun = new BinaryOperator(tok, Opcode.Iff);
arg1 = new NAryExpr(expr.tok, new UnaryOperator(tok, UnaryOperator.Opcode.Not), new ExprSeq(arg1));
@@ -1335,140 +1826,199 @@ namespace Microsoft.Boogie
break;
}
}
-
- public object Evaluate (object e1, object e2)
- {
- if (e1 == null || e2 == null) { return null; }
- switch (this.op)
- {
- case Opcode.Add:
- if (e1 is BigNum && e2 is BigNum) { return ((BigNum)e1)+((BigNum)e2); }
+ public object Evaluate(object e1, object e2) {
+ if (e1 == null || e2 == null) {
+ return null;
+ }
+
+ switch (this.op) {
+ case Opcode.Add:
+ if (e1 is BigNum && e2 is BigNum) {
+ return ((BigNum)e1) + ((BigNum)e2);
+ }
break;
- case Opcode.Sub:
- if (e1 is BigNum && e2 is BigNum) { return ((BigNum)e1)-((BigNum)e2); }
+ case Opcode.Sub:
+ if (e1 is BigNum && e2 is BigNum) {
+ return ((BigNum)e1) - ((BigNum)e2);
+ }
break;
- case Opcode.Mul:
- if (e1 is BigNum && e2 is BigNum) { return ((BigNum)e1)*((BigNum)e2); }
+ case Opcode.Mul:
+ if (e1 is BigNum && e2 is BigNum) {
+ return ((BigNum)e1) * ((BigNum)e2);
+ }
break;
- case Opcode.Div:
- if (e1 is BigNum && e2 is BigNum) { return /* TODO: right semantics? */ ((BigNum)e1)/((BigNum)e2); }
+ case Opcode.Div:
+ if (e1 is BigNum && e2 is BigNum) {
+ return /* TODO: right semantics? */ ((BigNum)e1) / ((BigNum)e2);
+ }
break;
- case Opcode.Mod:
- if (e1 is BigNum && e2 is BigNum) { return /* TODO: right semantics? */ ((BigNum)e1)%((BigNum)e2); }
+ case Opcode.Mod:
+ if (e1 is BigNum && e2 is BigNum) {
+ return /* TODO: right semantics? */ ((BigNum)e1) % ((BigNum)e2);
+ }
break;
- case Opcode.Lt:
- if (e1 is BigNum && e2 is BigNum) { return ((BigNum)e1)<((BigNum)e2); }
+ case Opcode.Lt:
+ if (e1 is BigNum && e2 is BigNum) {
+ return ((BigNum)e1) < ((BigNum)e2);
+ }
break;
- case Opcode.Le:
- if (e1 is BigNum && e2 is BigNum) { return ((BigNum)e1)<=((BigNum)e2); }
+ case Opcode.Le:
+ if (e1 is BigNum && e2 is BigNum) {
+ return ((BigNum)e1) <= ((BigNum)e2);
+ }
break;
- case Opcode.Gt:
- if (e1 is BigNum && e2 is BigNum) { return ((BigNum)e1)>((BigNum)e2); }
+ case Opcode.Gt:
+ if (e1 is BigNum && e2 is BigNum) {
+ return ((BigNum)e1) > ((BigNum)e2);
+ }
break;
- case Opcode.Ge:
- if (e1 is BigNum && e2 is BigNum) { return ((BigNum)e1)>=((BigNum)e2); }
+ case Opcode.Ge:
+ if (e1 is BigNum && e2 is BigNum) {
+ return ((BigNum)e1) >= ((BigNum)e2);
+ }
break;
- case Opcode.And: if (e1 is bool && e2 is bool) { return (bool)e1 && (bool)e2; } break;
- case Opcode.Or: if (e1 is bool && e2 is bool) { return (bool)e1 || (bool)e2; } break;
- case Opcode.Imp: if (e1 is bool && e2 is bool) { return ! (bool)e1 || (bool)e2; } break;
- case Opcode.Iff: if (e1 is bool && e2 is bool) { return e1 == e2; } break;
+ case Opcode.And:
+ if (e1 is bool && e2 is bool) {
+ return (bool)e1 && (bool)e2;
+ }
+ break;
+ case Opcode.Or:
+ if (e1 is bool && e2 is bool) {
+ return (bool)e1 || (bool)e2;
+ }
+ break;
+ case Opcode.Imp:
+ if (e1 is bool && e2 is bool) {
+ return !(bool)e1 || (bool)e2;
+ }
+ break;
+ case Opcode.Iff:
+ if (e1 is bool && e2 is bool) {
+ return e1 == e2;
+ }
+ break;
- case Opcode.Eq: return Equals(e1,e2);
- case Opcode.Neq: return ! Equals(e1,e2);
+ case Opcode.Eq:
+ return Equals(e1, e2);
+ case Opcode.Neq:
+ return !Equals(e1, e2);
- case Opcode.Subtype: throw new System.NotImplementedException();
+ case Opcode.Subtype:
+ throw new System.NotImplementedException();
}
throw new System.InvalidOperationException("bad types to binary operator " + this.op);
}
-
- public T Dispatch<T>(IAppliableVisitor<T>! visitor) {
+
+ public T Dispatch<T>(IAppliableVisitor<T> visitor) {
+ //Contract.Requires(visitor != null);
return visitor.Visit(this);
}
}
- public class FunctionCall : IAppliable, AI.IFunctionSymbol
- {
- private IdentifierExpr! name;
+ public class FunctionCall : IAppliable, AI.IFunctionSymbol {
+ private IdentifierExpr/*!*/ name;
public Function Func;
- public FunctionCall(IdentifierExpr! name) { this.name = name; }
- public FunctionCall(Function! f) { this.Func = f; this.name = new IdentifierExpr(Token.NoToken, f.Name); }
- public string! FunctionName { get { return this.name.Name; } }
+ public FunctionCall(IdentifierExpr name) {
+ Contract.Requires(name != null);
+ this.name = name;
+ }
+ public FunctionCall(Function f) {
+ Contract.Requires(f != null);
+ this.Func = f;
+ this.name = new IdentifierExpr(Token.NoToken, f.Name);
+ }
+ public string/*!*/ FunctionName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return this.name.Name;
+ }
+ }
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(name != null);
+ }
- public AI.IFunctionSymbol! AIFunctionSymbol {
- get {
- if (name.Name == "$typeof") {
- return AI.Value.Typeof;
- } else if (name.Name == "$allocated") {
- return AI.FieldName.Allocated;
- } else {
- return this;
- }
+
+ public AI.IFunctionSymbol/*!*/ AIFunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+
+ if (name.Name == "$typeof") {
+ return AI.Value.Typeof;
+ } else if (name.Name == "$allocated") {
+ return AI.FieldName.Allocated;
+ } else {
+ return this;
}
+ }
}
[Pure]
- public override string! ToString() {
- return name.Name;
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return name.Name;
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
public override bool Equals(object other) {
- FunctionCall fc = other as FunctionCall;
- return fc != null && this.Func == fc.Func;
- }
- [Pure]
- public override int GetHashCode()
- {
- assume this.Func != null;
- return Func.GetHashCode();
- }
-
- public AI.AIType! AIType {
- get
- {
- assume this.Func != null;
- return AI.Value.FunctionType(this.Func.InParams.Length);
- }
+ FunctionCall fc = other as FunctionCall;
+ return fc != null && this.Func == fc.Func;
+ }
+ [Pure]
+ public override int GetHashCode() {
+ Contract.Assume(this.Func != null);
+ return Func.GetHashCode();
}
- virtual public void Emit(ExprSeq! args, TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
+ public AI.AIType/*!*/ AIType {
+ get {
+ Contract.Ensures(Contract.Result<AIType>() != null);
+
+ Contract.Assume(this.Func != null);
+ return AI.Value.FunctionType(this.Func.InParams.Length);
+ }
+ }
+
+ virtual public void Emit(ExprSeq args, TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
+ Contract.Requires(args != null);
this.name.Emit(stream, 0xF0, false);
stream.Write("(");
args.Emit(stream);
stream.Write(")");
}
- public void Resolve(ResolutionContext! rc, Expr! subjectForErrorReporting)
- {
- if (Func != null)
- {
+ public void Resolve(ResolutionContext rc, Expr subjectForErrorReporting) {
+ //Contract.Requires(subjectForErrorReporting != null);
+ Contract.Requires(rc != null);
+ if (Func != null) {
// already resolved
return;
}
Func = rc.LookUpProcedure(name.Name) as Function;
- if (Func == null)
- {
+ if (Func == null) {
rc.Error(this.name, "use of undeclared function: {0}", name.Name);
}
}
- public virtual int ArgumentCount
- {
- get
- {
- assume Func != null; // ArgumentCount requires object to be properly resolved.
+ public virtual int ArgumentCount {
+ get {
+ Contract.Assume(Func != null); // ArgumentCount requires object to be properly resolved.
return Func.InParams.Length;
}
}
- public virtual Type Typecheck(ref ExprSeq! actuals, out TypeParamInstantiation! tpInstantiation, TypecheckingContext! tc)
- {
- assume this.Func != null;
- assume actuals.Length == Func.InParams.Length;
- assume Func.OutParams.Length == 1;
+ public virtual Type Typecheck(ref ExprSeq actuals, out TypeParamInstantiation tpInstantiation, TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ //Contract.Requires(actuals != null);
+ Contract.Ensures(Contract.ValueAtReturn(out actuals) != null);
+ Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+ Contract.Assume(this.Func != null);
+ Contract.Assume(actuals.Length == Func.InParams.Length);
+ Contract.Assume(Func.OutParams.Length == 1);
- List<Type!>! resultingTypeArgs;
+ List<Type/*!*/>/*!*/ resultingTypeArgs;
TypeSeq actualResultType =
Type.CheckArgumentTypes(Func.TypeParameters,
out resultingTypeArgs,
@@ -1476,177 +2026,221 @@ namespace Microsoft.Boogie
actuals,
Func.OutParams.ToTypeSeq,
null,
- // we need some token to report a possibly wrong number of
- // arguments
- actuals.Length > 0 ? ((!)actuals[0]).tok : Token.NoToken,
+ // we need some token to report a possibly wrong number of
+ // arguments
+ actuals.Length > 0 ? cce.NonNull(actuals[0]).tok : Token.NoToken,
"application of " + name.Name,
tc);
-
+
if (actualResultType == null) {
tpInstantiation = SimpleTypeParamInstantiation.EMPTY;
return null;
} else {
- assert actualResultType.Length == 1;
+ Contract.Assert(actualResultType.Length == 1);
tpInstantiation =
SimpleTypeParamInstantiation.From(Func.TypeParameters, resultingTypeArgs);
return actualResultType[0];
}
}
- public Type! ShallowType(ExprSeq! args) {
- assume name.Type != null;
+ public Type ShallowType(ExprSeq args) {
+ //Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+ Contract.Assume(name.Type != null);
return name.Type;
}
-
- public virtual T Dispatch<T>(IAppliableVisitor<T>! visitor) {
+
+ public virtual T Dispatch<T>(IAppliableVisitor<T> visitor) {
+ //Contract.Requires(visitor != null);
return visitor.Visit(this);
}
}
-
+
public class TypeCoercion : IAppliable {
- private IToken! tok;
- public Type! Type;
-
- public TypeCoercion(IToken! tok, Type! type) {
+ private IToken/*!*/ tok;
+ public Type/*!*/ Type;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ }
+
+ public TypeCoercion(IToken tok, Type type) {
+ Contract.Requires(type != null);
+ Contract.Requires(tok != null);
this.tok = tok;
this.Type = type;
}
- public string! FunctionName { get {
- return ":";
- } }
+ public string/*!*/ FunctionName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
- public void Emit(ExprSeq! args, TokenTextWriter! stream,
+ return ":";
+ }
+ }
+
+ public void Emit(ExprSeq/*!*/ args, TokenTextWriter/*!*/ stream,
int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(args != null);
+ //Contract.Requires(stream != null);
stream.SetToken(ref this.tok);
- assert args.Length == 1;
+ Contract.Assert(args.Length == 1);
// determine if parens are needed
int opBindingStrength = 0x90;
bool parensNeeded = opBindingStrength < contextBindingStrength ||
(fragileContext && opBindingStrength == contextBindingStrength);
- if (parensNeeded)
+ if (parensNeeded)
stream.Write("(");
- ((!)args[0]).Emit(stream, opBindingStrength, false);
+ cce.NonNull(args[0]).Emit(stream, opBindingStrength, false);
stream.Write("{0} ", FunctionName);
Type.Emit(stream, 0);
- if (parensNeeded)
+ if (parensNeeded)
stream.Write(")");
}
-
- public void Resolve(ResolutionContext! rc, Expr! subjectForErrorReporting) {
+
+ public void Resolve(ResolutionContext rc, Expr subjectForErrorReporting) {
+ //Contract.Requires(subjectForErrorReporting != null);
+ //Contract.Requires(rc != null);
this.Type = this.Type.ResolveType(rc);
}
- public int ArgumentCount { get {
- return 1;
- } }
+ public int ArgumentCount {
+ get {
+ return 1;
+ }
+ }
+
+ public Type Typecheck(ref ExprSeq/*!*/ args,
+ out TypeParamInstantiation/*!*/ tpInstantiation,
+ TypecheckingContext/*!*/ tc) {
+ //Contract.Requires(args != null);
+ //Contract.Requires(tc != null);
+ Contract.Ensures(args != null);
- public Type Typecheck(ref ExprSeq! args,
- out TypeParamInstantiation! tpInstantiation,
- TypecheckingContext! tc) {
- assume args.Length == 1;
+ Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+
+ Contract.Assume(args.Length == 1);
tpInstantiation = SimpleTypeParamInstantiation.EMPTY;
- if (!this.Type.Unify((!)((!)args[0]).Type))
+ if (!this.Type.Unify(cce.NonNull(cce.NonNull(args[0]).Type)))
tc.Error(this.tok, "{0} cannot be coerced to {1}",
- ((!)args[0]).Type, this.Type);
+ cce.NonNull(args[0]).Type, this.Type);
return this.Type;
}
- public Type! ShallowType(ExprSeq! args) {
+ public Type ShallowType(ExprSeq args) {
+ //Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
return this.Type;
}
- public AI.IFunctionSymbol! AIFunctionSymbol { get {
- // not really clear what should be returned here ...
- // should the operation be completely invisible for the abstract interpretation?
- return AI.Heap.UnsupportedHeapOp;
- } }
-
- public T Dispatch<T>(IAppliableVisitor<T>! visitor) {
+ public AI.IFunctionSymbol/*!*/ AIFunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+
+ // not really clear what should be returned here ...
+ // should the operation be completely invisible for the abstract interpretation?
+ return AI.Heap.UnsupportedHeapOp;
+ }
+ }
+
+ public T Dispatch<T>(IAppliableVisitor<T> visitor) {
+ //Contract.Requires(visitor != null);
return visitor.Visit(this);
}
}
- public class NAryExpr : Expr, AI.IFunApp
- {
- [Additive] [Peer]
- public IAppliable! Fun;
- public ExprSeq! Args;
+ public class NAryExpr : Expr, AI.IFunApp {
+ [Additive]
+ [Peer]
+ public IAppliable/*!*/ Fun;
+ public ExprSeq/*!*/ Args;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Fun != null);
+ Contract.Invariant(Args != null);
+ }
+
// The instantiation of type parameters that is determined during type checking.
// Which type parameters are available depends on the IAppliable
public TypeParamInstantiation TypeParameters = null;
[Captured]
- public NAryExpr(IToken! tok, IAppliable! fun, ExprSeq! args)
- : base(tok)
- {
+ public NAryExpr(IToken/*!*/ tok, IAppliable/*!*/ fun, ExprSeq/*!*/ args)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(fun != null);
+ Contract.Requires(args != null);
Fun = fun;
Args = args;
- assert forall{Expr arg in args; arg != null};
+ Contract.Assert(Contract.ForAll(0, args.Length, index => args[index] != null));
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- if (!(obj is NAryExpr)) return false;
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj is NAryExpr))
+ return false;
NAryExpr other = (NAryExpr)obj;
return object.Equals(this.Fun, other.Fun) && object.Equals(this.Args, other.Args);
}
- [Pure]
- public override int GetHashCode()
- {
+ [Pure]
+ public override int GetHashCode() {
int h = this.Fun.GetHashCode();
h ^= this.Args.GetHashCode();
return h;
}
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
stream.SetToken(this);
Fun.Emit(Args, stream, contextBindingStrength, fragileContext);
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
Fun.Resolve(rc, this);
- foreach (Expr! e in Args)
- {
+ foreach (Expr/*!*/ e in Args) {
+ Contract.Assert(e != null);
e.Resolve(rc);
}
}
- public override void ComputeFreeVariables(Set /*Variable*/! freeVars) {
- foreach (Expr! e in Args) {
+ public override void ComputeFreeVariables(Set /*Variable*/ freeVars) {
+ //Contract.Requires(freeVars != null);
+ foreach (Expr/*!*/ e in Args) {
+ Contract.Assert(e != null);
e.ComputeFreeVariables(freeVars);
}
// also add the free type variables
if (TypeParameters != null) {
- foreach (TypeVariable! var in TypeParameters.FormalTypeParams)
- foreach (TypeVariable! w in TypeParameters[var].FreeVariables)
+ foreach (TypeVariable/*!*/ var in TypeParameters.FormalTypeParams) {
+ Contract.Assert(var != null);
+ foreach (TypeVariable/*!*/ w in TypeParameters[var].FreeVariables) {
+ Contract.Assert(w != null);
freeVars.Add(w);
+ }
+ }
}
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
int prevErrorCount = tc.ErrorCount;
- foreach (Expr! e in Args)
- {
+ foreach (Expr/*!*/ e in Args) {
+ Contract.Assert(e != null);
e.Typecheck(tc);
}
- if (Fun.ArgumentCount != Args.Length)
- {
+ if (Fun.ArgumentCount != Args.Length) {
tc.Error(this, "wrong number of arguments to function: {0} ({1} instead of {2})",
Fun.FunctionName, Args.Length, Fun.ArgumentCount);
- }
- else if (tc.ErrorCount == prevErrorCount &&
- // if the type parameters are set, this node has already been
- // typechecked and does not need to be checked again
- TypeParameters == null)
- {
- TypeParamInstantiation! tpInsts;
+ } else if (tc.ErrorCount == prevErrorCount &&
+ // if the type parameters are set, this node has already been
+ // typechecked and does not need to be checked again
+ TypeParameters == null) {
+ TypeParamInstantiation tpInsts;
Type = Fun.Typecheck(ref Args, out tpInsts, tc);
if (Type != null && Type.IsBv && CommandLineOptions.Clo.Verify && CommandLineOptions.Clo.Bitvectors == CommandLineOptions.BvHandling.None) {
tc.Error(this, "no bitvector handling specified, please use /bv:i or /bv:z flag");
@@ -1654,8 +2248,7 @@ namespace Microsoft.Boogie
TypeParameters = tpInsts;
}
IOverloadedAppliable oa = Fun as IOverloadedAppliable;
- if (oa != null)
- {
+ if (oa != null) {
oa.ResolveOverloading(this);
}
if (Type == null) {
@@ -1663,43 +2256,55 @@ namespace Microsoft.Boogie
Type = new TypeProxy(this.tok, "type_checking_error");
}
}
- public override Type! ShallowType {
+ public override Type/*!*/ ShallowType {
get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
return Fun.ShallowType(Args);
}
}
-
- public override AI.IExpr! IExpr {
- get {
- return this;
- }
+
+ public override AI.IExpr/*!*/ IExpr {
+ get {
+ Contract.Ensures(Contract.Result<IExpr>() != null);
+
+ return this;
+ }
}
- public AI.IFunctionSymbol! FunctionSymbol {
- get {
- return Fun.AIFunctionSymbol;
- }
+ public AI.IFunctionSymbol/*!*/ FunctionSymbol {
+ get {
+
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+
+ return Fun.AIFunctionSymbol;
+ }
}
- public IList/*<AI.IExpr!>*/! Arguments {
- get {
- AI.IExpr[] a = new AI.IExpr[Args.Length];
- for (int i = 0; i < Args.Length; i++) {
- a[i] = ((!)Args[i]).IExpr;
- }
- return ArrayList.ReadOnly(a);
+ public IList/*<AI.IExpr!>*//*!*/ Arguments {
+ get {
+ Contract.Ensures(Contract.Result<IList>() != null);
+
+ AI.IExpr[] a = new AI.IExpr[Args.Length];
+ for (int i = 0; i < Args.Length; i++) {
+ a[i] = cce.NonNull(Args[i]).IExpr;
}
+ return ArrayList.ReadOnly(a);
+ }
}
- public AI.IFunApp! CloneWithArguments(IList/*<AI.IExpr!>*/! args) {
- return new NAryExpr(this.tok, this.Fun, BoogieFactory.IExprArray2ExprSeq(args));
+ public AI.IFunApp CloneWithArguments(IList/*<AI.IExpr!>*/ args) {
+ Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<AI.IFunApp>() != null);
+ return new NAryExpr(this.tok, this.Fun, BoogieFactory.IExprArray2ExprSeq(args));
}
[Pure]
- public object DoVisit(AI.ExprVisitor! visitor)
- {
+ public object DoVisit(AI.ExprVisitor visitor) {
+ Contract.Requires(visitor != null);
return visitor.VisitFunApp(this);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitNAryExpr(this);
}
}
@@ -1707,50 +2312,63 @@ namespace Microsoft.Boogie
public class MapSelect : IAppliable, AI.IFunctionSymbol {
public readonly int Arity;
- private readonly IToken! tok;
+ private readonly IToken/*!*/ tok;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ }
+
- public MapSelect(IToken! tok, int arity) {
+ public MapSelect(IToken tok, int arity) {
+ Contract.Requires(tok != null);
this.tok = tok;
this.Arity = arity;
}
- public string! FunctionName { get {
- return "MapSelect";
- } }
+ public string/*!*/ FunctionName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (!(obj is MapSelect)) return false;
+ return "MapSelect";
+ }
+ }
+
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (!(obj is MapSelect))
+ return false;
MapSelect other = (MapSelect)obj;
return this.Arity == other.Arity;
}
- [Pure]
- public override int GetHashCode()
- {
+ [Pure]
+ public override int GetHashCode() {
return Arity.GetHashCode() * 2823;
}
- public void Emit(ExprSeq! args, TokenTextWriter! stream,
+ public void Emit(ExprSeq/*!*/ args, TokenTextWriter/*!*/ stream,
int contextBindingStrength, bool fragileContext) {
- assume args.Length == Arity + 1;
+ //Contract.Requires(args != null);
+ //Contract.Requires(stream != null);
+ Contract.Assume(args.Length == Arity + 1);
Emit(args, stream, contextBindingStrength, fragileContext, false);
}
- public static void Emit(ExprSeq! args, TokenTextWriter! stream,
+ public static void Emit(ExprSeq/*!*/ args, TokenTextWriter/*!*/ stream,
int contextBindingStrength, bool fragileContext,
bool withRhs) {
+ Contract.Requires(args != null);
+ Contract.Requires(stream != null);
const int opBindingStrength = 0x70;
bool parensNeeded = opBindingStrength < contextBindingStrength ||
(fragileContext && opBindingStrength == contextBindingStrength);
- if (parensNeeded)
- {
+ if (parensNeeded) {
stream.Write("(");
}
- ((!)args[0]).Emit(stream, opBindingStrength, false);
+ cce.NonNull(args[0]).Emit(stream, opBindingStrength, false);
stream.Write("[");
string sep = "";
@@ -1758,45 +2376,56 @@ namespace Microsoft.Boogie
for (int i = 1; i < lastIndex; ++i) {
stream.Write(sep);
sep = ", ";
- ((!)args[i]).Emit(stream);
+ cce.NonNull(args[i]).Emit(stream);
}
if (withRhs) {
stream.Write(" := ");
- ((!)args.Last()).Emit(stream);
+ cce.NonNull(args.Last()).Emit(stream);
}
stream.Write("]");
- if (parensNeeded)
- {
+ if (parensNeeded) {
stream.Write(")");
- }
+ }
}
- public void Resolve(ResolutionContext! rc, Expr! subjectForErrorReporting) {
+ public void Resolve(ResolutionContext rc, Expr subjectForErrorReporting) {
+ //Contract.Requires(subjectForErrorReporting != null);
+ //Contract.Requires(rc != null);
// PR: nothing?
}
- public int ArgumentCount { get {
- return Arity + 1;
- } }
+ public int ArgumentCount {
+ get {
+ return Arity + 1;
+ }
+ }
// it is assumed that each of the arguments has already been typechecked
- public static Type Typecheck(Type! mapType,
- // we just pass an Absy, because in
- // the AssignCmd maps can also be
- // represented by non-expressions
- Absy! map,
- ExprSeq! indexes,
- // the type parameters, in this context, are the parameters of the
- // potentially polymorphic map type. Because it might happen that
- // the whole map type is unknown and represented using a MapTypeProxy,
- // the instantiations given in the following out-parameter are subject
- // to change if further unifications are done.
- out TypeParamInstantiation! tpInstantiation,
- TypecheckingContext! tc,
- IToken! typeCheckingSubject,
- string! opName) {
+ public static Type Typecheck(Type/*!*/ mapType,
+ // we just pass an Absy, because in
+ // the AssignCmd maps can also be
+ // represented by non-expressions
+ Absy/*!*/ map,
+ ExprSeq/*!*/ indexes,
+ // the type parameters, in this context, are the parameters of the
+ // potentially polymorphic map type. Because it might happen that
+ // the whole map type is unknown and represented using a MapTypeProxy,
+ // the instantiations given in the following out-parameter are subject
+ // to change if further unifications are done.
+ out TypeParamInstantiation/*!*/ tpInstantiation,
+ TypecheckingContext/*!*/ tc,
+ IToken/*!*/ typeCheckingSubject,
+ string/*!*/ opName) {
+ Contract.Requires(mapType != null);
+ Contract.Requires(map != null);
+ Contract.Requires(indexes != null);
+ Contract.Requires(tc != null);
+ Contract.Requires(typeCheckingSubject != null);
+ Contract.Requires(opName != null);
+ Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+
mapType = mapType.Expanded;
if (mapType.IsMap && mapType.MapArity != indexes.Length) {
tc.Error(typeCheckingSubject, "wrong number of arguments in {0}: {1} instead of {2}",
@@ -1821,54 +2450,69 @@ namespace Microsoft.Boogie
}
}
- public Type Typecheck(ref ExprSeq! args, out TypeParamInstantiation! tpInstantiation, TypecheckingContext! tc)
- {
- assume args.Length == Arity + 1;
+ public Type Typecheck(ref ExprSeq args, out TypeParamInstantiation tpInstantiation, TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ //Contract.Requires(args != null);
+ Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+ Contract.Assume(args.Length == Arity + 1);
- ExprSeq actualArgs = new ExprSeq ();
+ ExprSeq actualArgs = new ExprSeq();
for (int i = 1; i < args.Length; ++i)
actualArgs.Add(args[i]);
- return Typecheck((!)((!)args[0]).Type, (!)args[0],
+ return Typecheck(cce.NonNull(cce.NonNull(args[0]).Type), cce.NonNull(args[0]),
actualArgs, out tpInstantiation, tc, this.tok, "map select");
}
/// <summary>
/// Returns the result type of the IAppliable, supposing the argument are of the correct types.
/// </summary>
- public Type! ShallowType(ExprSeq! args) {
- Expr a0 = (!)args[0];
+ public Type ShallowType(ExprSeq args) {
+ //Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+ Expr a0 = cce.NonNull(args[0]);
Type a0Type = a0.ShallowType;
if (a0Type == null || !a0Type.IsMap) {
// we are unable to determine the type of the select, so just return an arbitrary type
return Type.Int;
}
MapType mapType = a0Type.AsMap;
- TypeSeq actualArgTypes = new TypeSeq ();
+ TypeSeq actualArgTypes = new TypeSeq();
for (int i = 1; i < args.Length; ++i) {
- actualArgTypes.Add(((!)args[i]).ShallowType);
+ actualArgTypes.Add(cce.NonNull(args[i]).ShallowType);
}
return Type.InferValueType(mapType.TypeParameters, mapType.Arguments, mapType.Result, actualArgTypes);
}
- public AI.IFunctionSymbol! AIFunctionSymbol { get {
+ public AI.IFunctionSymbol/*!*/ AIFunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+
switch (Arity) {
- case 1: return AI.Heap.Select1;
- case 2: return AI.Heap.Select2;
- default:
- // Maps with Arity arguments are not fully supported yet
- return AI.Heap.UnsupportedHeapOp;
+ case 1:
+ return AI.Heap.Select1;
+ case 2:
+ return AI.Heap.Select2;
+ default:
+ // Maps with Arity arguments are not fully supported yet
+ return AI.Heap.UnsupportedHeapOp;
}
- } }
-
- public AI.AIType! AIType {
- [Rep][ResultNotNewlyAllocated]
+ }
+ }
+
+ public AI.AIType/*!*/ AIType {
+ [Rep]
+ [ResultNotNewlyAllocated]
get {
+ Contract.Ensures(Contract.Result<AIType>() != null);
+
return AI.Prop.Type; // THAT is a type? PR: no idea whether this makes sense,
- // but it is the type of select1
- } }
+ // but it is the type of select1
+ }
+ }
- public T Dispatch<T>(IAppliableVisitor<T>! visitor) {
+ public T Dispatch<T>(IAppliableVisitor<T> visitor) {
+ //Contract.Requires(visitor != null);
return visitor.Visit(this);
}
}
@@ -1876,57 +2520,79 @@ namespace Microsoft.Boogie
public class MapStore : IAppliable, AI.IFunctionSymbol {
public readonly int Arity;
- public readonly IToken! tok;
+ public readonly IToken/*!*/ tok;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ }
+
- public MapStore(IToken! tok, int arity) {
+ public MapStore(IToken tok, int arity) {
+ Contract.Requires(tok != null);
this.tok = tok;
this.Arity = arity;
}
- public string! FunctionName { get {
- return "MapStore";
- } }
+ public string/*!*/ FunctionName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (!(obj is MapStore)) return false;
+ return "MapStore";
+ }
+ }
+
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (!(obj is MapStore))
+ return false;
MapStore other = (MapStore)obj;
return this.Arity == other.Arity;
}
- [Pure]
- public override int GetHashCode()
- {
+ [Pure]
+ public override int GetHashCode() {
return Arity.GetHashCode() * 28231;
}
- public void Emit(ExprSeq! args, TokenTextWriter! stream,
+ public void Emit(ExprSeq/*!*/ args, TokenTextWriter/*!*/ stream,
int contextBindingStrength, bool fragileContext) {
- assert args.Length == Arity + 2;
+ //Contract.Requires(args != null);
+ //Contract.Requires(stream != null);
+ Contract.Assert(args.Length == Arity + 2);
MapSelect.Emit(args, stream, contextBindingStrength, fragileContext, true);
}
- public void Resolve(ResolutionContext! rc, Expr! subjectForErrorReporting) {
+ public void Resolve(ResolutionContext rc, Expr subjectForErrorReporting) {
+ //Contract.Requires(subjectForErrorReporting != null);
+ //Contract.Requires(rc != null);
// PR: nothing?
}
- public int ArgumentCount { get {
- return Arity + 2;
- } }
+ public int ArgumentCount {
+ get {
+ return Arity + 2;
+ }
+ }
// it is assumed that each of the arguments has already been typechecked
- public static Type Typecheck(ExprSeq! args, out TypeParamInstantiation! tpInstantiation,
- TypecheckingContext! tc,
- IToken! typeCheckingSubject,
- string! opName) {
+ public static Type Typecheck(ExprSeq/*!*/ args, out TypeParamInstantiation/*!*/ tpInstantiation,
+ TypecheckingContext/*!*/ tc,
+ IToken/*!*/ typeCheckingSubject,
+ string/*!*/ opName) {
+ Contract.Requires(args != null);
+ Contract.Requires(tc != null);
+ Contract.Requires(typeCheckingSubject != null);
+ Contract.Requires(opName != null);
+ Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+
// part of the type checking works exactly as for MapSelect
- ExprSeq! selectArgs = new ExprSeq ();
+ ExprSeq selectArgs = new ExprSeq();
for (int i = 1; i < args.Length - 1; ++i)
selectArgs.Add(args[i]);
Type resultType =
- MapSelect.Typecheck((!)((!)args[0]).Type, (!)args[0],
+ MapSelect.Typecheck(cce.NonNull(cce.NonNull(args[0]).Type), cce.NonNull(args[0]),
selectArgs, out tpInstantiation, tc, typeCheckingSubject, opName);
// check the the rhs has the right type
@@ -1934,49 +2600,65 @@ namespace Microsoft.Boogie
// error messages have already been created by MapSelect.Typecheck
return null;
}
- Type rhsType = (!)((!)args.Last()).Type;
+ Type rhsType = cce.NonNull(cce.NonNull(args.Last()).Type);
if (!resultType.Unify(rhsType)) {
- tc.Error(((!)args.Last()).tok,
+ tc.Error(cce.NonNull(args.Last()).tok,
"right-hand side in {0} with wrong type: {1} (expected: {2})",
opName, rhsType, resultType);
return null;
}
-
- return ((!)args[0]).Type;
+
+ return cce.NonNull(args[0]).Type;
}
- public Type Typecheck(ref ExprSeq! args,
- out TypeParamInstantiation! tpInstantiation,
- TypecheckingContext! tc)
- {
- assert args.Length == Arity + 2;
+ public Type Typecheck(ref ExprSeq/*!*/ args,
+ out TypeParamInstantiation/*!*/ tpInstantiation,
+ TypecheckingContext/*!*/ tc) {
+ //Contract.Requires(args != null);
+ //Contract.Requires(tc != null);
+ Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+ Contract.Ensures(Contract.ValueAtReturn(out args) != null);
+ Contract.Assert(args.Length == Arity + 2);
return Typecheck(args, out tpInstantiation, tc, this.tok, "map store");
}
/// <summary>
/// Returns the result type of the IAppliable, supposing the argument are of the correct types.
/// </summary>
- public Type! ShallowType(ExprSeq! args) {
- return ((!)args[0]).ShallowType;
+ public Type ShallowType(ExprSeq args) {
+ //Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+ return cce.NonNull(args[0]).ShallowType;
}
- public AI.IFunctionSymbol! AIFunctionSymbol { get {
+ public AI.IFunctionSymbol/*!*/ AIFunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+
switch (Arity) {
- case 1: return AI.Heap.Update1;
- case 2: return AI.Heap.Update2;
- default:
- // Maps with Arity arguments are not fully supported yet
- return AI.Heap.UnsupportedHeapOp;
+ case 1:
+ return AI.Heap.Update1;
+ case 2:
+ return AI.Heap.Update2;
+ default:
+ // Maps with Arity arguments are not fully supported yet
+ return AI.Heap.UnsupportedHeapOp;
}
- } }
-
- public AI.AIType! AIType {
- [Rep][ResultNotNewlyAllocated]
+ }
+ }
+
+ public AI.AIType/*!*/ AIType {
+ [Rep]
+ [ResultNotNewlyAllocated]
get {
+ Contract.Ensures(Contract.Result<AIType>() != null);
+
return AI.Heap.Type;
- } }
-
- public T Dispatch<T>(IAppliableVisitor<T>! visitor) {
+ }
+ }
+
+ public T Dispatch<T>(IAppliableVisitor<T> visitor) {
+ //Contract.Requires(visitor != null);
return visitor.Visit(this);
}
}
@@ -1984,63 +2666,81 @@ namespace Microsoft.Boogie
public class IfThenElse : IAppliable, AI.IFunctionSymbol {
- public IToken! tok;
+ public IToken/*!*/ tok;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(tok != null);
+ }
+
- public IfThenElse(IToken! tok) {
+ public IfThenElse(IToken tok) {
+ Contract.Requires(tok != null);
this.tok = tok;
}
- public string! FunctionName { get {
- return "if-then-else";
- } }
+ public string/*!*/ FunctionName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (!(obj is IfThenElse)) return false;
+ return "if-then-else";
+ }
+ }
+
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (!(obj is IfThenElse))
+ return false;
return true;
}
- [Pure]
- public override int GetHashCode()
- {
+ [Pure]
+ public override int GetHashCode() {
return 1;
}
- public void Emit(ExprSeq! args, TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
+ public void Emit(ExprSeq args, TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
+ //Contract.Requires(args != null);
stream.SetToken(ref this.tok);
- assert args.Length == 3;
+ Contract.Assert(args.Length == 3);
stream.Write("(if ");
- ((!)args[0]).Emit(stream, 0x00, false);
+ cce.NonNull(args[0]).Emit(stream, 0x00, false);
stream.Write(" then ");
- ((!)args[1]).Emit(stream, 0x00, false);
+ cce.NonNull(args[1]).Emit(stream, 0x00, false);
stream.Write(" else ");
- ((!)args[2]).Emit(stream, 0x00, false);
+ cce.NonNull(args[2]).Emit(stream, 0x00, false);
stream.Write(")");
}
- public void Resolve(ResolutionContext! rc, Expr! subjectForErrorReporting) {
+ public void Resolve(ResolutionContext rc, Expr subjectForErrorReporting) {
+ //Contract.Requires(subjectForErrorReporting != null);
+ Contract.Requires(rc != null);
// PR: nothing?
}
- public int ArgumentCount { get {
- return 3;
- } }
+ public int ArgumentCount {
+ get {
+ return 3;
+ }
+ }
- public Type Typecheck(ref ExprSeq! args, out TypeParamInstantiation! tpInstantiation, TypecheckingContext! tc)
- {
- assert args.Length == 3;
+ public Type Typecheck(ref ExprSeq args, out TypeParamInstantiation tpInstantiation, TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ //Contract.Requires(args != null);
+ Contract.Ensures(args != null);
+ Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+ Contract.Assert(args.Length == 3);
// the default; the only binary operator with a type parameter is equality, but right
// we don't store this parameter because it does not appear necessary
tpInstantiation = SimpleTypeParamInstantiation.EMPTY;
- Expr arg0 = (!)args[0];
- Expr arg1 = (!)args[1];
- Expr arg2 = (!)args[2];
+ Expr arg0 = cce.NonNull(args[0]);
+ Expr arg1 = cce.NonNull(args[1]);
+ Expr arg2 = cce.NonNull(args[2]);
- if (!((!)arg0.Type).Unify(Type.Bool)) {
+ if (!cce.NonNull(arg0.Type).Unify(Type.Bool)) {
tc.Error(this.tok, "the first argument to if-then-else should be bool, not {0}", arg0.Type);
- } else if (!((!)arg1.Type).Unify((!)arg2.Type)) {
+ } else if (!cce.NonNull(arg1.Type).Unify(cce.NonNull(arg2.Type))) {
tc.Error(this.tok, "branches of if-then-else have incompatible types {0} and {1}", arg1.Type, arg2.Type);
} else {
return arg1.Type;
@@ -2052,60 +2752,87 @@ namespace Microsoft.Boogie
/// <summary>
/// Returns the result type of the IAppliable, supposing the argument are of the correct types.
/// </summary>
- public Type! ShallowType(ExprSeq! args) {
- return ((!)args[1]).ShallowType;
+ public Type ShallowType(ExprSeq args) {
+ //Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+ return cce.NonNull(args[1]).ShallowType;
}
- public AI.IFunctionSymbol! AIFunctionSymbol { get { return this; } }
-
- public AI.AIType! AIType {
- [Rep][ResultNotNewlyAllocated]
+ public AI.IFunctionSymbol/*!*/ AIFunctionSymbol {
get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+ return this;
+ }
+ }
+
+ public AI.AIType/*!*/ AIType {
+ [Rep]
+ [ResultNotNewlyAllocated]
+ get {
+ Contract.Ensures(Contract.Result<AIType>() != null);
+
return AI.Value.FunctionType(3);
- } }
-
- public T Dispatch<T>(IAppliableVisitor<T>! visitor) {
+ }
+ }
+
+ public T Dispatch<T>(IAppliableVisitor<T> visitor) {
+ //Contract.Requires(visitor != null);
return visitor.Visit(this);
}
}
-
- public class CodeExpr : Expr, AI.IUnknown
- {
- public VariableSeq! LocVars;
+
+ public class CodeExpr : Expr, AI.IUnknown {
+ public VariableSeq/*!*/ LocVars;
[Rep]
- public List<Block!>! Blocks;
- public CodeExpr(VariableSeq! localVariables, List<Block!>! blocks)
- : base(Token.NoToken)
- requires 0 < blocks.Count;
- {
+ public List<Block/*!*/>/*!*/ Blocks;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(LocVars != null);
+ Contract.Invariant(cce.NonNullElements(Blocks));
+ }
+
+ public CodeExpr(VariableSeq/*!*/ localVariables, List<Block/*!*/>/*!*/ blocks)
+ : base(Token.NoToken) {
+ Contract.Requires(localVariables != null);
+ Contract.Requires(cce.NonNullElements(blocks));
+ Contract.Requires(0 < blocks.Count);
LocVars = localVariables;
Blocks = blocks;
}
- public override AI.IExpr! IExpr { get { return this; } }
- [Pure] public object DoVisit(AI.ExprVisitor! visitor) { return this; }
-
- public override void ComputeFreeVariables(Set /*Variable*/! freeVars) {
+ public override AI.IExpr/*!*/ IExpr {
+ get {
+ Contract.Ensures(Contract.Result<IExpr>() != null);
+ return this;
+ }
+ }
+ [Pure]
+ public object DoVisit(AI.ExprVisitor visitor) {
+ Contract.Requires(visitor != null);
+ return this;
+ }
+
+ public override void ComputeFreeVariables(Set /*Variable*/ freeVars) {
+ //Contract.Requires(freeVars != null);
// Treat a BlockEexpr as if it has no free variables at all
}
- public override void Emit (TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
//level++;
int level = 0;
stream.WriteLine(level, "|{");
- if (this.LocVars.Length > 0)
- {
+ if (this.LocVars.Length > 0) {
stream.Write(level + 1, "var ");
this.LocVars.Emit(stream);
stream.WriteLine(";");
}
- foreach (Block! b in this.Blocks)
- {
- b.Emit(stream, level+1);
+ foreach (Block/*!*/ b in this.Blocks) {
+ Contract.Assert(b != null);
+ b.Emit(stream, level + 1);
}
stream.WriteLine();
@@ -2115,114 +2842,123 @@ namespace Microsoft.Boogie
stream.WriteLine();
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.PushVarContext();
- foreach (Variable! v in LocVars)
- {
+ foreach (Variable/*!*/ v in LocVars) {
+ Contract.Assert(v != null);
v.Register(rc);
v.Resolve(rc);
}
rc.PushProcedureContext();
- foreach (Block! b in Blocks)
- {
+ foreach (Block/*!*/ b in Blocks) {
+ Contract.Assert(b != null);
b.Register(rc);
}
-
- foreach (Block! b in Blocks)
- {
+
+ foreach (Block/*!*/ b in Blocks) {
+ Contract.Assert(b != null);
b.Resolve(rc);
}
-
+
rc.PopProcedureContext();
rc.PopVarContext();
}
- public override void Typecheck(TypecheckingContext! tc){
- foreach (Variable! v in LocVars){
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ foreach (Variable/*!*/ v in LocVars) {
+ Contract.Assert(v != null);
v.Typecheck(tc);
}
- foreach (Block! b in Blocks){
+ foreach (Block/*!*/ b in Blocks) {
+ Contract.Assert(b != null);
b.Typecheck(tc);
}
this.Type = Type.Bool;
}
- public override Type! ShallowType {
+ public override Type/*!*/ ShallowType {
get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
return Type.Bool;
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitCodeExpr(this);
}
}
+ public class BvExtractExpr : Expr, AI.IFunApp {
+ public /*readonly--except in StandardVisitor*/ Expr/*!*/ Bitvector;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Bitvector != null);
+ }
-
- public class BvExtractExpr : Expr, AI.IFunApp
- {
- public /*readonly--except in StandardVisitor*/ Expr! Bitvector;
public readonly int Start, End;
-
- public BvExtractExpr(IToken! tok, Expr! bv, int end, int start)
- : base(tok)
- {
+
+ public BvExtractExpr(IToken/*!*/ tok, Expr/*!*/ bv, int end, int start)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(bv != null);
Bitvector = bv;
Start = start;
End = end;
// base(tok);
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- if (!(obj is BvExtractExpr)) return false;
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj is BvExtractExpr))
+ return false;
BvExtractExpr other = (BvExtractExpr)obj;
return object.Equals(this.Bitvector, other.Bitvector) &&
this.Start.Equals(other.Start) && this.End.Equals(other.End);
}
- [Pure]
- public override int GetHashCode()
- {
+ [Pure]
+ public override int GetHashCode() {
int h = this.Bitvector.GetHashCode();
h ^= Start * 17 ^ End * 13;
return h;
}
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
stream.SetToken(this);
int opBindingStrength = 0x70;
bool parensNeeded = opBindingStrength < contextBindingStrength ||
(fragileContext && opBindingStrength == contextBindingStrength);
- if (parensNeeded)
- {
+ if (parensNeeded) {
stream.Write("(");
}
Bitvector.Emit(stream, opBindingStrength, false);
stream.Write("[" + End + ":" + Start + "]");
- if (parensNeeded)
- {
+ if (parensNeeded) {
stream.Write(")");
}
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
Bitvector.Resolve(rc);
}
- public override void ComputeFreeVariables(Set /*Variable*/! freeVars) {
+ public override void ComputeFreeVariables(Set /*Variable*/ freeVars) {
+ //Contract.Requires(freeVars != null);
Bitvector.ComputeFreeVariables(freeVars);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
Bitvector.Typecheck(tc);
- assert Bitvector.Type != null; // follows from postcondition of Expr.Typecheck
+ Contract.Assert(Bitvector.Type != null); // follows from postcondition of Expr.Typecheck
if (Start < 0) {
tc.Error(this, "start index in extract must not be negative");
@@ -2242,24 +2978,33 @@ namespace Microsoft.Boogie
Type = new TypeProxy(this.tok, "type_checking_error");
}
}
-
- public override Type! ShallowType {
+
+ public override Type/*!*/ ShallowType {
get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
return Type.GetBvType(End - Start);
}
}
-
- public override AI.IExpr! IExpr {
+
+ public override AI.IExpr/*!*/ IExpr {
get {
+ Contract.Ensures(Contract.Result<IExpr>() != null);
+
return this;
}
}
- public AI.IFunctionSymbol! FunctionSymbol {
- get { return AI.Bv.Extract;
+ public AI.IFunctionSymbol/*!*/ FunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+
+ return AI.Bv.Extract;
}
}
- public IList/*<AI.IExpr!>*/! Arguments {
+ public IList/*<AI.IExpr!>*//*!*/ Arguments {
get {
+ Contract.Ensures(Contract.Result<IList>() != null);
+
AI.IExpr[] a = new AI.IExpr[3];
a[0] = Bitvector.IExpr;
a[1] = new LiteralExpr(Token.NoToken, BigNum.FromInt(End));
@@ -2267,72 +3012,81 @@ namespace Microsoft.Boogie
return ArrayList.ReadOnly(a);
}
}
- public AI.IFunApp! CloneWithArguments(IList/*<AI.IExpr!>*/! args)
- {
- AI.IFunApp! retFun;
-
- if(args.Count == 3)
- {
+ public AI.IFunApp CloneWithArguments(IList/*<AI.IExpr!>*/ args) {
+ Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<AI.IFunApp>() != null);
+ AI.IFunApp retFun;
+
+ if (args.Count == 3) {
retFun = new BvExtractExpr(this.tok,
- BoogieFactory.IExpr2Expr((AI.IExpr!)args[0]),
- ((LiteralExpr!)args[1]).asBigNum.ToIntSafe,
- ((LiteralExpr!)args[2]).asBigNum.ToIntSafe);
- }
- else
- {
- assert false; // If we are something wrong is happended
+ BoogieFactory.IExpr2Expr(cce.NonNull((AI.IExpr)args[0])),
+ cce.NonNull((LiteralExpr/*!*/)args[1]).asBigNum.ToIntSafe,
+ cce.NonNull((LiteralExpr/*!*/)args[2]).asBigNum.ToIntSafe);
+ } else {
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // If we are something wrong is happended
}
return retFun;
}
[Pure]
- public object DoVisit(AI.ExprVisitor! visitor)
- {
+ public object DoVisit(AI.ExprVisitor visitor) {
+ Contract.Requires(visitor != null);
return visitor.VisitFunApp(this);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitBvExtractExpr(this);
}
}
- public class BvConcatExpr : Expr, AI.IFunApp
- {
- public /*readonly--except in StandardVisitor*/ Expr! E0, E1;
-
- public BvConcatExpr(IToken! tok, Expr! e0, Expr! e1)
- : base(tok)
- {
+ public class BvConcatExpr : Expr, AI.IFunApp {
+ public /*readonly--except in StandardVisitor*/ Expr/*!*/ E0, E1;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(E0 != null);
+ Contract.Invariant(E1 != null);
+ }
+
+
+ public BvConcatExpr(IToken/*!*/ tok, Expr/*!*/ e0, Expr/*!*/ e1)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(e0 != null);
+ Contract.Requires(e1 != null);
E0 = e0;
E1 = e1;
// base(tok);
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- if (!(obj is BvConcatExpr)) return false;
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj is BvConcatExpr))
+ return false;
BvConcatExpr other = (BvConcatExpr)obj;
return object.Equals(this.E0, other.E0) && object.Equals(this.E1, other.E1);
}
- [Pure]
- public override int GetHashCode()
- {
+ [Pure]
+ public override int GetHashCode() {
int h = this.E0.GetHashCode() ^ this.E1.GetHashCode() * 17;
return h;
}
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
stream.SetToken(this);
int opBindingStrength = 0x32;
bool parensNeeded = opBindingStrength < contextBindingStrength ||
(fragileContext && opBindingStrength == contextBindingStrength);
- if (parensNeeded)
- {
+ if (parensNeeded) {
stream.Write("(");
}
E0.Emit(stream, opBindingStrength, false);
@@ -2340,26 +3094,26 @@ namespace Microsoft.Boogie
// while this operator is associative, our incomplete axioms in int translation don't
// make much use of it, so better stick to the actual tree shape
E1.Emit(stream, opBindingStrength, true);
- if (parensNeeded)
- {
+ if (parensNeeded) {
stream.Write(")");
}
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
E0.Resolve(rc);
E1.Resolve(rc);
}
- public override void ComputeFreeVariables(Set /*Variable*/! freeVars) {
+ public override void ComputeFreeVariables(Set /*Variable*/ freeVars) {
+ //Contract.Requires(freeVars != null);
E0.ComputeFreeVariables(freeVars);
E1.ComputeFreeVariables(freeVars);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
E0.Typecheck(tc);
- assert E0.Type != null; // follows from postcondition of Expr.Typecheck
+ Contract.Assert(E0.Type != null); // follows from postcondition of Expr.Typecheck
E1.Typecheck(tc);
- assert E1.Type != null; // follows from postcondition of Expr.Typecheck
+ Contract.Assert(E1.Type != null); // follows from postcondition of Expr.Typecheck
if (E0.Type.Unify(new BvTypeProxy(this.tok, "concat0", 0)) && E1.Type.Unify(new BvTypeProxy(this.tok, "concat1", 0))) {
Type = new BvTypeProxy(this.tok, "concat", E0.Type, E1.Type);
@@ -2370,9 +3124,11 @@ namespace Microsoft.Boogie
Type = new TypeProxy(this.tok, "type_checking_error");
}
}
-
- public override Type! ShallowType {
+
+ public override Type/*!*/ ShallowType {
get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
Type t0 = E0.ShallowType;
Type t1 = E1.ShallowType;
int len0 = t0.IsBv ? t0.BvBits : /*expression is not type correct, so just pick an arbitrary number of bits*/0;
@@ -2380,49 +3136,57 @@ namespace Microsoft.Boogie
return Type.GetBvType(len0 + len1);
}
}
-
- public override AI.IExpr! IExpr {
- get {
- return this;
- }
+
+ public override AI.IExpr/*!*/ IExpr {
+ get {
+ Contract.Ensures(Contract.Result<IExpr>() != null);
+
+ return this;
+ }
}
- public AI.IFunctionSymbol! FunctionSymbol {
- get { return AI.Bv.Concat;
- }
+ public AI.IFunctionSymbol/*!*/ FunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<IFunctionSymbol>() != null);
+ return AI.Bv.Concat;
+ }
}
- public IList/*<AI.IExpr!>*/! Arguments {
- get {
- AI.IExpr[] a = new AI.IExpr[2];
- a[0] = E0.IExpr;
- a[1] = E1.IExpr;
- return ArrayList.ReadOnly(a);
- }
+ public IList/*<AI.IExpr!>*//*!*/ Arguments {
+ get {
+ Contract.Ensures(Contract.Result<IList>() != null);
+
+ AI.IExpr[] a = new AI.IExpr[2];
+ a[0] = E0.IExpr;
+ a[1] = E1.IExpr;
+ return ArrayList.ReadOnly(a);
+ }
}
- public AI.IFunApp! CloneWithArguments(IList/*<AI.IExpr!>*/! args)
- {
- AI.IFunApp! retFun;
-
- if(args.Count == 2)
- {
+ public AI.IFunApp CloneWithArguments(IList/*<AI.IExpr!>*/ args) {
+ Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<AI.IFunApp>() != null);
+ AI.IFunApp/*!*/ retFun;
+
+ if (args.Count == 2) {
retFun = new BvConcatExpr(this.tok,
- BoogieFactory.IExpr2Expr((AI.IExpr!)args[0]),
- BoogieFactory.IExpr2Expr((AI.IExpr!)args[1]));
- }
- else
- {
- assert false; // If we are something wrong is happended
+ BoogieFactory.IExpr2Expr(cce.NonNull((AI.IExpr/*!*/)args[0])),
+ BoogieFactory.IExpr2Expr(cce.NonNull((AI.IExpr/*!*/)args[1])));
+ } else {
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // If we are something wrong is happended
}
return retFun;
}
[Pure]
- public object DoVisit(AI.ExprVisitor! visitor)
- {
+ public object DoVisit(AI.ExprVisitor visitor) {
+ //Contract.Requires(visitor != null);
return visitor.VisitFunApp(this);
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitBvConcatExpr(this);
}
}
diff --git a/Source/Core/AbsyQuant.cs b/Source/Core/AbsyQuant.cs
index 7515d37d..c30211ca 100644
--- a/Source/Core/AbsyQuant.cs
+++ b/Source/Core/AbsyQuant.cs
@@ -7,17 +7,16 @@
// BoogiePL - AbsyQuant.cs
//---------------------------------------------------------------------------------------------
-namespace Microsoft.Boogie
-{
+namespace Microsoft.Boogie {
using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Boogie.AbstractInterpretation;
using AI = Microsoft.AbstractInterpretationFramework;
- using Microsoft.Contracts;
+ using System.Diagnostics.Contracts;
using Microsoft.Basetypes;
-
+
//---------------------------------------------------------------------
// Quantifiers and general binders
@@ -28,34 +27,77 @@ namespace Microsoft.Boogie
Exists,
Lambda
}
+ [ContractClassFor(typeof(BinderExpr))]
+ abstract class BinderExprContracts : BinderExpr {
+ public override BinderKind Kind {
+ get {
+ throw new NotImplementedException();
+ }
+ }
+ public BinderExprContracts():base(null,null,null,null,null){
+ }
+
+ public override Microsoft.AbstractInterpretationFramework.IFunctionSymbol FunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<AI.IFunctionSymbol>() != null);
+ throw new NotImplementedException();
+ }
+ }
- public abstract class BinderExpr : Expr
- {
- public TypeVariableSeq! TypeParameters;
- public VariableSeq! Dummies;
+ public override Type ShallowType {
+ get {
+ throw new NotImplementedException();
+ }
+ }
+
+ public override Microsoft.AbstractInterpretationFramework.IExpr IExpr {
+ get {
+ throw new NotImplementedException();
+ }
+ }
+ }
+ [ContractClass(typeof(BinderExprContracts))]
+ public abstract class BinderExpr : Expr {
+ public TypeVariableSeq/*!*/ TypeParameters;
+ public VariableSeq/*!*/ Dummies;
public QKeyValue Attributes;
- public Expr! Body;
+ public Expr/*!*/ Body;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(TypeParameters != null);
+ Contract.Invariant(Dummies != null);
+ Contract.Invariant(Body != null);
+ }
- public BinderExpr(IToken! tok, TypeVariableSeq! typeParameters,
- VariableSeq! dummies, QKeyValue kv, Expr! body)
- requires dummies.Length + typeParameters.Length > 0;
- {
- base(tok);
+ public BinderExpr(IToken/*!*/ tok, TypeVariableSeq/*!*/ typeParameters,
+ VariableSeq/*!*/ dummies, QKeyValue kv, Expr/*!*/ body)
+ : base(tok)//BASEMOVEA
+ {
+ Contract.Requires(tok != null);
+ Contract.Requires(typeParameters != null);
+ Contract.Requires(dummies != null);
+ Contract.Requires(body != null);
+ Contract.Requires(dummies.Length + typeParameters.Length > 0);
+ //base(tok);
TypeParameters = typeParameters;
Dummies = dummies;
Attributes = kv;
Body = body;
}
- abstract public BinderKind Kind { get; }
+ abstract public BinderKind Kind {
+ get;
+ }
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
if (!(obj is BinderExpr) ||
- this.Kind != ((BinderExpr)obj).Kind) return false;
+ this.Kind != ((BinderExpr)obj).Kind)
+ return false;
BinderExpr other = (BinderExpr)obj;
// Note, we consider quantifiers equal modulo the Triggers.
@@ -64,27 +106,26 @@ namespace Microsoft.Boogie
&& object.Equals(this.Body, other.Body);
}
- [Pure]
- public override int GetHashCode()
- {
+ [Pure]
+ public override int GetHashCode() {
int h = this.Dummies.GetHashCode();
// Note, we consider quantifiers equal modulo the Triggers.
h ^= this.Body.GetHashCode();
- h = h*5 + this.TypeParameters.GetHashCode();
+ h = h * 5 + this.TypeParameters.GetHashCode();
h *= ((int)Kind + 1);
return h;
}
- protected virtual void EmitTypeHint(TokenTextWriter! stream)
- {
+ protected virtual void EmitTypeHint(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
}
- protected virtual void EmitTriggers(TokenTextWriter! stream)
- {
+ protected virtual void EmitTriggers(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
}
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength, bool fragileContext)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength, bool fragileContext) {
+ //Contract.Requires(stream != null);
stream.Write(this, "({0}", Kind.ToString().ToLower());
this.EmitTypeHint(stream);
Type.EmitOptionalTypeParams(stream, TypeParameters);
@@ -96,29 +137,31 @@ namespace Microsoft.Boogie
stream.Write(" ");
}
this.EmitTriggers(stream);
-
+
this.Body.Emit(stream);
stream.Write(")");
}
- protected virtual void ResolveTriggers(ResolutionContext! rc)
- {
+ protected virtual void ResolveTriggers(ResolutionContext rc) {
+ Contract.Requires(rc != null);
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
if (rc.TriggerMode) {
rc.Error(this, "quantifiers are not allowed in triggers");
}
int previousTypeBinderState = rc.TypeBinderState;
try {
- foreach (TypeVariable! v in TypeParameters)
+ foreach (TypeVariable/*!*/ v in TypeParameters) {
+ Contract.Assert(v != null);
rc.AddTypeBinder(v);
+ }
rc.PushVarContext();
- foreach (Variable! v in Dummies)
- {
+ foreach (Variable/*!*/ v in Dummies) {
+ Contract.Assert(v != null);
v.Register(rc);
v.Resolve(rc);
}
@@ -128,7 +171,7 @@ namespace Microsoft.Boogie
this.ResolveTriggers(rc);
Body.Resolve(rc);
rc.PopVarContext();
-
+
// establish a canonical order of the type parameters
this.TypeParameters = Type.SortTypeParams(TypeParameters, Dummies.ToTypeSeq, null);
@@ -137,79 +180,101 @@ namespace Microsoft.Boogie
}
}
- public override void ComputeFreeVariables(Set /*Variable*/! freeVars) {
- foreach (Variable! v in Dummies) {
- assert !freeVars[v];
+ public override void ComputeFreeVariables(Set /*Variable*/ freeVars) {
+ //Contract.Requires(freeVars != null);
+ foreach (Variable/*!*/ v in Dummies) {
+ Contract.Assert(v != null);
+ Contract.Assert(!freeVars[v]);
}
Body.ComputeFreeVariables(freeVars);
- foreach (Variable! v in Dummies) {
- foreach (TypeVariable! w in v.TypedIdent.Type.FreeVariables)
+ foreach (Variable/*!*/ v in Dummies) {
+ Contract.Assert(v != null);
+ foreach (TypeVariable/*!*/ w in v.TypedIdent.Type.FreeVariables) {
+ Contract.Assert(w != null);
freeVars.Add(w);
+ }
}
- foreach (Variable! v in Dummies) {
+ foreach (Variable/*!*/ v in Dummies) {
+ Contract.Assert(v != null);
freeVars.Remove(v);
}
- foreach (TypeVariable! v in TypeParameters) {
+ foreach (TypeVariable/*!*/ v in TypeParameters) {
+ Contract.Assert(v != null);
freeVars.Remove(v);
}
}
- protected TypeVariableSeq! GetUnmentionedTypeParameters()
- {
- TypeVariableSeq! dummyParameters = Type.FreeVariablesIn(Dummies.ToTypeSeq);
- TypeVariableSeq! unmentionedParameters = new TypeVariableSeq ();
- foreach (TypeVariable! var in TypeParameters)
+ protected TypeVariableSeq GetUnmentionedTypeParameters() {
+ Contract.Ensures(Contract.Result<TypeVariableSeq>() != null);
+ TypeVariableSeq/*!*/ dummyParameters = Type.FreeVariablesIn(Dummies.ToTypeSeq);
+ Contract.Assert(dummyParameters != null);
+ TypeVariableSeq/*!*/ unmentionedParameters = new TypeVariableSeq();
+ foreach (TypeVariable/*!*/ var in TypeParameters) {
+ Contract.Assert(var != null);
if (!dummyParameters.Has(var))
unmentionedParameters.Add(var);
+ }
return unmentionedParameters;
}
-
- public abstract AI.IFunctionSymbol! FunctionSymbol { get; }
-
- internal sealed class AIQuantifier : AI.IFunApp
- {
- internal readonly AIFunctionRep! arg;
- internal AIQuantifier(BinderExpr! realQuantifier, int dummyIndex)
- : this(new AIFunctionRep(realQuantifier, dummyIndex))
- {
+
+ public abstract AI.IFunctionSymbol/*!*/ FunctionSymbol {
+ get;
+ }
+
+ internal sealed class AIQuantifier : AI.IFunApp {
+ internal readonly AIFunctionRep/*!*/ arg;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(arg != null);
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- if (!(obj is AIQuantifier)) return false;
-
+
+ internal AIQuantifier(BinderExpr/*!*/ realQuantifier, int dummyIndex)
+ : this(new AIFunctionRep(realQuantifier, dummyIndex)) {
+ Contract.Requires(realQuantifier != null);
+ }
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj is AIQuantifier))
+ return false;
+
AIQuantifier other = (AIQuantifier)obj;
return object.Equals(this.arg, other.arg);
}
- [Pure]
- public override int GetHashCode()
- {
+ [Pure]
+ public override int GetHashCode() {
return this.arg.GetHashCode();
}
-
- private AIQuantifier(AIFunctionRep! arg)
- {
+
+ private AIQuantifier(AIFunctionRep arg) {
+ Contract.Requires(arg != null);
this.arg = arg;
// base();
}
-
+
[Pure]
- public object DoVisit(AI.ExprVisitor! visitor)
- {
+ public object DoVisit(AI.ExprVisitor visitor) {
+ Contract.Requires(visitor != null);
return visitor.VisitFunApp(this);
}
-
- public AI.IFunctionSymbol! FunctionSymbol { get { return arg.RealQuantifier.FunctionSymbol; } }
-
+
+ public AI.IFunctionSymbol/*!*/ FunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<AI.IFunctionSymbol>() != null);
+ return arg.RealQuantifier.FunctionSymbol;
+ }
+ }
+
private IList/*?*/ argCache = null;
- public IList/*<IExpr!>*/! Arguments
- {
- get
- {
- if (argCache == null)
- {
+ public IList/*<IExpr!>*//*!*/ Arguments {
+
+ get {
+ Contract.Ensures(Contract.Result<IList>() != null);
+
+ if (argCache == null) {
IList a = new ArrayList(1);
a.Add(arg);
argCache = ArrayList.ReadOnly(a);
@@ -217,81 +282,93 @@ namespace Microsoft.Boogie
return argCache;
}
}
-
- public AI.IFunApp! CloneWithArguments(IList/*<IExpr!>*/! args)
- {
- assume args.Count == 1;
-
+
+ public AI.IFunApp CloneWithArguments(IList/*<IExpr!>*/ args) {
+ Contract.Requires(args != null);
+ Contract.Ensures(Contract.Result<AI.IFunApp>() != null);
+ Contract.Assume(args.Count == 1);
+
AIFunctionRep rep = args[0] as AIFunctionRep;
if (rep != null)
return new AIQuantifier(rep);
else
throw new System.NotImplementedException();
}
-
+
[Pure]
- public override string! ToString()
- {
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
return string.Format("{0}({1})", FunctionSymbol, arg);
}
}
-
- internal sealed class AIFunctionRep : AI.IFunction
- {
- internal readonly BinderExpr! RealQuantifier;
+
+ internal sealed class AIFunctionRep : AI.IFunction {
+ internal readonly BinderExpr/*!*/ RealQuantifier;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(RealQuantifier != null);
+ }
+
private readonly int dummyIndex;
-
- internal AIFunctionRep(BinderExpr! realQuantifier, int dummyIndex)
- {
+
+ internal AIFunctionRep(BinderExpr realQuantifier, int dummyIndex) {
+ Contract.Requires(realQuantifier != null);
this.RealQuantifier = realQuantifier;
this.dummyIndex = dummyIndex;
- assert realQuantifier.TypeParameters.Length == 0; // PR: don't know how to handle this yet
+ Contract.Assert(realQuantifier.TypeParameters.Length == 0); // PR: don't know how to handle this yet
// base();
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object obj)
- {
- if (obj == null) return false;
- if (!(obj is AIFunctionRep)) return false;
-
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object obj) {
+ if (obj == null)
+ return false;
+ if (!(obj is AIFunctionRep))
+ return false;
+
AIFunctionRep other = (AIFunctionRep)obj;
return object.Equals(this.RealQuantifier, other.RealQuantifier) && this.dummyIndex == other.dummyIndex;
}
- [Pure]
- public override int GetHashCode()
- {
+ [Pure]
+ public override int GetHashCode() {
return this.RealQuantifier.GetHashCode() ^ dummyIndex;
}
-
+
[Pure]
- public object DoVisit(AI.ExprVisitor! visitor)
- {
+ public object DoVisit(AI.ExprVisitor visitor) {
+ Contract.Requires(visitor != null);
return visitor.VisitFunction(this);
}
-
- public AI.IVariable! Param
- {
- get { return (!)RealQuantifier.Dummies[dummyIndex]; }
+
+ public AI.IVariable/*!*/ Param {
+
+ get {
+ Contract.Ensures(Contract.Result<AI.IVariable>() != null);
+ return cce.NonNull(RealQuantifier.Dummies[dummyIndex]);
+ }
+ }
+ public AI.AIType/*!*/ ParamType {
+ get {
+ Contract.Ensures(Contract.Result<AI.AIType>() != null);
+ throw new System.NotImplementedException();
+ }
}
- public AI.AIType! ParamType { get { throw new System.NotImplementedException(); } }
-
+
// We lazily convert to 1 dummy per quantifier representation for AIFramework
private AI.IExpr/*?*/ bodyCache = null;
- public AI.IExpr! Body
- {
- get
- {
- if (bodyCache == null)
- {
+ public AI.IExpr/*!*/ Body {
+ get {
+ Contract.Ensures(Contract.Result<AI.IExpr>() != null);
+
+ if (bodyCache == null) {
int dummyi = dummyIndex;
int dummylen = RealQuantifier.Dummies.Length;
- assume dummylen > dummyi;
-
+ Contract.Assume(dummylen > dummyi);
+
// return the actual body if there are no more dummies
if (dummyi + 1 == dummylen)
bodyCache = RealQuantifier.Body.IExpr;
- else
- {
+ else {
AIQuantifier innerquant = new AIQuantifier(RealQuantifier, dummyi + 1);
bodyCache = innerquant;
}
@@ -299,76 +376,83 @@ namespace Microsoft.Boogie
return bodyCache;
}
}
- public AI.IFunction! CloneWithBody(AI.IExpr! body)
- {
+ public AI.IFunction CloneWithBody(AI.IExpr body) {
+ Contract.Requires(body != null);
+ Contract.Ensures(Contract.Result<AI.IFunction>() != null);
BinderExpr realquant;
-
+
AIQuantifier innerquant = body as AIQuantifier;
- if (innerquant == null)
- {
+ if (innerquant == null) {
// new quantifier body, clone the real quantifier
realquant = (BinderExpr)RealQuantifier.Clone();
realquant.Body = BoogieFactory.IExpr2Expr(body);
- }
- else
- {
- if (innerquant.arg.dummyIndex > 0)
- {
+ } else {
+ if (innerquant.arg.dummyIndex > 0) {
realquant = innerquant.arg.RealQuantifier;
- }
- else
- {
+ } else {
realquant = (QuantifierExpr)RealQuantifier.Clone();
- VariableSeq! newdummies = new VariableSeq();
+ VariableSeq/*!*/ newdummies = new VariableSeq();
newdummies.Add(Param);
newdummies.AddRange(innerquant.arg.RealQuantifier.Dummies);
realquant.Dummies = newdummies;
realquant.Body = innerquant.arg.RealQuantifier.Body;
}
}
-
+
return new AIFunctionRep(realquant, dummyIndex);
}
[Pure]
- public override string! ToString()
- {
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
return string.Format("\\{0} :: {1}", Param, Body);
}
}
-
+
private AI.IExpr aiexprCache = null;
- public override AI.IExpr! IExpr {
+ public override AI.IExpr/*!*/ IExpr {
get {
+ Contract.Ensures(Contract.Result<AI.IExpr>() != null);
+
if (TypeParameters.Length > 0)
return new Constant(Token.NoToken, new TypedIdent(Token.NoToken, "anon", Type.Bool));
- if (aiexprCache == null)
- {
+ if (aiexprCache == null) {
aiexprCache = new AIQuantifier(this, 0);
}
return aiexprCache;
}
- }
+ }
}
public class QKeyValue : Absy {
- public readonly string! Key;
- public readonly List<object!>! Params; // each element is either a string or an Expr
+ public readonly string/*!*/ Key;
+ public readonly List<object/*!*/>/*!*/ Params; // each element is either a string or an Expr
public QKeyValue Next;
-
- public QKeyValue(IToken! tok, string! key, [Captured] List<object!>! parameters, QKeyValue next)
- {
- base(tok);
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Key != null);
+ Contract.Invariant(cce.NonNullElements(Params));
+ }
+
+
+ public QKeyValue(IToken tok, string key, [Captured] List<object/*!*/>/*!*/ parameters, QKeyValue next)
+ : base(tok) {//BASEMOVEA
+ Contract.Requires(key != null);
+ Contract.Requires(tok != null);
+ Contract.Requires(cce.NonNullElements(parameters));
+ //:base(tok);
Key = key;
Params = parameters;
Next = next;
}
-
- public void Emit(TokenTextWriter! stream) {
+
+ public void Emit(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
stream.Write("{:");
stream.Write(Key);
string sep = " ";
foreach (object p in Params) {
- stream.Write(sep); sep = ", ";
+ stream.Write(sep);
+ sep = ", ";
if (p is string) {
stream.Write("\"");
stream.Write((string)p);
@@ -379,32 +463,35 @@ namespace Microsoft.Boogie
}
stream.Write("}");
}
-
- public override void Resolve(ResolutionContext! rc) {
+
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
foreach (object p in Params) {
if (p is Expr) {
((Expr)p).Resolve(rc);
}
}
}
-
- public override void Typecheck(TypecheckingContext! tc) {
+
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
foreach (object p in Params) {
if (p is Expr) {
((Expr)p).Typecheck(tc);
}
}
}
- public void AddLast(QKeyValue! other){
+ public void AddLast(QKeyValue other) {
+ Contract.Requires(other != null);
QKeyValue current = this;
- while(current.Next!=null){
+ while (current.Next != null) {
current = current.Next;
}
current.Next = other;
}
// Look for {:name string} in list of attributes.
- public static string? FindStringAttribute(QKeyValue? kv, string! name)
- {
+ public static string FindStringAttribute(QKeyValue kv, string name) {
+ Contract.Requires(name != null);
for (; kv != null; kv = kv.Next) {
if (kv.Key == name) {
if (kv.Params.Count == 1 && kv.Params[0] is string) {
@@ -415,8 +502,8 @@ namespace Microsoft.Boogie
return null;
}
// Look for {:name expr} in list of attributes.
- public static Expr? FindExprAttribute(QKeyValue? kv, string! name)
- {
+ public static Expr FindExprAttribute(QKeyValue kv, string name) {
+ Contract.Requires(name != null);
for (; kv != null; kv = kv.Next) {
if (kv.Key == name) {
if (kv.Params.Count == 1 && kv.Params[0] is Expr) {
@@ -427,8 +514,8 @@ namespace Microsoft.Boogie
return null;
}
// Return 'true' if {:name true} or {:name} is an attribute in 'kv'
- public static bool FindBoolAttribute(QKeyValue? kv, string! name)
- {
+ public static bool FindBoolAttribute(QKeyValue kv, string name) {
+ Contract.Requires(name != null);
for (; kv != null; kv = kv.Next) {
if (kv.Key == name) {
return kv.Params.Count == 0 ||
@@ -438,63 +525,76 @@ namespace Microsoft.Boogie
return false;
}
- public static int FindIntAttribute(QKeyValue? kv, string! name, int defl)
- {
- Expr? e = FindExprAttribute(kv, name);
- LiteralExpr? l = e as LiteralExpr;
+ public static int FindIntAttribute(QKeyValue kv, string name, int defl) {
+ Contract.Requires(name != null);
+ Expr e = FindExprAttribute(kv, name);
+ LiteralExpr l = e as LiteralExpr;
if (l != null && l.isBigNum)
return l.asBigNum.ToIntSafe;
return defl;
}
}
-
+
public class Trigger : Absy {
public readonly bool Pos;
[Rep]
- public ExprSeq! Tr;
- invariant 1 <= Tr.Length;
- invariant !Pos ==> Tr.Length == 1;
+ public ExprSeq/*!*/ Tr;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Tr != null);
+ Contract.Invariant(1 <= Tr.Length);
+ Contract.Invariant(Pos || Tr.Length == 1);
+ }
+
+
public Trigger Next;
-
- public Trigger(IToken! tok, bool pos, ExprSeq! tr)
- requires 1 <= tr.Length;
- requires !pos ==> tr.Length == 1;
- {
- this(tok, pos, tr, null);
- }
-
- public Trigger(IToken! tok, bool pos, ExprSeq! tr, Trigger next)
- : base(tok)
- requires 1 <= tr.Length;
- requires !pos ==> tr.Length == 1;
- {
+
+ public Trigger(IToken tok, bool pos, ExprSeq tr)
+ : this(tok, pos, tr, null) {//BASEMOVEA
+ Contract.Requires(tr != null);
+ Contract.Requires(tok != null);
+ Contract.Requires(1 <= tr.Length);
+ Contract.Requires(pos || tr.Length == 1);
+ //:this(tok, pos, tr, null);
+ }
+
+ public Trigger(IToken/*!*/ tok, bool pos, ExprSeq/*!*/ tr, Trigger next)
+ : base(tok) {
+ Contract.Requires(tok != null);
+ Contract.Requires(tr != null);
+ Contract.Requires(1 <= tr.Length);
+ Contract.Requires(pos || tr.Length == 1);
this.Pos = pos;
this.Tr = tr;
this.Next = next;
// base(tok);
}
- public void Emit(TokenTextWriter! stream) {
+ public void Emit(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
stream.SetToken(this);
- assert this.Tr.Length >= 1;
- string! sep = Pos ? "{ " : "{:nopats ";
- foreach (Expr! e in this.Tr) {
+ Contract.Assert(this.Tr.Length >= 1);
+ string/*!*/ sep = Pos ? "{ " : "{:nopats ";
+ foreach (Expr/*!*/ e in this.Tr) {
+ Contract.Assert(e != null);
stream.Write(sep);
sep = ", ";
e.Emit(stream);
}
stream.Write(" }");
}
- public override void Resolve(ResolutionContext! rc) {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
rc.TriggerMode = true;
- foreach (Expr! e in this.Tr) {
+ foreach (Expr/*!*/ e in this.Tr) {
+ Contract.Assert(e != null);
e.Resolve(rc);
// just a variable by itself is not allowed
if (e is IdentifierExpr) {
rc.Error(e, "a matching pattern must be more than just a variable by itself: {0}", e);
}
-
+
// the free-variable check is performed in the surrounding quantifier expression (because that's
// where the bound variables are known)
}
@@ -504,134 +604,171 @@ namespace Microsoft.Boogie
/// <summary>
/// Add to "freeVars" the free variables in the triggering expressions.
/// </summary>
- public void ComputeFreeVariables(Set /*Variable*/! freeVars) {
- foreach (Expr! e in this.Tr) {
+ public void ComputeFreeVariables(Set /*Variable*/ freeVars) {
+ Contract.Requires(freeVars != null);
+ foreach (Expr/*!*/ e in this.Tr) {
+ Contract.Assert(e != null);
e.ComputeFreeVariables(freeVars);
}
}
- public override void Typecheck(TypecheckingContext! tc) {
- foreach (Expr! e in this.Tr) {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
+ foreach (Expr/*!*/ e in this.Tr) {
+ Contract.Assert(e != null);
e.Typecheck(tc);
}
}
- public void AddLast(Trigger other){
- Trigger current = this;
- while(current.Next!=null){
- current = current.Next;
- }
- current.Next = other;
+ public void AddLast(Trigger other) {
+ Trigger current = this;
+ while (current.Next != null) {
+ current = current.Next;
+ }
+ current.Next = other;
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitTrigger(this);
}
}
+ public class ForallExpr : QuantifierExpr {
+ public ForallExpr(IToken/*!*/ tok, TypeVariableSeq/*!*/ typeParams,
+ VariableSeq/*!*/ dummies, QKeyValue kv, Trigger triggers, Expr/*!*/ body)
+ : base(tok, typeParams, dummies, kv, triggers, body) {//BASEMOVEA
+ Contract.Requires(tok != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(dummies != null);
+ Contract.Requires(body != null);
+ Contract.Requires(dummies.Length + typeParams.Length > 0);
+ //:base(tok, typeParams, dummies, kv, triggers, body); // here for aesthetic reasons
+ }
+ public ForallExpr(IToken tok, VariableSeq dummies, Trigger triggers, Expr body)
+ : base(tok, new TypeVariableSeq(), dummies, null, triggers, body) {//BASEMOVEA
+ Contract.Requires(body != null);
+ Contract.Requires(dummies != null);
+ Contract.Requires(tok != null);
+ Contract.Requires(dummies.Length > 0);
+ //:base(tok, new TypeVariableSeq(), dummies, null, triggers, body); // here for aesthetic reasons
+ }
+ public ForallExpr(IToken tok, VariableSeq dummies, Expr body)
+ : base(tok, new TypeVariableSeq(), dummies, null, null, body) {//BASEMOVEA
+ Contract.Requires(body != null);
+ Contract.Requires(dummies != null);
+ Contract.Requires(tok != null);
+ Contract.Requires(dummies.Length > 0);
+ //:base(tok, new TypeVariableSeq(), dummies, null, null, body); // here for aesthetic reasons
+ }
+ public ForallExpr(IToken tok, TypeVariableSeq typeParams, VariableSeq dummies, Expr body)
+ : base(tok, typeParams, dummies, null, null, body) {//BASEMOVEA
+ Contract.Requires(body != null);
+ Contract.Requires(dummies != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(tok != null);
+ Contract.Requires(dummies.Length + typeParams.Length > 0);
+ //:base(tok, typeParams, dummies, null, null, body); // here for aesthetic reasons
+ }
+ public override AI.IFunctionSymbol/*!*/ FunctionSymbol {
+ get {
+ Contract.Ensures(Contract.Result<AI.IFunctionSymbol>() != null);
- public class ForallExpr : QuantifierExpr
- {
- public ForallExpr(IToken! tok, TypeVariableSeq! typeParams,
- VariableSeq! dummies, QKeyValue kv, Trigger triggers, Expr! body)
- requires dummies.Length + typeParams.Length > 0;
- {
- base(tok, typeParams, dummies, kv, triggers, body); // here for aesthetic reasons
- }
- public ForallExpr(IToken! tok, VariableSeq! dummies, Trigger triggers, Expr! body)
- requires dummies.Length > 0;
- {
- base(tok, new TypeVariableSeq(), dummies, null, triggers, body); // here for aesthetic reasons
- }
- public ForallExpr(IToken! tok, VariableSeq! dummies, Expr! body)
- requires dummies.Length > 0;
- {
- base(tok, new TypeVariableSeq(), dummies, null, null, body); // here for aesthetic reasons
- }
- public ForallExpr(IToken! tok, TypeVariableSeq! typeParams, VariableSeq! dummies, Expr! body)
- requires dummies.Length + typeParams.Length > 0;
- {
- base(tok, typeParams, dummies, null, null, body); // here for aesthetic reasons
- }
- public override AI.IFunctionSymbol! FunctionSymbol
- {
- get {
return AI.Prop.Forall;
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitForallExpr(this);
}
- public override BinderKind Kind { get { return BinderKind.Forall; } }
+ public override BinderKind Kind {
+ get {
+ return BinderKind.Forall;
+ }
+ }
}
-
- public class ExistsExpr : QuantifierExpr
- {
- public ExistsExpr(IToken! tok, TypeVariableSeq! typeParams, VariableSeq! dummies,
- QKeyValue kv, Trigger triggers, Expr! body)
- requires dummies.Length + typeParams.Length > 0;
- {
- base(tok, typeParams, dummies, kv, triggers, body); // here for aesthetic reasons
- }
- public ExistsExpr(IToken! tok, VariableSeq! dummies, Trigger triggers, Expr! body)
- requires dummies.Length > 0;
- {
- base(tok, new TypeVariableSeq (), dummies, null, triggers, body); // here for aesthetic reasons
- }
- public ExistsExpr(IToken! tok, VariableSeq! dummies, Expr! body)
- requires dummies.Length > 0;
- {
- base(tok, new TypeVariableSeq(), dummies, null, null, body); // here for aesthetic reasons
- }
- public override AI.IFunctionSymbol! FunctionSymbol
- {
+ public class ExistsExpr : QuantifierExpr {
+ public ExistsExpr(IToken/*!*/ tok, TypeVariableSeq/*!*/ typeParams, VariableSeq/*!*/ dummies,
+ QKeyValue kv, Trigger triggers, Expr/*!*/ body)
+ : base(tok, typeParams, dummies, kv, triggers, body) {//BASEMOVEA
+ Contract.Requires(tok != null);
+ Contract.Requires(typeParams != null);
+ Contract.Requires(dummies != null);
+ Contract.Requires(body != null);
+ Contract.Requires(dummies.Length + typeParams.Length > 0);
+ //:base(tok, typeParams, dummies, kv, triggers, body); // here for aesthetic reasons
+ }
+ public ExistsExpr(IToken tok, VariableSeq dummies, Trigger triggers, Expr body)
+ : base(tok, new TypeVariableSeq(), dummies, null, triggers, body) {//BASEMOVEA
+ Contract.Requires(body != null);
+ Contract.Requires(dummies != null);
+ Contract.Requires(tok != null);
+ Contract.Requires(dummies.Length > 0);
+ //:base(tok, new TypeVariableSeq(), dummies, null, triggers, body); // here for aesthetic reasons
+ }
+ public ExistsExpr(IToken tok, VariableSeq dummies, Expr body)
+ : base(tok, new TypeVariableSeq(), dummies, null, null, body) {//BASEMOVEA
+ Contract.Requires(body != null);
+ Contract.Requires(dummies != null);
+ Contract.Requires(tok != null);
+ Contract.Requires(dummies.Length > 0);
+ //:base(tok, new TypeVariableSeq(), dummies, null, null, body); // here for aesthetic reasons
+ }
+ public override AI.IFunctionSymbol/*!*/ FunctionSymbol {
get {
+ Contract.Ensures(Contract.Result<AI.IFunctionSymbol>() != null);
+
return AI.Prop.Exists;
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitExistsExpr(this);
}
- public override BinderKind Kind { get { return BinderKind.Exists; } }
+ public override BinderKind Kind {
+ get {
+ return BinderKind.Exists;
+ }
+ }
}
-
-
- public abstract class QuantifierExpr : BinderExpr
- {
+ public abstract class QuantifierExpr : BinderExpr {
public Trigger Triggers;
static int SkolemIds = 0;
- public static int GetNextSkolemId()
- {
+ public static int GetNextSkolemId() {
SkolemIds++;
return SkolemIds;
}
-
+
public readonly int SkolemId;
-
- public QuantifierExpr(IToken! tok, TypeVariableSeq! typeParameters,
- VariableSeq! dummies, QKeyValue kv, Trigger triggers, Expr! body)
- requires dummies.Length + typeParameters.Length > 0;
- {
- base(tok, typeParameters, dummies, kv, body);
-
- assert (this is ForallExpr) || (this is ExistsExpr);
-
+
+ public QuantifierExpr(IToken/*!*/ tok, TypeVariableSeq/*!*/ typeParameters,
+ VariableSeq/*!*/ dummies, QKeyValue kv, Trigger triggers, Expr/*!*/ body)
+ : base(tok, typeParameters, dummies, kv, body) {//BASEMOVEA
+ Contract.Requires(tok != null);
+ Contract.Requires(typeParameters != null);
+ Contract.Requires(dummies != null);
+ Contract.Requires(body != null);
+ Contract.Requires(dummies.Length + typeParameters.Length > 0);
+ //:base(tok, typeParameters, dummies, kv, body);
+
+ Contract.Assert((this is ForallExpr) || (this is ExistsExpr));
+
Triggers = triggers;
SkolemId = SkolemIds++;
}
- protected override void EmitTriggers(TokenTextWriter! stream)
- {
+ protected override void EmitTriggers(TokenTextWriter stream) {
+ //Contract.Requires(stream != null);
for (Trigger tr = this.Triggers; tr != null; tr = tr.Next) {
tr.Emit(stream);
stream.Write(" ");
@@ -640,8 +777,7 @@ namespace Microsoft.Boogie
// if the user says ( forall x :: forall y :: { f(x,y) } ... ) we transform it to
// (forall x, y :: { f(x,y) } ... ) otherwise the prover ignores the trigger
- private void MergeAdjecentQuantifier()
- {
+ private void MergeAdjecentQuantifier() {
QuantifierExpr qbody = Body as QuantifierExpr;
if (!(qbody != null && (qbody is ForallExpr) == (this is ForallExpr) && Triggers == null)) {
return;
@@ -668,18 +804,23 @@ namespace Microsoft.Boogie
}
#region never triggers
- private class NeverTriggerCollector : StandardVisitor
- {
- QuantifierExpr! parent;
- public NeverTriggerCollector(QuantifierExpr! p)
- {
+ private class NeverTriggerCollector : StandardVisitor {
+ QuantifierExpr/*!*/ parent;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(parent != null);
+ }
+
+ public NeverTriggerCollector(QuantifierExpr p) {
+ Contract.Requires(p != null);
parent = p;
}
- public override Expr! VisitNAryExpr(NAryExpr! node)
- {
+ public override Expr VisitNAryExpr(NAryExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
FunctionCall fn = node.Fun as FunctionCall;
- if (fn != null && ((!)fn.Func).NeverTrigger) {
+ if (fn != null && cce.NonNull(fn.Func).NeverTrigger) {
parent.Triggers = new Trigger(fn.Func.tok, false, new ExprSeq(node), parent.Triggers);
}
return base.VisitNAryExpr(node);
@@ -687,15 +828,16 @@ namespace Microsoft.Boogie
}
private bool neverTriggerApplied;
- private void ApplyNeverTriggers()
- {
+ private void ApplyNeverTriggers() {
if (neverTriggerApplied) {
return;
}
neverTriggerApplied = true;
for (Trigger t = Triggers; t != null; t = t.Next) {
- if (t.Pos) { return; }
+ if (t.Pos) {
+ return;
+ }
}
NeverTriggerCollector visitor = new NeverTriggerCollector(this);
@@ -703,8 +845,8 @@ namespace Microsoft.Boogie
}
#endregion
- protected override void ResolveTriggers(ResolutionContext! rc)
- {
+ protected override void ResolveTriggers(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
for (Trigger tr = this.Triggers; tr != null; tr = tr.Next) {
int prevErrorCount = rc.ErrorCount;
tr.Resolve(rc);
@@ -713,7 +855,8 @@ namespace Microsoft.Boogie
if (tr.Pos) {
Set /*Variable*/ freeVars = new Set /*Variable*/ ();
tr.ComputeFreeVariables(freeVars);
- foreach (Variable! v in Dummies) {
+ foreach (Variable/*!*/ v in Dummies) {
+ Contract.Assert(v != null);
if (!freeVars[v]) {
rc.Error(tr, "trigger must mention all quantified variables, but does not mention: {0}", v);
}
@@ -723,10 +866,10 @@ namespace Microsoft.Boogie
}
}
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
int oldErrorCount = rc.ErrorCount;
-
+
this.MergeAdjecentQuantifier();
base.Resolve(rc);
@@ -737,8 +880,8 @@ namespace Microsoft.Boogie
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
for (QKeyValue kv = this.Attributes; kv != null; kv = kv.Next) {
kv.Typecheck(tc);
}
@@ -746,9 +889,8 @@ namespace Microsoft.Boogie
tr.Typecheck(tc);
}
Body.Typecheck(tc);
- assert Body.Type != null; // follows from postcondition of Expr.Typecheck
- if (!Body.Type.Unify(Type.Bool))
- {
+ Contract.Assert(Body.Type != null); // follows from postcondition of Expr.Typecheck
+ if (!Body.Type.Unify(Type.Bool)) {
tc.Error(this, "quantifier body must be of type bool");
}
this.Type = Type.Bool;
@@ -756,7 +898,8 @@ namespace Microsoft.Boogie
// Check that type parameters occur in the types of the
// dummies, or otherwise in the triggers. This can only be
// done after typechecking
- TypeVariableSeq! unmentionedParameters = GetUnmentionedTypeParameters();
+ TypeVariableSeq/*!*/ unmentionedParameters = GetUnmentionedTypeParameters();
+ Contract.Assert(unmentionedParameters != null);
if (unmentionedParameters.Length > 0) {
// all the type parameters that do not occur in dummy types
@@ -767,7 +910,8 @@ namespace Microsoft.Boogie
if (tr.Pos) {
Set /*Variable*/ freeVars = new Set /*Variable*/ ();
tr.ComputeFreeVariables(freeVars);
- foreach (TypeVariable! v in unmentionedParameters) {
+ foreach (TypeVariable/*!*/ v in unmentionedParameters) {
+ Contract.Assert(v != null);
if (!freeVars[v])
tc.Error(tr,
"trigger does not mention {0}, which does not occur in variables types either",
@@ -777,41 +921,51 @@ namespace Microsoft.Boogie
}
}
}
- public override Type! ShallowType {
+ public override Type/*!*/ ShallowType {
get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
return Type.Bool;
}
}
-
+
}
- public class LambdaExpr : BinderExpr
- {
- public LambdaExpr(IToken! tok, TypeVariableSeq! typeParameters,
- VariableSeq! dummies, QKeyValue kv, Expr! body)
- requires dummies.Length + typeParameters.Length > 0;
- {
- base(tok, typeParameters, dummies, kv, body);
+ public class LambdaExpr : BinderExpr {
+ public LambdaExpr(IToken/*!*/ tok, TypeVariableSeq/*!*/ typeParameters,
+ VariableSeq/*!*/ dummies, QKeyValue kv, Expr/*!*/ body)
+ : base(tok, typeParameters, dummies, kv, body) {//BASEMOVEA
+ Contract.Requires(tok != null);
+ Contract.Requires(typeParameters != null);
+ Contract.Requires(dummies != null);
+ Contract.Requires(body != null);
+ Contract.Requires(dummies.Length + typeParameters.Length > 0);
+ //:base(tok, typeParameters, dummies, kv, body);
}
- public override BinderKind Kind { get { return BinderKind.Lambda; } }
+ public override BinderKind Kind {
+ get {
+ return BinderKind.Lambda;
+ }
+ }
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
base.Resolve(rc);
}
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
for (QKeyValue kv = this.Attributes; kv != null; kv = kv.Next) {
kv.Typecheck(tc);
}
Body.Typecheck(tc);
- assert Body.Type != null; // follows from postcondition of Expr.Typecheck
+ Contract.Assert(Body.Type != null); // follows from postcondition of Expr.Typecheck
- TypeSeq! argTypes = new TypeSeq();
- foreach (Variable! v in Dummies) {
+ TypeSeq/*!*/ argTypes = new TypeSeq();
+ foreach (Variable/*!*/ v in Dummies) {
+ Contract.Assert(v != null);
argTypes.Add(v.TypedIdent.Type);
}
this.Type = new MapType(this.tok, this.TypeParameters, argTypes, Body.Type);
@@ -819,19 +973,23 @@ namespace Microsoft.Boogie
// Check that type parameters occur in the types of the
// dummies, or otherwise in the triggers. This can only be
// done after typechecking
- TypeVariableSeq! unmentionedParameters = GetUnmentionedTypeParameters();
+ TypeVariableSeq/*!*/ unmentionedParameters = GetUnmentionedTypeParameters();
+ Contract.Assert(unmentionedParameters != null);
if (unmentionedParameters.Length > 0) {
tc.Error(this, "the type variable {0} does not occur in types of the lambda parameters", unmentionedParameters[0]);
}
}
- private Type? mapType;
- public override Type! ShallowType {
+ private Type mapType;
+ public override Type/*!*/ ShallowType {
get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
if (mapType == null) {
- TypeSeq! argTypes = new TypeSeq();
- foreach (Variable! v in Dummies) {
+ TypeSeq/*!*/ argTypes = new TypeSeq();
+ foreach (Variable/*!*/ v in Dummies) {
+ Contract.Assert(v != null);
argTypes.Add(v.TypedIdent.Type);
}
mapType = new MapType(this.tok, this.TypeParameters, argTypes, Body.ShallowType);
@@ -840,21 +998,21 @@ namespace Microsoft.Boogie
return mapType;
}
}
-
- public override AI.IFunctionSymbol! FunctionSymbol
- {
+
+ public override AI.IFunctionSymbol/*!*/ FunctionSymbol {
+
get {
+ Contract.Ensures(Contract.Result<AI.IFunctionSymbol>() != null);
+
return AI.Prop.Lambda;
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitLambdaExpr(this);
}
}
-
-
-}
-
+} \ No newline at end of file
diff --git a/Source/Core/AbsyType.cs b/Source/Core/AbsyType.cs
index 55b8913f..7f3baa67 100644
--- a/Source/Core/AbsyType.cs
+++ b/Source/Core/AbsyType.cs
@@ -7,24 +7,23 @@
// BoogiePL - Absy.cs
//---------------------------------------------------------------------------------------------
-namespace Microsoft.Boogie
-{
+namespace Microsoft.Boogie {
using System;
using System.Collections;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Boogie.AbstractInterpretation;
using AI = Microsoft.AbstractInterpretationFramework;
- using Microsoft.Contracts;
+ using System.Diagnostics.Contracts;
//=====================================================================
//---------------------------------------------------------------------
// Types
-
+ [ContractClass(typeof(TypeContracts))]
public abstract class Type : Absy {
- public Type(IToken! token)
- : base(token)
- {
+ public Type(IToken/*!*/ token)
+ : base(token) {
+ Contract.Requires(token != null);
}
//----------- Cloning ----------------------------------
@@ -34,59 +33,65 @@ namespace Microsoft.Boogie
// a type in which all bound variables have been replaced with new
// variables, whereas free variables have not changed
- public override Absy! Clone() {
- return this.Clone(new Dictionary<TypeVariable!, TypeVariable!> ());
+ public override Absy Clone() {
+ Contract.Ensures(Contract.Result<Absy>() != null);
+ return this.Clone(new Dictionary<TypeVariable/*!*/, TypeVariable/*!*/>());
}
- public abstract Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap);
+ public abstract Type/*!*/ Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap);
/// <summary>
/// Clones the type, but only syntactically. Anything resolved in the source
/// type is left unresolved (that is, with just the name) in the destination type.
/// </summary>
- public abstract Type! CloneUnresolved();
-
+ public abstract Type/*!*/ CloneUnresolved();
+
//----------- Linearisation ----------------------------------
- public void Emit(TokenTextWriter! stream) {
+ public void Emit(TokenTextWriter stream) {
+ Contract.Requires(stream != null);
this.Emit(stream, 0);
}
- public abstract void Emit(TokenTextWriter! stream, int contextBindingStrength);
+ public abstract void Emit(TokenTextWriter/*!*/ stream, int contextBindingStrength);
[Pure]
- public override string! ToString() {
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
System.IO.StringWriter buffer = new System.IO.StringWriter();
- using (TokenTextWriter stream = new TokenTextWriter("<buffer>", buffer, false))
- {
+ using (TokenTextWriter stream = new TokenTextWriter("<buffer>", buffer, false)) {
this.Emit(stream);
}
return buffer.ToString();
}
-
+
//----------- Equality ----------------------------------
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object that)
- {
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object that) {
if (ReferenceEquals(this, that))
return true;
Type thatType = that as Type;
return thatType != null && this.Equals(thatType,
- new TypeVariableSeq (),
- new TypeVariableSeq ());
+ new TypeVariableSeq(),
+ new TypeVariableSeq());
}
[Pure]
- public abstract bool Equals(Type! that,
- TypeVariableSeq! thisBoundVariables,
- TypeVariableSeq! thatBoundVariables);
+ public abstract bool Equals(Type/*!*/ that,
+ TypeVariableSeq/*!*/ thisBoundVariables,
+ TypeVariableSeq/*!*/ thatBoundVariables);
// used to skip leading type annotations (subexpressions of the
// resulting type might still contain annotations)
- internal virtual Type! Expanded { get {
- return this;
- } }
+ internal virtual Type/*!*/ Expanded {
+ get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ return this;
+ }
+ }
//----------- Unification of types -----------
@@ -95,23 +100,23 @@ namespace Microsoft.Boogie
/// If not possible, return false (which may have added some partial constraints).
/// No error is printed.
/// </summary>
- public bool Unify(Type! that) {
- return Unify(that, new TypeVariableSeq(), new Dictionary<TypeVariable!, Type!> ());
+ public bool Unify(Type that) {
+ Contract.Requires(that != null);
+ return Unify(that, new TypeVariableSeq(), new Dictionary<TypeVariable/*!*/, Type/*!*/>());
}
- public abstract bool Unify(Type! that,
- TypeVariableSeq! unifiableVariables,
- // an idempotent substitution that describes the
- // unification result up to a certain point
- IDictionary<TypeVariable!, Type!>! unifier);
- requires forall{TypeVariable key in unifier.Keys; unifiableVariables.Has(key)};
- requires IsIdempotent(unifier);
+ public abstract bool Unify(Type/*!*/ that,
+ TypeVariableSeq/*!*/ unifiableVariables,
+ // an idempotent substitution that describes the
+ // unification result up to a certain point
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ unifier);
+
[Pure]
- public static bool IsIdempotent(IDictionary<TypeVariable!, Type!>! unifier) {
- return forall{Type! t in unifier.Values;
- forall{TypeVariable! var in t.FreeVariables;
- !unifier.ContainsKey(var)}};
+ public static bool IsIdempotent(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ unifier) {
+ Contract.Requires(cce.NonNullElements(unifier));
+ return Contract.ForAll(unifier.Values, t => Contract.ForAll(0, t.FreeVariables.Length, var =>
+ !unifier.ContainsKey(t.FreeVariables[var])));
}
@@ -138,16 +143,16 @@ namespace Microsoft.Boogie
// given mappings that need to be taken into account
// the old unifier has to be idempotent as well
IDictionary<TypeVariable!, Type!>! unifier)
- requires forall{TypeVariable key in unifier.Keys; unifiableVariables.Has(key)};
- requires IsIdempotent(unifier);
- {
+ {
+ Contract.Requires(Contract.ForAll(unifier.Keys , key=> unifiableVariables.Has(key)));
+ Contract.Requires(IsIdempotent(unifier));
try {
this.Unify(that, unifiableVariables,
new TypeVariableSeq (), new TypeVariableSeq (), unifier);
} catch (UnificationFailedException) {
return false;
}
- return true;
+ return true;
}
public abstract void Unify(Type! that,
@@ -161,8 +166,8 @@ namespace Microsoft.Boogie
//----------- Substitution of free variables with types not containing bound variables -----------------
- public abstract Type! Substitute(IDictionary<TypeVariable!, Type!>! subst);
-
+ public abstract Type/*!*/ Substitute(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst);
+
//----------- Hashcodes ----------------------------------
// Hack to be able to access the hashcode of superclasses further up
@@ -173,44 +178,51 @@ namespace Microsoft.Boogie
}
[Pure]
- public override int GetHashCode()
- {
- return this.GetHashCode(new TypeVariableSeq ());
+ public override int GetHashCode() {
+ return this.GetHashCode(new TypeVariableSeq());
}
[Pure]
- public abstract int GetHashCode(TypeVariableSeq! boundVariables);
+ public abstract int GetHashCode(TypeVariableSeq/*!*/ boundVariables);
//----------- Resolution ----------------------------------
- public override void Resolve(ResolutionContext! rc)
- {
+ public override void Resolve(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
System.Diagnostics.Debug.Fail("Type.Resolve should never be called." +
" Use Type.ResolveType instead");
}
- public abstract Type! ResolveType(ResolutionContext! rc);
+ public abstract Type/*!*/ ResolveType(ResolutionContext/*!*/ rc);
- public override void Typecheck(TypecheckingContext! tc)
- {
+ public override void Typecheck(TypecheckingContext tc) {
+ //Contract.Requires(tc != null);
System.Diagnostics.Debug.Fail("Type.Typecheck should never be called");
}
// determine the free variables in a type, in the order in which the variables occur
- public abstract TypeVariableSeq! FreeVariables { get; }
+ public abstract TypeVariableSeq/*!*/ FreeVariables {
+ get;
+ }
// determine the free type proxies in a type, in the order in which they occur
- public abstract List<TypeProxy!>! FreeProxies { get; }
+ public abstract List<TypeProxy/*!*/>/*!*/ FreeProxies {
+ get;
+ }
- protected static void AppendWithoutDups<A>(List<A>! a, List<A>! b) {
+ protected static void AppendWithoutDups<A>(List<A> a, List<A> b) {
+ Contract.Requires(b != null);
+ Contract.Requires(a != null);
foreach (A x in b)
if (!a.Contains(x))
a.Add(x);
}
- public bool IsClosed { get {
- return FreeVariables.Length == 0;
- } }
+ public bool IsClosed {
+ get {
+ return FreeVariables.Length == 0;
+ }
+ }
//----------- Getters/Issers ----------------------------------
@@ -218,42 +230,114 @@ namespace Microsoft.Boogie
// C# "is" operator, because they handle type synonym annotations and
// type proxies correctly
- public virtual bool IsBasic { get { return false; } }
- public virtual bool IsInt { get { return false; } }
- public virtual bool IsBool { get { return false; } }
-
- public virtual bool IsVariable { get { return false; } }
- public virtual TypeVariable! AsVariable { get {
- assert false; // Type.AsVariable should never be called
- } }
- public virtual bool IsCtor { get { return false; } }
- public virtual CtorType! AsCtor { get {
- assert false; // Type.AsCtor should never be called
- } }
- public virtual bool IsMap { get { return false; } }
- public virtual MapType! AsMap { get {
- assert false; // Type.AsMap should never be called
- } }
- public virtual int MapArity { get {
- assert false; // Type.MapArity should never be called
- } }
- public virtual bool IsUnresolved { get { return false; } }
- public virtual UnresolvedTypeIdentifier! AsUnresolved { get {
- assert false; // Type.AsUnresolved should never be called
- } }
-
- public virtual bool IsBv { get { return false; } }
- public virtual int BvBits { get {
- assert false; // Type.BvBits should never be called
- } }
-
- public static readonly Type! Int = new BasicType(SimpleType.Int);
- public static readonly Type! Bool = new BasicType(SimpleType.Bool);
+ public virtual bool IsBasic {
+ get {
+ return false;
+ }
+ }
+ public virtual bool IsInt {
+ get {
+ return false;
+ }
+ }
+ public virtual bool IsBool {
+ get {
+ return false;
+ }
+ }
+
+ public virtual bool IsVariable {
+ get {
+ return false;
+ }
+ }
+ public virtual TypeVariable/*!*/ AsVariable {
+ get {
+ Contract.Ensures(Contract.Result<TypeVariable>() != null);
+
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // Type.AsVariable should never be called
+ }
+ }
+ public virtual bool IsCtor {
+ get {
+ return false;
+ }
+ }
+ public virtual CtorType/*!*/ AsCtor {
+ get {
+ Contract.Ensures(Contract.Result<CtorType>() != null);
+
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // Type.AsCtor should never be called
+ }
+ }
+ public virtual bool IsMap {
+ get {
+ return false;
+ }
+ }
+ public virtual MapType/*!*/ AsMap {
+ get {
+ Contract.Ensures(Contract.Result<MapType>() != null);
+
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // Type.AsMap should never be called
+ }
+ }
+ public virtual int MapArity {
+ get {
+
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // Type.MapArity should never be called
+ }
+ }
+ public virtual bool IsUnresolved {
+ get {
+ return false;
+ }
+ }
+ public virtual UnresolvedTypeIdentifier/*!*/ AsUnresolved {
+ get {
+ Contract.Ensures(Contract.Result<UnresolvedTypeIdentifier>() != null);
+
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // Type.AsUnresolved should never be called
+ }
+ }
+
+ public virtual bool IsBv {
+ get {
+ return false;
+ }
+ }
+ public virtual int BvBits {
+ get {
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // Type.BvBits should never be called
+ }
+ }
+
+ public static readonly Type/*!*/ Int = new BasicType(SimpleType.Int);
+ public static readonly Type/*!*/ Bool = new BasicType(SimpleType.Bool);
private static BvType[] bvtypeCache;
-
- static public BvType! GetBvType(int sz)
- requires 0 <= sz;
- {
+
+ static public BvType GetBvType(int sz) {
+ Contract.Requires(0 <= sz);
+ Contract.Ensures(Contract.Result<BvType>() != null);
+
if (bvtypeCache == null) {
bvtypeCache = new BvType[128];
}
@@ -281,20 +365,20 @@ namespace Microsoft.Boogie
IdentifierExprSeq actualOuts,
string! opName,
TypecheckingContext! tc)
- requires formalArgs.Length == actualArgs.Length;
- requires formalOuts == null <==> actualOuts == null;
- requires formalOuts != null ==> formalOuts.Length == actualOuts.Length;
- {
+ {
+ Contract.Requires(formalArgs.Length == actualArgs.Length);
+ Contract.Requires(formalOuts == null <==> actualOuts == null);
+ Contract.Requires(formalOuts != null ==> formalOuts.Length == actualOuts.Length);
TypeVariableSeq! boundVarSeq0 = new TypeVariableSeq ();
TypeVariableSeq! boundVarSeq1 = new TypeVariableSeq ();
Dictionary<TypeVariable!, Type!>! subst = new Dictionary<TypeVariable!, Type!>();
for (int i = 0; i < formalArgs.Length; ++i) {
try {
- Type! actualType = (!)((!)actualArgs[i]).Type;
+ Type! actualType = cce.NonNull((!)actualArgs[i]).Type;
// if the type variables to be matched occur in the actual
// argument types, something has gone very wrong
- assert forall{TypeVariable! var in typeParams;
+ Contract.Assert(forall{TypeVariable! var in typeParams);
!actualType.FreeVariables.Has(var)};
formalArgs[i].Unify(actualType,
typeParams,
@@ -309,17 +393,17 @@ namespace Microsoft.Boogie
formalArgs[i].Substitute(subst));
// the bound variable sequences should be empty ...
// so that we can continue with the unification
- assert boundVarSeq0.Length == 0 && boundVarSeq1.Length == 0;
+ Contract.Assert(boundVarSeq0.Length == 0 && boundVarSeq1.Length == 0);
}
}
if (formalOuts != null) {
for (int i = 0; i < formalOuts.Length; ++i) {
try {
- Type! actualType = (!)((!)actualOuts[i]).Type;
+ Type! actualType = cce.NonNull((!)actualOuts[i]).Type;
// if the type variables to be matched occur in the actual
// argument types, something has gone very wrong
- assert forall{TypeVariable! var in typeParams;
+ Contract.Assert(forall{TypeVariable! var in typeParams);
!actualType.FreeVariables.Has(var)};
formalOuts[i].Unify(actualType,
typeParams,
@@ -334,71 +418,79 @@ namespace Microsoft.Boogie
formalOuts[i].Substitute(subst));
// the bound variable sequences should be empty ...
// so that we can continue with the unification
- assert boundVarSeq0.Length == 0 && boundVarSeq1.Length == 0;
+ Contract.Assert(boundVarSeq0.Length == 0 && boundVarSeq1.Length == 0);
}
}
}
// we only allow type parameters to be substituted
- assert forall{TypeVariable! var in subst.Keys; typeParams.Has(var)};
+ Contract.Assert(Contract.ForAll(subst.Keys , var=> typeParams.Has(var)));
return subst;
}
#else
- public static IDictionary<TypeVariable!, Type!>!
- MatchArgumentTypes(TypeVariableSeq! typeParams,
- TypeSeq! formalArgs,
- ExprSeq! actualArgs,
+ public static IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/
+ MatchArgumentTypes(TypeVariableSeq/*!*/ typeParams,
+ TypeSeq/*!*/ formalArgs,
+ ExprSeq/*!*/ actualArgs,
TypeSeq formalOuts,
IdentifierExprSeq actualOuts,
- string! opName,
- TypecheckingContext! tc)
- requires formalArgs.Length == actualArgs.Length;
- requires formalOuts == null <==> actualOuts == null;
- requires formalOuts != null ==> formalOuts.Length == ((!)actualOuts).Length;
- requires tc != null ==> opName != null;
+ string/*!*/ opName,
+ TypecheckingContext/*!*/ tc) {
+ Contract.Requires(typeParams != null);
+ Contract.Requires(formalArgs != null);
+ Contract.Requires(actualArgs != null);
+ Contract.Requires(opName != null);
+ Contract.Requires(tc != null);
+ Contract.Requires(formalArgs.Length == actualArgs.Length);
+ Contract.Requires((formalOuts == null) == (actualOuts == null));
+ Contract.Requires(formalOuts == null || formalOuts.Length == cce.NonNull(actualOuts).Length);
+ Contract.Requires(tc == null || opName != null);//Redundant
+ Contract.Ensures(cce.NonNullElements(Contract.Result<IDictionary<TypeVariable, Type>>()));
+
// requires "actualArgs" and "actualOuts" to have been type checked
- {
- Dictionary<TypeVariable!, Type!> subst = new Dictionary<TypeVariable!, Type!>();
- foreach (TypeVariable! tv in typeParams) {
+
+ Dictionary<TypeVariable/*!*/, Type/*!*/> subst = new Dictionary<TypeVariable/*!*/, Type/*!*/>();
+ foreach (TypeVariable/*!*/ tv in typeParams) {
+ Contract.Assert(tv != null);
TypeProxy proxy = new TypeProxy(Token.NoToken, tv.Name);
subst.Add(tv, proxy);
}
-
+
for (int i = 0; i < formalArgs.Length; i++) {
Type formal = formalArgs[i].Substitute(subst);
- Type actual = (!)((!)actualArgs[i]).Type;
+ Type actual = cce.NonNull(cce.NonNull(actualArgs[i]).Type);
// if the type variables to be matched occur in the actual
// argument types, something has gone very wrong
- assert forall{TypeVariable! var in typeParams; !actual.FreeVariables.Has(var)};
+ Contract.Assert(Contract.ForAll(0, typeParams.Length, index => !actual.FreeVariables.Has(typeParams[index])));
if (!formal.Unify(actual)) {
- assume tc != null; // caller expected no errors
- assert opName != null; // follows from precondition
- tc.Error((!)actualArgs[i],
+ Contract.Assume(tc != null); // caller expected no errors
+ Contract.Assert(opName != null); // follows from precondition
+ tc.Error(cce.NonNull(actualArgs[i]),
"invalid type for argument {0} in {1}: {2} (expected: {3})",
i, opName, actual, formalArgs[i]);
}
}
-
+
if (formalOuts != null) {
for (int i = 0; i < formalOuts.Length; ++i) {
Type formal = formalOuts[i].Substitute(subst);
- Type actual = (!)((!)actualOuts)[i].Type;
+ Type actual = cce.NonNull(cce.NonNull(actualOuts)[i].Type);
// if the type variables to be matched occur in the actual
// argument types, something has gone very wrong
- assert forall{TypeVariable! var in typeParams; !actual.FreeVariables.Has(var)};
+ Contract.Assert(Contract.ForAll(0, typeParams.Length, var => !actual.FreeVariables.Has(typeParams[var])));
if (!formal.Unify(actual)) {
- assume tc != null; // caller expected no errors
- assert opName != null; // follows from precondition
+ Contract.Assume(tc != null); // caller expected no errors
+ Contract.Assert(opName != null); // follows from precondition
tc.Error(actualOuts[i],
"invalid type for out-parameter {0} in {1}: {2} (expected: {3})",
i, opName, actual, formal);
}
}
}
-
+
return subst;
}
#endif
@@ -407,18 +499,26 @@ namespace Microsoft.Boogie
//------------ on concrete types, substitute the result into the
//------------ result type. Null is returned for type errors
- public static TypeSeq CheckArgumentTypes(TypeVariableSeq! typeParams,
- out List<Type!>! actualTypeParams,
- TypeSeq! formalIns,
- ExprSeq! actualIns,
- TypeSeq! formalOuts,
+ public static TypeSeq CheckArgumentTypes(TypeVariableSeq/*!*/ typeParams,
+ out List<Type/*!*/>/*!*/ actualTypeParams,
+ TypeSeq/*!*/ formalIns,
+ ExprSeq/*!*/ actualIns,
+ TypeSeq/*!*/ formalOuts,
IdentifierExprSeq actualOuts,
- IToken! typeCheckingSubject,
- string! opName,
- TypecheckingContext! tc)
+ IToken/*!*/ typeCheckingSubject,
+ string/*!*/ opName,
+ TypecheckingContext/*!*/ tc)
// requires "actualIns" and "actualOuts" to have been type checked
{
- actualTypeParams = new List<Type!> ();
+ Contract.Requires(typeParams != null);
+
+ Contract.Requires(formalIns != null);
+ Contract.Requires(formalOuts != null);
+ Contract.Requires(actualIns != null);
+ Contract.Requires(actualOuts != null);
+ Contract.Requires(typeCheckingSubject != null);
+ Contract.Requires(opName != null);Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out actualTypeParams)));
+ actualTypeParams = new List<Type/*!*/>();
if (formalIns.Length != actualIns.Length) {
tc.Error(typeCheckingSubject, "wrong number of arguments in {0}: {1}",
@@ -431,20 +531,23 @@ namespace Microsoft.Boogie
opName, actualOuts.Length);
// if there are no type parameters, we can still return the result
// type and hope that the type checking proceeds
- actualTypeParams = new List<Type!> ();
+ actualTypeParams = new List<Type>();
return typeParams.Length == 0 ? formalOuts : null;
}
int previousErrorCount = tc.ErrorCount;
- IDictionary<TypeVariable!, Type!> subst =
+ IDictionary<TypeVariable/*!*/, Type/*!*/> subst =
MatchArgumentTypes(typeParams, formalIns, actualIns,
actualOuts != null ? formalOuts : null, actualOuts, opName, tc);
-
- foreach (TypeVariable! var in typeParams)
+ Contract.Assert(cce.NonNullElements(subst));
+ foreach (TypeVariable/*!*/ var in typeParams) {
+ Contract.Assert(var != null);
actualTypeParams.Add(subst[var]);
+ }
- TypeSeq! actualResults = new TypeSeq ();
- foreach (Type! t in formalOuts) {
+ TypeSeq/*!*/ actualResults = new TypeSeq();
+ foreach (Type/*!*/ t in formalOuts) {
+ Contract.Assert(t != null);
actualResults.Add(t.Substitute(subst));
}
TypeVariableSeq resultFreeVars = FreeVariablesIn(actualResults);
@@ -453,7 +556,7 @@ namespace Microsoft.Boogie
// in case we have been able to substitute all type parameters,
// we can still return the result type and hope that the
// type checking proceeds in a meaningful manner
- if (forall{TypeVariable! var in typeParams; !resultFreeVars.Has(var)})
+ if (Contract.ForAll(0, typeParams.Length, index => !resultFreeVars.Has(typeParams[index])))
return actualResults;
else
// otherwise there is no point in returning the result type,
@@ -461,7 +564,7 @@ namespace Microsoft.Boogie
return null;
}
- assert forall{TypeVariable! var in typeParams; !resultFreeVars.Has(var)};
+ Contract.Assert(Contract.ForAll(0, typeParams.Length, index => !resultFreeVars.Has(typeParams[index])));
return actualResults;
}
@@ -469,17 +572,26 @@ namespace Microsoft.Boogie
// about the same as Type.CheckArgumentTypes, but without
// detailed error reports
- public static Type! InferValueType(TypeVariableSeq! typeParams,
- TypeSeq! formalArgs,
- Type! formalResult,
- TypeSeq! actualArgs) {
- IDictionary<TypeVariable!, Type!>! subst =
+ public static Type/*!*/ InferValueType(TypeVariableSeq/*!*/ typeParams,
+ TypeSeq/*!*/ formalArgs,
+ Type/*!*/ formalResult,
+ TypeSeq/*!*/ actualArgs) {
+ Contract.Requires(typeParams != null);
+ Contract.Requires(formalArgs != null);
+ Contract.Requires(formalResult != null);
+ Contract.Requires(actualArgs != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst =
InferTypeParameters(typeParams, formalArgs, actualArgs);
+ Contract.Assert(cce.NonNullElements(subst));
- Type! res = formalResult.Substitute(subst);
+ Type/*!*/ res = formalResult.Substitute(subst);
+ Contract.Assert(res != null);
// all type parameters have to be substituted with concrete types
- TypeVariableSeq! resFreeVars = res.FreeVariables;
- assert forall{TypeVariable! var in typeParams; !resFreeVars.Has(var)};
+ TypeVariableSeq/*!*/ resFreeVars = res.FreeVariables;
+ Contract.Assert(resFreeVars != null);
+ Contract.Assert(Contract.ForAll(0, typeParams.Length, var => !resFreeVars.Has(typeParams[var])));
return res;
}
@@ -488,7 +600,8 @@ namespace Microsoft.Boogie
InferTypeParameters(TypeVariableSeq! typeParams,
TypeSeq! formalArgs,
TypeSeq! actualArgs)
- requires formalArgs.Length == actualArgs.Length; {
+ {
+ Contract.Requires(formalArgs.Length == actualArgs.Length);
TypeVariableSeq! boundVarSeq0 = new TypeVariableSeq ();
TypeVariableSeq! boundVarSeq1 = new TypeVariableSeq ();
@@ -496,7 +609,7 @@ namespace Microsoft.Boogie
for (int i = 0; i < formalArgs.Length; ++i) {
try {
- assert forall{TypeVariable! var in typeParams;
+ Contract.Assert(forall{TypeVariable! var in typeParams);
!actualArgs[i].FreeVariables.Has(var)};
formalArgs[i].Unify(actualArgs[i], typeParams,
boundVarSeq0, boundVarSeq1, subst);
@@ -507,47 +620,54 @@ namespace Microsoft.Boogie
}
// we only allow type parameters to be substituted
- assert forall{TypeVariable! var in subst.Keys; typeParams.Has(var)};
- return subst;
+ Contract.Assert(Contract.ForAll(subst.Keys , var=> typeParams.Has(var)));
+ return subst;
}
#else
/// <summary>
/// like Type.CheckArgumentTypes, but assumes no errors
/// (and only does arguments, not results; and takes actuals as TypeSeq, not ExprSeq)
/// </summary>
- public static IDictionary<TypeVariable!, Type!>!
- InferTypeParameters(TypeVariableSeq! typeParams,
- TypeSeq! formalArgs,
- TypeSeq! actualArgs)
- requires formalArgs.Length == actualArgs.Length;
- {
+ public static IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/
+ InferTypeParameters(TypeVariableSeq/*!*/ typeParams,
+ TypeSeq/*!*/ formalArgs,
+ TypeSeq/*!*/ actualArgs) {
+ Contract.Requires(typeParams != null);
+ Contract.Requires(formalArgs != null);
+ Contract.Requires(actualArgs != null);Contract.Requires(formalArgs.Length == actualArgs.Length);
+ Contract.Ensures(cce.NonNullElements(Contract.Result<IDictionary<TypeVariable, Type>>()));
+
+
TypeSeq proxies = new TypeSeq();
- Dictionary<TypeVariable!, Type!>! subst = new Dictionary<TypeVariable!, Type!>();
- foreach (TypeVariable! tv in typeParams) {
+ Dictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst = new Dictionary<TypeVariable/*!*/, Type/*!*/>();
+ foreach (TypeVariable/*!*/ tv in typeParams) {
+ Contract.Assert(tv != null);
TypeProxy proxy = new TypeProxy(Token.NoToken, tv.Name);
proxies.Add(proxy);
subst.Add(tv, proxy);
}
-
+
for (int i = 0; i < formalArgs.Length; i++) {
Type formal = formalArgs[i].Substitute(subst);
Type actual = actualArgs[i];
// if the type variables to be matched occur in the actual
// argument types, something has gone very wrong
- assert forall{TypeVariable! var in typeParams; !actual.FreeVariables.Has(var)};
+ Contract.Assert(Contract.ForAll(0, typeParams.Length, index => !actual.FreeVariables.Has(typeParams[index])));
if (!formal.Unify(actual)) {
- assume false; // caller expected no errors
+ Contract.Assume(false); // caller expected no errors
}
}
-
+
return subst;
}
#endif
-
+
//----------- Helper methods to deal with bound type variables ---------------
- public static void EmitOptionalTypeParams(TokenTextWriter! stream, TypeVariableSeq! typeParams) {
+ public static void EmitOptionalTypeParams(TokenTextWriter stream, TypeVariableSeq typeParams) {
+ Contract.Requires(typeParams != null);
+ Contract.Requires(stream != null);
if (typeParams.Length > 0) {
stream.Write("<");
typeParams.Emit(stream, ","); // default binding strength of 0 is ok
@@ -556,9 +676,13 @@ namespace Microsoft.Boogie
}
// Sort the type parameters according to the order of occurrence in the argument types
- public static TypeVariableSeq! SortTypeParams(TypeVariableSeq! typeParams,
- TypeSeq! argumentTypes, Type resultType)
- ensures result.Length == typeParams.Length; {
+ public static TypeVariableSeq/*!*/ SortTypeParams(TypeVariableSeq/*!*/ typeParams, TypeSeq/*!*/ argumentTypes, Type resultType) {
+ Contract.Requires(typeParams != null);
+ Contract.Requires(argumentTypes != null);
+ Contract.Requires(resultType != null);
+ Contract.Ensures(Contract.Result<TypeVariableSeq>() != null);
+
+ Contract.Ensures(Contract.Result<TypeVariableSeq>().Length == typeParams.Length);
if (typeParams.Length == 0) {
return typeParams;
}
@@ -569,13 +693,14 @@ namespace Microsoft.Boogie
}
// "freeVarsInUse" is already sorted, but it may contain type variables not in "typeParams".
// So, project "freeVarsInUse" onto "typeParams":
- TypeVariableSeq! sortedTypeParams = new TypeVariableSeq ();
- foreach (TypeVariable! var in freeVarsInUse) {
+ TypeVariableSeq sortedTypeParams = new TypeVariableSeq();
+ foreach (TypeVariable/*!*/ var in freeVarsInUse) {
+ Contract.Assert(var != null);
if (typeParams.Has(var)) {
sortedTypeParams.Add(var);
}
}
-
+
if (sortedTypeParams.Length < typeParams.Length)
// add the type parameters not mentioned in "argumentTypes" in
// the end of the list (this can happen for quantifiers)
@@ -588,16 +713,22 @@ namespace Microsoft.Boogie
// Return true if some type parameters appear only among "moreArgumentTypes" and
// not in "argumentTypes".
[Pure]
- public static bool CheckBoundVariableOccurrences(TypeVariableSeq! typeParams,
- TypeSeq! argumentTypes,
+ public static bool CheckBoundVariableOccurrences(TypeVariableSeq/*!*/ typeParams,
+ TypeSeq/*!*/ argumentTypes,
TypeSeq moreArgumentTypes,
- IToken! resolutionSubject,
- string! subjectName,
- ResolutionContext! rc) {
+ IToken/*!*/ resolutionSubject,
+ string/*!*/ subjectName,
+ ResolutionContext/*!*/ rc) {
+ Contract.Requires(typeParams != null);
+ Contract.Requires(argumentTypes != null);
+ Contract.Requires(resolutionSubject != null);
+ Contract.Requires(subjectName != null);
+ Contract.Requires(rc != null);
TypeVariableSeq freeVarsInArgs = FreeVariablesIn(argumentTypes);
TypeVariableSeq moFreeVarsInArgs = moreArgumentTypes == null ? null : FreeVariablesIn(moreArgumentTypes);
bool someTypeParamsAppearOnlyAmongMo = false;
- foreach (TypeVariable! var in typeParams) {
+ foreach (TypeVariable/*!*/ var in typeParams) {
+ Contract.Assert(var != null);
if (rc.LookUpTypeBinder(var.Name) == var) // avoid to complain twice about variables that are bound multiple times
{
if (freeVarsInArgs.Has(var)) {
@@ -615,28 +746,92 @@ namespace Microsoft.Boogie
}
[Pure]
- public static TypeVariableSeq! FreeVariablesIn(TypeSeq! arguments) {
- TypeVariableSeq! res = new TypeVariableSeq ();
- foreach (Type! t in arguments)
+ public static TypeVariableSeq FreeVariablesIn(TypeSeq arguments) {
+ Contract.Requires(arguments != null);
+ Contract.Ensures(Contract.Result<TypeVariableSeq>() != null);
+ TypeVariableSeq/*!*/ res = new TypeVariableSeq();
+ foreach (Type/*!*/ t in arguments) {
+ Contract.Assert(t != null);
res.AppendWithoutDups(t.FreeVariables);
+ }
return res;
}
}
+ [ContractClassFor(typeof(Type))]
+ public abstract class TypeContracts : Type {
+ public TypeContracts() :base(null){
+
+ }
+ public override List<TypeProxy> FreeProxies {
+ get {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<TypeProxy>>()));
+ throw new NotImplementedException();
+ }
+ }
+ public override TypeVariableSeq FreeVariables {
+ get {
+ Contract.Ensures(Contract.Result<TypeVariableSeq>() != null);
+ throw new NotImplementedException();
+ }
+ }
+ public override Type Clone(IDictionary<TypeVariable, TypeVariable> varMap) {
+ Contract.Requires(cce.NonNullElements(varMap));
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ throw new NotImplementedException();
+ }
+ public override Type CloneUnresolved() {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ throw new NotImplementedException();
+ }
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength) {
+ Contract.Requires(stream != null);
+ throw new NotImplementedException();
+ }
+ public override bool Equals(Type that, TypeVariableSeq thisBoundVariables, TypeVariableSeq thatBoundVariables) {
+ Contract.Requires(that != null);
+ Contract.Requires(thisBoundVariables != null);
+ Contract.Requires(thatBoundVariables != null);
+ throw new NotImplementedException();
+ }
+ public override bool Unify(Type that, TypeVariableSeq unifiableVariables, IDictionary<TypeVariable, Type> unifier) {
+ Contract.Requires(that != null);
+ Contract.Requires(unifiableVariables != null);
+ Contract.Requires(cce.NonNullElements(unifier));
+ Contract.Requires(Contract.ForAll(unifier.Keys, key => unifiableVariables.Has(key)));
+ Contract.Requires(IsIdempotent(unifier));
+ throw new NotImplementedException();
+ }
+ public override Type Substitute(IDictionary<TypeVariable, Type> subst) {
+ Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ throw new NotImplementedException();
+ }
+ public override Type ResolveType(ResolutionContext rc) {
+ Contract.Requires(rc != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+ throw new NotImplementedException();
+ }
+ public override int GetHashCode(TypeVariableSeq boundVariables) {
+ Contract.Requires(boundVariables != null);
+ throw new NotImplementedException();
+ }
+ }
//=====================================================================
- public class BasicType : Type
- {
+ public class BasicType : Type {
public readonly SimpleType T;
- public BasicType(IToken! token, SimpleType t)
- : base(token)
- {
+ public BasicType(IToken/*!*/ token, SimpleType t)
+ : base(token) {
+ Contract.Requires(token != null);
T = t;
// base(token);
}
public BasicType(SimpleType t)
- : base(Token.NoToken)
- {
+ : base(Token.NoToken) {
T = t;
// base(Token.NoToken);
}
@@ -646,39 +841,47 @@ namespace Microsoft.Boogie
// have to be created in the right way. It is /not/ ok to just clone
// everything recursively.
- public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
+ public override Type Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap) {
+ //Contract.Requires(cce.NonNullElements(varMap));
+ Contract.Ensures(Contract.Result<Type>() != null);
// BasicTypes are immutable anyway, we do not clone
return this;
}
- public override Type! CloneUnresolved() {
+ public override Type CloneUnresolved() {
+ Contract.Ensures(Contract.Result<Type>() != null);
return this;
}
//----------- Linearisation ----------------------------------
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength) {
+ //Contract.Requires(stream != null);
// no parentheses are necessary for basic types
stream.SetToken(this);
stream.Write("{0}", this);
}
[Pure]
- public override string! ToString()
- {
- switch (T)
- {
- case SimpleType.Int: return "int";
- case SimpleType.Bool: return "bool";
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ switch (T) {
+ case SimpleType.Int:
+ return "int";
+ case SimpleType.Bool:
+ return "bool";
}
Debug.Assert(false, "bad type " + T);
- assert false; // make compiler happy
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // make compiler happy
}
//----------- Equality ----------------------------------
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
public override bool Equals(object that) {
// shortcut
Type thatType = that as Type;
@@ -689,19 +892,22 @@ namespace Microsoft.Boogie
}
[Pure]
- public override bool Equals(Type! that,
- TypeVariableSeq! thisBoundVariables,
- TypeVariableSeq! thatBoundVariables) {
+ public override bool Equals(Type that, TypeVariableSeq thisBoundVariables, TypeVariableSeq thatBoundVariables) {
+ //Contract.Requires(thatBoundVariables != null);
+ //Contract.Requires(thisBoundVariables != null);
+ //Contract.Requires(that != null);
return this.Equals(that);
}
//----------- Unification of types -----------
- public override bool Unify(Type! that,
- TypeVariableSeq! unifiableVariables,
- // an idempotent substitution that describes the
- // unification result up to a certain point
- IDictionary<TypeVariable!, Type!>! unifier) {
+ public override bool Unify(Type that, TypeVariableSeq unifiableVariables, IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ unifier) {
+ //Contract.Requires(unifiableVariables != null);
+ //Contract.Requires(that != null);
+ Contract.Requires(cce.NonNullElements(unifier));
+ // an idempotent substitution that describes the
+ // unification result up to a certain point
+
that = that.Expanded;
if (that is TypeProxy || that is TypeVariable) {
return that.Unify(this, unifiableVariables, unifier);
@@ -728,64 +934,84 @@ namespace Microsoft.Boogie
//----------- Substitution of free variables with types not containing bound variables -----------------
- public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
+ public override Type Substitute(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst) {
+ //Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
return this;
}
//----------- Hashcodes ----------------------------------
[Pure]
- public override int GetHashCode(TypeVariableSeq! boundVariables)
- {
+ public override int GetHashCode(TypeVariableSeq boundVariables) {
+ //Contract.Requires(boundVariables != null);
return this.T.GetHashCode();
}
//----------- Resolution ----------------------------------
- public override Type! ResolveType(ResolutionContext! rc) {
+ public override Type ResolveType(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
// nothing to resolve
return this;
}
// determine the free variables in a type, in the order in which the variables occur
- public override TypeVariableSeq! FreeVariables {
+ public override TypeVariableSeq/*!*/ FreeVariables {
get {
- return new TypeVariableSeq (); // basic type are closed
+ Contract.Ensures(Contract.Result<TypeVariableSeq>() != null);
+
+ return new TypeVariableSeq(); // basic type are closed
}
}
- public override List<TypeProxy!>! FreeProxies { get {
- return new List<TypeProxy!> ();
- } }
+ public override List<TypeProxy/*!*/>/*!*/ FreeProxies {
+ get {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<TypeProxy>>()));
+ return new List<TypeProxy/*!*/>();
+ }
+ }
//----------- Getters/Issers ----------------------------------
- public override bool IsBasic { get { return true; } }
- public override bool IsInt { get { return this.T == SimpleType.Int; } }
- public override bool IsBool { get { return this.T == SimpleType.Bool; } }
+ public override bool IsBasic {
+ get {
+ return true;
+ }
+ }
+ public override bool IsInt {
+ get {
+ return this.T == SimpleType.Int;
+ }
+ }
+ public override bool IsBool {
+ get {
+ return this.T == SimpleType.Bool;
+ }
+ }
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitBasicType(this);
}
}
-
+
//=====================================================================
- public class BvType : Type
- {
+ public class BvType : Type {
public readonly int Bits;
-
- public BvType(IToken! token, int bits)
- : base(token)
- {
+
+ public BvType(IToken token, int bits)
+ : base(token) {
+ Contract.Requires(token != null);
Bits = bits;
}
-
+
public BvType(int bits)
- : base(Token.NoToken)
- {
- Bits = bits;
+ : base(Token.NoToken) {
+ Bits = bits;
}
//----------- Cloning ----------------------------------
@@ -793,47 +1019,56 @@ namespace Microsoft.Boogie
// have to be created in the right way. It is /not/ ok to just clone
// everything recursively.
- public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
+ public override Type Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap) {
+ //Contract.Requires(cce.NonNullElements(varMap));
+ Contract.Ensures(Contract.Result<Type>() != null);
// BvTypes are immutable anyway, we do not clone
return this;
}
- public override Type! CloneUnresolved() {
+ public override Type CloneUnresolved() {
+ Contract.Ensures(Contract.Result<Type>() != null);
return this;
}
//----------- Linearisation ----------------------------------
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength) {
+ //Contract.Requires(stream != null);
// no parentheses are necessary for bitvector-types
stream.SetToken(this);
stream.Write("{0}", this);
}
[Pure]
- public override string! ToString()
- {
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
return "bv" + Bits;
}
//----------- Equality ----------------------------------
[Pure]
- public override bool Equals(Type! that,
- TypeVariableSeq! thisBoundVariables,
- TypeVariableSeq! thatBoundVariables) {
+ public override bool Equals(Type/*!*/ that,
+ TypeVariableSeq/*!*/ thisBoundVariables,
+ TypeVariableSeq/*!*/ thatBoundVariables) {
+ //Contract.Requires(thisBoundVariables != null);
+ //Contract.Requires(thatBoundVariables != null);
+ //Contract.Requires(that != null);
BvType thatBvType = TypeProxy.FollowProxy(that.Expanded) as BvType;
return thatBvType != null && this.Bits == thatBvType.Bits;
}
//----------- Unification of types -----------
- public override bool Unify(Type! that,
- TypeVariableSeq! unifiableVariables,
- // an idempotent substitution that describes the
- // unification result up to a certain point
- IDictionary<TypeVariable!, Type!>! unifier) {
+ public override bool Unify(Type/*!*/ that,
+ TypeVariableSeq/*!*/ unifiableVariables,
+ // an idempotent substitution that describes the
+ // unification result up to a certain point
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ unifier) {
+ //Contract.Requires(that != null);
+ //Contract.Requires(unifiableVariables != null);
+ Contract.Requires(cce.NonNullElements(unifier));
that = that.Expanded;
if (that is TypeProxy || that is TypeVariable) {
return that.Unify(this, unifiableVariables, unifier);
@@ -843,11 +1078,13 @@ namespace Microsoft.Boogie
}
#if OLD_UNIFICATION
- public override void Unify(Type! that,
+ public override void Unify(Type that,
TypeVariableSeq! unifiableVariables,
TypeVariableSeq! thisBoundVariables,
TypeVariableSeq! thatBoundVariables,
- IDictionary<TypeVariable!, Type!>! result) {
+ IDictionary<TypeVariable!, Type!> result){
+Contract.Requires(result != null);
+Contract.Requires(that != null);
that = that.Expanded;
if (that is TypeVariable) {
that.Unify(this, unifiableVariables, thatBoundVariables, thisBoundVariables, result);
@@ -860,45 +1097,61 @@ namespace Microsoft.Boogie
//----------- Substitution of free variables with types not containing bound variables -----------------
- public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
+ public override Type Substitute(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst) {
+ //Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
return this;
}
//----------- Hashcodes ----------------------------------
[Pure]
- public override int GetHashCode(TypeVariableSeq! boundVariables)
- {
+ public override int GetHashCode(TypeVariableSeq boundVariables) {
+ //Contract.Requires(boundVariables != null);
return this.Bits.GetHashCode();
}
//----------- Resolution ----------------------------------
- public override Type! ResolveType(ResolutionContext! rc) {
+ public override Type ResolveType(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
// nothing to resolve
return this;
}
// determine the free variables in a type, in the order in which the variables occur
- public override TypeVariableSeq! FreeVariables {
+ public override TypeVariableSeq/*!*/ FreeVariables {
get {
- return new TypeVariableSeq (); // bitvector-type are closed
+ Contract.Ensures(Contract.Result<TypeVariableSeq>() != null);
+
+ return new TypeVariableSeq(); // bitvector-type are closed
}
}
- public override List<TypeProxy!>! FreeProxies { get {
- return new List<TypeProxy!> ();
- } }
+ public override List<TypeProxy/*!*/>/*!*/ FreeProxies {
+ get {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<TypeProxy>>()));
+ return new List<TypeProxy/*!*/>();
+ }
+ }
//----------- Getters/Issers ----------------------------------
- public override bool IsBv { get { return true; } }
- public override int BvBits { get {
- return Bits;
- } }
+ public override bool IsBv {
+ get {
+ return true;
+ }
+ }
+ public override int BvBits {
+ get {
+ return Bits;
+ }
+ }
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitBvType(this);
}
}
@@ -909,16 +1162,26 @@ namespace Microsoft.Boogie
// will be turned either into a TypeVariable, into a CtorType or into a BvType
// during the resolution phase
public class UnresolvedTypeIdentifier : Type {
- public readonly string! Name;
- public readonly TypeSeq! Arguments;
+ public readonly string/*!*/ Name;
+ public readonly TypeSeq/*!*/ Arguments;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Name != null);
+ Contract.Invariant(Arguments != null);
+ }
+
- public UnresolvedTypeIdentifier(IToken! token, string! name) {
- this(token, name, new TypeSeq ());
+ public UnresolvedTypeIdentifier(IToken token, string name)
+ : this(token, name, new TypeSeq()) {
+ Contract.Requires(name != null);
+ Contract.Requires(token != null);
}
- public UnresolvedTypeIdentifier(IToken! token, string! name, TypeSeq! arguments)
- : base(token)
- {
+ public UnresolvedTypeIdentifier(IToken token, string name, TypeSeq arguments)
+ : base(token) {
+ Contract.Requires(arguments != null);
+ Contract.Requires(name != null);
+ Contract.Requires(token != null);
this.Name = name;
this.Arguments = arguments;
}
@@ -928,64 +1191,93 @@ namespace Microsoft.Boogie
// have to be created in the right way. It is /not/ ok to just clone
// everything recursively
- public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
- TypeSeq! newArgs = new TypeSeq ();
- foreach(Type! t in Arguments)
+ public override Type Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap) {
+ //Contract.Requires(cce.NonNullElements(varMap));
+ Contract.Ensures(Contract.Result<Type>() != null);
+ TypeSeq/*!*/ newArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
newArgs.Add(t.Clone(varMap));
+ }
return new UnresolvedTypeIdentifier(tok, Name, newArgs);
}
- public override Type! CloneUnresolved() {
- TypeSeq! newArgs = new TypeSeq ();
- foreach(Type! t in Arguments)
+ public override Type CloneUnresolved() {
+ Contract.Ensures(Contract.Result<Type>() != null);
+ TypeSeq/*!*/ newArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
newArgs.Add(t.CloneUnresolved());
+ }
return new UnresolvedTypeIdentifier(tok, Name, newArgs);
}
//----------- Equality ----------------------------------
[Pure]
- public override bool Equals(Type! that,
- TypeVariableSeq! thisBoundVariables,
- TypeVariableSeq! thatBoundVariables) {
+ public override bool Equals(Type that,
+ TypeVariableSeq/*!*/ thisBoundVariables,
+ TypeVariableSeq/*!*/ thatBoundVariables) {
+ Contract.Requires(thisBoundVariables != null);
+ Contract.Requires(thatBoundVariables != null);
+ Contract.Requires(that != null);
System.Diagnostics.Debug.Fail("UnresolvedTypeIdentifier.Equals should never be called");
return false; // to make the compiler happy
}
//----------- Unification of types -----------
- public override bool Unify(Type! that,
- TypeVariableSeq! unifiableVariables,
- IDictionary<TypeVariable!, Type!>! result) {
- assert false; // UnresolvedTypeIdentifier.Unify should never be called
+ public override bool Unify(Type that,
+ TypeVariableSeq/*!*/ unifiableVariables,
+ IDictionary<TypeVariable/*!*/, Type/*!*/> result) {
+ Contract.Requires(unifiableVariables != null);
+ Contract.Requires(cce.NonNullElements(result));
+ Contract.Requires(that != null);
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // UnresolvedTypeIdentifier.Unify should never be called
}
#if OLD_UNIFICATION
- public override void Unify(Type! that,
+ public override void Unify(Type that,
TypeVariableSeq! unifiableVariables,
TypeVariableSeq! thisBoundVariables,
TypeVariableSeq! thatBoundVariables,
- IDictionary<TypeVariable!, Type!>! result) {
+ IDictionary<TypeVariable!, Type!> result){
+Contract.Requires(result != null);
+Contract.Requires(that != null);
System.Diagnostics.Debug.Fail("UnresolvedTypeIdentifier.Unify should never be called");
}
#endif
//----------- Substitution of free variables with types not containing bound variables -----------------
- public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
- assert false; // UnresolvedTypeIdentifier.Substitute should never be called
+ public override Type Substitute(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst) {
+ Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // UnresolvedTypeIdentifier.Substitute should never be called
}
//----------- Hashcodes ----------------------------------
[Pure]
- public override int GetHashCode(TypeVariableSeq! boundVariables) {
- assert false; // UnresolvedTypeIdentifier.GetHashCode should never be called
+ public override int GetHashCode(TypeVariableSeq boundVariables) {
+ Contract.Requires(boundVariables != null);
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // UnresolvedTypeIdentifier.GetHashCode should never be called
}
//----------- Resolution ----------------------------------
- public override Type! ResolveType(ResolutionContext! rc) {
+ public override Type ResolveType(ResolutionContext rc) {
+ Contract.Requires(rc != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
// first case: the type name denotes a bitvector-type
if (Name.StartsWith("bv") && Name.Length > 2) {
bool is_bv = true;
@@ -1026,7 +1318,7 @@ namespace Microsoft.Boogie
ctorDecl);
return this;
}
- return new CtorType (tok, ctorDecl, ResolveArguments(rc));
+ return new CtorType(tok, ctorDecl, ResolveArguments(rc));
}
// fourth case: the identifier denotes a type synonym
@@ -1038,8 +1330,8 @@ namespace Microsoft.Boogie
synDecl);
return this;
}
- TypeSeq! resolvedArgs = ResolveArguments(rc);
-
+ TypeSeq/*!*/ resolvedArgs = ResolveArguments(rc);
+ Contract.Assert(resolvedArgs != null);
return new TypeSynonymAnnotation(this.tok, synDecl, resolvedArgs);
@@ -1050,27 +1342,36 @@ namespace Microsoft.Boogie
return this;
}
- private TypeSeq! ResolveArguments(ResolutionContext! rc) {
- TypeSeq! resolvedArgs = new TypeSeq ();
- foreach (Type! t in Arguments)
+ private TypeSeq ResolveArguments(ResolutionContext rc) {
+ Contract.Requires(rc != null);
+ Contract.Ensures(Contract.Result<TypeSeq>() != null);
+ TypeSeq/*!*/ resolvedArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
resolvedArgs.Add(t.ResolveType(rc));
+ }
return resolvedArgs;
}
- public override TypeVariableSeq! FreeVariables {
+ public override TypeVariableSeq/*!*/ FreeVariables {
get {
- return new TypeVariableSeq ();
- }
+ Contract.Ensures(Contract.Result<TypeVariableSeq>() != null);
+
+ return new TypeVariableSeq();
+ }
}
- public override List<TypeProxy!>! FreeProxies { get {
- return new List<TypeProxy!> ();
- } }
+ public override List<TypeProxy/*!*/>/*!*/ FreeProxies {
+ get {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<TypeProxy>>()));
+ return new List<TypeProxy/*!*/>();
+ }
+ }
//----------- Linearisation ----------------------------------
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength) {
+ //Contract.Requires(stream != null);
stream.SetToken(this);
// PR: should unresolved types be syntactically distinguished from resolved types?
CtorType.EmitCtorType(this.Name, Arguments, stream, contextBindingStrength);
@@ -1078,11 +1379,21 @@ namespace Microsoft.Boogie
//----------- Getters/Issers ----------------------------------
- public override bool IsUnresolved { get { return true; } }
- public override UnresolvedTypeIdentifier! AsUnresolved { get { return this; } }
+ public override bool IsUnresolved {
+ get {
+ return true;
+ }
+ }
+ public override UnresolvedTypeIdentifier/*!*/ AsUnresolved {
+ get {
+ Contract.Ensures(Contract.Result<UnresolvedTypeIdentifier>() != null);
+ return this;
+ }
+ }
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitUnresolvedTypeIdentifier(this);
}
}
@@ -1090,11 +1401,17 @@ namespace Microsoft.Boogie
//=====================================================================
public class TypeVariable : Type {
- public readonly string! Name;
+ public readonly string/*!*/ Name;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Name != null);
+ }
- public TypeVariable(IToken! token, string! name)
- : base(token)
- {
+
+ public TypeVariable(IToken token, string name)
+ : base(token) {
+ Contract.Requires(name != null);
+ Contract.Requires(token != null);
this.Name = name;
}
@@ -1103,7 +1420,9 @@ namespace Microsoft.Boogie
// have to be created in the right way. It is /not/ ok to just clone
// everything recursively
- public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
+ public override Type Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap) {
+ //Contract.Requires(cce.NonNullElements(varMap));
+ Contract.Ensures(Contract.Result<Type>() != null);
// if this variable is mapped to some new variable, we take the new one
// otherwise, return this
TypeVariable res;
@@ -1114,18 +1433,22 @@ namespace Microsoft.Boogie
return res;
}
- public override Type! CloneUnresolved() {
+ public override Type CloneUnresolved() {
+ Contract.Ensures(Contract.Result<Type>() != null);
return this;
}
//----------- Equality ----------------------------------
[Pure]
- public override bool Equals(Type! that,
- TypeVariableSeq! thisBoundVariables,
- TypeVariableSeq! thatBoundVariables) {
+ public override bool Equals(Type that,
+ TypeVariableSeq/*!*/ thisBoundVariables,
+ TypeVariableSeq/*!*/ thatBoundVariables) {
+ //Contract.Requires(thisBoundVariables != null);
+ //Contract.Requires(thatBoundVariables != null);
+ //Contract.Requires(that != null);
TypeVariable thatAsTypeVar = TypeProxy.FollowProxy(that.Expanded) as TypeVariable;
-
+
if (thatAsTypeVar == null)
return false;
@@ -1138,11 +1461,14 @@ namespace Microsoft.Boogie
//----------- Unification of types -----------
- public override bool Unify(Type! that,
- TypeVariableSeq! unifiableVariables,
- // an idempotent substitution that describes the
- // unification result up to a certain point
- IDictionary<TypeVariable!, Type!>! unifier) {
+ public override bool Unify(Type/*!*/ that,
+ TypeVariableSeq/*!*/ unifiableVariables,
+ // an idempotent substitution that describes the
+ // unification result up to a certain point
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ unifier) {
+ //Contract.Requires(that != null);
+ //Contract.Requires(unifiableVariables != null);
+ //Contract.Requires(cce.NonNullElements(unifier));
that = that.Expanded;
if (that is TypeProxy && !(that is ConstrainedProxy))
return that.Unify(this, unifiableVariables, unifier);
@@ -1163,9 +1489,9 @@ namespace Microsoft.Boogie
// this cannot be instantiated with anything
// but that possibly can ...
-
+
TypeVariable tv = that as TypeVariable;
-
+
return tv != null &&
unifiableVariables.Has(tv) &&
that.Unify(this, unifiableVariables, unifier);
@@ -1174,43 +1500,50 @@ namespace Microsoft.Boogie
// TODO: the following might cause problems, because when applying substitutions
// to type proxies the substitutions are not propagated to the proxy
// constraints (right now at least)
- private bool addSubstitution(IDictionary<TypeVariable!, Type!>! oldSolution,
- // the type that "this" is instantiated with
- Type! newSubst)
- requires !oldSolution.ContainsKey(this); {
-
- Dictionary<TypeVariable!, Type!>! newMapping = new Dictionary<TypeVariable!, Type!> ();
+ private bool addSubstitution(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ oldSolution,
+ // the type that "this" is instantiated with
+ Type/*!*/ newSubst) {
+ Contract.Requires(cce.NonNullElements(oldSolution));
+ Contract.Requires(newSubst != null);
+ Contract.Requires(!oldSolution.ContainsKey(this));
+
+ Dictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ newMapping = new Dictionary<TypeVariable/*!*/, Type/*!*/>();
// apply the old (idempotent) substitution to the new instantiation
- Type! substSubst = newSubst.Substitute(oldSolution);
+ Type/*!*/ substSubst = newSubst.Substitute(oldSolution);
+ Contract.Assert(substSubst != null);
// occurs check
if (substSubst.FreeVariables.Has(this))
return false;
newMapping.Add(this, substSubst);
// apply the new substitution to the old ones to ensure idempotence
- List<TypeVariable!>! keys = new List<TypeVariable!> ();
+ List<TypeVariable/*!*/>/*!*/ keys = new List<TypeVariable/*!*/>();
keys.AddRange(oldSolution.Keys);
- foreach (TypeVariable! var in keys)
+ foreach (TypeVariable/*!*/ var in keys) {
+ Contract.Assert(var != null);
oldSolution[var] = oldSolution[var].Substitute(newMapping);
+ }
oldSolution.Add(this, substSubst);
- assert IsIdempotent(oldSolution);
+ Contract.Assert(IsIdempotent(oldSolution));
return true;
}
#if OLD_UNIFICATION
- public override void Unify(Type! that,
+ public override void Unify(Type that,
TypeVariableSeq! unifiableVariables,
TypeVariableSeq! thisBoundVariables,
TypeVariableSeq! thatBoundVariables,
- IDictionary<TypeVariable!, Type!>! result) {
+ IDictionary<TypeVariable!, Type!> result){
+Contract.Requires(result != null);
+Contract.Requires(that != null);
that = that.Expanded;
int thisIndex = thisBoundVariables.LastIndexOf(this);
if (thisIndex == -1) {
// this is not a bound variable and can possibly be matched on that
// that must not contain any bound variables
TypeVariableSeq! thatFreeVars = that.FreeVariables;
- if (exists{TypeVariable! var in thatBoundVariables; thatFreeVars.Has(var)})
+ if (Contract.Exists(thatBoundVariables, var=> thatFreeVars.Has(var)))
throw UNIFICATION_FAILED;
// otherwise, in case that is a typevariable it cannot be bound and
@@ -1250,10 +1583,12 @@ namespace Microsoft.Boogie
//----------- Substitution of free variables with types not containing bound variables -----------------
- public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
+ public override Type Substitute(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst) {
+ //Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
Type res;
if (subst.TryGetValue(this, out res)) {
- assert res != null;
+ Contract.Assert(res != null);
return res;
} else {
return this;
@@ -1263,7 +1598,8 @@ namespace Microsoft.Boogie
//----------- Hashcodes ----------------------------------
[Pure]
- public override int GetHashCode(TypeVariableSeq! boundVariables) {
+ public override int GetHashCode(TypeVariableSeq boundVariables) {
+ //Contract.Requires(boundVariables != null);
int thisIndex = boundVariables.LastIndexOf(this);
if (thisIndex == -1)
return GetBaseHashCode();
@@ -1272,8 +1608,8 @@ namespace Microsoft.Boogie
//----------- Linearisation ----------------------------------
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength) {
+ //Contract.Requires(stream != null);
// never put parentheses around variables
stream.SetToken(this);
stream.Write("{0}", TokenTextWriter.SanitizeIdentifier(this.Name));
@@ -1281,26 +1617,44 @@ namespace Microsoft.Boogie
//----------- Resolution ----------------------------------
- public override Type! ResolveType(ResolutionContext! rc) {
+ public override Type ResolveType(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ //Contract.Ensures(Contract.Result<Type>() != null);
// nothing to resolve
return this;
}
- public override TypeVariableSeq! FreeVariables {
- get { return new TypeVariableSeq(this); }
+ public override TypeVariableSeq/*!*/ FreeVariables {
+ get {
+ Contract.Ensures(Contract.Result<TypeVariableSeq>() != null);
+ return new TypeVariableSeq(this);
+ }
}
- public override List<TypeProxy!>! FreeProxies { get {
- return new List<TypeProxy!> ();
- } }
+ public override List<TypeProxy/*!*/>/*!*/ FreeProxies {
+ get {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<TypeProxy>>()));
+ return new List<TypeProxy/*!*/>();
+ }
+ }
//----------- Getters/Issers ----------------------------------
- public override bool IsVariable { get { return true; } }
- public override TypeVariable! AsVariable { get { return this; } }
+ public override bool IsVariable {
+ get {
+ return true;
+ }
+ }
+ public override TypeVariable/*!*/ AsVariable {
+ get {
+ Contract.Ensures(Contract.Result<TypeVariable>() != null);
+ return this;
+ }
+ }
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ //Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitTypeVariable(this);
}
}
@@ -1309,18 +1663,27 @@ namespace Microsoft.Boogie
public class TypeProxy : Type {
static int proxies = 0;
- protected readonly string! Name;
-
- public TypeProxy(IToken! token, string! givenName)
- {
- this(token, givenName, "proxy");
+ protected readonly string/*!*/ Name;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Name != null);
}
-
- protected TypeProxy(IToken! token, string! givenName, string! kind)
- {
+
+
+ public TypeProxy(IToken token, string givenName)
+ : this(token, givenName, "proxy") {
+ Contract.Requires(givenName != null);
+ Contract.Requires(token != null);
+ }
+
+ protected TypeProxy(IToken token, string givenName, string kind)
+ : base(token) {//BASEMOVE DANGER
+ Contract.Requires(kind != null);
+ Contract.Requires(givenName != null);
+ Contract.Requires(token != null);
Name = givenName + "$" + kind + "#" + proxies;
proxies++;
- base(token);
+ //:base(token);
}
private Type proxyFor;
@@ -1331,16 +1694,18 @@ namespace Microsoft.Boogie
if (anotherProxy != null && anotherProxy.proxyFor != null) {
// apply path shortening by bypassing "anotherProxy" (and possibly others)
proxyFor = anotherProxy.ProxyFor;
- assert proxyFor != null;
+ Contract.Assert(proxyFor != null);
}
return proxyFor;
}
}
-
- [Pure][Reads(ReadsAttribute.Reads.Everything)]
- public static Type! FollowProxy(Type! t)
- ensures result is TypeProxy ==> ((TypeProxy)result).proxyFor == null;
- {
+
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Everything)]
+ public static Type FollowProxy(Type t) {
+ Contract.Requires(t != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+ Contract.Ensures(!(Contract.Result<Type>() is TypeProxy) || ((TypeProxy)Contract.Result<Type>()).proxyFor == null);
if (t is TypeProxy) {
Type p = ((TypeProxy)t).ProxyFor;
if (p != null) {
@@ -1349,20 +1714,22 @@ namespace Microsoft.Boogie
}
return t;
}
-
- protected void DefineProxy(Type! ty)
- requires ProxyFor == null;
- {
+
+ protected void DefineProxy(Type ty) {
+ Contract.Requires(ty != null);
+ Contract.Requires(ProxyFor == null);
// follow ty down to the leaf level, so that we can avoid creating a cycle
ty = FollowProxy(ty);
if (!object.ReferenceEquals(this, ty)) {
proxyFor = ty;
}
}
-
+
//----------- Cloning ----------------------------------
- public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
+ public override Type Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap) {
+ //Contract.Requires(cce.NonNullElements(varMap));
+ Contract.Ensures(Contract.Result<Type>() != null);
Type p = ProxyFor;
if (p != null) {
return p.Clone(varMap);
@@ -1371,16 +1738,20 @@ namespace Microsoft.Boogie
}
}
- public override Type! CloneUnresolved() {
+ public override Type CloneUnresolved() {
+ Contract.Ensures(Contract.Result<Type>() != null);
return new TypeProxy(this.tok, this.Name); // the clone will have a name that ends with $proxy<n>$proxy<m>
}
//----------- Equality ----------------------------------
[Pure]
- public override bool Equals(Type! that,
- TypeVariableSeq! thisBoundVariables,
- TypeVariableSeq! thatBoundVariables) {
+ public override bool Equals(Type that,
+ TypeVariableSeq/*!*/ thisBoundVariables,
+ TypeVariableSeq/*!*/ thatBoundVariables) {
+ //Contract.Requires(thisBoundVariables != null);
+ //Contract.Requires(thatBoundVariables != null);
+ //Contract.Requires(that != null);
if (object.ReferenceEquals(this, that)) {
return true;
}
@@ -1396,15 +1767,19 @@ namespace Microsoft.Boogie
//----------- Unification of types -----------
// determine whether the occurs check fails: this is a strict subtype of that
- protected bool ReallyOccursIn(Type! that) {
+ protected bool ReallyOccursIn(Type that) {
+ Contract.Requires(that != null);
that = FollowProxy(that.Expanded);
return that.FreeProxies.Contains(this) &&
(that.IsCtor || that.IsMap && this != that && this.ProxyFor != that);
}
- public override bool Unify(Type! that,
- TypeVariableSeq! unifiableVariables,
- IDictionary<TypeVariable!, Type!>! result) {
+ public override bool Unify(Type that,
+ TypeVariableSeq/*!*/ unifiableVariables,
+ IDictionary<TypeVariable/*!*/, Type/*!*/> result) {
+ //Contract.Requires(cce.NonNullElements(result));
+ //Contract.Requires(unifiableVariables != null);
+ //Contract.Requires(that != null);
Type p = ProxyFor;
if (p != null) {
return p.Unify(that, unifiableVariables, result);
@@ -1419,7 +1794,9 @@ namespace Microsoft.Boogie
//----------- Substitution of free variables with types not containing bound variables -----------------
- public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
+ public override Type Substitute(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst) {
+ //Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
Type p = ProxyFor;
if (p != null) {
return p.Substitute(subst);
@@ -1431,7 +1808,8 @@ namespace Microsoft.Boogie
//----------- Hashcodes ----------------------------------
[Pure]
- public override int GetHashCode(TypeVariableSeq! boundVariables) {
+ public override int GetHashCode(TypeVariableSeq boundVariables) {
+ //Contract.Requires(boundVariables != null);
Type p = ProxyFor;
if (p != null) {
return p.GetHashCode(boundVariables);
@@ -1442,8 +1820,8 @@ namespace Microsoft.Boogie
//----------- Linearisation ----------------------------------
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength) {
+ //Contract.Requires(stream != null);
Type p = ProxyFor;
if (p != null) {
p.Emit(stream, contextBindingStrength);
@@ -1456,7 +1834,9 @@ namespace Microsoft.Boogie
//----------- Resolution ----------------------------------
- public override Type! ResolveType(ResolutionContext! rc) {
+ public override Type ResolveType(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
Type p = ProxyFor;
if (p != null) {
return p.ResolveType(rc);
@@ -1465,108 +1845,153 @@ namespace Microsoft.Boogie
}
}
- public override TypeVariableSeq! FreeVariables {
- get {
- Type p = ProxyFor;
- if (p != null) {
- return p.FreeVariables;
- } else {
- return new TypeVariableSeq();
- }
- }
+ public override TypeVariableSeq/*!*/ FreeVariables {
+ get {
+ Contract.Ensures(Contract.Result<TypeVariableSeq>() != null);
+
+ Type p = ProxyFor;
+ if (p != null) {
+ return p.FreeVariables;
+ } else {
+ return new TypeVariableSeq();
+ }
+ }
}
- public override List<TypeProxy!>! FreeProxies { get {
- Type p = ProxyFor;
- if (p != null) {
- return p.FreeProxies;
- } else {
- List<TypeProxy!>! res = new List<TypeProxy!> ();
- res.Add(this);
- return res;
- }
- } }
+ public override List<TypeProxy/*!*/>/*!*/ FreeProxies {
+ get {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<TypeProxy>>()));
+ Type p = ProxyFor;
+ if (p != null) {
+ return p.FreeProxies;
+ } else {
+ List<TypeProxy/*!*/>/*!*/ res = new List<TypeProxy/*!*/>();
+ res.Add(this);
+ return res;
+ }
+ }
+ }
//----------- Getters/Issers ----------------------------------
- public override bool IsBasic { get {
- Type p = ProxyFor;
- return p != null && p.IsBasic;
- } }
- public override bool IsInt { get {
- Type p = ProxyFor;
- return p != null && p.IsInt;
- } }
- public override bool IsBool { get {
- Type p = ProxyFor;
- return p != null && p.IsBool;
- } }
+ public override bool IsBasic {
+ get {
+ Type p = ProxyFor;
+ return p != null && p.IsBasic;
+ }
+ }
+ public override bool IsInt {
+ get {
+ Type p = ProxyFor;
+ return p != null && p.IsInt;
+ }
+ }
+ public override bool IsBool {
+ get {
+ Type p = ProxyFor;
+ return p != null && p.IsBool;
+ }
+ }
- public override bool IsVariable { get {
- Type p = ProxyFor;
- return p != null && p.IsVariable;
- } }
- public override TypeVariable! AsVariable { get {
- Type p = ProxyFor;
- assume p != null;
- return p.AsVariable;
- } }
+ public override bool IsVariable {
+ get {
+ Type p = ProxyFor;
+ return p != null && p.IsVariable;
+ }
+ }
+ public override TypeVariable/*!*/ AsVariable {
+ get {
+ Contract.Ensures(Contract.Result<TypeVariable>() != null);
- public override bool IsCtor { get {
- Type p = ProxyFor;
- return p != null && p.IsCtor;
- } }
- public override CtorType! AsCtor { get {
- Type p = ProxyFor;
- assume p != null;
- return p.AsCtor;
- } }
- public override bool IsMap { get {
- Type p = ProxyFor;
- return p != null && p.IsMap;
- } }
- public override MapType! AsMap { get {
- Type p = ProxyFor;
- assume p != null;
- return p.AsMap;
- } }
- public override int MapArity { get {
- Type p = ProxyFor;
- assume p != null;
- return p.MapArity;
- } }
- public override bool IsUnresolved { get {
- Type p = ProxyFor;
- return p != null && p.IsUnresolved;
- } }
- public override UnresolvedTypeIdentifier! AsUnresolved { get {
- Type p = ProxyFor;
- assume p != null;
- return p.AsUnresolved;
- } }
+ Type p = ProxyFor;
+ Contract.Assume(p != null);
+ return p.AsVariable;
+ }
+ }
- public override bool IsBv { get {
- Type p = ProxyFor;
- return p != null && p.IsBv;
- } }
- public override int BvBits { get {
- Type p = ProxyFor;
- assume p != null;
- return p.BvBits;
- } }
+ public override bool IsCtor {
+ get {
+ Type p = ProxyFor;
+ return p != null && p.IsCtor;
+ }
+ }
+ public override CtorType/*!*/ AsCtor {
+ get {
+ Contract.Ensures(Contract.Result<CtorType>() != null);
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ Type p = ProxyFor;
+ Contract.Assume(p != null);
+ return p.AsCtor;
+ }
+ }
+ public override bool IsMap {
+ get {
+ Type p = ProxyFor;
+ return p != null && p.IsMap;
+ }
+ }
+ public override MapType/*!*/ AsMap {
+ get {
+ Contract.Ensures(Contract.Result<MapType>() != null);
+
+ Type p = ProxyFor;
+ Contract.Assume(p != null);
+ return p.AsMap;
+ }
+ }
+ public override int MapArity {
+ get {
+ Type p = ProxyFor;
+ Contract.Assume(p != null);
+ return p.MapArity;
+ }
+ }
+ public override bool IsUnresolved {
+ get {
+ Type p = ProxyFor;
+ return p != null && p.IsUnresolved;
+ }
+ }
+ public override UnresolvedTypeIdentifier/*!*/ AsUnresolved {
+ get {
+ Contract.Ensures(Contract.Result<UnresolvedTypeIdentifier>() != null);
+
+ Type p = ProxyFor;
+ Contract.Assume(p != null);
+ return p.AsUnresolved;
+ }
+ }
+
+ public override bool IsBv {
+ get {
+ Type p = ProxyFor;
+ return p != null && p.IsBv;
+ }
+ }
+ public override int BvBits {
+ get {
+ Type p = ProxyFor;
+ Contract.Assume(p != null);
+ return p.BvBits;
+ }
+ }
+
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitTypeProxy(this);
}
}
public abstract class ConstrainedProxy : TypeProxy {
- protected ConstrainedProxy(IToken! token, string! givenName, string! kind) {
- base(token, givenName, kind);
+ protected ConstrainedProxy(IToken token, string givenName, string kind)
+ : base(token, givenName, kind) {
+ Contract.Requires(kind != null);
+ Contract.Requires(givenName != null);
+ Contract.Requires(token != null);
}
}
-
+
/// <summary>
/// Each instance of this class represents a set of bitvector types. In particular, it represents
/// a bitvector type bvN iff
@@ -1587,21 +2012,29 @@ namespace Microsoft.Boogie
/// </summary>
public class BvTypeProxy : ConstrainedProxy {
public int MinBits;
- List<BvTypeConstraint!> constraints;
+ List<BvTypeConstraint/*!*/> constraints;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(constraints, true));
+ }
+
class BvTypeConstraint {
- public Type! T0;
- public Type! T1;
- public BvTypeConstraint(Type! t0, Type! t1)
- requires t0.IsBv && t1.IsBv;
- {
+ public Type/*!*/ T0;
+ public Type/*!*/ T1;
+ public BvTypeConstraint(Type t0, Type t1) {
+ Contract.Requires(t1 != null);
+ Contract.Requires(t0 != null);
+ Contract.Requires(t0.IsBv && t1.IsBv);
T0 = t0;
T1 = t1;
}
}
-
- public BvTypeProxy(IToken! token, string! name, int minBits)
- {
- base(token, name, "bv" + minBits + "proxy");
+
+ public BvTypeProxy(IToken token, string name, int minBits)
+ : base(token, name, "bv" + minBits + "proxy") {//BASEMOVEA
+ Contract.Requires(name != null);
+ Contract.Requires(token != null);
+ //base(token, name, "bv" + minBits + "proxy");
this.MinBits = minBits;
}
@@ -1609,39 +2042,49 @@ namespace Microsoft.Boogie
/// Requires that any further constraints to be placed on t0 and t1 go via the object to
/// be constructed.
/// </summary>
- public BvTypeProxy(IToken! token, string! name, Type! t0, Type! t1)
- requires t0.IsBv && t1.IsBv;
- {
- base(token, name, "bvproxy");
+ public BvTypeProxy(IToken token, string name, Type t0, Type t1)
+ : base(token, name, "bvproxy") {//BASEMOVEA
+ Contract.Requires(t1 != null);
+ Contract.Requires(t0 != null);
+ Contract.Requires(name != null);
+ Contract.Requires(token != null);
+ Contract.Requires(t0.IsBv && t1.IsBv);
+ //:base(token, name, "bvproxy");
t0 = FollowProxy(t0);
t1 = FollowProxy(t1);
this.MinBits = MinBitsFor(t0) + MinBitsFor(t1);
- List<BvTypeConstraint!> list = new List<BvTypeConstraint!>();
+ List<BvTypeConstraint/*!*/> list = new List<BvTypeConstraint/*!*/>();
list.Add(new BvTypeConstraint(t0, t1));
this.constraints = list;
}
-
+
/// <summary>
/// Construct a BvTypeProxy like p, but with minBits.
/// </summary>
- private BvTypeProxy(BvTypeProxy! p, int minBits)
- {
- base(p.tok, p.Name, "");
+ private BvTypeProxy(BvTypeProxy p, int minBits)
+ : base(p.tok, p.Name, "") {//BASEMOVEA
+ Contract.Requires(p != null);
+ //:base(p.tok, p.Name, "");
this.MinBits = minBits;
this.constraints = p.constraints;
}
-
- private BvTypeProxy(IToken! token, string! name, int minBits, List<BvTypeConstraint!> constraints) {
- base(token, name, "");
+
+ private BvTypeProxy(IToken token, string name, int minBits, List<BvTypeConstraint/*!*/> constraints)
+ : base(token, name, "") {//BASEMOVEA
+ Contract.Requires(cce.NonNullElements(constraints, true));
+ Contract.Requires(name != null);
+ Contract.Requires(token != null);
+ //:base(token, name, "");
this.MinBits = minBits;
this.constraints = constraints;
}
-
- [Pure][Reads(ReadsAttribute.Reads.Everything)]
- private static int MinBitsFor(Type! t)
- requires t.IsBv;
- ensures 0 <= result;
- {
+
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Everything)]
+ private static int MinBitsFor(Type t) {
+ Contract.Requires(t != null);
+ Contract.Requires(t.IsBv);
+ Contract.Ensures(0 <= Contract.Result<int>());
if (t is BvType) {
return t.BvBits;
} else {
@@ -1651,7 +2094,9 @@ namespace Microsoft.Boogie
//----------- Cloning ----------------------------------
- public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
+ public override Type Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap) {
+ //Contract.Requires(cce.NonNullElements(varMap));
+ Contract.Ensures(Contract.Result<Type>() != null);
Type p = ProxyFor;
if (p != null) {
return p.Clone(varMap);
@@ -1660,15 +2105,19 @@ namespace Microsoft.Boogie
}
}
- public override Type! CloneUnresolved() {
+ public override Type CloneUnresolved() {
+ Contract.Ensures(Contract.Result<Type>() != null);
return new BvTypeProxy(this.tok, this.Name, this.MinBits, this.constraints); // the clone will have a name that ends with $bvproxy<n>$bvproxy<m>
}
//----------- Unification of types -----------
- public override bool Unify(Type! that,
- TypeVariableSeq! unifiableVariables,
- IDictionary<TypeVariable!, Type!>! result) {
+ public override bool Unify(Type that,
+ TypeVariableSeq unifiableVariables,
+ IDictionary<TypeVariable, Type> result) {
+ //Contract.Requires(cce.NonNullElements(result));
+ //Contract.Requires(unifiableVariables != null);
+ //Contract.Requires(that != null);
Type p = ProxyFor;
if (p != null) {
return p.Unify(that, unifiableVariables, result);
@@ -1695,7 +2144,7 @@ namespace Microsoft.Boogie
int minT1 = MinBitsFor(btc.T1);
int left = IncreaseBits(btc.T0, that.BvBits - minT1);
left = IncreaseBits(btc.T1, minT1 + left);
- assert left == 0; // because it should always be possible to increase the total size of a BvTypeConstraint pair (t0,t1) arbitrarily
+ Contract.Assert(left == 0); // because it should always be possible to increase the total size of a BvTypeConstraint pair (t0,t1) arbitrarily
}
}
DefineProxy(that);
@@ -1707,10 +2156,14 @@ namespace Microsoft.Boogie
// has a constraints list, then concatenate both constraints lists and define the previous
// proxies to the new one
if (this.constraints != null || bt.constraints != null) {
- List<BvTypeConstraint!> list = new List<BvTypeConstraint!>();
- if (this.constraints != null) { list.AddRange(this.constraints); }
- if (bt.constraints != null) { list.AddRange(bt.constraints); }
- BvTypeProxy np = new BvTypeProxy(this.tok, this.Name, max{this.MinBits, bt.MinBits}, list);
+ List<BvTypeConstraint/*!*/> list = new List<BvTypeConstraint/*!*/>();
+ if (this.constraints != null) {
+ list.AddRange(this.constraints);
+ }
+ if (bt.constraints != null) {
+ list.AddRange(bt.constraints);
+ }
+ BvTypeProxy np = new BvTypeProxy(this.tok, this.Name, Math.Max(this.MinBits, bt.MinBits), list);
this.DefineProxy(np);
bt.DefineProxy(np);
} else if (this.MinBits <= bt.MinBits) {
@@ -1729,16 +2182,16 @@ namespace Microsoft.Boogie
return false;
}
- private static int IncreaseBits(Type! t, int to)
- requires t.IsBv && 0 <= to && MinBitsFor(t) <= to;
- ensures 0 <= result && result <= to;
- {
+ private static int IncreaseBits(Type t, int to) {
+ Contract.Requires(t != null);
+ Contract.Requires(t.IsBv && 0 <= to && MinBitsFor(t) <= to);
+ Contract.Ensures(0 <= Contract.Result<int>() && Contract.Result<int>() <= to);
t = FollowProxy(t);
if (t is BvType) {
return to - t.BvBits;
} else {
BvTypeProxy p = (BvTypeProxy)t;
- assert p.MinBits <= to;
+ Contract.Assert(p.MinBits <= to);
if (p.MinBits < to) {
BvTypeProxy q = new BvTypeProxy(p, to);
p.DefineProxy(q);
@@ -1749,36 +2202,43 @@ namespace Microsoft.Boogie
//----------- Substitution of free variables with types not containing bound variables -----------------
- public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
+ public override Type Substitute(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst) {
+ //Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
if (this.ProxyFor == null) {
// check that the constraints are clean and do not contain any
// of the substituted variables (otherwise, we are in big trouble)
- assert forall{BvTypeConstraint! c in constraints;
- forall{TypeVariable! var in subst.Keys;
- !c.T0.FreeVariables.Has(var) && !c.T1.FreeVariables.Has(var)}};
+ Contract.Assert(Contract.ForAll(constraints, c =>
+ Contract.ForAll(subst.Keys, var =>
+ !c.T0.FreeVariables.Has(var) && !c.T1.FreeVariables.Has(var))));
}
return base.Substitute(subst);
}
-
+
//----------- Getters/Issers ----------------------------------
- public override bool IsBv { get {
- return true;
- } }
- public override int BvBits { get {
- // This method is supposed to return the number of bits supplied, but unless the proxy has been resolved,
- // we only have a lower bound on the number of bits supplied. But this method is not supposed to be
- // called until type checking has finished, at which time the minBits is stable.
- Type p = ProxyFor;
- if (p != null) {
- return p.BvBits;
- } else {
- return MinBits;
+ public override bool IsBv {
+ get {
+ return true;
+ }
+ }
+ public override int BvBits {
+ get {
+ // This method is supposed to return the number of bits supplied, but unless the proxy has been resolved,
+ // we only have a lower bound on the number of bits supplied. But this method is not supposed to be
+ // called until type checking has finished, at which time the minBits is stable.
+ Type p = ProxyFor;
+ if (p != null) {
+ return p.BvBits;
+ } else {
+ return MinBits;
+ }
}
- } }
+ }
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitBvTypeProxy(this);
}
}
@@ -1791,37 +2251,58 @@ namespace Microsoft.Boogie
// constraints can be satisfied.
public class MapTypeProxy : ConstrainedProxy {
public readonly int Arity;
- private readonly List<Constraint>! constraints = new List<Constraint> ();
+ private readonly List<Constraint>/*!*/ constraints = new List<Constraint>();
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(constraints != null);
+ }
+
// each constraint specifies that the given combination of argument/result
// types must be a possible instance of the formal map argument/result types
private struct Constraint {
- public readonly TypeSeq! Arguments;
- public readonly Type! Result;
+ public readonly TypeSeq/*!*/ Arguments;
+ public readonly Type/*!*/ Result;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Arguments != null);
+ Contract.Invariant(Result != null);
+ }
+
- public Constraint(TypeSeq! arguments, Type! result) {
+ public Constraint(TypeSeq arguments, Type result) {
+ Contract.Requires(result != null);
+ Contract.Requires(arguments != null);
Arguments = arguments;
Result = result;
}
- public Constraint Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
- TypeSeq! args = new TypeSeq ();
- foreach (Type! t in Arguments)
+ public Constraint Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap) {
+ Contract.Requires(cce.NonNullElements(varMap));
+ TypeSeq/*!*/ args = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
args.Add(t.Clone(varMap));
- Type! res = Result.Clone(varMap);
+ }
+ Type/*!*/ res = Result.Clone(varMap);
+ Contract.Assert(res != null);
return new Constraint(args, res);
}
- public bool Unify(MapType! that,
- TypeVariableSeq! unifiableVariables,
- IDictionary<TypeVariable!, Type!>! result)
- requires Arguments.Length == that.Arguments.Length; {
- Dictionary<TypeVariable!, Type!>! subst = new Dictionary<TypeVariable!, Type!>();
- foreach (TypeVariable! tv in that.TypeParameters) {
+ public bool Unify(MapType that,
+ TypeVariableSeq/*!*/ unifiableVariables,
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ result) {
+ Contract.Requires(unifiableVariables != null);
+ Contract.Requires(cce.NonNullElements(result));
+ Contract.Requires(that != null);
+ Contract.Requires(Arguments.Length == that.Arguments.Length);
+ Dictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst = new Dictionary<TypeVariable/*!*/, Type/*!*/>();
+ foreach (TypeVariable/*!*/ tv in that.TypeParameters) {
+ Contract.Assert(tv != null);
TypeProxy proxy = new TypeProxy(Token.NoToken, tv.Name);
subst.Add(tv, proxy);
}
-
+
bool good = true;
for (int i = 0; i < that.Arguments.Length; i++) {
Type t0 = that.Arguments[i].Substitute(subst);
@@ -1833,20 +2314,23 @@ namespace Microsoft.Boogie
}
}
- public MapTypeProxy(IToken! token, string! name, int arity)
- requires 0 <= arity; {
- base(token, name, "mapproxy");
+ public MapTypeProxy(IToken token, string name, int arity)
+ : base(token, name, "mapproxy") {//BASEMOVEA
+ Contract.Requires(name != null);
+ Contract.Requires(token != null);
+ Contract.Requires(0 <= arity);
+ //:base(token, name, "mapproxy");
this.Arity = arity;
}
- private void AddConstraint(Constraint c)
- requires c.Arguments.Length == Arity; {
+ private void AddConstraint(Constraint c) {
+ Contract.Requires(c.Arguments.Length == Arity);
Type f = ProxyFor;
MapType mf = f as MapType;
if (mf != null) {
- bool success = c.Unify(mf, new TypeVariableSeq(), new Dictionary<TypeVariable!, Type!> ());
- assert success;
+ bool success = c.Unify(mf, new TypeVariableSeq(), new Dictionary<TypeVariable/*!*/, Type/*!*/>());
+ Contract.Assert(success);
return;
}
@@ -1855,18 +2339,25 @@ namespace Microsoft.Boogie
mpf.AddConstraint(c);
return;
}
-
- assert f == null; // no other types should occur as specialisations of this proxy
+
+ Contract.Assert(f == null); // no other types should occur as specialisations of this proxy
constraints.Add(c);
}
- public Type CheckArgumentTypes(ExprSeq! actualArgs,
- out TypeParamInstantiation! tpInstantiation,
- IToken! typeCheckingSubject,
- string! opName,
- TypecheckingContext! tc)
- {
+ public Type CheckArgumentTypes(ExprSeq/*!*/ actualArgs,
+ out TypeParamInstantiation/*!*/ tpInstantiation,
+ IToken/*!*/ typeCheckingSubject,
+ string/*!*/ opName,
+ TypecheckingContext/*!*/ tc) {
+ Contract.Requires(actualArgs != null);
+ Contract.Requires(typeCheckingSubject != null);
+ Contract.Requires(opName != null);
+ Contract.Requires(tc != null);
+ Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+
+
+
Type f = ProxyFor;
MapType mf = f as MapType;
if (mf != null)
@@ -1876,27 +2367,34 @@ namespace Microsoft.Boogie
if (mpf != null)
return mpf.CheckArgumentTypes(actualArgs, out tpInstantiation, typeCheckingSubject, opName, tc);
- assert f == null; // no other types should occur as specialisations of this proxy
+ Contract.Assert(f == null); // no other types should occur as specialisations of this proxy
// otherwise, we just record the constraints given by this usage of the map type
- TypeSeq! arguments = new TypeSeq ();
- foreach (Expr! e in actualArgs)
+ TypeSeq/*!*/ arguments = new TypeSeq();
+ foreach (Expr/*!*/ e in actualArgs) {
+ Contract.Assert(e != null);
arguments.Add(e.Type);
- Type! result = new TypeProxy (tok, "result");
- AddConstraint(new Constraint (arguments, result));
+ }
+ Type/*!*/ result = new TypeProxy(tok, "result");
+ Contract.Assert(result != null);
+ AddConstraint(new Constraint(arguments, result));
- TypeSeq! argumentsResult = new TypeSeq ();
- foreach (Expr! e in actualArgs)
+ TypeSeq/*!*/ argumentsResult = new TypeSeq();
+ foreach (Expr/*!*/ e in actualArgs) {
+ Contract.Assert(e != null);
argumentsResult.Add(e.Type);
+ }
argumentsResult.Add(result);
-
+
tpInstantiation = new MapTypeProxyParamInstantiation(this, argumentsResult);
return result;
}
//----------- Cloning ----------------------------------
- public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
+ public override Type Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap) {
+ //Contract.Requires(cce.NonNullElements(varMap));
+ Contract.Ensures(Contract.Result<Type>() != null);
Type p = ProxyFor;
if (p != null) {
return p.Clone(varMap);
@@ -1910,14 +2408,14 @@ namespace Microsoft.Boogie
//----------- Linearisation ----------------------------------
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength) {
+ //Contract.Requires(stream != null);
Type p = ProxyFor;
if (p != null) {
p.Emit(stream, contextBindingStrength);
} else {
stream.Write("[");
- string! sep = "";
+ string/*!*/ sep = "";
for (int i = 0; i < Arity; ++i) {
stream.Write(sep);
sep = ", ";
@@ -1929,9 +2427,12 @@ namespace Microsoft.Boogie
//----------- Unification of types -----------
- public override bool Unify(Type! that,
- TypeVariableSeq! unifiableVariables,
- IDictionary<TypeVariable!, Type!>! result) {
+ public override bool Unify(Type/*!*/ that,
+ TypeVariableSeq/*!*/ unifiableVariables,
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ result) {
+ //Contract.Requires(that != null);
+ //Contract.Requires(unifiableVariables != null);
+ //Contract.Requires(cce.NonNullElements(result));
Type p = ProxyFor;
if (p != null) {
return p.Unify(that, unifiableVariables, result);
@@ -1946,7 +2447,7 @@ namespace Microsoft.Boogie
TypeVariable tv = that as TypeVariable;
- if (tv != null && unifiableVariables.Has(tv))
+ if (tv != null && unifiableVariables.Has(tv))
return that.Unify(this, unifiableVariables, result);
if (object.ReferenceEquals(this, that)) {
@@ -1983,35 +2484,51 @@ namespace Microsoft.Boogie
//----------- Substitution of free variables with types not containing bound variables -----------------
- public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
+ public override Type Substitute(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst) {
+ //Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
if (this.ProxyFor == null) {
// check that the constraints are clean and do not contain any
// of the substituted variables (otherwise, we are in big trouble)
- assert forall{Constraint c in constraints;
- forall{TypeVariable! var in subst.Keys;
- forall{Type! t in c.Arguments; !t.FreeVariables.Has(var)} &&
- !c.Result.FreeVariables.Has(var)}};
+ Contract.Assert(Contract.ForAll(constraints, c =>
+ Contract.ForAll(subst.Keys, var =>
+ Contract.ForAll(0, c.Arguments.Length, t => !c.Arguments[t].FreeVariables.Has(var)) &&
+ !c.Result.FreeVariables.Has(var))));
}
return base.Substitute(subst);
}
//----------- Getters/Issers ----------------------------------
- public override bool IsMap { get { return true; } }
- public override MapType! AsMap { get {
- Type p = ProxyFor;
- if (p != null) {
- return p.AsMap;
- } else {
- assert false; // what to do now?
+ public override bool IsMap {
+ get {
+ return true;
}
- } }
- public override int MapArity { get {
- return Arity;
- } }
+ }
+ public override MapType/*!*/ AsMap {
+ get {
+ Contract.Ensures(Contract.Result<MapType>() != null);
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ Type p = ProxyFor;
+ if (p != null) {
+ return p.AsMap;
+ } else {
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // what to do now?
+ }
+ }
+ }
+ public override int MapArity {
+ get {
+ return Arity;
+ }
+ }
+
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitMapTypeProxy(this);
}
}
@@ -2023,35 +2540,49 @@ namespace Microsoft.Boogie
// equivalent to ExpandedType, the annotations are only used to enable
// better pretty-printing
public class TypeSynonymAnnotation : Type {
- public Type! ExpandedType;
+ public Type/*!*/ ExpandedType;
- public readonly TypeSeq! Arguments;
+ public readonly TypeSeq/*!*/ Arguments;
// is set during resolution and determines whether the right number of arguments is given
- public readonly TypeSynonymDecl! Decl;
+ public readonly TypeSynonymDecl/*!*/ Decl;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(ExpandedType != null);
+ Contract.Invariant(Arguments != null);
+ Contract.Invariant(Decl != null);
+ }
- public TypeSynonymAnnotation(IToken! token, TypeSynonymDecl! decl, TypeSeq! arguments)
- : base(token)
- requires arguments.Length == decl.TypeParameters.Length;
- {
+
+ public TypeSynonymAnnotation(IToken/*!*/ token, TypeSynonymDecl/*!*/ decl, TypeSeq/*!*/ arguments)
+ : base(token) {
+ Contract.Requires(token != null);
+ Contract.Requires(decl != null);
+ Contract.Requires(arguments != null);
+ Contract.Requires(arguments.Length == decl.TypeParameters.Length);
this.Decl = decl;
this.Arguments = arguments;
// build a substitution that can be applied to the definition of
// the type synonym
- IDictionary<TypeVariable!, Type!>! subst =
- new Dictionary<TypeVariable!, Type!> ();
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst =
+ new Dictionary<TypeVariable/*!*/, Type/*!*/>();
for (int i = 0; i < arguments.Length; ++i)
subst.Add(decl.TypeParameters[i], arguments[i]);
ExpandedType = decl.Body.Substitute(subst);
}
- private TypeSynonymAnnotation(IToken! token, TypeSynonymDecl! decl, TypeSeq! arguments,
- Type! expandedType)
+ private TypeSynonymAnnotation(IToken/*!*/ token, TypeSynonymDecl/*!*/ decl, TypeSeq/*!*/ arguments,
+ Type/*!*/ expandedType)
: base(token) {
+ Contract.Requires(token != null);
+ Contract.Requires(decl != null);
+ Contract.Requires(arguments != null);
+ Contract.Requires(expandedType != null);
+
this.Decl = decl;
this.Arguments = arguments;
- this.ExpandedType = expandedType;
+ this.ExpandedType = expandedType;
}
//----------- Cloning ----------------------------------
@@ -2059,40 +2590,58 @@ namespace Microsoft.Boogie
// have to be created in the right way. It is /not/ ok to just clone
// everything recursively
- public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
- TypeSeq! newArgs = new TypeSeq ();
- foreach(Type! t in Arguments)
+ public override Type Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap) {
+ //Contract.Requires(cce.NonNullElements(varMap));
+ Contract.Ensures(Contract.Result<Type>() != null);
+ TypeSeq/*!*/ newArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
newArgs.Add(t.Clone(varMap));
- Type! newExpandedType = ExpandedType.Clone(varMap);
+ }
+ Type/*!*/ newExpandedType = ExpandedType.Clone(varMap);
+ Contract.Assert(newExpandedType != null);
return new TypeSynonymAnnotation(tok, Decl, newArgs, newExpandedType);
}
- public override Type! CloneUnresolved() {
- TypeSeq! newArgs = new TypeSeq ();
- foreach(Type! t in Arguments)
+ public override Type CloneUnresolved() {
+ Contract.Ensures(Contract.Result<Type>() != null);
+ TypeSeq/*!*/ newArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
newArgs.Add(t.CloneUnresolved());
+ }
return new TypeSynonymAnnotation(tok, Decl, newArgs);
}
//----------- Equality ----------------------------------
[Pure]
- public override bool Equals(Type! that,
- TypeVariableSeq! thisBoundVariables,
- TypeVariableSeq! thatBoundVariables) {
+ public override bool Equals(Type/*!*/ that,
+ TypeVariableSeq/*!*/ thisBoundVariables,
+ TypeVariableSeq/*!*/ thatBoundVariables) {
+ //Contract.Requires(that != null);
+ //Contract.Requires(thisBoundVariables != null);
+ //Contract.Requires(thatBoundVariables != null);
return ExpandedType.Equals(that, thisBoundVariables, thatBoundVariables);
}
// used to skip leading type annotations
- internal override Type! Expanded { get {
- return ExpandedType.Expanded;
- } }
+ internal override Type/*!*/ Expanded {
+ get {
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ return ExpandedType.Expanded;
+ }
+ }
//----------- Unification of types -----------
- public override bool Unify(Type! that,
- TypeVariableSeq! unifiableVariables,
- IDictionary<TypeVariable!, Type!>! result) {
+ public override bool Unify(Type/*!*/ that,
+ TypeVariableSeq/*!*/ unifiableVariables,
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ result) {
+ //Contract.Requires(that != null);
+ //Contract.Requires(unifiableVariables != null);
+ //Contract.Requires(cce.NonNullElements(result));
return ExpandedType.Unify(that, unifiableVariables, result);
}
@@ -2109,69 +2658,143 @@ namespace Microsoft.Boogie
//----------- Substitution of free variables with types not containing bound variables -----------------
- public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
+ public override Type Substitute(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst) {
+ //Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
if (subst.Count == 0)
return this;
- TypeSeq newArgs = new TypeSeq ();
- foreach (Type! t in Arguments)
+ TypeSeq newArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
newArgs.Add(t.Substitute(subst));
- Type! newExpandedType = ExpandedType.Substitute(subst);
+ }
+ Type/*!*/ newExpandedType = ExpandedType.Substitute(subst);
+ Contract.Assert(newExpandedType != null);
return new TypeSynonymAnnotation(tok, Decl, newArgs, newExpandedType);
}
//----------- Hashcodes ----------------------------------
[Pure]
- public override int GetHashCode(TypeVariableSeq! boundVariables) {
+ public override int GetHashCode(TypeVariableSeq boundVariables) {
+ //Contract.Requires(boundVariables != null);
return ExpandedType.GetHashCode(boundVariables);
}
//----------- Linearisation ----------------------------------
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength) {
+ //Contract.Requires(stream != null);
stream.SetToken(this);
CtorType.EmitCtorType(this.Decl.Name, Arguments, stream, contextBindingStrength);
}
//----------- Resolution ----------------------------------
- public override Type! ResolveType(ResolutionContext! rc) {
- TypeSeq resolvedArgs = new TypeSeq ();
- foreach (Type! t in Arguments)
+ public override Type ResolveType(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+ TypeSeq resolvedArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
resolvedArgs.Add(t.ResolveType(rc));
+ }
return new TypeSynonymAnnotation(tok, Decl, resolvedArgs);
}
- public override TypeVariableSeq! FreeVariables { get {
- return ExpandedType.FreeVariables;
- } }
+ public override TypeVariableSeq/*!*/ FreeVariables {
+ get {
+ Contract.Ensures(Contract.Result<TypeVariableSeq>() != null);
- public override List<TypeProxy!>! FreeProxies { get {
- return ExpandedType.FreeProxies;
- } }
+ return ExpandedType.FreeVariables;
+ }
+ }
+
+ public override List<TypeProxy/*!*/>/*!*/ FreeProxies {
+ get {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<TypeProxy>>()));
+ return ExpandedType.FreeProxies;
+ }
+ }
//----------- Getters/Issers ----------------------------------
- public override bool IsBasic { get { return ExpandedType.IsBasic; } }
- public override bool IsInt { get { return ExpandedType.IsInt; } }
- public override bool IsBool { get { return ExpandedType.IsBool; } }
+ public override bool IsBasic {
+ get {
+ return ExpandedType.IsBasic;
+ }
+ }
+ public override bool IsInt {
+ get {
+ return ExpandedType.IsInt;
+ }
+ }
+ public override bool IsBool {
+ get {
+ return ExpandedType.IsBool;
+ }
+ }
- public override bool IsVariable { get { return ExpandedType.IsVariable; } }
- public override TypeVariable! AsVariable { get { return ExpandedType.AsVariable; } }
- public override bool IsCtor { get { return ExpandedType.IsCtor; } }
- public override CtorType! AsCtor { get { return ExpandedType.AsCtor; } }
- public override bool IsMap { get { return ExpandedType.IsMap; } }
- public override MapType! AsMap { get { return ExpandedType.AsMap; } }
- public override bool IsUnresolved { get { return ExpandedType.IsUnresolved; } }
- public override UnresolvedTypeIdentifier! AsUnresolved { get {
- return ExpandedType.AsUnresolved; } }
+ public override bool IsVariable {
+ get {
+ return ExpandedType.IsVariable;
+ }
+ }
+ public override TypeVariable/*!*/ AsVariable {
+ get {
+ Contract.Ensures(Contract.Result<TypeVariable>() != null);
+ return ExpandedType.AsVariable;
+ }
+ }
+ public override bool IsCtor {
+ get {
+ return ExpandedType.IsCtor;
+ }
+ }
+ public override CtorType/*!*/ AsCtor {
+ get {
+ Contract.Ensures(Contract.Result<CtorType>() != null);
+ return ExpandedType.AsCtor;
+ }
+ }
+ public override bool IsMap {
+ get {
+ return ExpandedType.IsMap;
+ }
+ }
+ public override MapType/*!*/ AsMap {
+ get {
+ Contract.Ensures(Contract.Result<MapType>() != null);
+ return ExpandedType.AsMap;
+ }
+ }
+ public override bool IsUnresolved {
+ get {
+ return ExpandedType.IsUnresolved;
+ }
+ }
+ public override UnresolvedTypeIdentifier/*!*/ AsUnresolved {
+ get {
+ Contract.Ensures(Contract.Result<UnresolvedTypeIdentifier>() != null);
- public override bool IsBv { get { return ExpandedType.IsBv; } }
- public override int BvBits { get { return ExpandedType.BvBits; } }
+ return ExpandedType.AsUnresolved;
+ }
+ }
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override bool IsBv {
+ get {
+ return ExpandedType.IsBv;
+ }
+ }
+ public override int BvBits {
+ get {
+ return ExpandedType.BvBits;
+ }
+ }
+
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitTypeSynonymAnnotation(this);
}
}
@@ -2179,14 +2802,22 @@ namespace Microsoft.Boogie
//=====================================================================
public class CtorType : Type {
- public readonly TypeSeq! Arguments;
+ public readonly TypeSeq/*!*/ Arguments;
// is set during resolution and determines whether the right number of arguments is given
- public readonly TypeCtorDecl! Decl;
+ public readonly TypeCtorDecl/*!*/ Decl;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Arguments != null);
+ Contract.Invariant(Decl != null);
+ }
- public CtorType(IToken! token, TypeCtorDecl! decl, TypeSeq! arguments)
- : base(token)
- requires arguments.Length == decl.Arity;
- {
+
+ public CtorType(IToken/*!*/ token, TypeCtorDecl/*!*/ decl, TypeSeq/*!*/ arguments)
+ : base(token) {
+ Contract.Requires(token != null);
+ Contract.Requires(decl != null);
+ Contract.Requires(arguments != null);
+ Contract.Requires(arguments.Length == decl.Arity);
this.Decl = decl;
this.Arguments = arguments;
}
@@ -2196,23 +2827,31 @@ namespace Microsoft.Boogie
// have to be created in the right way. It is /not/ ok to just clone
// everything recursively
- public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
- TypeSeq! newArgs = new TypeSeq ();
- foreach(Type! t in Arguments)
+ public override Type Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap) {
+ //Contract.Requires(cce.NonNullElements(varMap));
+ Contract.Ensures(Contract.Result<Type>() != null);
+ TypeSeq/*!*/ newArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
newArgs.Add(t.Clone(varMap));
+ }
return new CtorType(tok, Decl, newArgs);
}
- public override Type! CloneUnresolved() {
- TypeSeq! newArgs = new TypeSeq ();
- foreach(Type! t in Arguments)
+ public override Type CloneUnresolved() {
+ Contract.Ensures(Contract.Result<Type>() != null);
+ TypeSeq/*!*/ newArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
newArgs.Add(t.CloneUnresolved());
+ }
return new CtorType(tok, Decl, newArgs);
}
//----------- Equality ----------------------------------
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
public override bool Equals(object that) {
Type thatType = that as Type;
if (thatType == null)
@@ -2228,9 +2867,9 @@ namespace Microsoft.Boogie
}
[Pure]
- public override bool Equals(Type! that,
- TypeVariableSeq! thisBoundVariables,
- TypeVariableSeq! thatBoundVariables) {
+ public override bool Equals(Type/*!*/ that,
+ TypeVariableSeq/*!*/ thisBoundVariables,
+ TypeVariableSeq/*!*/ thatBoundVariables) {
that = TypeProxy.FollowProxy(that.Expanded);
CtorType thatCtorType = that as CtorType;
if (thatCtorType == null || !this.Decl.Equals(thatCtorType.Decl))
@@ -2245,9 +2884,9 @@ namespace Microsoft.Boogie
//----------- Unification of types -----------
- public override bool Unify(Type! that,
- TypeVariableSeq! unifiableVariables,
- IDictionary<TypeVariable!, Type!>! result) {
+ public override bool Unify(Type/*!*/ that,
+ TypeVariableSeq/*!*/ unifiableVariables,
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ result) {
that = that.Expanded;
if (that is TypeProxy || that is TypeVariable)
return that.Unify(this, unifiableVariables, result);
@@ -2288,41 +2927,52 @@ namespace Microsoft.Boogie
//----------- Substitution of free variables with types not containing bound variables -----------------
- public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
+ public override Type Substitute(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst) {
+ //Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
if (subst.Count == 0)
return this;
- TypeSeq newArgs = new TypeSeq ();
- foreach (Type! t in Arguments)
+ TypeSeq newArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
newArgs.Add(t.Substitute(subst));
+ }
return new CtorType(tok, Decl, newArgs);
}
//----------- Hashcodes ----------------------------------
[Pure]
- public override int GetHashCode(TypeVariableSeq! boundVariables) {
+ public override int GetHashCode(TypeVariableSeq boundVariables) {
+ //Contract.Requires(boundVariables != null);
int res = 1637643879 * Decl.GetHashCode();
- foreach (Type! t in Arguments)
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
res = res * 3 + t.GetHashCode(boundVariables);
+ }
return res;
}
//----------- Linearisation ----------------------------------
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength) {
+ //Contract.Requires(stream != null);
stream.SetToken(this);
EmitCtorType(this.Decl.Name, Arguments, stream, contextBindingStrength);
}
-
- internal static void EmitCtorType(string! name, TypeSeq! args, TokenTextWriter! stream, int contextBindingStrength) {
+
+ internal static void EmitCtorType(string name, TypeSeq args, TokenTextWriter stream, int contextBindingStrength) {
+ Contract.Requires(stream != null);
+ Contract.Requires(args != null);
+ Contract.Requires(name != null);
int opBindingStrength = args.Length > 0 ? 0 : 2;
if (opBindingStrength < contextBindingStrength)
stream.Write("(");
stream.Write("{0}", TokenTextWriter.SanitizeIdentifier(name));
int i = args.Length;
- foreach (Type! t in args) {
+ foreach (Type/*!*/ t in args) {
+ Contract.Assert(t != null);
stream.Write(" ");
// use a lower binding strength for the last argument
// to allow map-types without parentheses
@@ -2336,36 +2986,55 @@ namespace Microsoft.Boogie
//----------- Resolution ----------------------------------
- public override Type! ResolveType(ResolutionContext! rc) {
- TypeSeq resolvedArgs = new TypeSeq ();
- foreach (Type! t in Arguments)
+ public override Type ResolveType(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+ TypeSeq resolvedArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
resolvedArgs.Add(t.ResolveType(rc));
+ }
return new CtorType(tok, Decl, resolvedArgs);
}
- public override TypeVariableSeq! FreeVariables {
- get {
- TypeVariableSeq! res = new TypeVariableSeq ();
- foreach (Type! t in Arguments)
- res.AppendWithoutDups(t.FreeVariables);
- return res;
- }
+ public override TypeVariableSeq/*!*/ FreeVariables {
+ get {
+ TypeVariableSeq/*!*/ res = new TypeVariableSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
+ res.AppendWithoutDups(t.FreeVariables);
+ }
+ return res;
+ }
}
- public override List<TypeProxy!>! FreeProxies { get {
- List<TypeProxy!>! res = new List<TypeProxy!> ();
- foreach (Type! t in Arguments)
- AppendWithoutDups(res, t.FreeProxies);
- return res;
- } }
+ public override List<TypeProxy/*!*/>/*!*/ FreeProxies {
+ get {
+ List<TypeProxy/*!*/>/*!*/ res = new List<TypeProxy/*!*/>();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
+ AppendWithoutDups(res, t.FreeProxies);
+ }
+ return res;
+ }
+ }
//----------- Getters/Issers ----------------------------------
- public override bool IsCtor { get { return true; } }
- public override CtorType! AsCtor { get { return this; } }
+ public override bool IsCtor {
+ get {
+ return true;
+ }
+ }
+ public override CtorType/*!*/ AsCtor {
+ get {
+ return this;
+ }
+ }
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitCtorType(this);
}
}
@@ -2375,13 +3044,24 @@ namespace Microsoft.Boogie
public class MapType : Type {
// an invariant is that each of the type parameters has to occur as
// free variable in at least one of the arguments
- public readonly TypeVariableSeq! TypeParameters;
- public readonly TypeSeq! Arguments;
- public Type! Result;
+ public readonly TypeVariableSeq/*!*/ TypeParameters;
+ public readonly TypeSeq/*!*/ Arguments;
+ public Type/*!*/ Result;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(TypeParameters != null);
+ Contract.Invariant(Arguments != null);
+ Contract.Invariant(Result != null);
+ }
+
+
+ public MapType(IToken/*!*/ token, TypeVariableSeq/*!*/ typeParameters, TypeSeq/*!*/ arguments, Type/*!*/ result)
+ : base(token) {
+ Contract.Requires(token != null);
+ Contract.Requires(typeParameters != null);
+ Contract.Requires(arguments != null);
+ Contract.Requires(result != null);
- public MapType(IToken! token, TypeVariableSeq! typeParameters, TypeSeq! arguments, Type! result)
- : base(token)
- {
this.TypeParameters = typeParameters;
this.Result = result;
this.Arguments = arguments;
@@ -2392,50 +3072,64 @@ namespace Microsoft.Boogie
// have to be created in the right way. It is /not/ ok to just clone
// everything recursively
- public override Type! Clone(IDictionary<TypeVariable!, TypeVariable!>! varMap) {
- IDictionary<TypeVariable!, TypeVariable!>! newVarMap =
- new Dictionary<TypeVariable!, TypeVariable!>();
- foreach (KeyValuePair<TypeVariable!, TypeVariable!> p in varMap) {
+ public override Type Clone(IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ varMap) {
+ //Contract.Requires(cce.NonNullElements(varMap));
+ Contract.Ensures(Contract.Result<Type>() != null);
+ IDictionary<TypeVariable/*!*/, TypeVariable/*!*/>/*!*/ newVarMap =
+ new Dictionary<TypeVariable/*!*/, TypeVariable/*!*/>();
+ foreach (KeyValuePair<TypeVariable/*!*/, TypeVariable/*!*/> p in varMap) {
+ Contract.Assert(cce.NonNullElements(p));
if (!TypeParameters.Has(p.Key))
newVarMap.Add(p);
}
- TypeVariableSeq! newTypeParams = new TypeVariableSeq ();
- foreach (TypeVariable! var in TypeParameters) {
- TypeVariable! newVar = new TypeVariable (var.tok, var.Name);
+ TypeVariableSeq/*!*/ newTypeParams = new TypeVariableSeq();
+ foreach (TypeVariable/*!*/ var in TypeParameters) {
+ Contract.Assert(var != null);
+ TypeVariable/*!*/ newVar = new TypeVariable(var.tok, var.Name);
+ Contract.Assert(newVar != null);
newVarMap.Add(var, newVar);
newTypeParams.Add(newVar);
}
- TypeSeq! newArgs = new TypeSeq ();
- foreach(Type! t in Arguments)
+ TypeSeq/*!*/ newArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
newArgs.Add(t.Clone(newVarMap));
- Type! newResult = Result.Clone(newVarMap);
+ }
+ Type/*!*/ newResult = Result.Clone(newVarMap);
+ Contract.Assert(newResult != null);
- return new MapType (this.tok, newTypeParams, newArgs, newResult);
+ return new MapType(this.tok, newTypeParams, newArgs, newResult);
}
- public override Type! CloneUnresolved() {
- TypeVariableSeq! newTypeParams = new TypeVariableSeq ();
- foreach (TypeVariable! var in TypeParameters) {
- TypeVariable! newVar = new TypeVariable (var.tok, var.Name);
+ public override Type CloneUnresolved() {
+ Contract.Ensures(Contract.Result<Type>() != null);
+ TypeVariableSeq/*!*/ newTypeParams = new TypeVariableSeq();
+ foreach (TypeVariable/*!*/ var in TypeParameters) {
+ Contract.Assert(var != null);
+ TypeVariable/*!*/ newVar = new TypeVariable(var.tok, var.Name);
+ Contract.Assert(newVar != null);
newTypeParams.Add(newVar);
}
- TypeSeq! newArgs = new TypeSeq ();
- foreach(Type! t in Arguments)
+ TypeSeq/*!*/ newArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
newArgs.Add(t.CloneUnresolved());
- Type! newResult = Result.CloneUnresolved();
+ }
+ Type/*!*/ newResult = Result.CloneUnresolved();
+ Contract.Assert(newResult != null);
- return new MapType (this.tok, newTypeParams, newArgs, newResult);
+ return new MapType(this.tok, newTypeParams, newArgs, newResult);
}
//----------- Equality ----------------------------------
[Pure]
- public override bool Equals(Type! that,
- TypeVariableSeq! thisBoundVariables,
- TypeVariableSeq! thatBoundVariables) {
+ public override bool Equals(Type/*!*/ that,
+ TypeVariableSeq/*!*/ thisBoundVariables,
+ TypeVariableSeq/*!*/ thatBoundVariables) {
that = TypeProxy.FollowProxy(that.Expanded);
MapType thatMapType = that as MapType;
if (thatMapType == null ||
@@ -2443,10 +3137,14 @@ namespace Microsoft.Boogie
this.Arguments.Length != thatMapType.Arguments.Length)
return false;
- foreach (TypeVariable! var in this.TypeParameters)
+ foreach (TypeVariable/*!*/ var in this.TypeParameters) {
+ Contract.Assert(var != null);
thisBoundVariables.Add(var);
- foreach (TypeVariable! var in thatMapType.TypeParameters)
+ }
+ foreach (TypeVariable/*!*/ var in thatMapType.TypeParameters) {
+ Contract.Assert(var != null);
thatBoundVariables.Add(var);
+ }
try {
@@ -2466,15 +3164,15 @@ namespace Microsoft.Boogie
thatBoundVariables.Remove();
}
}
-
+
return true;
}
//----------- Unification of types -----------
- public override bool Unify(Type! that,
- TypeVariableSeq! unifiableVariables,
- IDictionary<TypeVariable!, Type!>! result) {
+ public override bool Unify(Type/*!*/ that,
+ TypeVariableSeq/*!*/ unifiableVariables,
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ result) {
that = that.Expanded;
if (that is TypeProxy || that is TypeVariable)
return that.Unify(this, unifiableVariables, result);
@@ -2486,8 +3184,10 @@ namespace Microsoft.Boogie
return false;
// treat the bound variables of the two map types as equal...
- Dictionary<TypeVariable!, Type!>! subst0 = new Dictionary<TypeVariable!, Type!>();
- Dictionary<TypeVariable!, Type!>! subst1 = new Dictionary<TypeVariable!, Type!>();
+ Dictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst0 =
+ new Dictionary<TypeVariable/*!*/, Type/*!*/>();
+ Dictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst1 =
+ new Dictionary<TypeVariable/*!*/, Type/*!*/>();
TypeVariableSeq freshies = new TypeVariableSeq();
for (int i = 0; i < this.TypeParameters.Length; i++) {
TypeVariable tp0 = this.TypeParameters[i];
@@ -2514,16 +3214,23 @@ namespace Microsoft.Boogie
// non-substituted types ...
TypeVariableSeq freeVars = this.FreeVariables;
foreach (TypeVariable fr in freshies)
- if (freeVars.Has(fr)) { return false; } // fresh variable escaped
+ if (freeVars.Has(fr)) {
+ return false;
+ } // fresh variable escaped
freeVars = thatMapType.FreeVariables;
foreach (TypeVariable fr in freshies)
- if (freeVars.Has(fr)) { return false; } // fresh variable escaped
+ if (freeVars.Has(fr)) {
+ return false;
+ } // fresh variable escaped
// ... and in the resulting unifier of type variables
- foreach (KeyValuePair<TypeVariable!, Type!> pair in result) {
+ foreach (KeyValuePair<TypeVariable/*!*/, Type/*!*/> pair in result) {
+ Contract.Assert(cce.NonNullElements(pair));
freeVars = pair.Value.FreeVariables;
foreach (TypeVariable fr in freshies)
- if (freeVars.Has(fr)) { return false; } // fresh variable escaped
+ if (freeVars.Has(fr)) {
+ return false;
+ } // fresh variable escaped
}
}
@@ -2558,10 +3265,12 @@ namespace Microsoft.Boogie
if (thatMapType.collisionsPossible(result))
thatMapType = (MapType)that.Clone();
- foreach (TypeVariable! var in this.TypeParameters)
- thisBoundVariables.Add(var);
- foreach (TypeVariable! var in thatMapType.TypeParameters)
- thatBoundVariables.Add(var);
+ foreach(TypeVariable/*!*/ var in this.TypeParameters){
+Contract.Assert(var != null);
+ thisBoundVariables.Add(var);}
+ foreach(TypeVariable/*!*/ var in thatMapType.TypeParameters){
+Contract.Assert(var != null);
+ thatBoundVariables.Add(var);}
try {
@@ -2588,14 +3297,15 @@ namespace Microsoft.Boogie
//----------- Substitution of free variables with types not containing bound variables -----------------
[Pure]
- private bool collisionsPossible(IDictionary<TypeVariable!, Type!>! subst) {
+ private bool collisionsPossible(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst) {
+ Contract.Requires(cce.NonNullElements(subst));
// PR: could be written more efficiently
- return exists{TypeVariable! var in TypeParameters;
- subst.ContainsKey(var) ||
- exists{Type! t in subst.Values; t.FreeVariables.Has(var)}};
+ return Contract.Exists(0, TypeParameters.Length, i => subst.ContainsKey(TypeParameters[i]) || Contract.Exists(subst.Values, t => t.FreeVariables.Has(TypeParameters[i])));
}
- public override Type! Substitute(IDictionary<TypeVariable!, Type!>! subst) {
+ public override Type Substitute(IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ subst) {
+ //Contract.Requires(cce.NonNullElements(subst));
+ Contract.Ensures(Contract.Result<Type>() != null);
if (subst.Count == 0)
return this;
@@ -2608,15 +3318,19 @@ namespace Microsoft.Boogie
// variables are fresh
if (collisionsPossible(subst)) {
- MapType! newType = (MapType)this.Clone();
- assert newType.Equals(this) && !newType.collisionsPossible(subst);
+ MapType/*!*/ newType = (MapType)this.Clone();
+ Contract.Assert(newType != null);
+ Contract.Assert(newType.Equals(this) && !newType.collisionsPossible(subst));
return newType.Substitute(subst);
}
- TypeSeq newArgs = new TypeSeq ();
- foreach (Type! t in Arguments)
+ TypeSeq newArgs = new TypeSeq();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
newArgs.Add(t.Substitute(subst));
- Type! newResult = Result.Substitute(subst);
+ }
+ Type/*!*/ newResult = Result.Substitute(subst);
+ Contract.Assert(newResult != null);
return new MapType(tok, TypeParameters, newArgs, newResult);
}
@@ -2624,14 +3338,19 @@ namespace Microsoft.Boogie
//----------- Hashcodes ----------------------------------
[Pure]
- public override int GetHashCode(TypeVariableSeq! boundVariables) {
+ public override int GetHashCode(TypeVariableSeq boundVariables) {
+ //Contract.Requires(boundVariables != null);
int res = 7643761 * TypeParameters.Length + 65121 * Arguments.Length;
- foreach (TypeVariable! var in this.TypeParameters)
+ foreach (TypeVariable/*!*/ var in this.TypeParameters) {
+ Contract.Assert(var != null);
boundVariables.Add(var);
+ }
- foreach (Type! t in Arguments)
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
res = res * 5 + t.GetHashCode(boundVariables);
+ }
res = res * 7 + Result.GetHashCode(boundVariables);
for (int i = 0; i < this.TypeParameters.Length; ++i)
@@ -2642,8 +3361,8 @@ namespace Microsoft.Boogie
//----------- Linearisation ----------------------------------
- public override void Emit(TokenTextWriter! stream, int contextBindingStrength)
- {
+ public override void Emit(TokenTextWriter stream, int contextBindingStrength) {
+ //Contract.Requires(stream != null);
stream.SetToken(this);
const int opBindingStrength = 1;
@@ -2663,15 +3382,19 @@ namespace Microsoft.Boogie
//----------- Resolution ----------------------------------
- public override Type! ResolveType(ResolutionContext! rc) {
+ public override Type ResolveType(ResolutionContext rc) {
+ //Contract.Requires(rc != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
int previousState = rc.TypeBinderState;
try {
- foreach (TypeVariable! v in TypeParameters) {
+ foreach (TypeVariable/*!*/ v in TypeParameters) {
+ Contract.Assert(v != null);
rc.AddTypeBinder(v);
}
- TypeSeq resolvedArgs = new TypeSeq ();
- foreach (Type! ty in Arguments) {
+ TypeSeq resolvedArgs = new TypeSeq();
+ foreach (Type/*!*/ ty in Arguments) {
+ Contract.Assert(ty != null);
resolvedArgs.Add(ty.ResolveType(rc));
}
@@ -2683,72 +3406,100 @@ namespace Microsoft.Boogie
rc);
// sort the type parameters so that they are bound in the order of occurrence
- TypeVariableSeq! sortedTypeParams = SortTypeParams(TypeParameters, resolvedArgs, resolvedResult);
+ TypeVariableSeq/*!*/ sortedTypeParams = SortTypeParams(TypeParameters, resolvedArgs, resolvedResult);
+ Contract.Assert(sortedTypeParams != null);
return new MapType(tok, sortedTypeParams, resolvedArgs, resolvedResult);
} finally {
rc.TypeBinderState = previousState;
}
}
- public override TypeVariableSeq! FreeVariables {
+ public override TypeVariableSeq/*!*/ FreeVariables {
get {
- TypeVariableSeq! res = FreeVariablesIn(Arguments);
+ TypeVariableSeq/*!*/ res = FreeVariablesIn(Arguments);
+ Contract.Assert(res != null);
res.AppendWithoutDups(Result.FreeVariables);
- foreach (TypeVariable! v in TypeParameters)
+ foreach (TypeVariable/*!*/ v in TypeParameters) {
+ Contract.Assert(v != null);
res.Remove(v);
+ }
return res;
}
}
- public override List<TypeProxy!>! FreeProxies { get {
- List<TypeProxy!>! res = new List<TypeProxy!> ();
- foreach (Type! t in Arguments)
- AppendWithoutDups(res, t.FreeProxies);
- AppendWithoutDups(res, Result.FreeProxies);
- return res;
- } }
+ public override List<TypeProxy/*!*/>/*!*/ FreeProxies {
+ get {
+ List<TypeProxy/*!*/>/*!*/ res = new List<TypeProxy/*!*//*!*/>();
+ foreach (Type/*!*/ t in Arguments) {
+ Contract.Assert(t != null);
+ AppendWithoutDups(res, t.FreeProxies);
+ }
+ AppendWithoutDups(res, Result.FreeProxies);
+ return res;
+ }
+ }
//----------- Getters/Issers ----------------------------------
- public override bool IsMap { get { return true; } }
- public override MapType! AsMap { get { return this; } }
- public override int MapArity { get {
- return Arguments.Length;
- } }
+ public override bool IsMap {
+ get {
+ return true;
+ }
+ }
+ public override MapType/*!*/ AsMap {
+ get {
+ return this;
+ }
+ }
+ public override int MapArity {
+ get {
+ return Arguments.Length;
+ }
+ }
//------------ Match formal argument types of the map
//------------ on concrete types, substitute the result into the
//------------ result type. Null is returned if so many type checking
//------------ errors occur that the situation is hopeless
- public Type CheckArgumentTypes(ExprSeq! actualArgs,
- out TypeParamInstantiation! tpInstantiation,
- IToken! typeCheckingSubject,
- string! opName,
- TypecheckingContext! tc) {
- List<Type!>! actualTypeParams;
+ public Type CheckArgumentTypes(ExprSeq/*!*/ actualArgs,
+ out TypeParamInstantiation/*!*/ tpInstantiation,
+ IToken/*!*/ typeCheckingSubject,
+ string/*!*/ opName,
+ TypecheckingContext/*!*/ tc) {
+ Contract.Requires(actualArgs != null);
+ Contract.Requires(typeCheckingSubject != null);
+
+ Contract.Requires(opName != null);
+ Contract.Requires(tc != null);
+Contract.Ensures(Contract.ValueAtReturn(out tpInstantiation) != null);
+ List<Type/*!*/>/*!*/ actualTypeParams;
TypeSeq actualResult =
Type.CheckArgumentTypes(TypeParameters, out actualTypeParams, Arguments, actualArgs,
- new TypeSeq (Result), null, typeCheckingSubject, opName, tc);
+ new TypeSeq(Result), null, typeCheckingSubject, opName, tc);
if (actualResult == null) {
tpInstantiation = SimpleTypeParamInstantiation.EMPTY;
return null;
} else {
- assert actualResult.Length == 1;
+ Contract.Assert(actualResult.Length == 1);
tpInstantiation = SimpleTypeParamInstantiation.From(TypeParameters, actualTypeParams);
return actualResult[0];
}
}
- public override Absy! StdDispatch(StandardVisitor! visitor)
- {
+ public override Absy StdDispatch(StandardVisitor visitor) {
+ //Contract.Requires(visitor != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return visitor.VisitMapType(this);
}
}
//---------------------------------------------------------------------
- public enum SimpleType { Int, Bool };
+ public enum SimpleType {
+ Int,
+ Bool
+ };
//=====================================================================
@@ -2758,31 +3509,73 @@ namespace Microsoft.Boogie
// instead of using a simple list or dictionary, because in some cases
// (due to the type proxies for map types) the actual number and instantiation
// of type parameters can only be determined very late.
+ [ContractClass(typeof(TypeParamInstantiationContracts))]
public interface TypeParamInstantiation {
// return what formal type parameters there are
- List<TypeVariable!>! FormalTypeParams { get; }
+ List<TypeVariable/*!*/>/*!*/ FormalTypeParams {
+ get;
+ }
// given a formal type parameter, return the actual instantiation
- Type! this[TypeVariable! var] { get; }
+ Type/*!*/ this[TypeVariable/*!*/ var] {
+ get;
+ }
+ }
+ [ContractClassFor(typeof(TypeParamInstantiation))]
+ public abstract class TypeParamInstantiationContracts : TypeParamInstantiation {
+ #region TypeParamInstantiation Members
+
+ public List<TypeVariable> FormalTypeParams {
+
+ get {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<TypeVariable>>()));
+ throw new NotImplementedException();
+ }
+ }
+
+ public Type this[TypeVariable var] {
+ get {
+ Contract.Requires(var != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+
+ throw new NotImplementedException();
+ }
+ }
+
+ #endregion
}
+
public class SimpleTypeParamInstantiation : TypeParamInstantiation {
- private readonly List<TypeVariable!>! TypeParams;
- private readonly IDictionary<TypeVariable!, Type!>! Instantiations;
+ private readonly List<TypeVariable/*!*/>/*!*/ TypeParams;
+ [ContractInvariantMethod]
+ void TypeParamsInvariantMethod() {
+ Contract.Invariant(cce.NonNullElements(TypeParams));
+ }
+ private readonly IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ Instantiations;
+ [ContractInvariantMethod]
+ void InstantiationsInvariantMethod() {
+ Contract.Invariant(cce.NonNullElements(Instantiations));
+ }
- public SimpleTypeParamInstantiation(List<TypeVariable!>! typeParams,
- IDictionary<TypeVariable!, Type!>! instantiations) {
+ public SimpleTypeParamInstantiation(List<TypeVariable/*!*/>/*!*/ typeParams,
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ instantiations) {
+ Contract.Requires(cce.NonNullElements(typeParams));
+ Contract.Requires(cce.NonNullElements(instantiations));
this.TypeParams = typeParams;
this.Instantiations = instantiations;
}
- public static TypeParamInstantiation!
- From(TypeVariableSeq! typeParams, List<Type!>! actualTypeParams)
- requires typeParams.Length == actualTypeParams.Count; {
+ public static TypeParamInstantiation/*!*/ From(TypeVariableSeq typeParams, List<Type/*!*/>/*!*/ actualTypeParams) {
+ Contract.Requires(cce.NonNullElements(actualTypeParams));
+ Contract.Requires(typeParams != null);
+ Contract.Requires(typeParams.Length == actualTypeParams.Count);
+ Contract.Ensures(Contract.Result<TypeParamInstantiation>() != null);
+
if (typeParams.Length == 0)
return EMPTY;
- List<TypeVariable!>! typeParamList = new List<TypeVariable!> ();
- IDictionary<TypeVariable!, Type!>! dict = new Dictionary<TypeVariable!, Type!> ();
+ List<TypeVariable/*!*/>/*!*/ typeParamList = new List<TypeVariable/*!*/>();
+ IDictionary<TypeVariable/*!*/, Type/*!*/>/*!*/ dict = new Dictionary<TypeVariable/*!*/, Type/*!*/>();
for (int i = 0; i < typeParams.Length; ++i) {
typeParamList.Add(typeParams[i]);
dict.Add(typeParams[i], actualTypeParams[i]);
@@ -2790,18 +3583,28 @@ namespace Microsoft.Boogie
return new SimpleTypeParamInstantiation(typeParamList, dict);
}
- public static readonly TypeParamInstantiation! EMPTY =
- new SimpleTypeParamInstantiation (new List<TypeVariable!> (),
- new Dictionary<TypeVariable!, Type!> ());
+ public static readonly TypeParamInstantiation EMPTY =
+ new SimpleTypeParamInstantiation(new List<TypeVariable/*!*/>(),
+ new Dictionary<TypeVariable/*!*/, Type/*!*/>());
+ [ContractInvariantMethod]
+ void EMPTYInvariant() {
+ Contract.Invariant(EMPTY != null);
+ }
+
// return what formal type parameters there are
- public List<TypeVariable!>! FormalTypeParams { get {
- return TypeParams;
- } }
+ public List<TypeVariable/*!*/>/*!*/ FormalTypeParams {
+ get {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<TypeVariable>>()));
+ return TypeParams;
+ }
+ }
// given a formal type parameter, return the actual instantiation
- public Type! this[TypeVariable! var] { get {
- return Instantiations[var];
- } }
+ public Type/*!*/ this[TypeVariable/*!*/ var] {
+ get {
+ return Instantiations[var];
+ }
+ }
}
// Implementation of TypeParamInstantiation that refers to the current
@@ -2809,49 +3612,63 @@ namespace Microsoft.Boogie
// methods of this implementation can change in case the MapTypeProxy
// receives further unifications.
class MapTypeProxyParamInstantiation : TypeParamInstantiation {
- private readonly MapTypeProxy! Proxy;
+ private readonly MapTypeProxy/*!*/ Proxy;
// the argument and result type of this particular usage of the map
// type. these are necessary to derive the values of the type parameters
- private readonly TypeSeq! ArgumentsResult;
+ private readonly TypeSeq/*!*/ ArgumentsResult;
// field that is initialised once all necessary information is available
// (the MapTypeProxy is instantiated to an actual type) and the instantiation
// of a type parameter is queried
- private IDictionary<TypeVariable!, Type!> Instantiations = null;
+ private IDictionary<TypeVariable/*!*/, Type/*!*/> Instantiations = null;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Proxy != null);
+ Contract.Invariant(ArgumentsResult != null);
+ Contract.Invariant(cce.NonNullElements(Instantiations));
+ }
- public MapTypeProxyParamInstantiation(MapTypeProxy! proxy,
- TypeSeq! argumentsResult) {
+
+ public MapTypeProxyParamInstantiation(MapTypeProxy/*!*/ proxy,
+ TypeSeq/*!*/ argumentsResult) {
+ Contract.Requires(proxy != null);
+ Contract.Requires(argumentsResult != null);
this.Proxy = proxy;
this.ArgumentsResult = argumentsResult;
}
// return what formal type parameters there are
- public List<TypeVariable!>! FormalTypeParams { get {
- MapType realType = Proxy.ProxyFor as MapType;
- if (realType == null)
- // no instantiation of the map type is known, which means
- // that the map type is assumed to be monomorphic
- return new List<TypeVariable!> ();
- else
- return realType.TypeParameters.ToList();
- } }
+ public List<TypeVariable/*!*/>/*!*/ FormalTypeParams {
+ get {
+ MapType realType = Proxy.ProxyFor as MapType;
+ if (realType == null)
+ // no instantiation of the map type is known, which means
+ // that the map type is assumed to be monomorphic
+ return new List<TypeVariable/*!*/>();
+ else
+ return realType.TypeParameters.ToList();
+ }
+ }
// given a formal type parameter, return the actual instantiation
- public Type! this[TypeVariable! var] { get {
- // then there has to be an instantiation that is a polymorphic map type
- if (Instantiations == null) {
- MapType realType = Proxy.ProxyFor as MapType;
- assert realType != null;
- TypeSeq! formalArgs = new TypeSeq ();
- foreach (Type! t in realType.Arguments)
- formalArgs.Add(t);
- formalArgs.Add(realType.Result);
- Instantiations =
- Type.InferTypeParameters(realType.TypeParameters, formalArgs, ArgumentsResult);
- }
- return Instantiations[var];
- } }
+ public Type/*!*/ this[TypeVariable/*!*/ var] {
+ get {
+ // then there has to be an instantiation that is a polymorphic map type
+ if (Instantiations == null) {
+ MapType realType = Proxy.ProxyFor as MapType;
+ Contract.Assert(realType != null);
+ TypeSeq/*!*/ formalArgs = new TypeSeq();
+ foreach (Type/*!*/ t in realType.Arguments) {
+ Contract.Assert(t != null);
+ formalArgs.Add(t);
+ }
+ formalArgs.Add(realType.Result);
+ Instantiations =
+ Type.InferTypeParameters(realType.TypeParameters, formalArgs, ArgumentsResult);
+ }
+ return Instantiations[var];
+ }
+ }
}
-
-}
+} \ No newline at end of file
diff --git a/Source/Core/BoogiePL.atg b/Source/Core/BoogiePL.atg
index fe302acb..a44bbbff 100644
--- a/Source/Core/BoogiePL.atg
+++ b/Source/Core/BoogiePL.atg
@@ -19,31 +19,33 @@ COMPILER BoogiePL
/*--------------------------------------------------------------------------*/
-static Program! Pgm = new Program();
+static Program/*!*/ Pgm = new Program();
-static Expr! dummyExpr = new LiteralExpr(Token.NoToken, false);
-static Cmd! dummyCmd = new AssumeCmd(Token.NoToken, dummyExpr);
-static Block! dummyBlock = new Block(Token.NoToken, "dummyBlock", new CmdSeq(),
+static Expr/*!*/ dummyExpr = new LiteralExpr(Token.NoToken, false);
+static Cmd/*!*/ dummyCmd = new AssumeCmd(Token.NoToken, dummyExpr);
+static Block/*!*/ dummyBlock = new Block(Token.NoToken, "dummyBlock", new CmdSeq(),
new ReturnCmd(Token.NoToken));
-static Bpl.Type! dummyType = new BasicType(Token.NoToken, SimpleType.Bool);
-static Bpl.ExprSeq! dummyExprSeq = new ExprSeq ();
-static TransferCmd! dummyTransferCmd = new ReturnCmd(Token.NoToken);
-static StructuredCmd! dummyStructuredCmd = new BreakCmd(Token.NoToken, null);
+static Bpl.Type/*!*/ dummyType = new BasicType(Token.NoToken, SimpleType.Bool);
+static Bpl.ExprSeq/*!*/ dummyExprSeq = new ExprSeq ();
+static TransferCmd/*!*/ dummyTransferCmd = new ReturnCmd(Token.NoToken);
+static StructuredCmd/*!*/ dummyStructuredCmd = new BreakCmd(Token.NoToken, null);
///<summary>
///Returns the number of parsing errors encountered. If 0, "program" returns as
///the parsed program.
///</summary>
-public static int Parse (string! filename, /*maybe null*/ List<string!> defines, out /*maybe null*/ Program program) /* throws System.IO.IOException */ {
+public static int Parse (string/*!*/ filename, /*maybe null*/ List<string/*!*/> defines, out /*maybe null*/ Program program) /* throws System.IO.IOException */ {
+Contract.Requires(filename != null);
+Contract.Requires(cce.NonNullElements(defines,true));
FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
if (defines == null) {
- defines = new List<string!>();
+ defines = new List<string/*!*/>();
}
string s = ParserHelper.Fill(stream, defines);
- 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);
@@ -69,21 +71,24 @@ public static int Parse (string! filename, /*maybe null*/ List<string!> defines,
private class BvBounds : Expr {
public BigNum Lower;
public BigNum Upper;
- public BvBounds(IToken! tok, BigNum lower, BigNum upper) {
- base(tok);
+ public BvBounds(IToken/*!*/ tok, BigNum lower, BigNum upper) :base(tok){//BASEMOVE
+ Contract.Requires(tok != null);
+ //:base(tok);
this.Lower = lower;
this.Upper = upper;
}
- public override Type! ShallowType { get { return Bpl.Type.Int; } }
- public override void Resolve(ResolutionContext! rc) {
+ public override Type/*!*/ ShallowType { get {Contract.Ensures(Contract.Result<Type>() != null); return Bpl.Type.Int; } }
+ public override void Resolve(ResolutionContext/*!*/ rc) {
+ Contract.Requires(rc != null);
rc.Error(this, "bitvector bounds in illegal position");
}
- public override void Emit(TokenTextWriter! stream,
+ public override void Emit(TokenTextWriter/*!*/ stream,
int contextBindingStrength, bool fragileContext) {
- assert false;
+ Contract.Requires(stream != null);
+ {Contract.Assert(false);throw new cce.UnreachableException();}
}
- public override void ComputeFreeVariables(Set! freeVars) { assert false; }
- public override AI.IExpr! IExpr { get { assert false; } }
+ public override void ComputeFreeVariables(Set/*!*/ freeVars) {Contract.Requires(freeVars != null); {Contract.Assert(false);throw new cce.UnreachableException();} }
+ public override AI.IExpr/*!*/ IExpr { get { Contract.Ensures(Contract.Result<AI.IExpr>()!=null); {Contract.Assert(false);throw new cce.UnreachableException();} } }
}
/*--------------------------------------------------------------------------*/
@@ -124,21 +129,28 @@ PRODUCTIONS
/*------------------------------------------------------------------------*/
BoogiePL
-= (. VariableSeq! vs;
- DeclarationSeq! ds;
- Axiom! ax;
- List<Declaration!>! ts;
- Procedure! pr;
+= (. VariableSeq/*!*/ vs;
+ DeclarationSeq/*!*/ ds;
+ Axiom/*!*/ ax;
+ List<Declaration/*!*/>/*!*/ ts;
+ Procedure/*!*/ pr;
Implementation im;
- Implementation! nnim;
+ Implementation/*!*/ nnim;
.)
- { Consts<out vs> (. foreach (Bpl.Variable! v in vs) { Pgm.TopLevelDeclarations.Add(v); } .)
- | Function<out ds> (. foreach (Bpl.Declaration! d in ds) { Pgm.TopLevelDeclarations.Add(d); } .)
+ { Consts<out vs> (. foreach(Bpl.Variable/*!*/ v in vs){
+Contract.Assert(v != null);
+ Pgm.TopLevelDeclarations.Add(v); } .)
+ | Function<out ds> (. foreach(Bpl.Declaration/*!*/ d in ds){
+Contract.Assert(d != null);
+ Pgm.TopLevelDeclarations.Add(d); } .)
| Axiom<out ax> (. Pgm.TopLevelDeclarations.Add(ax); .)
- | UserDefinedTypes<out ts> (. foreach (Declaration! td in ts) {
+ | UserDefinedTypes<out ts> (. foreach(Declaration/*!*/ td in ts){
+Contract.Assert(td != null);
Pgm.TopLevelDeclarations.Add(td);
} .)
- | GlobalVars<out vs> (. foreach (Bpl.Variable! v in vs) { Pgm.TopLevelDeclarations.Add(v); } .)
+ | GlobalVars<out vs> (. foreach(Bpl.Variable/*!*/ v in vs){
+Contract.Assert(v != null);
+ Pgm.TopLevelDeclarations.Add(v); } .)
| Procedure<out pr, out im> (. Pgm.TopLevelDeclarations.Add(pr);
if (im != null) {
Pgm.TopLevelDeclarations.Add(im);
@@ -150,43 +162,47 @@ BoogiePL
.
/*------------------------------------------------------------------------*/
-GlobalVars<out VariableSeq! ds>
-= (. TypedIdentSeq! tyds = new TypedIdentSeq(); ds = new VariableSeq(); QKeyValue kv = null; .)
+GlobalVars<out VariableSeq/*!*/ ds>
+= (. Contract.Ensures(Contract.ValueAtReturn(out ds) != null); TypedIdentSeq/*!*/ tyds = new TypedIdentSeq(); ds = new VariableSeq(); QKeyValue kv = null; .)
"var"
{ Attribute<ref kv> }
IdsTypeWheres<true, tyds> ";"
- (. foreach(TypedIdent! tyd in tyds) {
+ (. foreach(TypedIdent/*!*/ tyd in tyds){
+Contract.Assert(tyd != null);
ds.Add(new GlobalVariable(tyd.tok, tyd, kv));
}
.)
.
-LocalVars<VariableSeq! ds>
-= (. TypedIdentSeq! tyds = new TypedIdentSeq(); QKeyValue kv = null; .)
+LocalVars<VariableSeq/*!*/ ds>
+= (. Contract.Ensures(Contract.ValueAtReturn(out ds) != null); TypedIdentSeq/*!*/ tyds = new TypedIdentSeq(); QKeyValue kv = null; .)
"var"
{ Attribute<ref kv> }
IdsTypeWheres<true, tyds> ";"
- (. foreach(TypedIdent! tyd in tyds) {
+ (. foreach(TypedIdent/*!*/ tyd in tyds){
+Contract.Assert(tyd != null);
ds.Add(new LocalVariable(tyd.tok, tyd, kv));
}
.)
.
-ProcFormals<bool incoming, bool allowWhereClauses, out VariableSeq! ds>
-= (. TypedIdentSeq! tyds = new TypedIdentSeq(); ds = new VariableSeq(); .)
+ProcFormals<bool incoming, bool allowWhereClauses, out VariableSeq/*!*/ ds>
+= (.Contract.Ensures(Contract.ValueAtReturn(out ds) != null); TypedIdentSeq/*!*/ tyds = new TypedIdentSeq(); ds = new VariableSeq(); .)
"("
[ IdsTypeWheres<allowWhereClauses, tyds> ]
")"
- (. foreach (TypedIdent! tyd in tyds) {
+ (. foreach(TypedIdent/*!*/ tyd in tyds){
+Contract.Assert(tyd != null);
ds.Add(new Formal(tyd.tok, tyd, incoming));
}
.)
.
-BoundVars<IToken! x, out VariableSeq! ds>
-= (. TypedIdentSeq! tyds = new TypedIdentSeq(); ds = new VariableSeq(); .)
+BoundVars<IToken/*!*/ x, out VariableSeq/*!*/ ds>
+= (. Contract.Requires(x != null); Contract.Ensures(Contract.ValueAtReturn(out ds) != null); TypedIdentSeq/*!*/ tyds = new TypedIdentSeq(); ds = new VariableSeq(); .)
IdsTypeWheres<false, tyds>
- (. foreach (TypedIdent! tyd in tyds) {
+ (. foreach(TypedIdent/*!*/ tyd in tyds){
+Contract.Assert(tyd != null);
ds.Add(new BoundVariable(tyd.tok, tyd));
}
.)
@@ -194,11 +210,12 @@ BoundVars<IToken! x, out VariableSeq! ds>
/*------------------------------------------------------------------------*/
/* IdsType is used with const declarations */
-IdsType<out TypedIdentSeq! tyds>
-= (. TokenSeq! ids; Bpl.Type! ty; .)
+IdsType<out TypedIdentSeq/*!*/ tyds>
+= (. Contract.Ensures(Contract.ValueAtReturn(out tyds) != null); TokenSeq/*!*/ ids; Bpl.Type/*!*/ ty; .)
Idents<out ids> ":" Type<out ty>
(. tyds = new TypedIdentSeq();
- foreach (Token! id in ids) {
+ foreach(Token/*!*/ id in ids){
+Contract.Assert(id != null);
tyds.Add(new TypedIdent(id, id.val, ty, null));
}
.)
@@ -206,14 +223,14 @@ IdsType<out TypedIdentSeq! tyds>
/* IdsTypeWheres is used with the declarations of global and local variables,
procedure parameters, and quantifier bound variables. */
-IdsTypeWheres<bool allowWhereClauses, TypedIdentSeq! tyds>
-=
+IdsTypeWheres<bool allowWhereClauses, TypedIdentSeq/*!*/ tyds>
+=(.Contract.Requires(tyds != null);.)
IdsTypeWhere<allowWhereClauses, tyds>
{ "," IdsTypeWhere<allowWhereClauses, tyds> }
.
-IdsTypeWhere<bool allowWhereClauses, TypedIdentSeq! tyds>
-= (. TokenSeq! ids; Bpl.Type! ty; Expr wh = null; Expr! nne; .)
+IdsTypeWhere<bool allowWhereClauses, TypedIdentSeq/*!*/ tyds>
+= (.Contract.Requires(tyds != null); TokenSeq/*!*/ ids; Bpl.Type/*!*/ ty; Expr wh = null; Expr/*!*/ nne; .)
Idents<out ids> ":" Type<out ty>
[ "where" Expression<out nne> (. if (allowWhereClauses) {
wh = nne;
@@ -222,32 +239,33 @@ IdsTypeWhere<bool allowWhereClauses, TypedIdentSeq! tyds>
}
.)
]
- (. foreach (Token! id in ids) {
+ (. foreach(Token/*!*/ id in ids){
+Contract.Assert(id != null);
tyds.Add(new TypedIdent(id, id.val, ty, wh));
}
.)
.
/*------------------------------------------------------------------------*/
-Type<out Bpl.Type! ty>
-= (. IToken! tok; ty = dummyType; .)
+Type<out Bpl.Type/*!*/ ty>
+= (.Contract.Ensures(Contract.ValueAtReturn(out ty) != null); IToken/*!*/ tok; ty = dummyType; .)
(
TypeAtom<out ty>
|
- Ident<out tok> (. TypeSeq! args = new TypeSeq (); .)
+ Ident<out tok> (. TypeSeq/*!*/ args = new TypeSeq (); .)
[ TypeArgs<args> ] (. ty = new UnresolvedTypeIdentifier (tok, tok.val, args); .)
|
MapType<out ty>
)
.
-TypeArgs<TypeSeq! ts>
-= (. IToken! tok; Type! ty; .)
+TypeArgs<TypeSeq/*!*/ ts>
+= (.Contract.Requires(ts != null); IToken/*!*/ tok; Type/*!*/ ty; .)
(
TypeAtom<out ty> (. ts.Add(ty); .)
[ TypeArgs<ts> ]
|
- Ident<out tok> (. TypeSeq! args = new TypeSeq ();
+ Ident<out tok> (. TypeSeq/*!*/ args = new TypeSeq ();
ts.Add(new UnresolvedTypeIdentifier (tok, tok.val, args)); .)
[ TypeArgs<ts> ]
|
@@ -255,8 +273,8 @@ TypeArgs<TypeSeq! ts>
)
.
-TypeAtom<out Bpl.Type! ty>
-= (. ty = dummyType; .)
+TypeAtom<out Bpl.Type/*!*/ ty>
+= (.Contract.Ensures(Contract.ValueAtReturn(out ty) != null); ty = dummyType; .)
( "int" (. ty = new BasicType(t, SimpleType.Int); .)
| "bool" (. ty = new BasicType(t, SimpleType.Bool); .)
/* note: bitvectors are handled in UnresolvedTypeIdentifier */
@@ -267,12 +285,12 @@ TypeAtom<out Bpl.Type! ty>
)
.
-MapType<out Bpl.Type! ty>
-= (. IToken tok = null;
- IToken! nnTok;
- TypeSeq! arguments = new TypeSeq();
- Type! result;
- TypeVariableSeq! typeParameters = new TypeVariableSeq();
+MapType<out Bpl.Type/*!*/ ty>
+= (.Contract.Ensures(Contract.ValueAtReturn(out ty) != null); IToken tok = null;
+ IToken/*!*/ nnTok;
+ TypeSeq/*!*/ arguments = new TypeSeq();
+ Type/*!*/ result;
+ TypeVariableSeq/*!*/ typeParameters = new TypeVariableSeq();
.)
[ TypeParams<out nnTok, out typeParameters> (. tok = nnTok; .) ]
"[" (. if (tok == null) tok = t; .)
@@ -284,20 +302,21 @@ MapType<out Bpl.Type! ty>
.)
.
-TypeParams<out IToken! tok, out Bpl.TypeVariableSeq! typeParams>
-= (. TokenSeq! typeParamToks; .)
+TypeParams<out IToken/*!*/ tok, out Bpl.TypeVariableSeq/*!*/ typeParams>
+= (.Contract.Ensures(Contract.ValueAtReturn(out tok) != null); Contract.Ensures(Contract.ValueAtReturn(out typeParams) != null); TokenSeq/*!*/ typeParamToks; .)
"<" (. tok = t; .)
Idents<out typeParamToks>
">"
(.
typeParams = new TypeVariableSeq ();
- foreach (Token! id in typeParamToks)
- typeParams.Add(new TypeVariable(id, id.val));
+ foreach(Token/*!*/ id in typeParamToks){
+Contract.Assert(id != null);
+ typeParams.Add(new TypeVariable(id, id.val));}
.)
.
-Types<TypeSeq! ts>
-= (. Bpl.Type! ty; .)
+Types<TypeSeq/*!*/ ts>
+= (. Contract.Requires(ts != null); Bpl.Type/*!*/ ty; .)
Type<out ty> (. ts.Add(ty); .)
{ "," Type<out ty> (. ts.Add(ty); .)
}
@@ -305,12 +324,12 @@ Types<TypeSeq! ts>
/*------------------------------------------------------------------------*/
-Consts<out VariableSeq! ds>
-= (. IToken! y; TypedIdentSeq! xs;
+Consts<out VariableSeq/*!*/ ds>
+= (. Contract.Ensures(Contract.ValueAtReturn(out ds) != null); IToken/*!*/ y; TypedIdentSeq/*!*/ xs;
ds = new VariableSeq();
bool u = false; QKeyValue kv = null;
bool ChildrenComplete = false;
- List<ConstantParent!> Parents = null; .)
+ List<ConstantParent/*!*/> Parents = null; .)
"const" (. y = t; .)
{ Attribute<ref kv> }
[ "unique" (. u = true; .)
@@ -318,16 +337,17 @@ Consts<out VariableSeq! ds>
IdsType<out xs>
[ OrderSpec<out ChildrenComplete, out Parents> ]
(. bool makeClone = false;
- foreach(TypedIdent! x in xs) {
+ foreach(TypedIdent/*!*/ x in xs){
+Contract.Assert(x != null);
// ensure that no sharing is introduced
- List<ConstantParent!> ParentsClone;
+ List<ConstantParent/*!*/> ParentsClone;
if (makeClone && Parents != null) {
- ParentsClone = new List<ConstantParent!> ();
- foreach (ConstantParent! p in Parents)
+ ParentsClone = new List<ConstantParent/*!*/> ();
+ foreach (ConstantParent/*!*/ p in Parents){Contract.Assert(p != null);
ParentsClone.Add(new ConstantParent (
new IdentifierExpr (p.Parent.tok, p.Parent.Name),
- p.Unique));
+ p.Unique));}
} else {
ParentsClone = Parents;
}
@@ -339,12 +359,12 @@ Consts<out VariableSeq! ds>
";"
.
-OrderSpec<.out bool ChildrenComplete, out List<ConstantParent!> Parents.>
-= (. ChildrenComplete = false;
+OrderSpec<.out bool ChildrenComplete, out List<ConstantParent/*!*/> Parents.>
+= (.Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out Parents),true)); ChildrenComplete = false;
Parents = null;
bool u;
- IToken! parent; .)
- "extends" (. Parents = new List<ConstantParent!> ();
+ IToken/*!*/ parent; .)
+ "extends" (. Parents = new List<ConstantParent/*!*/> ();
u = false; .)
[
[ "unique" (. u = true; .)
@@ -364,17 +384,18 @@ OrderSpec<.out bool ChildrenComplete, out List<ConstantParent!> Parents.>
.
/*------------------------------------------------------------------------*/
-Function<out DeclarationSeq! ds>
-= (. ds = new DeclarationSeq(); IToken! z;
- IToken! typeParamTok;
- TypeVariableSeq! typeParams = new TypeVariableSeq();
+Function<out DeclarationSeq/*!*/ ds>
+= (. Contract.Ensures(Contract.ValueAtReturn(out ds) != null);
+ds = new DeclarationSeq(); IToken/*!*/ z;
+ IToken/*!*/ typeParamTok;
+ TypeVariableSeq/*!*/ typeParams = new TypeVariableSeq();
VariableSeq arguments = new VariableSeq();
- TypedIdent! tyd;
+ TypedIdent/*!*/ tyd;
TypedIdent retTyd = null;
- Type! retTy;
+ Type/*!*/ retTy;
QKeyValue kv = null;
Expr definition = null;
- Expr! tmp;
+ Expr/*!*/ tmp;
.)
"function" { Attribute<ref kv> } Ident<out z>
[ TypeParams<out typeParamTok, out typeParams> ]
@@ -395,11 +416,13 @@ Function<out DeclarationSeq! ds>
} else {
tyd = retTyd;
}
- Function! func = new Function(z, z.val, typeParams, arguments,
+ Function/*!*/ func = new Function(z, z.val, typeParams, arguments,
new Formal(tyd.tok, tyd, false), null, kv);
+ Contract.Assert(func != null);
ds.Add(func);
bool allUnnamed = true;
- foreach (Formal! f in arguments) {
+ foreach(Formal/*!*/ f in arguments){
+Contract.Assert(f != null);
if (f.TypedIdent.Name != "") {
allUnnamed = false;
break;
@@ -408,7 +431,7 @@ Function<out DeclarationSeq! ds>
if (!allUnnamed) {
Type prevType = null;
for (int i = arguments.Length - 1; i >= 0; i--) {
- TypedIdent! curr = ((!)arguments[i]).TypedIdent;
+ TypedIdent/*!*/ curr = cce.NonNull(arguments[i]).TypedIdent;
if (curr.Name == "") {
if (prevType == null) {
this.errors.SemErr(curr.tok, "the type of the last parameter is unspecified");
@@ -416,8 +439,8 @@ Function<out DeclarationSeq! ds>
}
Type ty = curr.Type;
if (ty is UnresolvedTypeIdentifier &&
- ((!)(ty as UnresolvedTypeIdentifier)).Arguments.Length == 0) {
- curr.Name = ((!)(ty as UnresolvedTypeIdentifier)).Name;
+ cce.NonNull(ty as UnresolvedTypeIdentifier).Arguments.Length == 0) {
+ curr.Name = cce.NonNull(ty as UnresolvedTypeIdentifier).Name;
curr.Type = prevType;
} else {
this.errors.SemErr(curr.tok, "expecting an identifier as parameter name");
@@ -435,15 +458,17 @@ Function<out DeclarationSeq! ds>
VariableSeq dummies = new VariableSeq();
ExprSeq callArgs = new ExprSeq();
int i = 0;
- foreach (Formal! f in arguments) {
+ foreach(Formal/*!*/ f in arguments){
+Contract.Assert(f != null);
string nm = f.TypedIdent.HasName ? f.TypedIdent.Name : "_" + i;
dummies.Add(new BoundVariable(f.tok, new TypedIdent(f.tok, nm, f.TypedIdent.Type)));
callArgs.Add(new IdentifierExpr(f.tok, nm));
i++;
}
- TypeVariableSeq! quantifiedTypeVars = new TypeVariableSeq ();
- foreach (TypeVariable! t in typeParams)
- quantifiedTypeVars.Add(new TypeVariable (Token.NoToken, t.Name));
+ TypeVariableSeq/*!*/ quantifiedTypeVars = new TypeVariableSeq ();
+ foreach(TypeVariable/*!*/ t in typeParams){
+Contract.Assert(t != null);
+ quantifiedTypeVars.Add(new TypeVariable (Token.NoToken, t.Name));}
Expr call = new NAryExpr(z, new FunctionCall(new IdentifierExpr(z, z.val)), callArgs);
// specify the type of the function, because it might be that
@@ -462,12 +487,12 @@ Function<out DeclarationSeq! ds>
.)
.
-VarOrType<out TypedIdent! tyd>
-= (. string! varName = ""; Bpl.Type! ty; IToken! tok; .)
+VarOrType<out TypedIdent/*!*/ tyd>
+= (.Contract.Ensures(Contract.ValueAtReturn(out tyd) != null); string/*!*/ varName = ""; Bpl.Type/*!*/ ty; IToken/*!*/ tok; .)
Type<out ty> (. tok = ty.tok; .)
[ ":" (. if (ty is UnresolvedTypeIdentifier &&
- ((!)(ty as UnresolvedTypeIdentifier)).Arguments.Length == 0) {
- varName = ((!)(ty as UnresolvedTypeIdentifier)).Name;
+ cce.NonNull(ty as UnresolvedTypeIdentifier).Arguments.Length == 0) {
+ varName = cce.NonNull(ty as UnresolvedTypeIdentifier).Name;
} else {
this.SemErr("expected identifier before ':'");
}
@@ -478,17 +503,17 @@ VarOrType<out TypedIdent! tyd>
.
/*------------------------------------------------------------------------*/
-Axiom<out Axiom! m>
-= (. Expr! e; QKeyValue kv = null; .)
+Axiom<out Axiom/*!*/ m>
+= (.Contract.Ensures(Contract.ValueAtReturn(out m) != null); Expr/*!*/ e; QKeyValue kv = null; .)
"axiom"
{ Attribute<ref kv> }
- (. IToken! x = t; .)
+ (. IToken/*!*/ x = t; .)
Proposition<out e> ";" (. m = new Axiom(x,e, null, kv); .)
.
/*------------------------------------------------------------------------*/
-UserDefinedTypes<.out List<Declaration!>! ts.>
-= (. Declaration! decl; QKeyValue kv = null; ts = new List<Declaration!> (); .)
+UserDefinedTypes<.out List<Declaration/*!*/>/*!*/ ts.>
+= (. Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out ts))); Declaration/*!*/ decl; QKeyValue kv = null; ts = new List<Declaration/*!*/> (); .)
"type"
{ Attribute<ref kv> }
UserDefinedType<out decl, kv> (. ts.Add(decl); .)
@@ -496,9 +521,9 @@ UserDefinedTypes<.out List<Declaration!>! ts.>
";"
.
-UserDefinedType<out Declaration! decl, QKeyValue kv>
-= (. IToken! id; IToken! id2; TokenSeq! paramTokens = new TokenSeq ();
- Type! body = dummyType; bool synonym = false; .)
+UserDefinedType<out Declaration/*!*/ decl, QKeyValue kv>
+= (. Contract.Ensures(Contract.ValueAtReturn(out decl) != null); IToken/*!*/ id; IToken/*!*/ id2; TokenSeq/*!*/ paramTokens = new TokenSeq ();
+ Type/*!*/ body = dummyType; bool synonym = false; .)
Ident<out id>
[ WhiteSpaceIdents<out paramTokens> ]
[
@@ -507,9 +532,10 @@ UserDefinedType<out Declaration! decl, QKeyValue kv>
]
(.
if (synonym) {
- TypeVariableSeq! typeParams = new TypeVariableSeq();
- foreach (Token! t in paramTokens)
- typeParams.Add(new TypeVariable(t, t.val));
+ TypeVariableSeq/*!*/ typeParams = new TypeVariableSeq();
+ foreach(Token/*!*/ t in paramTokens){
+Contract.Assert(t != null);
+ typeParams.Add(new TypeVariable(t, t.val));}
decl = new TypeSynonymDecl(id, id.val, typeParams, body, kv);
} else {
decl = new TypeCtorDecl(id, id.val, paramTokens.Length, kv);
@@ -519,16 +545,16 @@ UserDefinedType<out Declaration! decl, QKeyValue kv>
/*------------------------------------------------------------------------*/
-Procedure<out Procedure! proc, out /*maybe null*/ Implementation impl>
-= (. IToken! x;
- TypeVariableSeq! typeParams;
- VariableSeq! ins, outs;
- RequiresSeq! pre = new RequiresSeq();
- IdentifierExprSeq! mods = new IdentifierExprSeq();
- EnsuresSeq! post = new EnsuresSeq();
-
- VariableSeq! locals = new VariableSeq();
- StmtList! stmtList;
+Procedure<out Procedure/*!*/ proc, out /*maybe null*/ Implementation impl>
+= (. Contract.Ensures(Contract.ValueAtReturn(out proc) != null); IToken/*!*/ x;
+ TypeVariableSeq/*!*/ typeParams;
+ VariableSeq/*!*/ ins, outs;
+ RequiresSeq/*!*/ pre = new RequiresSeq();
+ IdentifierExprSeq/*!*/ mods = new IdentifierExprSeq();
+ EnsuresSeq/*!*/ post = new EnsuresSeq();
+
+ VariableSeq/*!*/ locals = new VariableSeq();
+ StmtList/*!*/ stmtList;
QKeyValue kv = null;
impl = null;
.)
@@ -549,12 +575,12 @@ Procedure<out Procedure! proc, out /*maybe null*/ Implementation impl>
.
-Implementation<out Implementation! impl>
-= (. IToken! x;
- TypeVariableSeq! typeParams;
- VariableSeq! ins, outs;
- VariableSeq! locals;
- StmtList! stmtList;
+Implementation<out Implementation/*!*/ impl>
+= (. Contract.Ensures(Contract.ValueAtReturn(out impl) != null); IToken/*!*/ x;
+ TypeVariableSeq/*!*/ typeParams;
+ VariableSeq/*!*/ ins, outs;
+ VariableSeq/*!*/ locals;
+ StmtList/*!*/ stmtList;
QKeyValue kv;
.)
@@ -565,9 +591,10 @@ Implementation<out Implementation! impl>
.
-ProcSignature<bool allowWhereClausesOnFormals, out IToken! name, out TypeVariableSeq! typeParams,
- out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv>
-= (. IToken! typeParamTok; typeParams = new TypeVariableSeq();
+ProcSignature<bool allowWhereClausesOnFormals, out IToken/*!*/ name, out TypeVariableSeq/*!*/ typeParams,
+ out VariableSeq/*!*/ ins, out VariableSeq/*!*/ outs, out QKeyValue kv>
+= (. Contract.Ensures(Contract.ValueAtReturn(out name) != null); Contract.Ensures(Contract.ValueAtReturn(out typeParams) != null); Contract.Ensures(Contract.ValueAtReturn(out ins) != null); Contract.Ensures(Contract.ValueAtReturn(out outs) != null);
+ IToken/*!*/ typeParamTok; typeParams = new TypeVariableSeq();
outs = new VariableSeq(); kv = null; .)
{ Attribute<ref kv> }
Ident<out name>
@@ -577,10 +604,11 @@ ProcSignature<bool allowWhereClausesOnFormals, out IToken! name, out TypeVariabl
.
-Spec<RequiresSeq! pre, IdentifierExprSeq! mods, EnsuresSeq! post>
-= (. TokenSeq! ms; .)
+Spec<RequiresSeq/*!*/ pre, IdentifierExprSeq/*!*/ mods, EnsuresSeq/*!*/ post>
+= (.Contract.Requires(pre != null); Contract.Requires(mods != null); Contract.Requires(post != null); TokenSeq/*!*/ ms; .)
( "modifies"
- [ Idents<out ms> (. foreach (IToken! m in ms) {
+ [ Idents<out ms> (. foreach(IToken/*!*/ m in ms){
+Contract.Assert(m != null);
mods.Add(new IdentifierExpr(m, m.val));
}
.)
@@ -590,8 +618,8 @@ Spec<RequiresSeq! pre, IdentifierExprSeq! mods, EnsuresSeq! post>
)
.
-SpecPrePost<bool free, RequiresSeq! pre, EnsuresSeq! post>
-= (. Expr! e; VariableSeq! locals; BlockSeq! blocks; Token tok = null; QKeyValue kv = null; .)
+SpecPrePost<bool free, RequiresSeq/*!*/ pre, EnsuresSeq/*!*/ post>
+= (. Contract.Requires(pre != null); Contract.Requires(post != null); Expr/*!*/ e; VariableSeq/*!*/ locals; BlockSeq/*!*/ blocks; Token tok = null; QKeyValue kv = null; .)
( "requires" (. tok = t; .)
{ Attribute<ref kv> }
Proposition<out e> ";" (. pre.Add(new Requires(tok, free, e, null, kv)); .)
@@ -603,38 +631,38 @@ SpecPrePost<bool free, RequiresSeq! pre, EnsuresSeq! post>
/*------------------------------------------------------------------------*/
-ImplBody<out VariableSeq! locals, out StmtList! stmtList>
-= (. locals = new VariableSeq(); .)
+ImplBody<out VariableSeq/*!*/ locals, out StmtList/*!*/ stmtList>
+= (. Contract.Ensures(Contract.ValueAtReturn(out locals) != null); Contract.Ensures(Contract.ValueAtReturn(out stmtList) != null); locals = new VariableSeq(); .)
"{"
{ LocalVars<locals> }
StmtList<out stmtList>
.
/* the StmtList also reads the final curly brace */
-StmtList<out StmtList! stmtList>
-= (. List<BigBlock!> bigblocks = new List<BigBlock!>();
+StmtList<out StmtList/*!*/ stmtList>
+= (. Contract.Ensures(Contract.ValueAtReturn(out stmtList) != null); List<BigBlock/*!*/> bigblocks = new List<BigBlock/*!*/>();
/* built-up state for the current BigBlock: */
IToken startToken = null; string currentLabel = null;
CmdSeq cs = null; /* invariant: startToken != null ==> cs != null */
/* temporary variables: */
IToken label; Cmd c; BigBlock b;
- StructuredCmd ec = null; StructuredCmd! ecn;
- TransferCmd tc = null; TransferCmd! tcn;
+ StructuredCmd ec = null; StructuredCmd/*!*/ ecn;
+ TransferCmd tc = null; TransferCmd/*!*/ tcn;
.)
{
( LabelOrCmd<out c, out label>
(. if (c != null) {
// LabelOrCmd read a Cmd
- assert label == null;
+ Contract.Assert(label == null);
if (startToken == null) { startToken = c.tok; cs = new CmdSeq(); }
- assert cs != null;
+ Contract.Assert(cs != null);
cs.Add(c);
} else {
// LabelOrCmd read a label
- assert label != null;
+ Contract.Assert(label != null);
if (startToken != null) {
- assert cs != null;
+ Contract.Assert(cs != null);
// dump the built-up state into a BigBlock
b = new BigBlock(startToken, currentLabel, cs, null, null);
bigblocks.Add(b);
@@ -649,7 +677,7 @@ StmtList<out StmtList! stmtList>
| StructuredCmd<out ecn>
(. ec = ecn;
if (startToken == null) { startToken = ec.tok; cs = new CmdSeq(); }
- assert cs != null;
+ Contract.Assert(cs != null);
b = new BigBlock(startToken, currentLabel, cs, ec, null);
bigblocks.Add(b);
startToken = null; currentLabel = null; cs = null;
@@ -658,7 +686,7 @@ StmtList<out StmtList! stmtList>
| TransferCmd<out tcn>
(. tc = tcn;
if (startToken == null) { startToken = tc.tok; cs = new CmdSeq(); }
- assert cs != null;
+ Contract.Assert(cs != null);
b = new BigBlock(startToken, currentLabel, cs, null, tc);
bigblocks.Add(b);
startToken = null; currentLabel = null; cs = null;
@@ -667,12 +695,12 @@ StmtList<out StmtList! stmtList>
)
}
"}"
- (. IToken! endCurly = t;
+ (. IToken/*!*/ endCurly = t;
if (startToken == null && bigblocks.Count == 0) {
startToken = t; cs = new CmdSeq();
}
if (startToken != null) {
- assert cs != null;
+ Contract.Assert(cs != null);
b = new BigBlock(startToken, currentLabel, cs, null, null);
bigblocks.Add(b);
}
@@ -681,22 +709,24 @@ StmtList<out StmtList! stmtList>
.)
.
-TransferCmd<out TransferCmd! tc>
-= (. tc = dummyTransferCmd;
- Token y; TokenSeq! xs;
+TransferCmd<out TransferCmd/*!*/ tc>
+= (. Contract.Ensures(Contract.ValueAtReturn(out tc) != null); tc = dummyTransferCmd;
+ Token y; TokenSeq/*!*/ xs;
StringSeq ss = new StringSeq();
.)
( "goto" (. y = t; .)
- Idents<out xs> (. foreach (IToken! s in xs) { ss.Add(s.val); }
+ Idents<out xs> (. foreach(IToken/*!*/ s in xs){
+Contract.Assert(s != null);
+ ss.Add(s.val); }
tc = new GotoCmd(y, ss);
.)
| "return" (. tc = new ReturnCmd(t); .)
) ";"
.
-StructuredCmd<out StructuredCmd! ec>
-= (. ec = dummyStructuredCmd; assume ec.IsPeerConsistent;
- IfCmd! ifcmd; WhileCmd! wcmd; BreakCmd! bcmd;
+StructuredCmd<out StructuredCmd/*!*/ ec>
+= (. Contract.Ensures(Contract.ValueAtReturn(out ec) != null); ec = dummyStructuredCmd; Contract.Assume(cce.IsPeerConsistent(ec));
+ IfCmd/*!*/ ifcmd; WhileCmd/*!*/ wcmd; BreakCmd/*!*/ bcmd;
.)
( IfCmd<out ifcmd> (. ec = ifcmd; .)
| WhileCmd<out wcmd> (. ec = wcmd; .)
@@ -704,12 +734,12 @@ StructuredCmd<out StructuredCmd! ec>
)
.
-IfCmd<out IfCmd! ifcmd>
-= (. IToken! x;
+IfCmd<out IfCmd/*!*/ ifcmd>
+= (. Contract.Ensures(Contract.ValueAtReturn(out ifcmd) != null); IToken/*!*/ x;
Expr guard;
- StmtList! thn;
- IfCmd! elseIf; IfCmd elseIfOption = null;
- StmtList! els; StmtList elseOption = null;
+ StmtList/*!*/ thn;
+ IfCmd/*!*/ elseIf; IfCmd elseIfOption = null;
+ StmtList/*!*/ els; StmtList elseOption = null;
.)
"if" (. x = t; .)
Guard<out guard>
@@ -723,14 +753,14 @@ IfCmd<out IfCmd! ifcmd>
(. ifcmd = new IfCmd(x, guard, thn, elseIfOption, elseOption); .)
.
-WhileCmd<out WhileCmd! wcmd>
-= (. IToken! x; Token z;
- Expr guard; Expr! e; bool isFree;
- List<PredicateCmd!> invariants = new List<PredicateCmd!>();
- StmtList! body;
+WhileCmd<out WhileCmd/*!*/ wcmd>
+= (. Contract.Ensures(Contract.ValueAtReturn(out wcmd) != null); IToken/*!*/ x; Token z;
+ Expr guard; Expr/*!*/ e; bool isFree;
+ List<PredicateCmd/*!*/> invariants = new List<PredicateCmd/*!*/>();
+ StmtList/*!*/ 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; z = la/*lookahead token*/; .)
[ "free" (. isFree = true; .)
]
@@ -748,7 +778,7 @@ WhileCmd<out WhileCmd! wcmd>
.
Guard<out Expr e>
-= (. Expr! ee; e = null; .)
+= (. Expr/*!*/ ee; e = null; .)
"("
( "*" (. e = null; .)
| Expression<out ee> (. e = ee; .)
@@ -756,8 +786,8 @@ Guard<out Expr e>
")"
.
-BreakCmd<out BreakCmd! bcmd>
-= (. IToken! x; IToken! y;
+BreakCmd<out BreakCmd/*!*/ bcmd>
+= (.Contract.Ensures(Contract.ValueAtReturn(out bcmd) != null); IToken/*!*/ x; IToken/*!*/ y;
string breakLabel = null;
.)
"break" (. x = t; .)
@@ -769,11 +799,11 @@ BreakCmd<out BreakCmd! bcmd>
LabelOrCmd<out Cmd c, out IToken label>
/* ensures (c == null) != (label != null) */
-= (. IToken! x; Expr! e;
- TokenSeq! xs;
+= (. IToken/*!*/ x; Expr/*!*/ e;
+ TokenSeq/*!*/ xs;
IdentifierExprSeq ids;
c = dummyCmd; label = null;
- Cmd! cn;
+ Cmd/*!*/ cn;
QKeyValue kv = null;
.)
( LabelOrAssign<out c, out label>
@@ -786,7 +816,8 @@ LabelOrCmd<out Cmd c, out IToken label>
";"
| "havoc" (. x = t; .)
Idents<out xs> ";" (. ids = new IdentifierExprSeq();
- foreach (IToken! y in xs) {
+ foreach(IToken/*!*/ y in xs){
+Contract.Assert(y != null);
ids.Add(new IdentifierExpr(y, y.val));
}
c = new HavocCmd(x,ids);
@@ -799,17 +830,17 @@ LabelOrCmd<out Cmd c, out IToken label>
LabelOrAssign<out Cmd c, out IToken label>
/* ensures (c == null) != (label != null) */
-= (. IToken! id; IToken! x, y; Expr! e, e0;
+= (. IToken/*!*/ id; IToken/*!*/ x, y; Expr/*!*/ e, e0;
c = dummyCmd; label = null;
- AssignLhs! lhs;
- List<AssignLhs!>! lhss;
- List<Expr!>! rhss;
- List<Expr!>! indexes;
+ AssignLhs/*!*/ lhs;
+ List<AssignLhs/*!*/>/*!*/ lhss;
+ List<Expr/*!*/>/*!*/ rhss;
+ List<Expr/*!*/>/*!*/ indexes;
.)
Ident<out id> (. x = t; .)
( ":" (. c = null; label = x; .)
- | (. lhss = new List<AssignLhs!>(); .)
+ | (. lhss = new List<AssignLhs/*!*/>(); .)
(. lhs = new SimpleAssignLhs(id, new IdentifierExpr(id, id.val)); .)
{ MapAssignIndex<out y, out indexes> (. lhs = new MapAssignLhs(y, lhs, indexes); .) }
@@ -823,7 +854,7 @@ LabelOrAssign<out Cmd c, out IToken label>
}
":=" (. x = t; /* use location of := */ .)
- Expression<out e0> (. rhss = new List<Expr!> ();
+ Expression<out e0> (. rhss = new List<Expr/*!*/> ();
rhss.Add(e0); .)
{ ","
Expression<out e0> (. rhss.Add(e0); .)
@@ -832,9 +863,9 @@ LabelOrAssign<out Cmd c, out IToken label>
)
.
-MapAssignIndex<.out IToken! x, out List<Expr!>! indexes.>
-= (. indexes = new List<Expr!> ();
- Expr! e;
+MapAssignIndex<.out IToken/*!*/ x, out List<Expr/*!*/>/*!*/ indexes.>
+= (.Contract.Ensures(Contract.ValueAtReturn(out x) != null); Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out indexes))); indexes = new List<Expr/*!*/> ();
+ Expr/*!*/ e;
.)
"[" (. x = t; .)
[
@@ -847,10 +878,10 @@ MapAssignIndex<.out IToken! x, out List<Expr!>! indexes.>
.
/*------------------------------------------------------------------------*/
-CallCmd<out Cmd! c>
-= (. IToken! x; IToken! first; IToken p;
- List<IdentifierExpr>! ids = new List<IdentifierExpr>();
- List<Expr>! es = new List<Expr>();
+CallCmd<out Cmd/*!*/ c>
+= (. Contract.Ensures(Contract.ValueAtReturn(out c) != null); IToken/*!*/ x; IToken/*!*/ first; IToken p;
+ List<IdentifierExpr>/*!*/ ids = new List<IdentifierExpr>();
+ List<Expr>/*!*/ es = new List<Expr>();
QKeyValue kv = null;
Expr en; List<Expr> args;
c = dummyCmd;
@@ -925,7 +956,7 @@ CallCmd<out Cmd! c>
CallOutIdent<out IToken id>
= (. id = null;
- IToken! p;
+ IToken/*!*/ p;
.)
( "*"
| Ident<out p> (. id = p; .)
@@ -934,7 +965,7 @@ CallOutIdent<out IToken id>
CallForallArg<out Expr exprOptional>
= (. exprOptional = null;
- Expr! e;
+ Expr/*!*/ e;
.)
( "*"
| Expression<out e> (. exprOptional = e; .)
@@ -942,38 +973,38 @@ CallForallArg<out Expr exprOptional>
.
/*------------------------------------------------------------------------*/
-Proposition<out Expr! e>
-=
+Proposition<out Expr/*!*/ e>
+=(.Contract.Ensures(Contract.ValueAtReturn(out e) != null);.)
Expression<out e>
.
/*------------------------------------------------------------------------*/
-Idents<out TokenSeq! xs>
-= (. IToken! id; xs = new TokenSeq(); .)
+Idents<out TokenSeq/*!*/ xs>
+= (.Contract.Ensures(Contract.ValueAtReturn(out xs) != null); IToken/*!*/ id; xs = new TokenSeq(); .)
Ident<out id> (. xs.Add(id); .)
{ "," Ident<out id> (. xs.Add(id); .)
}
.
/*------------------------------------------------------------------------*/
-WhiteSpaceIdents<out TokenSeq! xs>
-= (. IToken! id; xs = new TokenSeq(); .)
+WhiteSpaceIdents<out TokenSeq/*!*/ xs>
+= (. Contract.Ensures(Contract.ValueAtReturn(out xs) != null); IToken/*!*/ id; xs = new TokenSeq(); .)
Ident<out id> (. xs.Add(id); .)
{ Ident<out id> (. xs.Add(id); .)
}
.
/*------------------------------------------------------------------------*/
-Expressions<out ExprSeq! es>
-= (. Expr! e; es = new ExprSeq(); .)
+Expressions<out ExprSeq/*!*/ es>
+= (. Contract.Ensures(Contract.ValueAtReturn(out es) != null); Expr/*!*/ e; es = new ExprSeq(); .)
Expression<out e> (. es.Add(e); .)
{ "," Expression<out e> (. es.Add(e); .)
}
.
/*------------------------------------------------------------------------*/
-Expression<out Expr! e0>
-= (. IToken! x; Expr! e1; .)
+Expression<out Expr/*!*/ e0>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; .)
ImpliesExpression<false, out e0>
{ EquivOp (. x = t; .)
ImpliesExpression<false, out e1>
@@ -984,8 +1015,8 @@ Expression<out Expr! e0>
EquivOp = "<==>" | '\u21d4'.
/*------------------------------------------------------------------------*/
-ImpliesExpression<bool noExplies, out Expr! e0>
-= (. IToken! x; Expr! e1; .)
+ImpliesExpression<bool noExplies, out Expr/*!*/ e0>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; .)
LogicalExpression<out e0>
[
ImpliesOp (. x = t; .)
@@ -1011,8 +1042,8 @@ ImpliesOp = "==>" | '\u21d2'.
ExpliesOp = "<==" | '\u21d0'.
/*------------------------------------------------------------------------*/
-LogicalExpression<out Expr! e0>
-= (. IToken! x; Expr! e1; BinaryOperator.Opcode op; .)
+LogicalExpression<out Expr/*!*/ e0>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; BinaryOperator.Opcode op; .)
RelationalExpression<out e0>
[ AndOp (. x = t; .)
RelationalExpression<out e1>
@@ -1035,16 +1066,16 @@ AndOp = "&&" | '\u2227'.
OrOp = "||" | '\u2228'.
/*------------------------------------------------------------------------*/
-RelationalExpression<out Expr! e0>
-= (. IToken! x; Expr! e1; BinaryOperator.Opcode op; .)
+RelationalExpression<out Expr/*!*/ e0>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; BinaryOperator.Opcode op; .)
BvTerm<out e0>
[ RelOp<out x, out op>
BvTerm<out e1> (. e0 = Expr.Binary(x, op, e0, e1); .)
]
.
-RelOp<out IToken! x, out BinaryOperator.Opcode op>
-= (. x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/; .)
+RelOp<out IToken/*!*/ x, out BinaryOperator.Opcode op>
+= (.Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/; .)
( "==" (. x = t; op=BinaryOperator.Opcode.Eq; .)
| "<" (. x = t; op=BinaryOperator.Opcode.Lt; .)
| ">" (. x = t; op=BinaryOperator.Opcode.Gt; .)
@@ -1059,8 +1090,8 @@ RelOp<out IToken! x, out BinaryOperator.Opcode op>
.
/*------------------------------------------------------------------------*/
-BvTerm<out Expr! e0>
-= (. IToken! x; Expr! e1; .)
+BvTerm<out Expr/*!*/ e0>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; .)
Term<out e0>
{ "++" (. x = t; .)
Term<out e1> (. e0 = new BvConcatExpr(x, e0, e1); .)
@@ -1069,32 +1100,32 @@ BvTerm<out Expr! e0>
/*------------------------------------------------------------------------*/
-Term<out Expr! e0>
-= (. IToken! x; Expr! e1; BinaryOperator.Opcode op; .)
+Term<out Expr/*!*/ e0>
+= (.Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; BinaryOperator.Opcode op; .)
Factor<out e0>
{ AddOp<out x, out op>
Factor<out e1> (. e0 = Expr.Binary(x, op, e0, e1); .)
}
.
-AddOp<out IToken! x, out BinaryOperator.Opcode op>
-= (. x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/; .)
+AddOp<out IToken/*!*/ x, out BinaryOperator.Opcode op>
+= (.Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/; .)
( "+" (. x = t; op=BinaryOperator.Opcode.Add; .)
| "-" (. x = t; op=BinaryOperator.Opcode.Sub; .)
)
.
/*------------------------------------------------------------------------*/
-Factor<out Expr! e0>
-= (. IToken! x; Expr! e1; BinaryOperator.Opcode op; .)
+Factor<out Expr/*!*/ e0>
+= (.Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; BinaryOperator.Opcode op; .)
UnaryExpression<out e0>
{ MulOp<out x, out op>
UnaryExpression<out e1> (. e0 = Expr.Binary(x, op, e0, e1); .)
}
.
-MulOp<out IToken! x, out BinaryOperator.Opcode op>
-= (. x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/; .)
+MulOp<out IToken/*!*/ x, out BinaryOperator.Opcode op>
+= (. Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/; .)
( "*" (. x = t; op=BinaryOperator.Opcode.Mul; .)
| "/" (. x = t; op=BinaryOperator.Opcode.Div; .)
| "%" (. x = t; op=BinaryOperator.Opcode.Mod; .)
@@ -1102,8 +1133,8 @@ MulOp<out IToken! x, out BinaryOperator.Opcode op>
.
/*------------------------------------------------------------------------*/
-UnaryExpression<out Expr! e>
-= (. IToken! x;
+UnaryExpression<out Expr/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x;
e = dummyExpr;
.)
( "-" (. x = t; .)
@@ -1125,9 +1156,9 @@ NegOp = "!" | '\u00ac'.
will cause a parse error because "<" is treated as the beginning of a
map type. */
-CoercionExpression<out Expr! e>
-= (. IToken! x;
- Type! coercedTo;
+CoercionExpression<out Expr/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x;
+ Type/*!*/ coercedTo;
BigNum bn;
.)
ArrayExpression<out e>
@@ -1149,11 +1180,11 @@ CoercionExpression<out Expr! e>
.
/*------------------------------------------------------------------------*/
-ArrayExpression<out Expr! e>
-= (. IToken! x;
- Expr! index0 = dummyExpr; Expr! e1;
+ArrayExpression<out Expr/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x;
+ Expr/*!*/ index0 = dummyExpr; Expr/*!*/ e1;
bool store; bool bvExtract;
- ExprSeq! allArgs = dummyExprSeq;
+ ExprSeq/*!*/ allArgs = dummyExprSeq;
.)
AtomExpression<out e>
{ "[" (. x = t; allArgs = new ExprSeq ();
@@ -1195,16 +1226,16 @@ ArrayExpression<out Expr! e>
/*------------------------------------------------------------------------*/
-AtomExpression<out Expr! e>
-= (. IToken! x; int n; BigNum bn;
- ExprSeq! es; VariableSeq! ds; Trigger trig;
- TypeVariableSeq! typeParams;
- IdentifierExpr! id;
- Bpl.Type! ty;
+AtomExpression<out Expr/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; int n; BigNum bn;
+ ExprSeq/*!*/ es; VariableSeq/*!*/ ds; Trigger trig;
+ TypeVariableSeq/*!*/ typeParams;
+ IdentifierExpr/*!*/ id;
+ Bpl.Type/*!*/ ty;
QKeyValue kv;
e = dummyExpr;
- VariableSeq! locals;
- List<Block!>! blocks;
+ VariableSeq/*!*/ locals;
+ List<Block/*!*/>/*!*/ blocks;
.)
( "false" (. e = new LiteralExpr(t, false); .)
| "true" (. e = new LiteralExpr(t, true); .)
@@ -1248,9 +1279,9 @@ AtomExpression<out Expr! e>
)
.
-CodeExpression<.out VariableSeq! locals, out List<Block!>! blocks.>
-= (. locals = new VariableSeq(); Block! b;
- blocks = new List<Block!>();
+CodeExpression<.out VariableSeq/*!*/ locals, out List<Block/*!*/>/*!*/ blocks.>
+= (. Contract.Ensures(Contract.ValueAtReturn(out locals) != null); Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out blocks))); locals = new VariableSeq(); Block/*!*/ b;
+ blocks = new List<Block/*!*/>();
.)
"|{"
{ LocalVars<locals> }
@@ -1260,28 +1291,30 @@ CodeExpression<.out VariableSeq! locals, out List<Block!>! blocks.>
"}|"
.
-SpecBlock<out Block! b>
-= (. IToken! x; IToken! y;
+SpecBlock<out Block/*!*/ b>
+= (. Contract.Ensures(Contract.ValueAtReturn(out b) != null); IToken/*!*/ x; IToken/*!*/ y;
Cmd c; IToken label;
CmdSeq cs = new CmdSeq();
- TokenSeq! xs;
+ TokenSeq/*!*/ xs;
StringSeq ss = new StringSeq();
b = dummyBlock;
- Expr! e;
+ Expr/*!*/ e;
.)
Ident<out x> ":"
{ LabelOrCmd<out c, out label>
(. if (c != null) {
- assert label == null;
+ Contract.Assert(label == null);
cs.Add(c);
} else {
- assert label != null;
+ Contract.Assert(label != null);
SemErr("SpecBlock's can only have one label");
}
.)
}
( "goto" (. y = t; .)
- Idents<out xs> (. foreach (IToken! s in xs) { ss.Add(s.val); }
+ Idents<out xs> (. foreach(IToken/*!*/ s in xs){
+Contract.Assert(s != null);
+ ss.Add(s.val); }
b = new Block(x,x.val,cs,new GotoCmd(y,ss));
.)
| "return" Expression<out e>
@@ -1296,13 +1329,13 @@ Attribute<ref QKeyValue kv>
.
AttributeOrTrigger<ref QKeyValue kv, ref Trigger trig>
-= (. IToken! tok; Expr! e; ExprSeq! es;
+= (. IToken/*!*/ tok; Expr/*!*/ e; ExprSeq/*!*/ es;
string key; string value;
- List<object!> parameters; object! param;
+ List<object/*!*/> parameters; object/*!*/ param;
.)
"{" (. tok = t; .)
(
- ":" ident (. key = t.val; parameters = new List<object!>(); .)
+ ":" ident (. key = t.val; parameters = new List<object/*!*/>(); .)
[ AttributeParameter<out param> (. parameters.Add(param); .)
{ "," AttributeParameter<out param> (. parameters.Add(param); .)
}
@@ -1339,28 +1372,31 @@ AttributeOrTrigger<ref QKeyValue kv, ref Trigger trig>
"}"
.
-AttributeParameter<out object! o>
-= (. o = "error";
- Expr! e;
+AttributeParameter<out object/*!*/ o>
+= (. Contract.Ensures(Contract.ValueAtReturn(out o) != null);
+ o = "error";
+ Expr/*!*/ e;
.)
( string (. o = t.val.Substring(1, t.val.Length-2); .)
| Expression<out e> (. o = e; .)
)
.
-IfThenElseExpression<out Expr! e>
-= (. IToken! tok;
- Expr! e0, e1, e2;
+IfThenElseExpression<out Expr/*!*/ e>
+= (. Contract.Ensures(Contract.ValueAtReturn(out e) != null);
+ IToken/*!*/ tok;
+ Expr/*!*/ e0, e1, e2;
e = dummyExpr; .)
"if" (. tok = t; .) Expression<out e0> "then" Expression<out e1> "else" Expression<out e2>
(. e = new NAryExpr(tok, new IfThenElse(tok), new ExprSeq(e0, e1, e2)); .)
.
-QuantifierBody<IToken! q, out TypeVariableSeq! typeParams, out VariableSeq! ds,
- out QKeyValue kv, out Trigger trig, out Expr! body>
-= (. trig = null; typeParams = new TypeVariableSeq ();
- IToken! tok; Expr! e; ExprSeq! es;
+QuantifierBody<IToken/*!*/ q, out TypeVariableSeq/*!*/ typeParams, out VariableSeq/*!*/ ds,
+ out QKeyValue kv, out Trigger trig, out Expr/*!*/ body>
+= (. Contract.Requires(q != null); Contract.Ensures(Contract.ValueAtReturn(out typeParams) != null); Contract.Ensures(Contract.ValueAtReturn(out ds) != null); Contract.Ensures(Contract.ValueAtReturn(out body) != null);
+trig = null; typeParams = new TypeVariableSeq ();
+ IToken/*!*/ tok; Expr/*!*/ e; ExprSeq/*!*/ es;
kv = null; string key; string value;
ds = new VariableSeq ();
.)
@@ -1381,8 +1417,8 @@ Lambda = "lambda" | '\u03bb'.
QSep = "::" | '\u2022'.
/*------------------------------------------------------------------------*/
-Ident<out IToken! x>
-=
+Ident<out IToken/*!*/ x>
+=(.Contract.Ensures(Contract.ValueAtReturn(out x) != null);.)
ident (. x = t;
if (x.val.StartsWith("\\"))
x.val = x.val.Substring(1);
@@ -1420,5 +1456,4 @@ BvLit<out BigNum n, out int m>
}
.)
.
-
-END BoogiePL.
+END BoogiePL. \ No newline at end of file
diff --git a/Source/Core/CommandLineOptions.cs b/Source/Core/CommandLineOptions.cs
index 6808be61..20a2fede 100644
--- a/Source/Core/CommandLineOptions.cs
+++ b/Source/Core/CommandLineOptions.cs
@@ -9,39 +9,75 @@ using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Diagnostics;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
using Cci = System.Compiler;
-namespace Microsoft.Boogie
-{
- public class CommandLineOptions
- {
- public static string! VersionNumber { get { return (!)((!)System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location)).FileVersion; } }
+namespace Microsoft.Boogie {
+ public class CommandLineOptions {
+ public static string/*!*/ VersionNumber {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return cce.NonNull(cce.NonNull(System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly().Location)).FileVersion);
+ }
+ }
public const string ToolNameBoogie = "Boogie program verifier";
public const string ToolNameSpecSharp = "Spec# program verifier";
public const string ToolNameDafny = "Dafny program verifier";
- public static string! VersionSuffix { get { return " version " + VersionNumber + ", Copyright (c) 2003-2010, Microsoft."; } }
- public string! InputFileExtension {
- set
- modifies _toolname, _version;
- {
+ public static string/*!*/ VersionSuffix {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return " version " + VersionNumber + ", Copyright (c) 2003-2010, Microsoft.";
+ }
+ }
+ public string/*!*/ InputFileExtension {
+ set {
+ Contract.Requires(value != null);
+ //modifies _toolname, _version;
switch (value) {
- case ".bpl": _toolname = ToolNameBoogie; break;
- case ".dfy": _toolname = ToolNameDafny; break;
- default: _toolname = ToolNameSpecSharp; break;
+ case ".bpl":
+ _toolname = ToolNameBoogie;
+ break;
+ case ".dfy":
+ _toolname = ToolNameDafny;
+ break;
+ default:
+ _toolname = ToolNameSpecSharp;
+ break;
}
_version = _toolname + VersionSuffix;
}
}
- string! _toolname = ToolNameBoogie;
- string! _version = ToolNameBoogie + VersionSuffix;
- public string! ToolName { get { return _toolname; } }
- public string! Version { get { return _version; } }
-
- public static CommandLineOptions! Clo = new CommandLineOptions(); // singleton to access all global data
-
- public string! Environment = "";
- public string! FileName = "unknown";
+ string/*!*/ _toolname = ToolNameBoogie;
+ string/*!*/ _version = ToolNameBoogie + VersionSuffix;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(_toolname != null);
+ Contract.Invariant(_version != null);
+ Contract.Invariant(Clo != null);
+ Contract.Invariant(Environment != null);
+ Contract.Invariant(FileName != null);
+ Contract.Invariant(cce.NonNullElements(Files));
+ Contract.Invariant(cce.NonNullElements(ContractAssemblies));
+ Contract.Invariant(FileTimestamp != null);
+ }
+
+ public string/*!*/ ToolName {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return _toolname;
+ }
+ }
+ public string/*!*/ Version {
+ get {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return _version;
+ }
+ }
+
+ public static CommandLineOptions/*!*/ Clo = new CommandLineOptions(); // singleton to access all global data
+
+ public string/*!*/ Environment = "";
+ public string/*!*/ FileName = "unknown";
public const long Megabyte = 1048576;
@@ -49,37 +85,48 @@ namespace Microsoft.Boogie
public bool RunningBoogieFromCommandLine = false; // "false" means running Boogie from the plug-in
public bool RunningBoogieOnSsc = true; // "true" means running Boogie on ssc input while false means running it on bpl input
-
+
public bool AttrHelpRequested = false;
-
- [Peer] public List<string!>! Files = new List<string!>();
- public List<string!>! ContractAssemblies = new List<string!>();
-
- public string! FileTimestamp = ((!)DateTime.Now.ToString("o")).Replace(':', '.');
- public void ExpandFilename(ref string pattern)
- {
+
+ [Peer]
+ public List<string/*!*/>/*!*/ Files = new List<string/*!*/>();
+ public List<string/*!*/>/*!*/ ContractAssemblies = new List<string/*!*/>();
+
+ public string/*!*/ FileTimestamp = cce.NonNull(DateTime.Now.ToString("o")).Replace(':', '.');
+ public void ExpandFilename(ref string pattern) {
if (pattern != null) {
pattern = pattern.Replace("@PREFIX@", LogPrefix).Replace("@TIME@", FileTimestamp);
- string fn = Files.Count == 0 ? "" : Files[Files.Count-1];
+ string fn = Files.Count == 0 ? "" : Files[Files.Count - 1];
fn = fn.Replace('/', '-').Replace('\\', '-');
pattern = pattern.Replace("@FILE@", fn);
}
}
+ [ContractInvariantMethod]
+ void ObjectInvariant2() {
+ Contract.Invariant(LogPrefix != null);
+ Contract.Invariant(0 <= PrintUnstructured && PrintUnstructured < 3); // 0 = print only structured, 1 = both structured and unstructured, 2 = only unstructured
+
+ }
+
public string PrintFile = null;
public int PrintUnstructured = 0;
- invariant 0 <= PrintUnstructured && PrintUnstructured < 3; // 0 = print only structured, 1 = both structured and unstructured, 2 = only unstructured
+
public bool PrintDesugarings = false;
public string SimplifyLogFilePath = null;
public string SMTLibOutputPath = "boogie-vc-@PROC@.smt";
- public string! LogPrefix = "";
+ public string/*!*/ LogPrefix = "";
public bool PrintInstrumented = false;
public bool InstrumentWithAsserts = false;
- public enum InstrumentationPlaces { LoopHeaders, Everywhere }
+ public enum InstrumentationPlaces {
+ LoopHeaders,
+ Everywhere
+ }
public InstrumentationPlaces InstrumentInfer = InstrumentationPlaces.LoopHeaders;
public bool PrintWithUniqueASTIds = false;
private string XmlSinkFilename = null;
- [Peer] public XmlSink XmlSink = null;
+ [Peer]
+ public XmlSink XmlSink = null;
public bool Wait = false;
public bool Trace = false;
public bool TraceTimes = false;
@@ -94,93 +141,145 @@ namespace Microsoft.Boogie
public bool UseUncheckedContracts = false;
public bool SimplifyLogFileAppend = false;
public bool SoundnessSmokeTest = false;
-
+
private bool noConsistencyChecks = false;
public bool NoConsistencyChecks {
- get {return !Verify ? true : noConsistencyChecks;}
+ get {
+ return !Verify ? true : noConsistencyChecks;
+ }
set
- modifies noConsistencyChecks;
- {noConsistencyChecks = value;}
+ //modifies noConsistencyChecks;
+ {
+ noConsistencyChecks = value;
+ }
}
public string DafnyPrintFile = null;
public bool Compile = true;
-
- public enum ProverWarnings { None, Stdout, Stderr }
+
+ public enum ProverWarnings {
+ None,
+ Stdout,
+ Stderr
+ }
public ProverWarnings PrintProverWarnings = ProverWarnings.None;
public int ProverShutdownLimit = 0;
-
- public enum SubsumptionOption { Never, NotForQuantifiers, Always }
+
+ public enum SubsumptionOption {
+ Never,
+ NotForQuantifiers,
+ Always
+ }
public SubsumptionOption UseSubsumption = SubsumptionOption.Always;
public bool AlwaysAssumeFreeLoopInvariants = false;
- public enum ShowEnvironment { Never, DuringPrint, Always }
+ public enum ShowEnvironment {
+ Never,
+ DuringPrint,
+ Always
+ }
public ShowEnvironment ShowEnv = ShowEnvironment.DuringPrint;
public bool DontShowLogo = false;
-
+ [ContractInvariantMethod]
+ void ObjectInvariant3() {
+ Contract.Invariant(0 <= CheckingLevel && CheckingLevel < 3);
+ Contract.Invariant(0 <= OrderStrength && OrderStrength < 2);
+ Contract.Invariant(0 <= SummationAxiomStrength && SummationAxiomStrength < 2);
+ Contract.Invariant(0 <= InductiveMinMax && InductiveMinMax < 6);
+ Contract.Invariant(0 <= FCOStrength && FCOStrength < 6);
+ Contract.Invariant(-1 <= LoopFrameConditions && LoopFrameConditions < 3);
+ Contract.Invariant(0 <= ModifiesDefault && ModifiesDefault < 7);
+ Contract.Invariant((0 <= PrintErrorModel && PrintErrorModel <= 2) || PrintErrorModel == 4);
+ Contract.Invariant(0 <= EnhancedErrorMessages && EnhancedErrorMessages < 2);
+ Contract.Invariant(0 <= StepsBeforeWidening && StepsBeforeWidening <= 9);
+ Contract.Invariant(-1 <= BracketIdsInVC && BracketIdsInVC <= 1);
+ Contract.Invariant(cce.NonNullElements(ProverOptions));
+
+
+
+
+
+
+ }
+
public int CheckingLevel = 2;
- invariant 0 <= CheckingLevel && CheckingLevel < 3;
- public enum Methodology { Boogie, VisibleState }
+ public enum Methodology {
+ Boogie,
+ VisibleState
+ }
public Methodology MethodologySelection = Methodology.Boogie;
public int OrderStrength = 0;
- invariant 0 <= OrderStrength && OrderStrength < 2;
public bool UseArithDistributionAxioms = false;
public int SummationAxiomStrength = 1;
- invariant 0 <= SummationAxiomStrength && SummationAxiomStrength < 2;
public int InductiveMinMax = 0;
- invariant 0 <= InductiveMinMax && InductiveMinMax < 6;
public int FCOStrength = 5;
- invariant 0 <= FCOStrength && FCOStrength < 6;
public int LoopUnrollCount = -1; // -1 means don't unroll loops
public int LoopFrameConditions = -1; // -1 means not specified -- this will be replaced by the "implications" section below
- invariant -1 <= LoopFrameConditions && LoopFrameConditions < 3;
public int ModifiesDefault = 5;
- invariant 0 <= ModifiesDefault && ModifiesDefault < 7;
public bool LocalModifiesChecks = true;
public bool NoVerifyByDefault = false;
- public enum OwnershipModelOption { Standard, Experimental, Trivial }
+ public enum OwnershipModelOption {
+ Standard,
+ Experimental,
+ Trivial
+ }
public OwnershipModelOption OwnershipModelEncoding = OwnershipModelOption.Standard;
public int PrintErrorModel = 0;
public string PrintErrorModelFile = null;
- invariant (0 <= PrintErrorModel && PrintErrorModel <= 2) || PrintErrorModel == 4;
public bool CEVPrint = false;
public int EnhancedErrorMessages = 0;
- invariant 0 <= EnhancedErrorMessages && EnhancedErrorMessages < 2;
public bool ForceBplErrors = false; // if true, boogie error is shown even if "msg" attribute is present
-
- public enum BvHandling { None, Z3Native, ToInt }
+ public enum BvHandling {
+ None,
+ Z3Native,
+ ToInt
+ }
public BvHandling Bitvectors = BvHandling.Z3Native;
-
public bool UseArrayTheory = false;
- public bool MonomorphicArrays { get { return UseArrayTheory || TypeEncodingMethod == TypeEncoding.Monomorphic; } }
+ public bool MonomorphicArrays {
+ get {
+ return UseArrayTheory || TypeEncodingMethod == TypeEncoding.Monomorphic;
+ }
+ }
public bool ExpandLambdas = true; // not useful from command line, only to be set to false programatically
-
- public bool DoModSetAnalysis = false;
+ public bool DoModSetAnalysis = false;
public bool UseAbstractInterpretation = true; // true iff the user want to use abstract interpretation
public int /*0..9*/StepsBeforeWidening = 0; // The number of steps that must be done before applying a widen operator
- invariant 0 <= StepsBeforeWidening && StepsBeforeWidening <= 9;
- public enum VCVariety { Structured, Block, Local, BlockNested, BlockReach, BlockNestedReach, Dag, Doomed, Unspecified }
+
+ public enum VCVariety {
+ Structured,
+ Block,
+ Local,
+ BlockNested,
+ BlockReach,
+ BlockNestedReach,
+ Dag,
+ Doomed,
+ Unspecified
+ }
public VCVariety vcVariety = VCVariety.Unspecified; // will not be Unspecified after command line has been parsed
public bool useDoomDebug = false; // Will use doomed analysis to search for errors if set
-
+
public bool RemoveEmptyBlocks = true;
- public bool CoalesceBlocks = true;
-
- [Rep] public ProverFactory TheProverFactory;
+ public bool CoalesceBlocks = true;
+
+ [Rep]
+ public ProverFactory TheProverFactory;
public string ProverName;
- [Peer] public List<string!>! ProverOptions = new List<string!>();
+ [Peer]
+ public List<string/*!*/>/*!*/ ProverOptions = new List<string/*!*/>();
public int BracketIdsInVC = -1; // -1 - not specified, 0 - no, 1 - yes
public bool CausalImplies = false;
- invariant -1 <= BracketIdsInVC && BracketIdsInVC <= 1;
+
public int SimplifyProverMatchDepth = -1; // -1 means not specified
public int ProverKillTime = -1; // -1 means not specified
public int SmokeTimeout = 10; // default to 10s
public int ProverCCLimit = 5;
public bool z3AtFlag = true;
- public bool RestartProverPerVC = false;
+ public bool RestartProverPerVC = false;
public double VcsMaxCost = 1.0;
public double VcsPathJoinMult = 0.8;
@@ -196,16 +295,26 @@ namespace Microsoft.Boogie
public bool houdiniEnabled = false;
public bool DebugRefuted = false;
-
- public XmlSink XmlRefuted
- {
- get { if (DebugRefuted) return XmlSink; else return null; }
+
+ public XmlSink XmlRefuted {
+ get {
+ if (DebugRefuted)
+ return XmlSink;
+ else
+ return null;
+ }
}
-
- [Peer] public List<string!>! Z3Options = new List<string!>();
+ [ContractInvariantMethod]
+ void ObjectInvariant4() {
+ Contract.Invariant(cce.NonNullElements(Z3Options));
+ Contract.Invariant(0 <= Z3lets && Z3lets < 4);
+ }
+
+ [Peer]
+ public List<string/*!*/>/*!*/ Z3Options = new List<string/*!*/>();
public bool Z3types = false;
public int Z3lets = 3; // 0 - none, 1 - only LET TERM, 2 - only LET FORMULA, 3 - (default) any
- invariant 0 <= Z3lets && Z3lets < 4;
+
// Maximum amount of virtual memory (in bytes) for the prover to use
//
@@ -215,13 +324,24 @@ namespace Microsoft.Boogie
// Minimum number of prover calls before restart
public int MinNumOfProverCalls = 5;
- public enum PlatformType{notSpecified, v1, v11, v2, cli1}
+ public enum PlatformType {
+ notSpecified,
+ v1,
+ v11,
+ v2,
+ cli1
+ }
public PlatformType TargetPlatform;
public string TargetPlatformLocation;
public string StandardLibraryLocation;
-
+
// whether procedure inlining is enabled at call sites.
- public enum Inlining { None, Assert, Assume, Spec };
+ public enum Inlining {
+ None,
+ Assert,
+ Assume,
+ Spec
+ };
public Inlining ProcedureInlining = Inlining.Assume;
public bool PrintInlined = false;
public bool ExtractLoops = false;
@@ -230,44 +350,69 @@ namespace Microsoft.Boogie
public int StratifiedInliningOption = 0;
public int RecursionBound = 500;
public string CoverageReporterPath = null;
-
- public enum TypeEncoding { None, Predicates, Arguments, Monomorphic };
+
+ public enum TypeEncoding {
+ None,
+ Predicates,
+ Arguments,
+ Monomorphic
+ };
public TypeEncoding TypeEncodingMethod = TypeEncoding.Predicates;
public bool Monomorphize = false;
-
+
public bool ReflectAdd = false;
public int LiveVariableAnalysis = 1;
-
+
// Static constructor
- static CommandLineOptions()
- {
+ static CommandLineOptions() {
if (System.Type.GetType("Mono.Runtime") == null) { // MONO
- TraceListenerCollection! dbl = Debug.Listeners;
- assume dbl.IsPeerConsistent; // hangs off static field
+ TraceListenerCollection/*!*/ dbl = Debug.Listeners;
+ Contract.Assert(dbl != null);
+ Contract.Assume(cce.IsPeerConsistent(dbl)); // hangs off static field
#if WHIDBEY
dbl.Add(new ConsoleTraceListener());
#else
- dpl.Add(new DefaultTraceListener());
+ dbl.Add(new DefaultTraceListener());
#endif
}
}
private string methodToLog = null;
private string methodToBreakOn = null;
-
- [Rep] private List<string!> procsToCheck = null; // null means "no restriction"
- [Rep] private List<string!> methodsToTranslateSubstring = null; // null means "no restriction"
- [Rep] private List<string!> methodsToTranslateMethod = null; // null means "no restriction"
- [Rep] private List<string!> methodsToTranslateMethodQualified = null; // null means "no restriction"
- [Rep] private List<string!> methodsToTranslateClass = null; // null means "no restriction"
- [Rep] private List<string!> methodsToTranslateClassQualified = null; // null means "no restriction"
- [Rep] private List<string!> methodsToTranslateFile = null; // null means "no restriction"
- [Rep] private List<string!>! methodsToTranslateExclude = new List<string!>();
-
- public class AiFlags
- {
+ [ContractInvariantMethod]
+ void ObjectInvariant5() {
+ Contract.Invariant(cce.NonNullElements(procsToCheck, true));
+ Contract.Invariant(cce.NonNullElements(methodsToTranslateClass, true));
+ Contract.Invariant(cce.NonNullElements(methodsToTranslateClassQualified, true));
+ Contract.Invariant(cce.NonNullElements(methodsToTranslateExclude));
+ Contract.Invariant(cce.NonNullElements(methodsToTranslateFile, true));
+ Contract.Invariant(cce.NonNullElements(methodsToTranslateMethod, true));
+ Contract.Invariant(cce.NonNullElements(methodsToTranslateMethodQualified, true));
+ Contract.Invariant(cce.NonNullElements(methodsToTranslateSubstring, true));
+ Contract.Invariant(Ai != null);
+ Contract.Invariant(houdiniFlags != null);
+ }
+
+ [Rep]
+ private List<string/*!*/> procsToCheck = null; // null means "no restriction"
+ [Rep]
+ private List<string/*!*/> methodsToTranslateSubstring = null; // null means "no restriction"
+ [Rep]
+ private List<string/*!*/> methodsToTranslateMethod = null; // null means "no restriction"
+ [Rep]
+ private List<string/*!*/> methodsToTranslateMethodQualified = null; // null means "no restriction"
+ [Rep]
+ private List<string/*!*/> methodsToTranslateClass = null; // null means "no restriction"
+ [Rep]
+ private List<string/*!*/> methodsToTranslateClassQualified = null; // null means "no restriction"
+ [Rep]
+ private List<string/*!*/> methodsToTranslateFile = null; // null means "no restriction"
+ [Rep]
+ private List<string/*!*/>/*!*/ methodsToTranslateExclude = new List<string/*!*/>();
+
+ public class AiFlags {
public bool Intervals = false;
public bool Constant = false;
public bool DynamicType = false;
@@ -275,26 +420,24 @@ namespace Microsoft.Boogie
public bool Polyhedra = false;
public bool DebugStatistics = false;
- public bool AnySet
- {
- get
- {
- return Intervals
- || Constant
- || DynamicType
- || Nullness
- || Polyhedra;
- }
- }
+ public bool AnySet {
+ get {
+ return Intervals
+ || Constant
+ || DynamicType
+ || Nullness
+ || Polyhedra;
+ }
+ }
}
- public AiFlags! Ai = new AiFlags();
+ public AiFlags/*!*/ Ai = new AiFlags();
public class HoudiniFlags {
public bool continueAtError = false;
public bool incremental = false;
}
-
- public HoudiniFlags! houdiniFlags = new HoudiniFlags();
+
+ public HoudiniFlags/*!*/ houdiniFlags = new HoudiniFlags();
[Verify(false)]
public CommandLineOptions() {
@@ -312,47 +455,44 @@ namespace Microsoft.Boogie
/// </summary>
/// <param name="args">Consumed ("captured" and possibly modified) by the method.</param>
[Verify(false)]
- public int Parse([Captured] string[]! args)
- requires forall{int i in (0:args.Length); args[i] != null};
- ensures TheProverFactory != null;
- ensures vcVariety != VCVariety.Unspecified;
- ensures -2 <= result && result <= 2 && result != 0;
- {
+ public int Parse([Captured] string[]/*!*/ args) {
+ Contract.Requires(cce.NonNullElements(args));
+ Contract.Ensures(TheProverFactory != null);
+ Contract.Ensures(vcVariety != VCVariety.Unspecified);
+ Contract.Ensures(-2 <= Contract.Result<int>() && Contract.Result<int>() <= 2 && Contract.Result<int>() != 0);
// save the command line options for the log files
Environment += "Command Line Options:";
foreach (string s in args)
- Environment += " " + s;
- args = (string[]!)args.Clone(); // the operations performed may mutate the array, so make a copy
- CommandLineParseState! ps = new CommandLineParseState(args);
+ Environment += " " + s;
+ args = cce.NonNull((string[])args.Clone()); // the operations performed may mutate the array, so make a copy
+ CommandLineParseState/*!*/ ps = new CommandLineParseState(args);
+ Contract.Assert(ps != null);
int res = 1; // the result value
-
- while (ps.i < args.Length)
- invariant ps.IsPeerConsistent;
- invariant ps.args == args;
- {
+
+ while (ps.i < args.Length) {
+ cce.LoopInvariant(cce.IsPeerConsistent(ps));
+ cce.LoopInvariant(ps.args == args);
ps.s = args[ps.i];
- assert ps.s != null;
+ Contract.Assert(ps.s != null);
ps.s = ps.s.Trim();
int colonIndex = ps.s.IndexOf(':');
- if (colonIndex >= 0 && (ps.s.StartsWith("-") || ps.s.StartsWith("/")))
- {
+ if (colonIndex >= 0 && (ps.s.StartsWith("-") || ps.s.StartsWith("/"))) {
ps.hasColonArgument = true;
- args[ps.i] = ps.s.Substring(colonIndex+1);
+ args[ps.i] = ps.s.Substring(colonIndex + 1);
ps.s = ps.s.Substring(0, colonIndex);
- }
- else
- {
- expose(ps) {
+ } else {
+ cce.BeginExpose(ps);
+ {
ps.i++;
}
+ cce.EndExpose();
ps.hasColonArgument = false;
- }
+ }
ps.nextIndex = ps.i;
- switch (ps.s)
- {
+ switch (ps.s) {
case "-help":
case "/help":
case "-?":
@@ -368,31 +508,48 @@ namespace Microsoft.Boogie
AttrHelpRequested = true;
}
break;
-
+
case "-infer":
case "/infer":
- if (ps.ConfirmArgumentCount(1)) {
- foreach (char c in (!)args[ps.i])
- {
- switch (c)
- {
- case 'i': Ai.Intervals = true; UseAbstractInterpretation = true; break;
- case 'c': Ai.Constant = true; UseAbstractInterpretation = true; break;
- case 'd': Ai.DynamicType = true; UseAbstractInterpretation = true; break;
- case 'n': Ai.Nullness = true; UseAbstractInterpretation = true; break;
- case 'p': Ai.Polyhedra = true; UseAbstractInterpretation = true; break;
- case 's': Ai.DebugStatistics = true; UseAbstractInterpretation = true; break;
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
+ if (ps.ConfirmArgumentCount(1)) {
+ foreach (char c in cce.NonNull(args[ps.i])) {
+ switch (c) {
+ case 'i':
+ Ai.Intervals = true;
+ UseAbstractInterpretation = true;
+ break;
+ case 'c':
+ Ai.Constant = true;
+ UseAbstractInterpretation = true;
+ break;
+ case 'd':
+ Ai.DynamicType = true;
+ UseAbstractInterpretation = true;
+ break;
+ case 'n':
+ Ai.Nullness = true;
+ UseAbstractInterpretation = true;
+ break;
+ case 'p':
+ Ai.Polyhedra = true;
+ UseAbstractInterpretation = true;
+ break;
+ case 's':
+ Ai.DebugStatistics = true;
+ UseAbstractInterpretation = true;
+ break;
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
case '9':
- StepsBeforeWidening = (int) char.GetNumericValue(c); break;
+ StepsBeforeWidening = (int)char.GetNumericValue(c);
+ break;
default:
ps.Error("Invalid argument '{0}' to option {1}", c.ToString(), ps.s);
break;
@@ -400,7 +557,7 @@ namespace Microsoft.Boogie
}
}
break;
-
+
case "-noinfer":
case "/noinfer":
if (ps.ConfirmArgumentCount(0)) {
@@ -408,8 +565,8 @@ namespace Microsoft.Boogie
}
break;
- case "-log":
- case "/log":
+ case "-log":
+ case "/log":
if (ps.hasColonArgument) {
methodToLog = args[ps.i];
ps.nextIndex = ps.i + 1;
@@ -417,62 +574,59 @@ namespace Microsoft.Boogie
methodToLog = "*";
}
break;
-
- case "-logInfer":
- case "/logInfer":
- Microsoft.AbstractInterpretationFramework.Lattice.LogSwitch = true;
- break;
-
- case "-break":
- case "/break":
- if (ps.hasColonArgument)
- {
- methodToBreakOn = args[ps.i];
- ps.nextIndex = ps.i + 1;
- }
- else
- {
- System.Diagnostics.Debugger.Break();
+
+ case "-logInfer":
+ case "/logInfer":
+ Microsoft.AbstractInterpretationFramework.Lattice.LogSwitch = true;
+ break;
+
+ case "-break":
+ case "/break":
+ if (ps.hasColonArgument) {
+ methodToBreakOn = args[ps.i];
+ ps.nextIndex = ps.i + 1;
+ } else {
+ System.Diagnostics.Debugger.Break();
}
break;
-
- case "-launch":
- case "/launch":
- System.Diagnostics.Debugger.Launch();
- break;
-
+
+ case "-launch":
+ case "/launch":
+ System.Diagnostics.Debugger.Launch();
+ break;
+
case "-proc":
case "/proc":
if (procsToCheck == null) {
- procsToCheck = new List<string!>();
+ procsToCheck = new List<string/*!*/>();
}
if (ps.ConfirmArgumentCount(1)) {
- procsToCheck.Add((!)args[ps.i]);
+ procsToCheck.Add(cce.NonNull(args[ps.i]));
}
break;
case "-translate":
case "/translate":
if (methodsToTranslateSubstring == null) {
- methodsToTranslateSubstring = new List<string!>();
+ methodsToTranslateSubstring = new List<string/*!*/>();
}
if (ps.ConfirmArgumentCount(1)) {
- methodsToTranslateSubstring.Add((!)args[ps.i]);
+ methodsToTranslateSubstring.Add(cce.NonNull(args[ps.i]));
}
break;
case "-trMethod":
case "/trMethod":
if (ps.ConfirmArgumentCount(1)) {
- string m = (!)args[ps.i];
+ string m = cce.NonNull(args[ps.i]);
if (0 <= m.IndexOf('.')) {
if (methodsToTranslateMethodQualified == null) {
- methodsToTranslateMethodQualified = new List<string!>();
+ methodsToTranslateMethodQualified = new List<string/*!*/>();
}
methodsToTranslateMethodQualified.Add(m);
} else {
if (methodsToTranslateMethod == null) {
- methodsToTranslateMethod = new List<string!>();
+ methodsToTranslateMethod = new List<string/*!*/>();
}
methodsToTranslateMethod.Add(m);
}
@@ -482,15 +636,15 @@ namespace Microsoft.Boogie
case "-trClass":
case "/trClass":
if (ps.ConfirmArgumentCount(1)) {
- string m = (!)args[ps.i];
+ string m = cce.NonNull(args[ps.i]);
if (0 <= m.IndexOf('.')) {
if (methodsToTranslateClassQualified == null) {
- methodsToTranslateClassQualified = new List<string!>();
+ methodsToTranslateClassQualified = new List<string/*!*/>();
}
methodsToTranslateClassQualified.Add(m);
} else {
if (methodsToTranslateClass == null) {
- methodsToTranslateClass = new List<string!>();
+ methodsToTranslateClass = new List<string/*!*/>();
}
methodsToTranslateClass.Add(m);
}
@@ -500,109 +654,100 @@ namespace Microsoft.Boogie
case "-trFile":
case "/trFile":
if (methodsToTranslateFile == null) {
- methodsToTranslateFile = new List<string!>();
+ methodsToTranslateFile = new List<string/*!*/>();
}
if (ps.ConfirmArgumentCount(1)) {
- methodsToTranslateFile.Add((!)args[ps.i]);
+ methodsToTranslateFile.Add(cce.NonNull(args[ps.i]));
}
break;
case "-trExclude":
case "/trExclude":
if (ps.ConfirmArgumentCount(1)) {
- methodsToTranslateExclude.Add((!)args[ps.i]);
+ methodsToTranslateExclude.Add(cce.NonNull(args[ps.i]));
}
break;
case "-xml":
case "/xml":
- if (ps.ConfirmArgumentCount(1))
- {
+ if (ps.ConfirmArgumentCount(1)) {
XmlSinkFilename = args[ps.i];
}
- break;
-
+ break;
+
case "-print":
case "/print":
- if (ps.ConfirmArgumentCount(1))
- {
+ if (ps.ConfirmArgumentCount(1)) {
PrintFile = args[ps.i];
}
break;
-
+
case "-dprint":
case "/dprint":
- if (ps.ConfirmArgumentCount(1))
- {
+ if (ps.ConfirmArgumentCount(1)) {
DafnyPrintFile = args[ps.i];
}
break;
-
+
case "-compile":
case "/compile": {
- int compile = 0;
- if (ps.GetNumericArgument(ref compile, 2)) {
- Compile = compile == 1;
+ int compile = 0;
+ if (ps.GetNumericArgument(ref compile, 2)) {
+ Compile = compile == 1;
+ }
+ break;
}
- break;
- }
case "-contracts":
case "/contracts":
case "-c":
case "/c":
- if (ps.ConfirmArgumentCount(1))
- {
- ContractAssemblies.Add((!)args[ps.i]);
+ if (ps.ConfirmArgumentCount(1)) {
+ ContractAssemblies.Add(cce.NonNull(args[ps.i]));
}
break;
-
+
case "-proverLog":
case "/proverLog":
- if (ps.ConfirmArgumentCount(1))
- {
+ if (ps.ConfirmArgumentCount(1)) {
SimplifyLogFilePath = args[ps.i];
}
break;
-
+
case "-logPrefix":
case "/logPrefix":
- if (ps.ConfirmArgumentCount(1))
- {
- string s = (!)args[ps.i];
+ if (ps.ConfirmArgumentCount(1)) {
+ string s = cce.NonNull(args[ps.i]);
LogPrefix += s.Replace('/', '-').Replace('\\', '-');
}
break;
-
+
case "-proverShutdownLimit":
case "/proverShutdownLimit":
ps.GetNumericArgument(ref ProverShutdownLimit);
break;
-
+
case "-smtOutput":
case "/smtOutput":
- if (ps.ConfirmArgumentCount(1))
- {
+ if (ps.ConfirmArgumentCount(1)) {
SMTLibOutputPath = args[ps.i];
}
break;
-
+
case "-errorTrace":
case "/errorTrace":
ps.GetNumericArgument(ref ErrorTrace, 3);
break;
-
+
case "-level":
case "/level":
ps.GetNumericArgument(ref CheckingLevel, 3);
break;
-
+
case "-methodology":
case "/methodology":
- if (ps.ConfirmArgumentCount(1))
- {
- switch (args[ps.i])
- {
+ if (ps.ConfirmArgumentCount(1)) {
+ switch (args[ps.i]) {
case "b":
case "Boogie":
case "boogie":
@@ -618,67 +763,70 @@ namespace Microsoft.Boogie
}
}
break;
-
+
case "-proverWarnings":
case "/proverWarnings": {
- int pw = 0;
- if (ps.GetNumericArgument(ref pw, 3)) {
- switch (pw) {
- case 0:
- PrintProverWarnings = ProverWarnings.None;
- break;
- case 1:
- PrintProverWarnings = ProverWarnings.Stdout;
- break;
- case 2:
- PrintProverWarnings = ProverWarnings.Stderr;
- break;
- default:
- assert false; // postcondition of GetNumericArgument guarantees that we don't get here
+ int pw = 0;
+ if (ps.GetNumericArgument(ref pw, 3)) {
+ switch (pw) {
+ case 0:
+ PrintProverWarnings = ProverWarnings.None;
+ break;
+ case 1:
+ PrintProverWarnings = ProverWarnings.Stdout;
+ break;
+ case 2:
+ PrintProverWarnings = ProverWarnings.Stderr;
+ break;
+ default: {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // postcondition of GetNumericArgument guarantees that we don't get here
+ }
}
+ break;
}
- break;
- }
case "-env":
case "/env": {
- int e = 0;
- if (ps.GetNumericArgument(ref e, 3)) {
- switch (e) {
- case 0:
- ShowEnv = ShowEnvironment.Never;
- break;
- case 1:
- ShowEnv = ShowEnvironment.DuringPrint;
- break;
- case 2:
- ShowEnv = ShowEnvironment.Always;
- break;
- default:
- assert false; // postcondition of GetNumericArgument guarantees that we don't get here
+ int e = 0;
+ if (ps.GetNumericArgument(ref e, 3)) {
+ switch (e) {
+ case 0:
+ ShowEnv = ShowEnvironment.Never;
+ break;
+ case 1:
+ ShowEnv = ShowEnvironment.DuringPrint;
+ break;
+ case 2:
+ ShowEnv = ShowEnvironment.Always;
+ break;
+ default: {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // postcondition of GetNumericArgument guarantees that we don't get here
+ }
}
+ break;
}
- break;
- }
case "-loopUnroll":
case "/loopUnroll":
ps.GetNumericArgument(ref LoopUnrollCount);
break;
-
+
case "-modifiesOnLoop":
case "/modifiesOnLoop":
ps.GetNumericArgument(ref LoopFrameConditions, 3);
break;
-
+
case "-modifiesDefault":
case "/modifiesDefault":
ps.GetNumericArgument(ref ModifiesDefault, 7);
break;
-
+
case "-localModifiesChecks":
- case "/localModifiesChecks":
- {
+ case "/localModifiesChecks": {
int localChecks = 0;
ps.GetNumericArgument(ref localChecks, 2);
LocalModifiesChecks = (localChecks != 0);
@@ -689,7 +837,7 @@ namespace Microsoft.Boogie
case "/orderStrength":
ps.GetNumericArgument(ref OrderStrength, 2);
break;
-
+
case "-summationStrength":
case "/summationStrength":
ps.GetNumericArgument(ref SummationAxiomStrength, 2);
@@ -704,13 +852,11 @@ namespace Microsoft.Boogie
case "/fcoStrength":
ps.GetNumericArgument(ref FCOStrength, 6);
break;
-
+
case "-ownerModelEncoding":
case "/ownerModelEncoding":
- if (ps.ConfirmArgumentCount(1))
- {
- switch (args[ps.i])
- {
+ if (ps.ConfirmArgumentCount(1)) {
+ switch (args[ps.i]) {
case "s":
case "standard":
OwnershipModelEncoding = OwnershipModelOption.Standard;
@@ -729,13 +875,11 @@ namespace Microsoft.Boogie
}
}
break;
-
+
case "-printModel":
case "/printModel":
- if (ps.ConfirmArgumentCount(1))
- {
- switch (args[ps.i])
- {
+ if (ps.ConfirmArgumentCount(1)) {
+ switch (args[ps.i]) {
case "0":
PrintErrorModel = 0;
break;
@@ -755,46 +899,42 @@ namespace Microsoft.Boogie
}
break;
-
+
case "-cev":
case "/cev":
- if (ps.ConfirmArgumentCount(1))
- {
+ if (ps.ConfirmArgumentCount(1)) {
PrintErrorModelFile = args[ps.i];
}
CEVPrint = true;
- break;
+ break;
case "-printModelToFile":
case "/printModelToFile":
- if (ps.ConfirmArgumentCount(1))
- {
+ if (ps.ConfirmArgumentCount(1)) {
PrintErrorModelFile = args[ps.i];
}
- break;
+ break;
+
-
case "-enhancedErrorMessages":
case "/enhancedErrorMessages":
ps.GetNumericArgument(ref EnhancedErrorMessages, 2);
break;
-
+
case "-forceBplErrors":
case "/forceBplErrors":
ForceBplErrors = true;
- break;
-
+ break;
+
case "-bv":
case "/bv":
- if (ps.ConfirmArgumentCount(1))
- {
+ if (ps.ConfirmArgumentCount(1)) {
if (TheProverFactory == null) {
TheProverFactory = ProverFactory.Load("Z3");
ProverName = "Z3".ToUpper();
}
- switch (args[ps.i])
- {
+ switch (args[ps.i]) {
case "n":
Bitvectors = BvHandling.None;
break;
@@ -810,72 +950,73 @@ namespace Microsoft.Boogie
}
}
break;
-
+
case "-contractInfer":
case "/contractInfer":
ContractInfer = true;
TheProverFactory = ProverFactory.Load("ContractInference");
ProverName = "ContractInference".ToUpper();
break;
-
+
case "-subsumption":
case "/subsumption": {
- int s = 0;
- if (ps.GetNumericArgument(ref s, 3)) {
- switch (s) {
- case 0:
- UseSubsumption = SubsumptionOption.Never;
- break;
- case 1:
- UseSubsumption = SubsumptionOption.NotForQuantifiers;
- break;
- case 2:
- UseSubsumption = SubsumptionOption.Always;
- break;
- default:
- assert false; // postcondition of GetNumericArgument guarantees that we don't get here
+ int s = 0;
+ if (ps.GetNumericArgument(ref s, 3)) {
+ switch (s) {
+ case 0:
+ UseSubsumption = SubsumptionOption.Never;
+ break;
+ case 1:
+ UseSubsumption = SubsumptionOption.NotForQuantifiers;
+ break;
+ case 2:
+ UseSubsumption = SubsumptionOption.Always;
+ break;
+ default: {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ } // postcondition of GetNumericArgument guarantees that we don't get here
+ }
}
+ break;
}
- break;
- }
-
+
case "-liveVariableAnalysis":
case "/liveVariableAnalysis": {
- int lva = 0;
- if (ps.GetNumericArgument(ref lva, 3)) {
- LiveVariableAnalysis = lva;
+ int lva = 0;
+ if (ps.GetNumericArgument(ref lva, 3)) {
+ LiveVariableAnalysis = lva;
+ }
+ break;
}
- break;
- }
-
+
case "-removeEmptyBlocks":
case "/removeEmptyBlocks": {
- int reb = 0;
- if (ps.GetNumericArgument(ref reb, 2)) {
- RemoveEmptyBlocks = reb == 1;
+ int reb = 0;
+ if (ps.GetNumericArgument(ref reb, 2)) {
+ RemoveEmptyBlocks = reb == 1;
+ }
+ break;
}
- break;
- }
-
+
case "-coalesceBlocks":
case "/coalesceBlocks": {
- int cb = 0;
- if (ps.GetNumericArgument(ref cb, 2)) {
- CoalesceBlocks = cb == 1;
+ int cb = 0;
+ if (ps.GetNumericArgument(ref cb, 2)) {
+ CoalesceBlocks = cb == 1;
+ }
+ break;
}
- break;
- }
case "/DoomDebug":
vcVariety = VCVariety.Doomed;
useDoomDebug = true;
break;
-
+
case "-vc":
case "/vc":
if (ps.ConfirmArgumentCount(1)) {
- switch (args[ps.i])
- {
+ switch (args[ps.i]) {
case "s":
case "structured":
vcVariety = VCVariety.Structured;
@@ -915,15 +1056,15 @@ namespace Microsoft.Boogie
case "-prover":
case "/prover":
if (ps.ConfirmArgumentCount(1)) {
- TheProverFactory = ProverFactory.Load((!)args[ps.i]);
- ProverName = ((!)args[ps.i]).ToUpper();
+ TheProverFactory = ProverFactory.Load(cce.NonNull(args[ps.i]));
+ ProverName = cce.NonNull(args[ps.i]).ToUpper();
}
break;
case "-proverOpt":
case "/proverOpt":
if (ps.ConfirmArgumentCount(1)) {
- ProverOptions.Add((!)args[ps.i]);
+ ProverOptions.Add(cce.NonNull(args[ps.i]));
}
break;
@@ -936,8 +1077,7 @@ namespace Microsoft.Boogie
case "-inline":
case "/inline":
if (ps.ConfirmArgumentCount(1)) {
- switch (args[ps.i])
- {
+ switch (args[ps.i]) {
case "none":
ProcedureInlining = Inlining.None;
break;
@@ -959,13 +1099,12 @@ namespace Microsoft.Boogie
case "-lazyInline":
case "/lazyInline":
if (ps.ConfirmArgumentCount(1)) {
- switch (args[ps.i])
- {
+ switch (args[ps.i]) {
case "0":
- LazyInlining = 0;
+ LazyInlining = 0;
break;
case "1":
- LazyInlining = 1;
+ LazyInlining = 1;
break;
case "2":
LazyInlining = 2;
@@ -979,44 +1118,42 @@ namespace Microsoft.Boogie
case "-stratifiedInline":
case "/stratifiedInline":
if (ps.ConfirmArgumentCount(1)) {
- switch (args[ps.i])
- {
+ switch (args[ps.i]) {
case "0":
- StratifiedInlining = 0;
+ StratifiedInlining = 0;
break;
case "1":
- StratifiedInlining = 1;
+ StratifiedInlining = 1;
break;
default:
- StratifiedInlining = Int32.Parse((!)args[ps.i]);
+ StratifiedInlining = Int32.Parse(cce.NonNull(args[ps.i]));
//ps.Error("Invalid argument \"{0}\" to option {1}", args[ps.i], ps.s);
break;
}
}
- break;
+ break;
case "-recursionBound":
- case "/recursionBound":
- if (ps.ConfirmArgumentCount(1)) {
- RecursionBound = Int32.Parse((!)args[ps.i]);
+ case "/recursionBound":
+ if(ps.ConfirmArgumentCount(1)){
+ RecursionBound = Int32.Parse(cce.NonNull(args[ps.i]));
}
- break;
+ break;
case "-coverageReporter":
case "/coverageReporter":
if (ps.ConfirmArgumentCount(1)) {
CoverageReporterPath = args[ps.i];
}
- break;
- case "-stratifiedInlineOption":
+ break;
+ case "-stratifiedInilneOption":
case "/stratifiedInlineOption":
if (ps.ConfirmArgumentCount(1)) {
- StratifiedInliningOption = Int32.Parse((!)args[ps.i]);
+ StratifiedInliningOption=Int32.Parse(cce.NonNull(args[ps.i]));
}
- break;
+ break;
case "-typeEncoding":
case "/typeEncoding":
if (ps.ConfirmArgumentCount(1)) {
- switch (args[ps.i])
- {
+ switch (args[ps.i]) {
case "n":
case "none":
TypeEncodingMethod = TypeEncoding.None;
@@ -1043,8 +1180,7 @@ namespace Microsoft.Boogie
case "-instrumentInfer":
case "/instrumentInfer":
if (ps.ConfirmArgumentCount(1)) {
- switch (args[ps.i])
- {
+ switch (args[ps.i]) {
case "e":
InstrumentInfer = InstrumentationPlaces.Everywhere;
break;
@@ -1064,14 +1200,13 @@ namespace Microsoft.Boogie
break;
case "-proverMemoryLimit":
- case "/proverMemoryLimit":
- {
- int d = 0;
- if (ps.GetNumericArgument(ref d)) {
- MaxProverMemory = d * Megabyte;
+ case "/proverMemoryLimit": {
+ int d = 0;
+ if (ps.GetNumericArgument(ref d)) {
+ MaxProverMemory = d * Megabyte;
+ }
+ break;
}
- break;
- }
case "-vcsMaxCost":
case "/vcsMaxCost":
@@ -1127,7 +1262,7 @@ namespace Microsoft.Boogie
case "/simplifyMatchDepth":
ps.GetNumericArgument(ref SimplifyProverMatchDepth);
break;
-
+
case "-timeLimit":
case "/timeLimit":
ps.GetNumericArgument(ref ProverKillTime);
@@ -1137,17 +1272,16 @@ namespace Microsoft.Boogie
case "/smokeTimeout":
ps.GetNumericArgument(ref SmokeTimeout);
break;
-
+
case "-errorLimit":
case "/errorLimit":
ps.GetNumericArgument(ref ProverCCLimit);
break;
-
+
case "-z3opt":
case "/z3opt":
- if (ps.ConfirmArgumentCount(1))
- {
- Z3Options.Add((!)args[ps.i]);
+ if (ps.ConfirmArgumentCount(1)) {
+ Z3Options.Add(cce.NonNull(args[ps.i]));
}
break;
@@ -1158,61 +1292,64 @@ namespace Microsoft.Boogie
case "-platform":
case "/platform":
- if (ps.ConfirmArgumentCount(1))
- {
- StringCollection platformOptions = this.ParseNamedArgumentList(args[ps.i]);
- if (platformOptions != null && platformOptions.Count > 0){
- try{
- this.TargetPlatform = (PlatformType)(!)Enum.Parse(typeof(PlatformType), (!)platformOptions[0]);
- }
- catch {
- ps.Error("Bad /platform type '{0}'", platformOptions[0]);
- break;
- }
- if (platformOptions.Count > 1){
- this.TargetPlatformLocation = platformOptions[1];
- if (!Directory.Exists(platformOptions[1])) {
- ps.Error("/platform directory '{0}' does not exist", platformOptions[1]);
- break;
- }
- }
+ if (ps.ConfirmArgumentCount(1)) {
+ StringCollection platformOptions = this.ParseNamedArgumentList(args[ps.i]);
+ if (platformOptions != null && platformOptions.Count > 0) {
+ try {
+ this.TargetPlatform = (PlatformType)cce.NonNull(Enum.Parse(typeof(PlatformType), cce.NonNull(platformOptions[0])));
+ } catch {
+ ps.Error("Bad /platform type '{0}'", platformOptions[0]);
+ break;
+ }
+ if (platformOptions.Count > 1) {
+ this.TargetPlatformLocation = platformOptions[1];
+ if (!Directory.Exists(platformOptions[1])) {
+ ps.Error("/platform directory '{0}' does not exist", platformOptions[1]);
+ break;
+ }
}
+ }
}
break;
case "-stdlib":
case "/stdlib":
- if (ps.ConfirmArgumentCount(1))
- {
+ if (ps.ConfirmArgumentCount(1)) {
this.StandardLibraryLocation = args[ps.i];
}
break;
case "-Houdini":
case "/Houdini":
- this.houdiniEnabled=true;
- if (ps.hasColonArgument) {
- if (ps.ConfirmArgumentCount(1)) {
- foreach (char c in (!)args[ps.i])
- {
- switch (c)
- {
- case 'c': houdiniFlags.continueAtError = true; break;
- case 'i': houdiniFlags.incremental = true; break;
- default : ps.Error("Unknown houdini flag: " + c + "\n"); break;
- }
- }
- }
- }
- break;
-
+ this.houdiniEnabled = true;
+ if (ps.hasColonArgument) {
+ if (ps.ConfirmArgumentCount(1)) {
+ foreach (char c in cce.NonNull(args[ps.i])) {
+ switch (c) {
+ case 'c':
+ houdiniFlags.continueAtError = true;
+ break;
+ case 'i':
+ houdiniFlags.incremental = true;
+ break;
+ default:
+ ps.Error("Unknown houdini flag: " + c + "\n");
+ break;
+ }
+ }
+ }
+ }
+ break;
+
default:
- assume true;
+ Contract.Assume(true);
bool option = false;
if (ps.CheckBooleanFlag("printUnstructured", ref option)) {
- expose(this) {
+ cce.BeginExpose(this);
+ {
PrintUnstructured = option ? 1 : 0;
}
+ cce.EndExpose();
} else if (
ps.CheckBooleanFlag("printDesugared", ref PrintDesugarings) ||
ps.CheckBooleanFlag("printInstrumented", ref PrintInstrumented) ||
@@ -1225,7 +1362,7 @@ namespace Microsoft.Boogie
ps.CheckBooleanFlag("overlookTypeErrors", ref OverlookBoogieTypeErrors) ||
ps.CheckBooleanFlag("noVerify", ref Verify, false) ||
ps.CheckBooleanFlag("traceverify", ref TraceVerify) ||
- ps.CheckBooleanFlag("noConsistencyChecks", ref NoConsistencyChecks, true) ||
+ ps.CheckBooleanFlag("noConsistencyChecks", ref noConsistencyChecks, true) ||
ps.CheckBooleanFlag("alwaysAssumeFreeLoopInvariants", ref AlwaysAssumeFreeLoopInvariants, true) ||
ps.CheckBooleanFlag("nologo", ref DontShowLogo) ||
ps.CheckBooleanFlag("noVerifyByDefault", ref NoVerifyByDefault) ||
@@ -1246,16 +1383,11 @@ namespace Microsoft.Boogie
ps.CheckBooleanFlag("monomorphize", ref Monomorphize) ||
ps.CheckBooleanFlag("useArrayTheory", ref UseArrayTheory) ||
ps.CheckBooleanFlag("doModSetAnalysis", ref DoModSetAnalysis)
- )
- {
+ ) {
// one of the boolean flags matched
- }
- else if (ps.s.StartsWith("-") || ps.s.StartsWith("/"))
- {
+ } else if (ps.s.StartsWith("-") || ps.s.StartsWith("/")) {
ps.Error("unknown switch: {0}", ps.s);
- }
- else if (ps.ConfirmArgumentCount(0))
- {
+ } else if (ps.ConfirmArgumentCount(0)) {
string filename = ps.s;
string extension = Path.GetExtension(filename);
if (extension != null) {
@@ -1266,11 +1398,14 @@ namespace Microsoft.Boogie
}
break;
}
- expose(ps) ps.i = ps.nextIndex;
+ cce.BeginExpose(ps);
+ ps.i = ps.nextIndex;
+ cce.EndExpose();
}
-
- assume true;
- if (ps.encounteredErrors) res *= 2;
+
+ Contract.Assume(true);
+ if (ps.encounteredErrors)
+ res *= 2;
if (res < 0) { // help requested
Usage();
} else if (AttrHelpRequested) {
@@ -1278,18 +1413,19 @@ namespace Microsoft.Boogie
} else if (ps.encounteredErrors) {
Console.WriteLine("Use /help for available options");
}
-
+
SetProverOptions();
-
- if (Trace) { BoogieDebug.DoPrinting = true; } // reuse the -trace option for debug printing
+
+ if (Trace) {
+ BoogieDebug.DoPrinting = true;
+ } // reuse the -trace option for debug printing
return res;
}
- private void SetProverOptions()
- modifies this.*;
- ensures TheProverFactory != null;
- ensures vcVariety != VCVariety.Unspecified;
- {
+ private void SetProverOptions() {
+ //modifies this.*;
+ Contract.Ensures(TheProverFactory != null);
+ Contract.Ensures(vcVariety != VCVariety.Unspecified);
// expand macros in filenames, now that LogPrefix is fully determined
ExpandFilename(ref XmlSinkFilename);
ExpandFilename(ref PrintFile);
@@ -1298,16 +1434,18 @@ namespace Microsoft.Boogie
ExpandFilename(ref SMTLibOutputPath);
ExpandFilename(ref PrintErrorModelFile);
- assume XmlSink == null; // XmlSink is to be set here
+ Contract.Assume(XmlSink == null); // XmlSink is to be set here
if (XmlSinkFilename != null) {
XmlSink = new XmlSink(XmlSinkFilename);
}
-
+
if (TheProverFactory == null) {
- expose(this) {
+ cce.BeginExpose(this);
+ {
TheProverFactory = ProverFactory.Load("Z3");
ProverName = "Z3".ToUpper();
}
+ cce.EndExpose();
}
if (vcVariety == VCVariety.Unspecified) {
@@ -1322,33 +1460,36 @@ namespace Microsoft.Boogie
LoopFrameConditions = 2;
}
}
-
+
if (CEVPrint && PrintErrorModel == 0) {
PrintErrorModel = 1;
}
-
+
switch (InductiveMinMax) {
- case 1: case 2: case 4: case 5:
+ case 1:
+ case 2:
+ case 4:
+ case 5:
ReflectAdd = true; // these InductiveMinMax modes imply ReflectAdd
break;
default:
break;
}
-
+
if (MethodologySelection == Methodology.VisibleState) {
OwnershipModelEncoding = OwnershipModelOption.Trivial;
}
-
+
if (UseArrayTheory) {
Monomorphize = true;
}
-
+
if (LazyInlining > 0) {
TypeEncodingMethod = TypeEncoding.Monomorphic;
UseArrayTheory = true;
UseAbstractInterpretation = false;
}
-
+
if (StratifiedInlining > 0) {
TypeEncodingMethod = TypeEncoding.Monomorphic;
UseArrayTheory = true;
@@ -1358,34 +1499,41 @@ namespace Microsoft.Boogie
- public bool UserWantsMethodLogging (string! methodFullName)
- {
- if (methodToLog == null) { return false; }
- return methodToLog == "*" || methodFullName.IndexOf(methodToLog) >= 0;
+ public bool UserWantsMethodLogging(string methodFullName) {
+ Contract.Requires(methodFullName != null);
+ if (methodToLog == null) {
+ return false;
+ }
+ return methodToLog == "*" || methodFullName.IndexOf(methodToLog) >= 0;
}
-
- public bool UserWantsToBreak (string! methodFullName)
- {
- if (methodToBreakOn == null) { return false; }
- return methodFullName.IndexOf(methodToBreakOn) >= 0;
+
+ public bool UserWantsToBreak(string methodFullName) {
+ Contract.Requires(methodFullName != null);
+ if (methodToBreakOn == null) {
+ return false;
+ }
+ return methodFullName.IndexOf(methodToBreakOn) >= 0;
}
-
- public bool UserWantsToCheckRoutine(string! methodFullname)
- {
+
+ public bool UserWantsToCheckRoutine(string methodFullname) {
+ Contract.Requires(methodFullname != null);
if (procsToCheck == null) {
// no preference
return true;
}
- return exists{string s in procsToCheck; 0 <= methodFullname.IndexOf(s)};
+ return Contract.Exists(procsToCheck, s => 0 <= methodFullname.IndexOf(s));
}
- public bool UserWantsToTranslateRoutine(Cci.Method! method, string! methodFullname) {
+ public bool UserWantsToTranslateRoutine(Cci.Method method, string methodFullname) {
+ Contract.Requires(methodFullname != null);
+ Contract.Requires(method != null);
return UserWantsToTranslateRoutineInclude(method, methodFullname) &&
- !exists{string s in methodsToTranslateExclude; 0 <= methodFullname.IndexOf(s)};
+ !Contract.Exists(methodsToTranslateExclude, s => 0 <= methodFullname.IndexOf(s));
}
-
- public bool UserWantsToTranslateRoutineInclude(Cci.Method! method, string! methodFullname)
- {
+
+ public bool UserWantsToTranslateRoutineInclude(Cci.Method method, string methodFullname) {
+ Contract.Requires(methodFullname != null);
+ Contract.Requires(method != null);
if (methodsToTranslateSubstring == null &&
methodsToTranslateClass == null &&
methodsToTranslateClassQualified == null &&
@@ -1396,20 +1544,20 @@ namespace Microsoft.Boogie
return true;
}
if (methodsToTranslateSubstring != null) {
- if (exists{string s in methodsToTranslateSubstring; 0 <= methodFullname.IndexOf(s)}) {
+ if (Contract.Exists(methodsToTranslateSubstring, s => 0 <= methodFullname.IndexOf(s))) {
return true;
}
}
if (methodsToTranslateMethod != null) {
string methodName = method.Name.Name;
- assert methodsToTranslateMethod != null;
+ Contract.Assert(methodsToTranslateMethod != null);
if (methodsToTranslateMethod.Contains(methodName)) {
return true;
}
}
if (methodsToTranslateMethodQualified != null && method.DeclaringType != null) {
string methodName = method.DeclaringType.Name.Name + "." + method.Name.Name;
- assert methodsToTranslateMethodQualified != null;
+ Contract.Assert(methodsToTranslateMethodQualified != null);
if (methodsToTranslateMethodQualified.Contains(methodName)) {
return true;
}
@@ -1450,7 +1598,8 @@ namespace Microsoft.Boogie
/// <summary>
/// Returns the file containing "method". Returns null f that information is not available.
/// </summary>
- static string GetSourceDocument(Cci.Method! method) {
+ static string GetSourceDocument(Cci.Method method) {
+ Contract.Requires(method != null);
// Start by looking for a source context in the method itself. However, if the program
// was read from a binary, then there is no source location for the method. If so, there
// some other ways we might find a source location.
@@ -1488,7 +1637,8 @@ namespace Microsoft.Boogie
return null; // no source location found
}
- [Pure] static string GetSourceDocumentFromStatements(Cci.StatementList list) {
+ [Pure]
+ static string GetSourceDocumentFromStatements(Cci.StatementList list) {
if (list != null) {
foreach (Cci.Statement c in list) {
if (c != null && c.SourceContext.Document != null) {
@@ -1506,22 +1656,27 @@ namespace Microsoft.Boogie
return null;
}
- class CommandLineParseState
- {
+ class CommandLineParseState {
public string s;
public bool hasColonArgument;
- public readonly string[]! args;
+ public readonly string[]/*!*/ args;
public int i;
public int nextIndex;
public bool encounteredErrors;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(args != null);
+ Contract.Invariant(0 <= i && i <= args.Length);
+ Contract.Invariant(0 <= nextIndex && nextIndex <= args.Length);
+
+ }
+
- invariant 0 <= i && i <= args.Length;
- invariant 0 <= nextIndex && nextIndex <= args.Length;
- public CommandLineParseState(string[]! args)
- requires forall{int i in (0:args.Length); args[i] != null};
- ensures this.args == args;
- {
+ public CommandLineParseState(string[] args) {
+ Contract.Requires(args != null);
+ Contract.Requires(Contract.ForAll(0, args.Length, i => args[i] != null));
+ Contract.Ensures(this.args == args);
this.s = null; // set later by client
this.hasColonArgument = false; // set later by client
this.args = args;
@@ -1530,22 +1685,21 @@ namespace Microsoft.Boogie
this.encounteredErrors = false;
}
- public bool CheckBooleanFlag(string! flagName, ref bool flag, bool valueWhenPresent)
- modifies nextIndex, encounteredErrors, Console.Error.*;
- {
+ public bool CheckBooleanFlag(string flagName, ref bool flag, bool valueWhenPresent) {
+ Contract.Requires(flagName != null);
+ //modifies nextIndex, encounteredErrors, Console.Error.*;
bool flagPresent = false;
-
- if ((s == "/"+flagName || s == "-"+flagName) && ConfirmArgumentCount(0))
- {
- flag = valueWhenPresent;
- flagPresent = true;
- }
+
+ if ((s == "/" + flagName || s == "-" + flagName) && ConfirmArgumentCount(0)) {
+ flag = valueWhenPresent;
+ flagPresent = true;
+ }
return flagPresent;
}
-
- public bool CheckBooleanFlag(string! flagName, ref bool flag)
- modifies nextIndex, encounteredErrors, Console.Error.*;
- {
+
+ public bool CheckBooleanFlag(string flagName, ref bool flag) {
+ Contract.Requires(flagName != null);
+ //modifies nextIndex, encounteredErrors, Console.Error.*;
return CheckBooleanFlag(flagName, ref flag, true);
}
@@ -1553,14 +1707,12 @@ namespace Microsoft.Boogie
/// If there is one argument and it is a non-negative integer, then set "arg" to that number and return "true".
/// Otherwise, emit error message, leave "arg" unchanged, and return "false".
/// </summary>
- public bool GetNumericArgument(ref int arg)
- modifies nextIndex, encounteredErrors, Console.Error.*;
- {
- if (this.ConfirmArgumentCount(1))
- {
+ public bool GetNumericArgument(ref int arg) {
+ //modifies nextIndex, encounteredErrors, Console.Error.*;
+ if (this.ConfirmArgumentCount(1)) {
try {
- assume args[i] != null;
- assert args[i] is string; // needed to prove args[i].IsPeerConsistent
+ Contract.Assume(args[i] != null);
+ Contract.Assert(args[i] is string); // needed to prove args[i].IsPeerConsistent
int d = Convert.ToInt32(this.args[this.i]);
if (0 <= d) {
arg = d;
@@ -1575,16 +1727,15 @@ namespace Microsoft.Boogie
Error("Invalid argument \"{0}\" to option {1}", args[this.i], this.s);
return false;
}
-
+
/// <summary>
/// If there is one argument and it is a non-negative integer less than "limit",
/// then set "arg" to that number and return "true".
/// Otherwise, emit error message, leave "arg" unchanged, and return "false".
/// </summary>
- public bool GetNumericArgument(ref int arg, int limit)
- requires this.i < args.Length;
- modifies nextIndex, encounteredErrors, Console.Error.*;
- {
+ public bool GetNumericArgument(ref int arg, int limit) {
+ Contract.Requires(this.i < args.Length);
+ //modifies nextIndex, encounteredErrors, Console.Error.*;
int a = arg;
if (!GetNumericArgument(ref a)) {
return false;
@@ -1596,19 +1747,17 @@ namespace Microsoft.Boogie
return false;
}
}
-
+
/// <summary>
/// If there is one argument and it is a non-negative real, then set "arg" to that number and return "true".
/// Otherwise, emit an error message, leave "arg" unchanged, and return "false".
/// </summary>
- public bool GetNumericArgument(ref double arg)
- modifies nextIndex, encounteredErrors, Console.Error.*;
- {
- if (this.ConfirmArgumentCount(1))
- {
+ public bool GetNumericArgument(ref double arg) {
+ //modifies nextIndex, encounteredErrors, Console.Error.*;
+ if (this.ConfirmArgumentCount(1)) {
try {
- assume args[i] != null;
- assert args[i] is string; // needed to prove args[i].IsPeerConsistent
+ Contract.Assume(args[i] != null);
+ Contract.Assert(args[i] is string); // needed to prove args[i].IsPeerConsistent
double d = Convert.ToDouble(this.args[this.i]);
if (0 <= d) {
arg = d;
@@ -1623,71 +1772,68 @@ namespace Microsoft.Boogie
Error("Invalid argument \"{0}\" to option {1}", args[this.i], this.s);
return false;
}
-
- public bool ConfirmArgumentCount(int argCount)
- requires 0 <= argCount;
- modifies nextIndex, encounteredErrors, Console.Error.*;
- ensures result == ( !(hasColonArgument && argCount != 1) && !(args.Length < i + argCount) );
- {
- if (hasColonArgument && argCount != 1)
- {
+
+ public bool ConfirmArgumentCount(int argCount) {
+ Contract.Requires(0 <= argCount);
+ //modifies nextIndex, encounteredErrors, Console.Error.*;
+ Contract.Ensures(Contract.Result<bool>() == (!(hasColonArgument && argCount != 1) && !(args.Length < i + argCount)));
+ if (hasColonArgument && argCount != 1) {
Error("\"{0}\" cannot take a colon argument", s);
nextIndex = args.Length;
return false;
- }
- else if (args.Length < i + argCount)
- {
+ } else if (args.Length < i + argCount) {
Error("\"{0}\" expects {1} argument{2}", s, argCount.ToString(), (string)(argCount == 1 ? "" : "s"));
nextIndex = args.Length;
return false;
- }
- else
- {
+ } else {
nextIndex = i + argCount;
return true;
}
}
- public void Error(string! message, params string[]! args)
- modifies encounteredErrors, Console.Error.*;
- {
+ public void Error(string message, params string[] args) {
+ Contract.Requires(args != null);
+ Contract.Requires(message != null);
+ //modifies encounteredErrors, Console.Error.*;
Console.Error.WriteLine("Boogie: Error: " + String.Format(message, args));
encounteredErrors = true;
}
}
- public virtual StringCollection ParseNamedArgumentList(string argList){
- if (argList == null || argList.Length == 0) return null;
+ public virtual StringCollection ParseNamedArgumentList(string argList) {
+ if (argList == null || argList.Length == 0)
+ return null;
StringCollection result = new StringCollection();
int i = 0;
- for (int n = argList.Length; i < n;)
- invariant 0 <= i;
- {
+ for (int n = argList.Length; i < n; ) {
+ cce.LoopInvariant(0 <= i);
int separatorIndex = this.GetArgumentSeparatorIndex(argList, i);
- if (separatorIndex > i){
- result.Add(argList.Substring(i, separatorIndex-i));
- i = separatorIndex+1;
+ if (separatorIndex > i) {
+ result.Add(argList.Substring(i, separatorIndex - i));
+ i = separatorIndex + 1;
continue;
}
result.Add(argList.Substring(i));
break;
- }
+ }
return result;
}
- public int GetArgumentSeparatorIndex(string! argList, int startIndex)
- requires 0 <= startIndex && startIndex <= argList.Length;
- ensures result < argList.Length;
- {
+ public int GetArgumentSeparatorIndex(string argList, int startIndex) {
+ Contract.Requires(argList != null);
+ Contract.Requires(0 <= startIndex && startIndex <= argList.Length);
+ Contract.Ensures(Contract.Result<int>() < argList.Length);
int commaIndex = argList.IndexOf(",", startIndex);
int semicolonIndex = argList.IndexOf(";", startIndex);
- if (commaIndex == -1) return semicolonIndex;
- if (semicolonIndex == -1) return commaIndex;
- if (commaIndex < semicolonIndex) return commaIndex;
+ if (commaIndex == -1)
+ return semicolonIndex;
+ if (semicolonIndex == -1)
+ return commaIndex;
+ if (commaIndex < semicolonIndex)
+ return commaIndex;
return semicolonIndex;
}
- public static void AttributeUsage()
- {
+ public static void AttributeUsage() {
Console.WriteLine(
@"Boogie: The following attributes are supported by this implementation.
@@ -1772,15 +1918,16 @@ namespace Microsoft.Boogie
private static bool printedHelp = false;
- public static void Usage()
- {
- // Ensure that we only print the help message once,
- // no matter how many enabling conditions for printing
- // help were triggered.
- if (printedHelp) { return; }
- printedHelp = true;
-
- Console.WriteLine(@"Boogie: usage: Boogie [ option ... ] [ filename ... ]
+ public static void Usage() {
+ // Ensure that we only print the help message once,
+ // no matter how many enabling conditions for printing
+ // help were triggered.
+ if (printedHelp) {
+ return;
+ }
+ printedHelp = true;
+
+ Console.WriteLine(@"Boogie: usage: Boogie [ option ... ] [ filename ... ]
where <option> is one of
---- General options -------------------------------------------------------
@@ -1907,11 +2054,12 @@ namespace Microsoft.Boogie
---- Inference options -----------------------------------------------------
/infer:<flags> : use abstract interpretation to infer invariants
- The default is /infer:i" // This is not 100% true, as the /infer ALWAYS creates
- // a multilattice, whereas if nothing is specified then
- // intervals are isntantiated WITHOUT being embedded in
- // a multilattice
- + @"
+ The default is /infer:i"
+ // This is not 100% true, as the /infer ALWAYS creates
+ // a multilattice, whereas if nothing is specified then
+ // intervals are isntantiated WITHOUT being embedded in
+ // a multilattice
+ + @"
<flags> are as follows (missing <flags> means all)
i = intervals
c = constant propagation
diff --git a/Source/Core/Core.csproj b/Source/Core/Core.csproj
index 4929e1c7..97648748 100644
--- a/Source/Core/Core.csproj
+++ b/Source/Core/Core.csproj
@@ -1,232 +1,138 @@
-<?xml version="1.0" encoding="utf-8"?>
-<VisualStudioProject>
- <XEN ProjectType="Local"
- SchemaVersion="1.0"
- Name="Core"
- ProjectGuid="47bc34f1-a173-40be-84c2-9332b4418387"
- >
- <Build>
- <Settings ApplicationIcon=""
- AssemblyName="Core"
- OutputType="Library"
- RootNamespace="Core"
- StartupObject=""
- TargetPlatform="v2"
- TargetPlatformLocation=""
- ShadowedAssembly=""
- StandardLibraryLocation=""
- >
- <Config Name="Debug"
- AllowUnsafeBlocks="False"
- BaseAddress="285212672"
- CheckForOverflowUnderflow="False"
- ConfigurationOverrideFile=""
- DefineConstants="DEBUG;TRACE;WHIDBEY"
- DocumentationFile=""
- DebugSymbols="True"
- FileAlignment="4096"
- IncrementalBuild="True"
- Optimize="False"
- OutputPath="bin\Debug"
- RegisterForComInterop="False"
- RemoveIntegerChecks="false"
- TreatWarningsAsErrors="False"
- WarningLevel="4"
- RunProgramVerifier="False"
- ProgramVerifierCommandLineOptions=""
- ReferenceTypesAreNonNullByDefault="False"
- RunProgramVerifierWhileEditing="False"
- AllowPointersToManagedStructures="False"
- CheckContractAdmissibility="True"
- CheckPurity="False"
- DisableAssumeChecks="False"
- DisableDefensiveChecks="False"
- DisableGuardedClassesChecks="False"
- DisableInternalChecks="False"
- DisableInternalContractsMetadata="False"
- DisablePublicContractsMetadata="False"
- DebugMode="Project"
- StartProgram=""
- StartURL=""
- StartPage=""
- UseIE="False"
- EnableRemoteDebugging="False"
- RemoteDebugMachine=""
- />
- <Config Name="Release"
- AllowUnsafeBlocks="false"
- BaseAddress="285212672"
- CheckForOverflowUnderflow="false"
- ConfigurationOverrideFile=""
- DefineConstants="TRACE;WHIDBEY"
- DocumentationFile=""
- DebugSymbols="false"
- FileAlignment="4096"
- IncrementalBuild="false"
- Optimize="true"
- OutputPath="bin\release"
- RegisterForComInterop="false"
- RemoveIntegerChecks="false"
- TreatWarningsAsErrors="True"
- WarningLevel="4"
- />
- </Settings>
- <References>
- <Reference Name="Mscorlib.Contracts"
- AssemblyName="Mscorlib.Contracts"
- Private="false"
- HintPath="../../Binaries/Mscorlib.Contracts.dll"
- />
- <Reference Name="System"
- AssemblyName="System"
- Private="false"
- />
- <Reference Name="System.Compiler.Framework"
- AssemblyName="System.Compiler.Framework"
- Private="true"
- HintPath="../../Binaries/System.Compiler.Framework.dll"
- />
- <Reference Name="AIFramework"
- Project="{24B55172-AD8B-47D1-8952-5A95CFDB9B31}"
- Private="true"
- />
- <Reference Name="System.Compiler"
- AssemblyName="System.Compiler"
- Private="true"
- HintPath="../../Binaries/System.Compiler.dll"
- />
- <Reference Name="System.Compiler.Contracts"
- AssemblyName="System.Compiler.Contracts"
- Private="false"
- HintPath="../../Binaries/System.Compiler.Contracts.dll"
- />
- <Reference Name="Graph"
- Project="{4C28FB90-630E-4B55-A937-11A011B79765}"
- Private="true"
- />
- <Reference Name="System.XML"
- AssemblyName="System.XML"
- Private="false"
- />
- <Reference Name="System.Xml.Contracts"
- AssemblyName="System.Xml.Contracts"
- Private="false"
- HintPath="../../Binaries/System.Xml.Contracts.dll"
- />
- <Reference Name="FSharp.Core"
- AssemblyName="FSharp.Core"
- Private="false"
- HintPath="../../Binaries/FSharp.Core.dll"
- />
- <Reference Name="Basetypes"
- Project="{0C692837-77EC-415F-BF04-395E3ED06E9A}"
- Private="true"
- />
- </References>
- </Build>
- <Files>
- <Include>
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="Absy.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="..\version.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="Duplicator.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="OOLongUtil.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="PureCollections.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="ResolutionContext.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="StandardVisitor.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="Util.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="CommandLineOptions.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="scanner.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="parser.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="ParserHelper.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="GraphAlgorithms.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="AbsyType.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="AbsyCmd.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="AbsyExpr.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="AbsyQuant.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="Xml.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="Inline.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="LambdaHelper.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="LoopUnroll.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="VCExp.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="TypeAmbiguitySeeker.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="AssemblyInfo.ssc"
- />
- <File BuildAction="Compile"
- SubType="Code"
- RelPath="DeadVarElim.ssc"
- />
- </Include>
- </Files>
- </XEN>
-</VisualStudioProject>
+<?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>{B230A69C-C466-4065-B9C1-84D80E76D802}</ProjectGuid>
+ <OutputType>Library</OutputType>
+ <AppDesignerFolder>Properties</AppDesignerFolder>
+ <RootNamespace>Core</RootNamespace>
+ <AssemblyName>Core</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>%28none%29</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="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="Graph, Version=2.0.0.0, Culture=neutral, PublicKeyToken=736440c9b414ea16, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\Binaries\Graph.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="Microsoft.SpecSharp.Runtime, Version=1.0.21126.0, Culture=neutral, PublicKeyToken=736440c9b414ea16, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\Binaries\Microsoft.SpecSharp.Runtime.dll</HintPath>
+ </Reference>
+ <Reference Include="System" />
+ <Reference Include="System.Compiler, Version=1.0.21126.0, Culture=neutral, PublicKeyToken=736440c9b414ea16, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\Binaries\System.Compiler.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Compiler.Framework, Version=1.0.21126.0, Culture=neutral, PublicKeyToken=736440c9b414ea16, processorArchitecture=MSIL">
+ <SpecificVersion>False</SpecificVersion>
+ <HintPath>..\..\Binaries\System.Compiler.Framework.dll</HintPath>
+ </Reference>
+ <Reference Include="System.Xml" />
+ </ItemGroup>
+ <ItemGroup>
+ <Compile Include="Absy.cs" />
+ <Compile Include="AbsyCmd.cs" />
+ <Compile Include="AbsyExpr.cs" />
+ <Compile Include="AbsyQuant.cs" />
+ <Compile Include="AbsyType.cs" />
+ <Compile Include="cce.cs" />
+ <Compile Include="CommandLineOptions.cs" />
+ <Compile Include="DeadVarElim.cs" />
+ <Compile Include="Duplicator.cs" />
+ <Compile Include="GraphAlgorithms.cs" />
+ <Compile Include="Inline.cs" />
+ <Compile Include="LambdaHelper.cs" />
+ <Compile Include="LoopUnroll.cs" />
+ <Compile Include="OOLongUtil.cs" />
+ <Compile Include="Parser.cs" />
+ <Compile Include="ParserHelper.cs" />
+ <Compile Include="PureCollections.cs" />
+ <Compile Include="ResolutionContext.cs" />
+ <Compile Include="Scanner.cs" />
+ <Compile Include="StandardVisitor.cs" />
+ <Compile Include="TypeAmbiguitySeeker.cs" />
+ <Compile Include="Util.cs" />
+ <Compile Include="VCExp.cs" />
+ <Compile Include="Xml.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/Core/DeadVarElim.cs b/Source/Core/DeadVarElim.cs
index 1a5d0b30..240920c5 100644
--- a/Source/Core/DeadVarElim.cs
+++ b/Source/Core/DeadVarElim.cs
@@ -2,111 +2,140 @@
using System.Collections.Generic;
using Graphing;
using PureCollections;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
-namespace Microsoft.Boogie
-{
+namespace Microsoft.Boogie {
public class UnusedVarEliminator : VariableCollector {
- public static void Eliminate(Program! program) {
+ public static void Eliminate(Program program) {
+ Contract.Requires(program != null);
UnusedVarEliminator elim = new UnusedVarEliminator();
elim.Visit(program);
}
-
- private UnusedVarEliminator() {
- base();
+
+ private UnusedVarEliminator()
+ : base() {//BasemoveA
+
+ }
+
+ public override Implementation VisitImplementation(Implementation node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Implementation>() != null);
+ //Console.WriteLine("Procedure {0}", node.Name);
+ Implementation/*!*/ impl = base.VisitImplementation(node);
+ Contract.Assert(impl != null);
+ //Console.WriteLine("Old number of local variables = {0}", impl.LocVars.Length);
+ Microsoft.Boogie.VariableSeq/*!*/ vars = new Microsoft.Boogie.VariableSeq();
+ foreach (Variable/*!*/ var in impl.LocVars) {
+ Contract.Assert(var != null);
+ if (usedVars.Contains(var))
+ vars.Add(var);
+ }
+ impl.LocVars = vars;
+ //Console.WriteLine("New number of local variables = {0}", impl.LocVars.Length);
+ //Console.WriteLine("---------------------------------");
+ usedVars.Clear();
+ return impl;
}
-
- public override Implementation! VisitImplementation(Implementation! node) {
- //Console.WriteLine("Procedure {0}", node.Name);
- Implementation! impl = base.VisitImplementation(node);
- //Console.WriteLine("Old number of local variables = {0}", impl.LocVars.Length);
- Microsoft.Boogie.VariableSeq! vars = new Microsoft.Boogie.VariableSeq();
- foreach (Variable! var in impl.LocVars) {
- if (usedVars.Contains(var))
- vars.Add(var);
- }
- impl.LocVars = vars;
- //Console.WriteLine("New number of local variables = {0}", impl.LocVars.Length);
- //Console.WriteLine("---------------------------------");
- usedVars.Clear();
- return impl;
- }
}
-
+
public class ModSetCollector : StandardVisitor {
static Procedure proc;
- static Dictionary<Procedure!, Set<Variable!>!>! modSets;
+ static Dictionary<Procedure/*!*/, Set<Variable/*!*/>/*!*/>/*!*/ modSets;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(modSets));
+ Contract.Invariant(Contract.ForAll(modSets.Values, v => cce.NonNullElements(v)));
+ }
+
static bool moreProcessingRequired;
-
- public static void DoModSetAnalysis(Program! program) {
+
+ public static void DoModSetAnalysis(Program program) {
+ Contract.Requires(program != null);
int procCount = 0;
- foreach (Declaration! decl in program.TopLevelDeclarations) {
+ foreach (Declaration/*!*/ decl in program.TopLevelDeclarations) {
+ Contract.Assert(decl != null);
if (decl is Procedure)
procCount++;
}
Console.WriteLine("Number of procedures = {0}", procCount);
-
- modSets = new Dictionary<Procedure!, Set<Variable!>!>();
-
- Set<Procedure!> implementedProcs = new Set<Procedure!> ();
- foreach (Declaration! decl in program.TopLevelDeclarations) {
+
+ modSets = new Dictionary<Procedure/*!*/, Set<Variable/*!*/>/*!*/>();
+
+ Set<Procedure/*!*/> implementedProcs = new Set<Procedure/*!*/>();
+ foreach (Declaration/*!*/ decl in program.TopLevelDeclarations) {
+ Contract.Assert(decl != null);
if (decl is Implementation) {
- Implementation impl = (Implementation) decl;
+ Implementation impl = (Implementation)decl;
if (impl.Proc != null)
implementedProcs.Add(impl.Proc);
}
}
- foreach (Declaration! decl in program.TopLevelDeclarations) {
- if (decl is Procedure && !implementedProcs.Contains((Procedure!) decl)) {
- proc = (Procedure) decl;
- foreach (IdentifierExpr! expr in proc.Modifies) {
+ foreach (Declaration/*!*/ decl in program.TopLevelDeclarations) {
+ Contract.Assert(decl != null);
+ if (decl is Procedure && !implementedProcs.Contains(cce.NonNull((Procedure)decl))) {
+ proc = (Procedure)decl;
+ foreach (IdentifierExpr/*!*/ expr in proc.Modifies) {
+ Contract.Assert(expr != null);
ProcessVariable(expr.Decl);
}
proc = null;
}
}
-
+
moreProcessingRequired = true;
while (moreProcessingRequired) {
moreProcessingRequired = false;
ModSetCollector modSetCollector = new ModSetCollector();
modSetCollector.Visit(program);
}
-
+
procCount = 0;
- foreach (Procedure! x in modSets.Keys) {
+ foreach (Procedure/*!*/ x in modSets.Keys) {
+ Contract.Assert(x != null);
procCount++;
Console.Write("{0} : ", x.Name);
- foreach (Variable! y in modSets[x]) {
+ foreach (Variable/*!*/ y in modSets[x]) {
+ Contract.Assert(y != null);
Console.Write("{0}, ", y.Name);
}
Console.WriteLine("");
}
Console.WriteLine("Number of procedures with nonempty modsets = {0}", procCount);
}
-
- public override Implementation! VisitImplementation(Implementation! node) {
+
+ public override Implementation VisitImplementation(Implementation node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Implementation>() != null);
proc = node.Proc;
- Implementation! ret = base.VisitImplementation(node);
+ Implementation/*!*/ ret = base.VisitImplementation(node);
+ Contract.Assert(ret != null);
proc = null;
-
+
return ret;
}
- public override Cmd! VisitAssignCmd(AssignCmd! assignCmd) {
+ public override Cmd VisitAssignCmd(AssignCmd assignCmd) {
+ //Contract.Requires(assignCmd != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
Cmd ret = base.VisitAssignCmd(assignCmd);
- foreach (AssignLhs! lhs in assignCmd.Lhss) {
- ProcessVariable(lhs.DeepAssignedVariable);
- }
+ foreach (AssignLhs/*!*/ lhs in assignCmd.Lhss) {
+ Contract.Assert(lhs != null);
+ ProcessVariable(lhs.DeepAssignedVariable);
+ }
return ret;
}
- public override Cmd! VisitHavocCmd(HavocCmd! havocCmd) {
+ public override Cmd VisitHavocCmd(HavocCmd havocCmd) {
+ //Contract.Requires(havocCmd != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
Cmd ret = base.VisitHavocCmd(havocCmd);
- foreach (IdentifierExpr! expr in havocCmd.Vars) {
+ foreach (IdentifierExpr/*!*/ expr in havocCmd.Vars) {
+ Contract.Assert(expr != null);
ProcessVariable(expr.Decl);
- }
- return ret;
+ }
+ return ret;
}
- public override Cmd! VisitCallCmd(CallCmd! callCmd) {
+ public override Cmd VisitCallCmd(CallCmd callCmd) {
+ //Contract.Requires(callCmd != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
Cmd ret = base.VisitCallCmd(callCmd);
Procedure callee = callCmd.Proc;
if (callee != null && modSets.ContainsKey(callee)) {
@@ -117,101 +146,131 @@ namespace Microsoft.Boogie
return ret;
}
private static void ProcessVariable(Variable var) {
- Procedure! localProc = (!)proc;
- if (var == null) return;
- if (!(var is GlobalVariable)) return;
- if (var.Name == "alloc") return;
- if (!modSets.ContainsKey(localProc)) {
- modSets[localProc] = new Set<Variable!> ();
- }
- if (modSets[localProc].Contains(var)) return;
- moreProcessingRequired = true;
- modSets[localProc].Add(var);
+ Procedure/*!*/ localProc = cce.NonNull(proc);
+ if (var == null)
+ return;
+ if (!(var is GlobalVariable))
+ return;
+ if (var.Name == "alloc")
+ return;
+ if (!modSets.ContainsKey(localProc)) {
+ modSets[localProc] = new Set<Variable/*!*/>();
+ }
+ if (modSets[localProc].Contains(var))
+ return;
+ moreProcessingRequired = true;
+ modSets[localProc].Add(var);
}
}
-
+
public class VariableCollector : StandardVisitor {
- public System.Collections.Generic.Set<Variable!>! usedVars;
- public System.Collections.Generic.Set<Variable!>! oldVarsUsed;
- int insideOldExpr;
-
- public VariableCollector() {
- usedVars = new System.Collections.Generic.Set<Variable!>();
- oldVarsUsed = new System.Collections.Generic.Set<Variable!>();
- insideOldExpr = 0;
- }
-
- public override Expr! VisitOldExpr(OldExpr! node)
- {
- insideOldExpr ++;
+ public System.Collections.Generic.Set<Variable/*!*/>/*!*/ usedVars;
+ public System.Collections.Generic.Set<Variable/*!*/>/*!*/ oldVarsUsed;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(usedVars));
+ Contract.Invariant(cce.NonNullElements(oldVarsUsed));
+ }
+
+ int insideOldExpr;
+
+ public VariableCollector() {
+ usedVars = new System.Collections.Generic.Set<Variable/*!*/>();
+ oldVarsUsed = new System.Collections.Generic.Set<Variable/*!*/>();
+ insideOldExpr = 0;
+ }
+
+ public override Expr VisitOldExpr(OldExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ insideOldExpr++;
node.Expr = this.VisitExpr(node.Expr);
- insideOldExpr --;
- return node;
+ insideOldExpr--;
+ return node;
}
-
- public override Expr! VisitIdentifierExpr(IdentifierExpr! node) {
+
+ public override Expr VisitIdentifierExpr(IdentifierExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
if (node.Decl != null) {
usedVars.Add(node.Decl);
- if(insideOldExpr > 0) {
+ if (insideOldExpr > 0) {
oldVarsUsed.Add(node.Decl);
}
}
return node;
}
- }
-
- public class BlockCoalescer : StandardVisitor {
- public static void CoalesceBlocks(Program! program) {
+ }
+
+ public class BlockCoalescer : StandardVisitor {
+ public static void CoalesceBlocks(Program program) {
+ Contract.Requires(program != null);
BlockCoalescer blockCoalescer = new BlockCoalescer();
blockCoalescer.Visit(program);
}
-
- private static Set<Block!>! ComputeMultiPredecessorBlocks(Implementation !impl) {
- Set<Block!> visitedBlocks = new Set<Block!>();
- Set<Block!> multiPredBlocks = new Set<Block!>();
- Stack<Block!> dfsStack = new Stack<Block!>();
+
+ private static Set<Block/*!*/>/*!*/ ComputeMultiPredecessorBlocks(Implementation/*!*/ impl) {
+ Contract.Requires(impl != null);
+ Contract.Ensures(cce.NonNullElements(Contract.Result<Set<Block>>()));
+ Set<Block/*!*/> visitedBlocks = new Set<Block/*!*/>();
+ Set<Block/*!*/> multiPredBlocks = new Set<Block/*!*/>();
+ Stack<Block/*!*/> dfsStack = new Stack<Block/*!*/>();
dfsStack.Push(impl.Blocks[0]);
while (dfsStack.Count > 0) {
- Block! b = dfsStack.Pop();
+ Block/*!*/ b = dfsStack.Pop();
+ Contract.Assert(b != null);
if (visitedBlocks.Contains(b)) {
multiPredBlocks.Add(b);
continue;
}
visitedBlocks.Add(b);
- if (b.TransferCmd == null) continue;
- if (b.TransferCmd is ReturnCmd) continue;
- assert b.TransferCmd is GotoCmd;
- GotoCmd gotoCmd = (GotoCmd) b.TransferCmd;
- if (gotoCmd.labelTargets == null) continue;
- foreach (Block! succ in gotoCmd.labelTargets) {
+ if (b.TransferCmd == null)
+ continue;
+ if (b.TransferCmd is ReturnCmd)
+ continue;
+ Contract.Assert(b.TransferCmd is GotoCmd);
+ GotoCmd gotoCmd = (GotoCmd)b.TransferCmd;
+ if (gotoCmd.labelTargets == null)
+ continue;
+ foreach (Block/*!*/ succ in gotoCmd.labelTargets) {
+ Contract.Assert(succ != null);
dfsStack.Push(succ);
}
}
return multiPredBlocks;
}
-
- public override Implementation! VisitImplementation(Implementation! impl) {
+
+ public override Implementation VisitImplementation(Implementation impl) {
+ //Contract.Requires(impl != null);
+ Contract.Ensures(Contract.Result<Implementation>() != null);
//Console.WriteLine("Procedure {0}", impl.Name);
//Console.WriteLine("Initial number of blocks = {0}", impl.Blocks.Count);
-
- Set<Block!> multiPredBlocks = ComputeMultiPredecessorBlocks(impl);
- Set<Block!> visitedBlocks = new Set<Block!>();
- Set<Block!> removedBlocks = new Set<Block!>();
- Stack<Block!> dfsStack = new Stack<Block!>();
+
+ Set<Block/*!*/> multiPredBlocks = ComputeMultiPredecessorBlocks(impl);
+ Contract.Assert(cce.NonNullElements(multiPredBlocks));
+ Set<Block/*!*/> visitedBlocks = new Set<Block/*!*/>();
+ Set<Block/*!*/> removedBlocks = new Set<Block/*!*/>();
+ Stack<Block/*!*/> dfsStack = new Stack<Block/*!*/>();
dfsStack.Push(impl.Blocks[0]);
while (dfsStack.Count > 0) {
- Block! b = dfsStack.Pop();
- if (visitedBlocks.Contains(b)) continue;
+ Block/*!*/ b = dfsStack.Pop();
+ Contract.Assert(b != null);
+ if (visitedBlocks.Contains(b))
+ continue;
visitedBlocks.Add(b);
- if (b.TransferCmd == null) continue;
- if (b.TransferCmd is ReturnCmd) continue;
- assert b.TransferCmd is GotoCmd;
- GotoCmd gotoCmd = (GotoCmd) b.TransferCmd;
- if (gotoCmd.labelTargets == null) continue;
+ if (b.TransferCmd == null)
+ continue;
+ if (b.TransferCmd is ReturnCmd)
+ continue;
+ Contract.Assert(b.TransferCmd is GotoCmd);
+ GotoCmd gotoCmd = (GotoCmd)b.TransferCmd;
+ if (gotoCmd.labelTargets == null)
+ continue;
if (gotoCmd.labelTargets.Length == 1) {
- Block! succ = (!)gotoCmd.labelTargets[0];
+ Block/*!*/ succ = cce.NonNull(gotoCmd.labelTargets[0]);
if (!multiPredBlocks.Contains(succ)) {
- foreach (Cmd! cmd in succ.Cmds) {
+ foreach (Cmd/*!*/ cmd in succ.Cmds) {
+ Contract.Assert(cmd != null);
b.Cmds.Add(cmd);
}
b.TransferCmd = succ.TransferCmd;
@@ -224,162 +283,176 @@ namespace Microsoft.Boogie
visitedBlocks.Remove(b);
continue;
}
- }
- foreach (Block! succ in gotoCmd.labelTargets) {
+ }
+ foreach (Block/*!*/ succ in gotoCmd.labelTargets) {
+ Contract.Assert(succ != null);
dfsStack.Push(succ);
}
}
-
- List<Block!> newBlocks = new List<Block!>();
- foreach (Block! b in impl.Blocks) {
+
+ List<Block/*!*/> newBlocks = new List<Block/*!*/>();
+ foreach (Block/*!*/ b in impl.Blocks) {
+ Contract.Assert(b != null);
if (!removedBlocks.Contains(b)) {
newBlocks.Add(b);
}
}
impl.Blocks = newBlocks;
-
+
// Console.WriteLine("Final number of blocks = {0}", impl.Blocks.Count);
return impl;
}
}
-
+
public class LiveVariableAnalysis {
- public static void ClearLiveVariables(Implementation! impl) {
- foreach (Block! block in impl.Blocks) {
+ public static void ClearLiveVariables(Implementation impl) {
+ Contract.Requires(impl != null);
+ foreach (Block/*!*/ block in impl.Blocks) {
+ Contract.Assert(block != null);
block.liveVarsBefore = null;
}
}
-
- public static void ComputeLiveVariables(Implementation! impl) {
- Microsoft.Boogie.Helpers.ExtraTraceInformation("Starting live variable analysis");
- Graphing.Graph<Block> dag = new Graph<Block>();
- dag.AddSource((!)impl.Blocks[0]); // there is always at least one node in the graph
- foreach (Block b in impl.Blocks)
- {
+
+ public static void ComputeLiveVariables(Implementation impl) {
+ Contract.Requires(impl != null);
+ Microsoft.Boogie.Helpers.ExtraTraceInformation("Starting live variable analysis");
+ Graphing.Graph<Block> dag = new Graph<Block>();
+ dag.AddSource(cce.NonNull(impl.Blocks[0])); // there is always at least one node in the graph
+ foreach (Block b in impl.Blocks) {
GotoCmd gtc = b.TransferCmd as GotoCmd;
- if (gtc != null)
- {
- assume gtc.labelTargets != null;
- foreach (Block! dest in gtc.labelTargets)
- {
+ if (gtc != null) {
+ Contract.Assume(gtc.labelTargets != null);
+ foreach (Block/*!*/ dest in gtc.labelTargets) {
+ Contract.Assert(dest != null);
dag.AddEdge(dest, b);
}
}
}
-
+
IEnumerable<Block> sortedNodes = dag.TopologicalSort();
- foreach (Block! block in sortedNodes) {
- Set<Variable!>! liveVarsAfter = new Set<Variable!>();
- if (block.TransferCmd is GotoCmd) {
- GotoCmd gotoCmd = (GotoCmd) block.TransferCmd;
- if (gotoCmd.labelTargets != null) {
- foreach (Block! succ in gotoCmd.labelTargets) {
- assert succ.liveVarsBefore != null;
- liveVarsAfter.AddRange(succ.liveVarsBefore);
- }
- }
- }
-
+ foreach (Block/*!*/ block in sortedNodes) {
+ Contract.Assert(block != null);
+ Set<Variable/*!*/>/*!*/ liveVarsAfter = new Set<Variable/*!*/>();
+ if (block.TransferCmd is GotoCmd) {
+ GotoCmd gotoCmd = (GotoCmd)block.TransferCmd;
+ if (gotoCmd.labelTargets != null) {
+ foreach (Block/*!*/ succ in gotoCmd.labelTargets) {
+ Contract.Assert(succ != null);
+ Contract.Assert(succ.liveVarsBefore != null);
+ liveVarsAfter.AddRange(succ.liveVarsBefore);
+ }
+ }
+ }
+
CmdSeq cmds = block.Cmds;
- int len = cmds.Length;
- for (int i = len - 1; i >= 0; i--) {
- if(cmds[i] is CallCmd) {
- Procedure! proc = (!)((CallCmd!)cmds[i]).Proc;
- if(InterProcGenKill.HasSummary(proc.Name)) {
- liveVarsAfter =
- InterProcGenKill.PropagateLiveVarsAcrossCall((CallCmd!)cmds[i], liveVarsAfter);
- continue;
- }
- }
- Propagate(cmds[i], liveVarsAfter);
- }
-
- block.liveVarsBefore = liveVarsAfter;
-
- }
- }
-
- // perform in place update of liveSet
- public static void Propagate(Cmd! cmd, Set<Variable!>! liveSet) {
- if (cmd is AssignCmd) {
- AssignCmd! assignCmd = (AssignCmd) cmd;
- // I must first iterate over all the targets and remove the live ones.
- // After the removals are done, I must add the variables referred on
- // the right side of the removed targets
- Set<int> indexSet = new Set<int>();
- int index = 0;
- foreach (AssignLhs! lhs in assignCmd.Lhss) {
- Variable var = lhs.DeepAssignedVariable;
- if (var != null && liveSet.Contains(var)) {
- indexSet.Add(index);
- if (lhs is SimpleAssignLhs) {
- // we should only remove non-map target variables because there is an implicit
- // read of a map variable in an assignment to it
- liveSet.Remove(var);
- }
- }
- index++;
- }
- index = 0;
- foreach (Expr! expr in assignCmd.Rhss) {
- if (indexSet.Contains(index)) {
- VariableCollector! collector = new VariableCollector();
- collector.Visit(expr);
- liveSet.AddRange(collector.usedVars);
- AssignLhs lhs = assignCmd.Lhss[index];
- if (lhs is MapAssignLhs) {
- // If the target is a map, then all indices are also read
- MapAssignLhs malhs = (MapAssignLhs) lhs;
- foreach (Expr e in malhs.Indexes) {
- VariableCollector! c = new VariableCollector();
- c.Visit(e);
- liveSet.AddRange(c.usedVars);
- }
- }
- }
- index++;
- }
- } else if (cmd is HavocCmd) {
- HavocCmd! havocCmd = (HavocCmd) cmd;
- foreach (IdentifierExpr! expr in havocCmd.Vars) {
- if (expr.Decl != null) {
- liveSet.Remove(expr.Decl);
- }
- }
- } else if (cmd is PredicateCmd) {
- assert (cmd is AssertCmd || cmd is AssumeCmd);
- PredicateCmd! predicateCmd = (PredicateCmd) cmd;
- if (predicateCmd.Expr is LiteralExpr) {
- LiteralExpr le = (LiteralExpr) predicateCmd.Expr;
- if (le.IsFalse) {
- liveSet.Clear();
- }
- } else {
- VariableCollector! collector = new VariableCollector();
- collector.Visit(predicateCmd.Expr);
- liveSet.AddRange(collector.usedVars);
- }
- } else if (cmd is CommentCmd) {
+ int len = cmds.Length;
+ for (int i = len - 1; i >= 0; i--) {
+ if (cmds[i] is CallCmd) {
+ Procedure/*!*/ proc = cce.NonNull(cce.NonNull((CallCmd/*!*/)cmds[i]).Proc);
+ if (InterProcGenKill.HasSummary(proc.Name)) {
+ liveVarsAfter =
+ InterProcGenKill.PropagateLiveVarsAcrossCall(cce.NonNull((CallCmd/*!*/)cmds[i]), liveVarsAfter);
+ continue;
+ }
+ }
+ Propagate(cmds[i], liveVarsAfter);
+ }
+
+ block.liveVarsBefore = liveVarsAfter;
+
+ }
+ }
+
+ // perform in place update of liveSet
+ public static void Propagate(Cmd cmd, Set<Variable/*!*/>/*!*/ liveSet) {
+ Contract.Requires(cmd != null);
+ Contract.Requires(cce.NonNullElements(liveSet));
+ if (cmd is AssignCmd) {
+ AssignCmd/*!*/ assignCmd = (AssignCmd)cce.NonNull(cmd);
+ // I must first iterate over all the targets and remove the live ones.
+ // After the removals are done, I must add the variables referred on
+ // the right side of the removed targets
+ Set<int> indexSet = new Set<int>();
+ int index = 0;
+ foreach (AssignLhs/*!*/ lhs in assignCmd.Lhss) {
+ Contract.Assert(lhs != null);
+ Variable var = lhs.DeepAssignedVariable;
+ if (var != null && liveSet.Contains(var)) {
+ indexSet.Add(index);
+ if (lhs is SimpleAssignLhs) {
+ // we should only remove non-map target variables because there is an implicit
+ // read of a map variable in an assignment to it
+ liveSet.Remove(var);
+ }
+ }
+ index++;
+ }
+ index = 0;
+ foreach (Expr/*!*/ expr in assignCmd.Rhss) {
+ Contract.Assert(expr != null);
+ if (indexSet.Contains(index)) {
+ VariableCollector/*!*/ collector = new VariableCollector();
+ collector.Visit(expr);
+ liveSet.AddRange(collector.usedVars);
+ AssignLhs lhs = assignCmd.Lhss[index];
+ if (lhs is MapAssignLhs) {
+ // If the target is a map, then all indices are also read
+ MapAssignLhs malhs = (MapAssignLhs)lhs;
+ foreach (Expr e in malhs.Indexes) {
+ VariableCollector/*!*/ c = new VariableCollector();
+ c.Visit(e);
+ liveSet.AddRange(c.usedVars);
+ }
+ }
+ }
+ index++;
+ }
+ } else if (cmd is HavocCmd) {
+ HavocCmd/*!*/ havocCmd = (HavocCmd)cmd;
+ foreach (IdentifierExpr/*!*/ expr in havocCmd.Vars) {
+ Contract.Assert(expr != null);
+ if (expr.Decl != null) {
+ liveSet.Remove(expr.Decl);
+ }
+ }
+ } else if (cmd is PredicateCmd) {
+ Contract.Assert((cmd is AssertCmd || cmd is AssumeCmd));
+ PredicateCmd/*!*/ predicateCmd = (PredicateCmd)cce.NonNull(cmd);
+ if (predicateCmd.Expr is LiteralExpr) {
+ LiteralExpr le = (LiteralExpr)predicateCmd.Expr;
+ if (le.IsFalse) {
+ liveSet.Clear();
+ }
+ } else {
+ VariableCollector/*!*/ collector = new VariableCollector();
+ collector.Visit(predicateCmd.Expr);
+ liveSet.AddRange(collector.usedVars);
+ }
+ } else if (cmd is CommentCmd) {
// comments are just for debugging and don't affect verification
} else if (cmd is SugaredCmd) {
- SugaredCmd! sugCmd = (SugaredCmd) cmd;
+ SugaredCmd/*!*/ sugCmd = (SugaredCmd)cce.NonNull(cmd);
Propagate(sugCmd.Desugaring, liveSet);
} else if (cmd is StateCmd) {
- StateCmd! stCmd = (StateCmd) cmd;
- CmdSeq! cmds = stCmd.Cmds;
+ StateCmd/*!*/ stCmd = (StateCmd)cce.NonNull(cmd);
+ CmdSeq/*!*/ cmds = cce.NonNull(stCmd.Cmds);
int len = cmds.Length;
for (int i = len - 1; i >= 0; i--) {
Propagate(cmds[i], liveSet);
}
- foreach (Variable! v in stCmd.Locals) {
+ foreach (Variable/*!*/ v in stCmd.Locals) {
+ Contract.Assert(v != null);
liveSet.Remove(v);
}
} else {
- assert false;
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ }
}
- }
+ }
}
-
+
/*
// An idempotent semiring interface
abstract public class Weight {
@@ -391,844 +464,1066 @@ namespace Microsoft.Boogie
abstract public Weight! projectLocals()
}
*/
-
+
// Weight domain for LiveVariableAnalysis (Gen/Kill)
-
+
public class GenKillWeight {
- // lambda S. (S - kill) union gen
- Set<Variable!>! gen;
- Set<Variable!>! kill;
- bool isZero;
-
- public static GenKillWeight! oneWeight = new GenKillWeight(new Set<Variable!>(), new Set<Variable!>());
- public static GenKillWeight! zeroWeight = new GenKillWeight();
-
- // initializes to zero
- public GenKillWeight() {
- this.isZero = true;
- this.gen = new Set<Variable!>();
- this.kill = new Set<Variable!>();
- }
-
- public GenKillWeight(Set<Variable!> gen, Set<Variable!> kill) {
- assert gen != null;
- assert kill != null;
- this.gen = gen;
- this.kill = kill;
- this.isZero = false;
- }
-
- public static GenKillWeight! one() {
- return oneWeight;
- }
-
- public static GenKillWeight! zero() {
- return zeroWeight;
- }
-
- public static GenKillWeight! extend(GenKillWeight! w1, GenKillWeight! w2) {
- if(w1.isZero || w2.isZero) return zero();
-
- return new GenKillWeight(w1.gen.Union(w2.gen.Difference(w1.kill)), w1.kill.Union(w2.kill));
- }
-
- public static GenKillWeight! combine(GenKillWeight! w1, GenKillWeight! w2) {
- if(w1.isZero) return w2;
- if(w2.isZero) return w1;
-
- return new GenKillWeight(w1.gen.Union(w2.gen), w1.kill.Intersection(w2.kill));
- }
-
- public static GenKillWeight! projectLocals(GenKillWeight! w) {
- Set<Variable!> gen = w.gen.FindAll(isGlobal);
- Set<Variable!> kill = w.kill.FindAll(isGlobal);
-
- return new GenKillWeight(gen, kill);
- }
-
- public static bool isEqual(GenKillWeight! w1, GenKillWeight! w2) {
- if(w1.isZero) return w2.isZero;
- if(w2.isZero) return w1.isZero;
-
- return (w1.gen.Equals(w2.gen) && w1.kill.Equals(w2.kill));
- }
-
- private static bool isGlobal(Variable! v)
- {
- return (v is GlobalVariable);
- }
-
- [Pure]
- public override string! ToString() {
- return string.Format("({0},{1})", gen.ToString(), kill.ToString());
- }
-
- public Set<Variable!>! getLiveVars() {
- return gen;
- }
-
- public Set<Variable!>! getLiveVars(Set<Variable!>! lv) {
- Set<Variable!>! temp = (!)lv.Difference(kill);
- return (!)temp.Union(gen);
- }
-
+ // lambda S. (S - kill) union gen
+ Set<Variable/*!*/>/*!*/ gen;
+ Set<Variable/*!*/>/*!*/ kill;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(gen));
+ Contract.Invariant(cce.NonNullElements(kill));
+ Contract.Invariant(oneWeight != null);
+ Contract.Invariant(zeroWeight != null);
+ }
+
+ bool isZero;
+
+ public static GenKillWeight/*!*/ oneWeight = new GenKillWeight(new Set<Variable/*!*/>(), new Set<Variable/*!*/>());
+ public static GenKillWeight/*!*/ zeroWeight = new GenKillWeight();
+
+ // initializes to zero
+ public GenKillWeight() {
+ this.isZero = true;
+ this.gen = new Set<Variable/*!*/>();
+ this.kill = new Set<Variable/*!*/>();
+ }
+
+ public GenKillWeight(Set<Variable/*!*/> gen, Set<Variable/*!*/> kill) {
+ Contract.Requires(cce.NonNullElements(gen));
+ Contract.Requires(cce.NonNullElements(kill));
+ Contract.Assert(gen != null);
+ Contract.Assert(kill != null);
+ this.gen = gen;
+ this.kill = kill;
+ this.isZero = false;
+ }
+
+ public static GenKillWeight one() {
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+ return oneWeight;
+ }
+
+ public static GenKillWeight zero() {
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+ return zeroWeight;
+ }
+
+ public static GenKillWeight extend(GenKillWeight w1, GenKillWeight w2) {
+ Contract.Requires(w2 != null);
+ Contract.Requires(w1 != null);
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+ if (w1.isZero || w2.isZero)
+ return zero();
+
+ return new GenKillWeight(w1.gen.Union(w2.gen.Difference(w1.kill)), w1.kill.Union(w2.kill));
+ }
+
+ public static GenKillWeight combine(GenKillWeight w1, GenKillWeight w2) {
+ Contract.Requires(w2 != null);
+ Contract.Requires(w1 != null);
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+ if (w1.isZero)
+ return w2;
+ if (w2.isZero)
+ return w1;
+
+ return new GenKillWeight(w1.gen.Union(w2.gen), w1.kill.Intersection(w2.kill));
+ }
+
+ public static GenKillWeight projectLocals(GenKillWeight w) {
+ Contract.Requires(w != null);
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+ Set<Variable/*!*/> gen = w.gen.FindAll(isGlobal);
+ Contract.Assert(cce.NonNullElements(gen));
+ Set<Variable/*!*/> kill = w.kill.FindAll(isGlobal);
+ Contract.Assert(cce.NonNullElements(kill));
+
+ return new GenKillWeight(gen, kill);
+ }
+
+ public static bool isEqual(GenKillWeight w1, GenKillWeight w2) {
+ Contract.Requires(w2 != null);
+ Contract.Requires(w1 != null);
+ if (w1.isZero)
+ return w2.isZero;
+ if (w2.isZero)
+ return w1.isZero;
+
+ return (w1.gen.Equals(w2.gen) && w1.kill.Equals(w2.kill));
+ }
+
+ private static bool isGlobal(Variable v) {
+ Contract.Requires(v != null);
+ return (v is GlobalVariable);
+ }
+
+ [Pure]
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return string.Format("({0},{1})", gen.ToString(), kill.ToString());
+ }
+
+ public Set<Variable/*!*/>/*!*/ getLiveVars() {
+ Contract.Ensures(cce.NonNullElements(Contract.Result<Set<Variable>>()));
+ return gen;
+ }
+
+ public Set<Variable/*!*/>/*!*/ getLiveVars(Set<Variable/*!*/>/*!*/ lv) {
+ Contract.Requires(cce.NonNullElements(lv));
+ Contract.Ensures(cce.NonNullElements(Contract.Result<Set<Variable>>()));
+ Set<Variable/*!*/>/*!*/ temp = cce.NonNull(lv.Difference(kill));
+ return cce.NonNull(temp.Union(gen));
+ }
+
}
-
- public class ICFG
- {
- public Graph<Block!>! graph;
- // Map from procedure to the list of blocks that call that procedure
- public Dictionary<string!, List<Block!>!>! procsCalled;
- public Set<Block!>! nodes;
- public Dictionary<Block!, Set<Block!>!>! succEdges;
- public Dictionary<Block!, Set<Block!>!>! predEdges;
- private Dictionary<Block!, int>! priority;
-
- public Set<Block!>! srcNodes;
- public Set<Block!>! exitNodes;
-
- public Dictionary<Block!, GenKillWeight!>! weightBefore;
- public Dictionary<Block!, GenKillWeight!>! weightAfter;
- public Dictionary<Block!, Set<Variable!>!>! liveVarsAfter;
- public Dictionary<Block!, Set<Variable!>!>! liveVarsBefore;
-
- public GenKillWeight! summary;
- public Implementation! impl;
-
- [NotDelayed]
- public ICFG(Implementation! impl) {
- this.graph = new Graph<Block!>();
- this.procsCalled = new Dictionary<string!, List<Block!>!>();
- this.nodes = new Set<Block!>();
- this.succEdges = new Dictionary<Block!, Set<Block!>!>();
- this.predEdges = new Dictionary<Block!, Set<Block!>!>();
-
- this.priority = new Dictionary<Block!, int>();
-
- this.srcNodes = new Set<Block!>();
- this.exitNodes = new Set<Block!>();
-
- this.weightBefore = new Dictionary<Block!, GenKillWeight!>();
- this.weightAfter = new Dictionary<Block!, GenKillWeight!>();
- this.liveVarsAfter = new Dictionary<Block!, Set<Variable!>!>();
- this.liveVarsBefore = new Dictionary<Block!, Set<Variable!>!>();
-
- summary = GenKillWeight.zero();
- this.impl = impl;
-
- base();
-
- Initialize(impl);
-
- }
-
- private void Initialize(Implementation! impl) {
- addSource(impl.Blocks[0]);
- graph.AddSource(impl.Blocks[0]);
-
- foreach(Block! b in impl.Blocks) {
- if(b.TransferCmd is ReturnCmd) {
- exitNodes.Add(b);
- } else {
- GotoCmd gc = b.TransferCmd as GotoCmd;
- assert gc != null;
- assert gc.labelTargets != null;
- foreach(Block! t in gc.labelTargets) {
- addEdge(b,t);
- graph.AddEdge(b,t);
- }
- }
-
- weightBefore[b] = GenKillWeight.zero();
- weightAfter[b] = GenKillWeight.zero();
-
- foreach(Cmd! c in b.Cmds) {
- if(c is CallCmd) {
- CallCmd! cc = (CallCmd!)c;
- assert cc.Proc != null;
- string! procName = cc.Proc.Name;
- if(!procsCalled.ContainsKey(procName)) {
- procsCalled.Add(procName, new List<Block!>());
- }
- procsCalled[procName].Add(b);
- }
+
+ public class ICFG {
+ public Graph<Block/*!*/>/*!*/ graph;
+ // Map from procedure to the list of blocks that call that procedure
+ public Dictionary<string/*!*/, List<Block/*!*/>/*!*/>/*!*/ procsCalled;
+ public Set<Block/*!*/>/*!*/ nodes;
+ public Dictionary<Block/*!*/, Set<Block/*!*/>/*!*/>/*!*/ succEdges;
+ public Dictionary<Block/*!*/, Set<Block/*!*/>/*!*/>/*!*/ predEdges;
+ private Dictionary<Block/*!*/, int>/*!*/ priority;
+
+ public Set<Block/*!*/>/*!*/ srcNodes;
+ public Set<Block/*!*/>/*!*/ exitNodes;
+
+ public Dictionary<Block/*!*/, GenKillWeight/*!*/>/*!*/ weightBefore;
+ public Dictionary<Block/*!*/, GenKillWeight/*!*/>/*!*/ weightAfter;
+ public Dictionary<Block/*!*/, Set<Variable/*!*/>/*!*/>/*!*/ liveVarsAfter;
+ public Dictionary<Block/*!*/, Set<Variable/*!*/>/*!*/>/*!*/ liveVarsBefore;
+
+ public GenKillWeight/*!*/ summary;
+ public Implementation/*!*/ impl;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(graph.TopologicalSort()));
+ Contract.Invariant(cce.NonNullElements(procsCalled));
+ Contract.Invariant(cce.NonNullElements(nodes));
+ Contract.Invariant(cce.NonNullElements(succEdges));
+ Contract.Invariant(cce.NonNullElements(predEdges));
+ Contract.Invariant(cce.NonNullElements(priority));
+ Contract.Invariant(cce.NonNullElements(srcNodes));
+ Contract.Invariant(cce.NonNullElements(exitNodes));
+ Contract.Invariant(cce.NonNullElements(weightBefore));
+ Contract.Invariant(cce.NonNullElements(weightAfter));
+ Contract.Invariant(cce.NonNullElements(liveVarsAfter));
+ Contract.Invariant(cce.NonNullElements(liveVarsBefore));
+ Contract.Invariant(summary != null);
+ Contract.Invariant(impl != null);
+ }
+
+
+ [NotDelayed]
+ public ICFG(Implementation impl) {//BASEMOVE DANGER
+ Contract.Requires(impl != null);
+ this.graph = new Graph<Block/*!*/>();
+ this.procsCalled = new Dictionary<string/*!*/, List<Block/*!*/>/*!*/>();
+ this.nodes = new Set<Block/*!*/>();
+ this.succEdges = new Dictionary<Block/*!*/, Set<Block/*!*/>/*!*/>();
+ this.predEdges = new Dictionary<Block/*!*/, Set<Block/*!*/>/*!*/>();
+
+ this.priority = new Dictionary<Block/*!*/, int>();
+
+ this.srcNodes = new Set<Block/*!*/>();
+ this.exitNodes = new Set<Block/*!*/>();
+
+ this.weightBefore = new Dictionary<Block/*!*/, GenKillWeight/*!*/>();
+ this.weightAfter = new Dictionary<Block/*!*/, GenKillWeight/*!*/>();
+ this.liveVarsAfter = new Dictionary<Block/*!*/, Set<Variable/*!*/>/*!*/>();
+ this.liveVarsBefore = new Dictionary<Block/*!*/, Set<Variable/*!*/>/*!*/>();
+
+ summary = GenKillWeight.zero();
+ this.impl = impl;
+
+ //:base();
+
+ Initialize(impl);
+
+ }
+
+ private void Initialize(Implementation impl) {
+ Contract.Requires(impl != null);
+ addSource(impl.Blocks[0]);
+ graph.AddSource(impl.Blocks[0]);
+
+ foreach (Block/*!*/ b in impl.Blocks) {
+ Contract.Assert(b != null);
+ if (b.TransferCmd is ReturnCmd) {
+ exitNodes.Add(b);
+ } else {
+ GotoCmd gc = b.TransferCmd as GotoCmd;
+ Contract.Assert(gc != null);
+ Contract.Assert(gc.labelTargets != null);
+ foreach (Block/*!*/ t in gc.labelTargets) {
+ Contract.Assert(t != null);
+ addEdge(b, t);
+ graph.AddEdge(b, t);
+ }
+ }
+
+ weightBefore[b] = GenKillWeight.zero();
+ weightAfter[b] = GenKillWeight.zero();
+
+ foreach (Cmd/*!*/ c in b.Cmds) {
+ Contract.Assert(c != null);
+ if (c is CallCmd) {
+ CallCmd/*!*/ cc = cce.NonNull((CallCmd/*!*/)c);
+ Contract.Assert(cc.Proc != null);
+ string/*!*/ procName = cc.Proc.Name;
+ Contract.Assert(procName != null);
+ if (!procsCalled.ContainsKey(procName)) {
+ procsCalled.Add(procName, new List<Block/*!*/>());
}
- }
-
- List<Block>! sortedNodes;
- bool acyclic;
-
- graph.TarjanTopSort(out acyclic, out sortedNodes);
-
- if(!acyclic) {
- Console.WriteLine("Warning: graph is not a dag");
- }
-
- int num = sortedNodes.Count;
- foreach(Block! b in sortedNodes) {
- priority.Add(b,num);
- num--;
- }
-
- }
-
- public int getPriority(Block! b) {
- if(priority.ContainsKey(b)) return priority[b];
- return Int32.MaxValue;
- }
-
- private void addSource(Block! b) {
- registerNode(b);
- this.srcNodes.Add(b);
- }
-
- private void addExit(Block! b) {
- registerNode(b);
- this.exitNodes.Add(b);
- }
-
- private void registerNode(Block! b) {
- if(!succEdges.ContainsKey(b)) {
- succEdges.Add(b, new Set<Block!>());
- }
-
- if(!predEdges.ContainsKey(b)) {
- predEdges.Add(b, new Set<Block!>());
- }
-
- nodes.Add(b);
- }
-
- private void addEdge(Block! src, Block! tgt) {
- registerNode(src);
- registerNode(tgt);
-
- succEdges[src].Add(tgt);
- predEdges[tgt].Add(src);
- }
-
-
+ procsCalled[procName].Add(b);
+ }
+ }
+ }
+
+ List<Block>/*!*/ sortedNodes;
+ bool acyclic;
+
+ graph.TarjanTopSort(out acyclic, out sortedNodes);
+
+ if (!acyclic) {
+ Console.WriteLine("Warning: graph is not a dag");
+ }
+
+ int num = sortedNodes.Count;
+ foreach (Block/*!*/ b in sortedNodes) {
+ Contract.Assert(b != null);
+ priority.Add(b, num);
+ num--;
+ }
+
+ }
+
+ public int getPriority(Block b) {
+ Contract.Requires(b != null);
+ if (priority.ContainsKey(b))
+ return priority[b];
+ return Int32.MaxValue;
+ }
+
+ private void addSource(Block b) {
+ Contract.Requires(b != null);
+ registerNode(b);
+ this.srcNodes.Add(b);
+ }
+
+ private void addExit(Block b) {
+ Contract.Requires(b != null);
+ registerNode(b);
+ this.exitNodes.Add(b);
+ }
+
+ private void registerNode(Block b) {
+ Contract.Requires(b != null);
+ if (!succEdges.ContainsKey(b)) {
+ succEdges.Add(b, new Set<Block/*!*/>());
+ }
+
+ if (!predEdges.ContainsKey(b)) {
+ predEdges.Add(b, new Set<Block/*!*/>());
+ }
+
+ nodes.Add(b);
+ }
+
+ private void addEdge(Block src, Block tgt) {
+ Contract.Requires(tgt != null);
+ Contract.Requires(src != null);
+ registerNode(src);
+ registerNode(tgt);
+
+ succEdges[src].Add(tgt);
+ predEdges[tgt].Add(src);
+ }
+
+
}
-
+
// Interprocedural Gen/Kill Analysis
- public class InterProcGenKill
- {
- Program! program;
- Dictionary<string!, ICFG!>! procICFG;
- Dictionary<string!, Procedure!>! name2Proc;
- Dictionary<string!, List<WorkItem!>!>! callers;
- Graph<string!>! callGraph;
- Dictionary<string!, int>! procPriority;
- int maxBlocksInProc;
-
- WorkList! workList;
-
- Implementation! mainImpl;
-
- static Dictionary<string!, Set<Variable!>!>! varsLiveAtExit = new Dictionary<string!, Set<Variable!>!>();
- static Dictionary<string!, Set<Variable!>!>! varsLiveAtEntry = new Dictionary<string!, Set<Variable!>!>();
- static Dictionary<string!, GenKillWeight!>! varsLiveSummary = new Dictionary<string!, GenKillWeight!>();
-
- [NotDelayed]
- public InterProcGenKill(Implementation! impl, Program! program) {
- this.program = program;
- procICFG = new Dictionary<string!, ICFG!>();
- name2Proc = new Dictionary<string!, Procedure!>();
- workList = new WorkList();
- this.callers = new Dictionary<string!, List<WorkItem!>!>();
- this.callGraph = new Graph<string!>();
- this.procPriority = new Dictionary<string!, int>();
- this.maxBlocksInProc = 0;
- this.mainImpl = impl;
-
- Dictionary<string!, Implementation!>! name2Impl = new Dictionary<string!, Implementation!>();
- varsLiveAtExit.Clear();
- varsLiveAtEntry.Clear();
- varsLiveSummary.Clear();
-
- base();
-
- foreach(Declaration! decl in program.TopLevelDeclarations) {
- if(decl is Implementation) {
- Implementation! imp = (Implementation!)decl;
- name2Impl[imp.Name] = imp;
- } else if(decl is Procedure) {
- Procedure! proc = (!)(decl as Procedure);
- name2Proc[proc.Name] = proc;
- }
+ public class InterProcGenKill {
+ Program/*!*/ program;
+ Dictionary<string/*!*/, ICFG/*!*/>/*!*/ procICFG;
+ Dictionary<string/*!*/, Procedure/*!*/>/*!*/ name2Proc;
+ Dictionary<string/*!*/, List<WorkItem/*!*/>/*!*/>/*!*/ callers;
+ Graph<string/*!*/>/*!*/ callGraph;
+ Dictionary<string/*!*/, int>/*!*/ procPriority;
+ int maxBlocksInProc;
+
+ WorkList/*!*/ workList;
+
+ Implementation/*!*/ mainImpl;
+
+ static Dictionary<string/*!*/, Set<Variable/*!*/>/*!*/>/*!*/ varsLiveAtExit = new Dictionary<string/*!*/, Set<Variable/*!*/>/*!*/>();
+ static Dictionary<string/*!*/, Set<Variable/*!*/>/*!*/>/*!*/ varsLiveAtEntry = new Dictionary<string/*!*/, Set<Variable/*!*/>/*!*/>();
+ static Dictionary<string/*!*/, GenKillWeight/*!*/>/*!*/ varsLiveSummary = new Dictionary<string/*!*/, GenKillWeight/*!*/>();
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(workList != null);
+ Contract.Invariant(mainImpl != null);
+ Contract.Invariant(program != null);
+ Contract.Invariant(cce.NonNullElements(procICFG));
+ Contract.Invariant(cce.NonNullElements(name2Proc));
+ Contract.Invariant(cce.NonNullElements(callers) &&
+ Contract.ForAll(callers.Values, v => cce.NonNullElements(v)));
+ Contract.Invariant(cce.NonNullElements(callGraph.TopologicalSort()));
+ Contract.Invariant(cce.NonNullElements(procPriority));
+ Contract.Invariant(cce.NonNullElements(varsLiveAtEntry));
+ Contract.Invariant(cce.NonNullElements(varsLiveAtExit) &&
+ Contract.ForAll(varsLiveAtExit.Values, v => cce.NonNullElements(v)));
+ Contract.Invariant(cce.NonNullElements(varsLiveSummary));
+ Contract.Invariant(cce.NonNullElements(weightCacheAfterCall));
+ Contract.Invariant(cce.NonNullElements(weightCacheBeforeCall));
+ }
+
+
+ [NotDelayed]
+ public InterProcGenKill(Implementation impl, Program program) {//BASEMOVE DANGER
+ Contract.Requires(program != null);
+ Contract.Requires(impl != null);
+ this.program = program;
+ procICFG = new Dictionary<string/*!*/, ICFG/*!*/>();
+ name2Proc = new Dictionary<string/*!*/, Procedure/*!*/>();
+ workList = new WorkList();
+ this.callers = new Dictionary<string/*!*/, List<WorkItem/*!*/>/*!*/>();
+ this.callGraph = new Graph<string/*!*/>();
+ this.procPriority = new Dictionary<string/*!*/, int>();
+ this.maxBlocksInProc = 0;
+ this.mainImpl = impl;
+
+ Dictionary<string/*!*/, Implementation/*!*/>/*!*/ name2Impl = new Dictionary<string/*!*/, Implementation/*!*/>();
+ varsLiveAtExit.Clear();
+ varsLiveAtEntry.Clear();
+ varsLiveSummary.Clear();
+
+ //base();
+
+ foreach (Declaration/*!*/ decl in program.TopLevelDeclarations) {
+ Contract.Assert(decl != null);
+ if (decl is Implementation) {
+ Implementation/*!*/ imp = (Implementation/*!*/)cce.NonNull(decl);
+ name2Impl[imp.Name] = imp;
+ } else if (decl is Procedure) {
+ Procedure/*!*/ proc = cce.NonNull(decl as Procedure);
+ name2Proc[proc.Name] = proc;
}
-
- ICFG! mainICFG = new ICFG(mainImpl);
- procICFG.Add(mainICFG.impl.Name, mainICFG);
- callGraph.AddSource(mainICFG.impl.Name);
-
- List<ICFG!>! procsToConsider = new List<ICFG!>();
- procsToConsider.Add(mainICFG);
-
- while(procsToConsider.Count != 0) {
- ICFG! p = procsToConsider[0];
- procsToConsider.RemoveAt(0);
-
- foreach(string! callee in p.procsCalled.Keys) {
- if(!name2Impl.ContainsKey(callee)) continue;
-
- callGraph.AddEdge(p.impl.Name, callee);
-
- if(maxBlocksInProc < p.nodes.Count) {
- maxBlocksInProc = p.nodes.Count;
- }
-
- if(!callers.ContainsKey(callee)) {
- callers.Add(callee, new List<WorkItem!>());
- }
- foreach(Block! b in p.procsCalled[callee]) {
- callers[callee].Add(new WorkItem(p, b));
- }
-
- if(procICFG.ContainsKey(callee)) continue;
- ICFG! ncfg = new ICFG(name2Impl[callee]);
- procICFG.Add(callee, ncfg);
- procsToConsider.Add(ncfg);
- }
+ }
+
+ ICFG/*!*/ mainICFG = new ICFG(mainImpl);
+ Contract.Assert(mainICFG != null);
+ procICFG.Add(mainICFG.impl.Name, mainICFG);
+ callGraph.AddSource(mainICFG.impl.Name);
+
+ List<ICFG/*!*/>/*!*/ procsToConsider = new List<ICFG/*!*/>();
+ procsToConsider.Add(mainICFG);
+
+ while (procsToConsider.Count != 0) {
+ ICFG/*!*/ p = procsToConsider[0];
+ Contract.Assert(p != null);
+ procsToConsider.RemoveAt(0);
+
+ foreach (string/*!*/ callee in p.procsCalled.Keys) {
+ Contract.Assert(callee != null);
+ if (!name2Impl.ContainsKey(callee))
+ continue;
+
+ callGraph.AddEdge(p.impl.Name, callee);
+
+ if (maxBlocksInProc < p.nodes.Count) {
+ maxBlocksInProc = p.nodes.Count;
+ }
+
+ if (!callers.ContainsKey(callee)) {
+ callers.Add(callee, new List<WorkItem/*!*/>());
+ }
+ foreach (Block/*!*/ b in p.procsCalled[callee]) {
+ Contract.Assert(b != null);
+ callers[callee].Add(new WorkItem(p, b));
+ }
+
+ if (procICFG.ContainsKey(callee))
+ continue;
+ ICFG/*!*/ ncfg = new ICFG(name2Impl[callee]);
+ Contract.Assert(ncfg != null);
+ procICFG.Add(callee, ncfg);
+ procsToConsider.Add(ncfg);
}
-
- bool acyclic;
- List<string>! sortedNodes;
- callGraph.TarjanTopSort(out acyclic, out sortedNodes);
-
- assert acyclic;
-
- int cnt = 0;
- for(int i = sortedNodes.Count - 1; i >= 0; i--) {
- string s = sortedNodes[i];
- if(s == null) continue;
- procPriority.Add(s, cnt);
- cnt++;
+ }
+
+ bool acyclic;
+ List<string>/*!*/ sortedNodes;
+ callGraph.TarjanTopSort(out acyclic, out sortedNodes);
+
+ Contract.Assert(acyclic);
+
+ int cnt = 0;
+ for (int i = sortedNodes.Count - 1; i >= 0; i--) {
+ string s = sortedNodes[i];
+ if (s == null)
+ continue;
+ procPriority.Add(s, cnt);
+ cnt++;
+ }
+
+ }
+
+ public static Set<Variable/*!*/>/*!*/ GetVarsLiveAtExit(Implementation impl, Program prog) {
+ Contract.Requires(prog != null);
+ Contract.Requires(impl != null);
+ Contract.Ensures(cce.NonNullElements(Contract.Result<Set<Variable>>()));
+ if (varsLiveAtExit.ContainsKey(impl.Name)) {
+ return varsLiveAtExit[impl.Name];
+ }
+ // Return default: all globals and out params
+ Set<Variable/*!*/>/*!*/ lv = new Set<Variable/*!*/>();
+ foreach (Variable/*!*/ v in prog.GlobalVariables()) {
+ Contract.Assert(v != null);
+ lv.Add(v);
+ }
+ foreach (Variable/*!*/ v in impl.OutParams) {
+ Contract.Assert(v != null);
+ lv.Add(v);
+ }
+ return lv;
+ }
+
+ public static Set<Variable/*!*/>/*!*/ GetVarsLiveAtEntry(Implementation impl, Program prog) {
+ Contract.Requires(prog != null);
+ Contract.Requires(impl != null);
+ Contract.Ensures(cce.NonNullElements(Contract.Result<Set<Variable>>()));
+ if (varsLiveAtEntry.ContainsKey(impl.Name)) {
+ return varsLiveAtEntry[impl.Name];
+ }
+ // Return default: all globals and in params
+ Set<Variable/*!*/>/*!*/ lv = new Set<Variable/*!*/>();
+ foreach (Variable/*!*/ v in prog.GlobalVariables()) {
+ Contract.Assert(v != null);
+ lv.Add(v);
+ }
+ foreach (Variable/*!*/ v in impl.InParams) {
+ Contract.Assert(v != null);
+ lv.Add(v);
+ }
+ return lv;
+ }
+
+ public static bool HasSummary(string name) {
+ Contract.Requires(name != null);
+ return varsLiveSummary.ContainsKey(name);
+ }
+
+ public static Set<Variable/*!*/>/*!*/ PropagateLiveVarsAcrossCall(CallCmd cmd, Set<Variable/*!*/>/*!*/ lvAfter) {
+ Contract.Requires(cmd != null);
+ Contract.Requires(cce.NonNullElements(lvAfter));
+ Contract.Ensures(cce.NonNullElements(Contract.Result<Set<Variable>>()));
+ Procedure/*!*/ proc = cce.NonNull(cmd.Proc);
+ if (varsLiveSummary.ContainsKey(proc.Name)) {
+ GenKillWeight/*!*/ w1 = getWeightBeforeCall(cmd);
+ Contract.Assert(w1 != null);
+ GenKillWeight/*!*/ w2 = varsLiveSummary[proc.Name];
+ Contract.Assert(w2 != null);
+ GenKillWeight/*!*/ w3 = getWeightAfterCall(cmd);
+ Contract.Assert(w3 != null);
+ GenKillWeight/*!*/ w = GenKillWeight.extend(w1, GenKillWeight.extend(w2, w3));
+ Contract.Assert(w != null);
+ return w.getLiveVars(lvAfter);
+ }
+ Set<Variable/*!*/>/*!*/ ret = new Set<Variable/*!*/>();
+ ret.AddRange(lvAfter);
+ LiveVariableAnalysis.Propagate(cmd, ret);
+ return ret;
+ }
+
+ class WorkItem {
+ public ICFG/*!*/ cfg;
+ public Block/*!*/ block;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cfg != null);
+ Contract.Invariant(block != null);
+ }
+
+
+ public WorkItem(ICFG cfg, Block block) {
+ Contract.Requires(block != null);
+ Contract.Requires(cfg != null);
+ this.cfg = cfg;
+ this.block = block;
+ }
+
+ public GenKillWeight getWeightAfter() {
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+ return cfg.weightAfter[block];
+ }
+
+ public bool setWeightBefore(GenKillWeight w) {
+ Contract.Requires(w != null);
+ GenKillWeight/*!*/ prev = cfg.weightBefore[block];
+ Contract.Assert(prev != null);
+ GenKillWeight/*!*/ curr = GenKillWeight.combine(w, prev);
+ Contract.Assert(curr != null);
+ if (GenKillWeight.isEqual(prev, curr))
+ return false;
+ cfg.weightBefore[block] = curr;
+ return true;
+ }
+
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object other) {
+ WorkItem/*!*/ wi = (WorkItem/*!*/)cce.NonNull(other);
+ return (wi.cfg == cfg && wi.block == block);
+ }
+
+ [Pure]
+ public override int GetHashCode() {
+ return 0;
+ }
+
+ public string getLabel() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return cfg.impl.Name + "::" + block.Label;
+ }
+
+ }
+
+ private void AddToWorkList(WorkItem wi) {
+ Contract.Requires(wi != null);
+ int i = procPriority[wi.cfg.impl.Name];
+ int j = wi.cfg.getPriority(wi.block);
+ int priority = (i * maxBlocksInProc) + j;
+
+ workList.Add(wi, priority);
+ }
+
+ private void AddToWorkListReverse(WorkItem wi) {
+ Contract.Requires(wi != null);
+ int i = procPriority[wi.cfg.impl.Name];
+ int j = wi.cfg.getPriority(wi.block);
+ int priority = (procPriority.Count - i) * maxBlocksInProc + j;
+ workList.Add(wi, priority);
+ }
+
+ class WorkList {
+ SortedList<int, int>/*!*/ priorities;
+ Set<string/*!*/>/*!*/ labels;
+
+ Dictionary<int, List<WorkItem/*!*/>/*!*/>/*!*/ workList;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(priorities != null);
+ Contract.Invariant(cce.NonNullElements(labels));
+ Contract.Invariant(cce.NonNullElements(workList) &&
+ Contract.ForAll(workList.Values, v => cce.NonNullElements(v)));
+ }
+
+
+ public WorkList() {
+ labels = new Set<string/*!*/>();
+ priorities = new SortedList<int, int>();
+ workList = new Dictionary<int, List<WorkItem/*!*/>/*!*/>();
+ }
+
+ public void Add(WorkItem wi, int priority) {
+ Contract.Requires(wi != null);
+ string/*!*/ lab = wi.getLabel();
+ Contract.Assert(lab != null);
+ if (labels.Contains(lab)) {
+ // Already on worklist
+ return;
}
-
- }
-
- public static Set<Variable!>! GetVarsLiveAtExit(Implementation! impl, Program! prog) {
- if(varsLiveAtExit.ContainsKey(impl.Name)) {
- return varsLiveAtExit[impl.Name];
- }
- // Return default: all globals and out params
- Set<Variable!>! lv = new Set<Variable!>();
- foreach(Variable! v in prog.GlobalVariables()) {
- lv.Add(v);
- }
- foreach(Variable! v in impl.OutParams) {
- lv.Add(v);
- }
- return lv;
- }
-
- public static Set<Variable!>! GetVarsLiveAtEntry(Implementation! impl, Program! prog) {
- if(varsLiveAtEntry.ContainsKey(impl.Name)) {
- return varsLiveAtEntry[impl.Name];
- }
- // Return default: all globals and in params
- Set<Variable!>! lv = new Set<Variable!>();
- foreach(Variable! v in prog.GlobalVariables()) {
- lv.Add(v);
- }
- foreach(Variable! v in impl.InParams) {
- lv.Add(v);
- }
- return lv;
- }
-
- public static bool HasSummary(string! name) {
- return varsLiveSummary.ContainsKey(name);
- }
-
- public static Set<Variable!>! PropagateLiveVarsAcrossCall(CallCmd! cmd, Set<Variable!>! lvAfter) {
- Procedure! proc = (!)cmd.Proc;
- if(varsLiveSummary.ContainsKey(proc.Name)) {
- GenKillWeight! w1 = getWeightBeforeCall(cmd);
- GenKillWeight! w2 = varsLiveSummary[proc.Name];
- GenKillWeight! w3 = getWeightAfterCall(cmd);
- GenKillWeight! w = GenKillWeight.extend(w1, GenKillWeight.extend(w2, w3));
- return w.getLiveVars(lvAfter);
+ labels.Add(lab);
+ if (!workList.ContainsKey(priority)) {
+ workList.Add(priority, new List<WorkItem/*!*/>());
}
- Set<Variable!>! ret = new Set<Variable!>();
- ret.AddRange(lvAfter);
- LiveVariableAnalysis.Propagate(cmd, ret);
- return ret;
- }
-
- class WorkItem {
- public ICFG! cfg;
- public Block! block;
-
- public WorkItem(ICFG! cfg, Block! block) {
- this.cfg = cfg;
- this.block = block;
- }
-
- public GenKillWeight! getWeightAfter() {
- return cfg.weightAfter[block];
- }
-
- public bool setWeightBefore(GenKillWeight! w) {
- GenKillWeight! prev = cfg.weightBefore[block];
- GenKillWeight! curr = GenKillWeight.combine(w, prev);
- if(GenKillWeight.isEqual(prev, curr)) return false;
- cfg.weightBefore[block] = curr;
- return true;
- }
-
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals(object other)
- {
- WorkItem! wi = (WorkItem!)(other);
- return (wi.cfg == cfg && wi.block == block);
+ workList[priority].Add(wi);
+ if (!priorities.ContainsKey(priority)) {
+ priorities.Add(priority, 0);
}
-
- [Pure]
- public override int GetHashCode()
- {
- return 0;
+
+ priorities[priority] = priorities[priority] + 1;
+ }
+
+ public WorkItem Get() {
+ Contract.Ensures(Contract.Result<WorkItem>() != null);
+ // Get minimum priority
+ int p = cce.NonNull(priorities.Keys)[0];
+ priorities[p] = priorities[p] - 1;
+ if (priorities[p] == 0) {
+ priorities.Remove(p);
}
-
- public string! getLabel() {
- return cfg.impl.Name + "::" + block.Label;
+
+ // Get a WI with this priority
+ WorkItem/*!*/ wi = workList[p][0];
+ Contract.Assert(wi != null);
+ workList[p].RemoveAt(0);
+
+ // update labels
+ labels.Remove(wi.getLabel());
+ return wi;
+ }
+
+ public int Count {
+ get {
+ return labels.Count;
}
-
- }
-
- private void AddToWorkList(WorkItem! wi) {
- int i = procPriority[wi.cfg.impl.Name];
- int j = wi.cfg.getPriority(wi.block);
- int priority = (i * maxBlocksInProc) + j;
-
- workList.Add(wi, priority);
- }
-
- private void AddToWorkListReverse(WorkItem! wi) {
- int i = procPriority[wi.cfg.impl.Name];
- int j = wi.cfg.getPriority(wi.block);
- int priority = (procPriority.Count - i) * maxBlocksInProc + j;
- workList.Add(wi, priority);
- }
-
- class WorkList {
- SortedList<int,int>! priorities;
- Set<string!>! labels;
-
- Dictionary<int, List<WorkItem!>!>! workList;
-
- public WorkList() {
- labels = new Set<string!>();
- priorities = new SortedList<int,int>();
- workList = new Dictionary<int, List<WorkItem!>!>();
+ }
+ }
+
+ private GenKillWeight getSummary(CallCmd cmd) {
+ Contract.Requires(cmd != null);
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+ Contract.Assert(cmd.Proc != null);
+ string/*!*/ procName = cmd.Proc.Name;
+ Contract.Assert(procName != null);
+ if (procICFG.ContainsKey(procName)) {
+ ICFG/*!*/ cfg = procICFG[procName];
+ Contract.Assert(cfg != null);
+ return GenKillWeight.projectLocals(cfg.summary);
+ }
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ }
+ }
+
+ public static void ComputeLiveVars(Implementation impl, Program/*!*/ prog) {
+ Contract.Requires(prog != null);
+ Contract.Requires(impl != null);
+ InterProcGenKill/*!*/ ipgk = new InterProcGenKill(impl, prog);
+ Contract.Assert(ipgk != null);
+ ipgk.Compute();
+ }
+
+ public void Compute() {
+ // Put all exit nodes in the worklist
+ foreach (ICFG/*!*/ cfg in procICFG.Values) {
+ Contract.Assert(cfg != null);
+ foreach (Block/*!*/ eb in cfg.exitNodes) {
+ Contract.Assert(eb != null);
+ WorkItem/*!*/ wi = new WorkItem(cfg, eb);
+ Contract.Assert(wi != null);
+ cfg.weightAfter[eb] = GenKillWeight.one();
+ AddToWorkList(wi);
}
-
- public void Add(WorkItem! wi, int priority) {
- string! lab = wi.getLabel();
- if(labels.Contains(lab)) {
- // Already on worklist
- return;
- }
- labels.Add(lab);
- if(!workList.ContainsKey(priority)) {
- workList.Add(priority, new List<WorkItem!>());
- }
- workList[priority].Add(wi);
- if(!priorities.ContainsKey(priority)) {
- priorities.Add(priority,0);
- }
-
- priorities[priority] = priorities[priority] + 1;
+ }
+
+ while (workList.Count != 0) {
+ WorkItem/*!*/ wi = workList.Get();
+ Contract.Assert(wi != null);
+ process(wi);
+ }
+
+ // Propagate LV to all procedures
+ foreach (ICFG/*!*/ cfg in procICFG.Values) {
+ Contract.Assert(cfg != null);
+ foreach (Block/*!*/ b in cfg.nodes) {
+ Contract.Assert(b != null);
+ cfg.liveVarsAfter.Add(b, new Set<Variable/*!*/>());
+ cfg.liveVarsBefore.Add(b, new Set<Variable/*!*/>());
}
-
- public WorkItem! Get() {
- // Get minimum priority
- int p = ((!)priorities.Keys)[0];
- priorities[p] = priorities[p] - 1;
- if(priorities[p] == 0) {
- priorities.Remove(p);
- }
-
- // Get a WI with this priority
- WorkItem! wi = workList[p][0];
- workList[p].RemoveAt(0);
-
- // update labels
- labels.Remove(wi.getLabel());
- return wi;
+ }
+
+ ICFG/*!*/ mainCfg = procICFG[mainImpl.Name];
+ Contract.Assert(mainCfg != null);
+ foreach (Block/*!*/ eb in mainCfg.exitNodes) {
+ Contract.Assert(eb != null);
+ WorkItem/*!*/ wi = new WorkItem(mainCfg, eb);
+ Contract.Assert(wi != null);
+ AddToWorkListReverse(wi);
+ }
+
+ while (workList.Count != 0) {
+ WorkItem/*!*/ wi = workList.Get();
+ Contract.Assert(wi != null);
+ processLV(wi);
+ }
+
+ // Set live variable info
+ foreach (ICFG/*!*/ cfg in procICFG.Values) {
+ Contract.Assert(cfg != null);
+ Set<Variable/*!*/>/*!*/ lv = new Set<Variable/*!*/>();
+ foreach (Block/*!*/ eb in cfg.exitNodes) {
+ Contract.Assert(eb != null);
+ lv.AddRange(cfg.liveVarsAfter[eb]);
}
-
- public int Count {
- get {
- return labels.Count;
- }
+ varsLiveAtExit.Add(cfg.impl.Name, lv);
+ lv = new Set<Variable/*!*/>();
+ foreach (Block/*!*/ eb in cfg.srcNodes) {
+ Contract.Assert(eb != null);
+ lv.AddRange(cfg.liveVarsBefore[eb]);
}
- }
-
- private GenKillWeight! getSummary(CallCmd! cmd) {
- assert cmd.Proc != null;
- string! procName = cmd.Proc.Name;
- if(procICFG.ContainsKey(procName)) {
- ICFG! cfg = procICFG[procName];
- return GenKillWeight.projectLocals(cfg.summary);
- }
- assert false;
- }
-
- public static void ComputeLiveVars(Implementation! impl, Program !prog) {
- InterProcGenKill! ipgk = new InterProcGenKill(impl, prog);
- ipgk.Compute();
- }
-
- public void Compute() {
- // Put all exit nodes in the worklist
- foreach(ICFG! cfg in procICFG.Values) {
- foreach(Block! eb in cfg.exitNodes) {
- WorkItem! wi = new WorkItem(cfg, eb);
- cfg.weightAfter[eb] = GenKillWeight.one();
- AddToWorkList(wi);
- }
- }
-
- while(workList.Count != 0) {
- WorkItem! wi = workList.Get();
- process(wi);
- }
-
- // Propagate LV to all procedures
- foreach(ICFG! cfg in procICFG.Values) {
- foreach(Block! b in cfg.nodes) {
- cfg.liveVarsAfter.Add(b, new Set<Variable!>());
- cfg.liveVarsBefore.Add(b, new Set<Variable!>());
- }
- }
-
- ICFG! mainCfg = procICFG[mainImpl.Name];
- foreach(Block! eb in mainCfg.exitNodes) {
- WorkItem! wi = new WorkItem(mainCfg, eb);
- AddToWorkListReverse(wi);
- }
-
- while(workList.Count != 0) {
- WorkItem! wi = workList.Get();
- processLV(wi);
- }
-
- // Set live variable info
- foreach(ICFG! cfg in procICFG.Values) {
- Set<Variable!>! lv = new Set<Variable!>();
- foreach(Block! eb in cfg.exitNodes) {
- lv.AddRange(cfg.liveVarsAfter[eb]);
- }
- varsLiveAtExit.Add(cfg.impl.Name, lv);
- lv = new Set<Variable!>();
- foreach(Block! eb in cfg.srcNodes) {
- lv.AddRange(cfg.liveVarsBefore[eb]);
+ varsLiveAtEntry.Add(cfg.impl.Name, lv);
+ varsLiveSummary.Add(cfg.impl.Name, cfg.summary);
+ }
+
+ /*
+ foreach(Block/*!*/
+ /* b in mainImpl.Blocks){
+Contract.Assert(b != null);
+//Set<Variable!> lv = cfg.weightBefore[b].getLiveVars();
+b.liveVarsBefore = procICFG[mainImpl.Name].liveVarsAfter[b];
+//foreach(GlobalVariable/*!*/
+ /* v in program.GlobalVariables()){Contract.Assert(v != null);
+// b.liveVarsBefore.Add(v);
+//}
+}
+*/
+ }
+
+ // Called when summaries have already been computed
+ private void processLV(WorkItem wi) {
+ Contract.Requires(wi != null);
+ ICFG/*!*/ cfg = wi.cfg;
+ Contract.Assert(cfg != null);
+ Block/*!*/ block = wi.block;
+ Contract.Assert(block != null);
+ Set<Variable/*!*/>/*!*/ lv = cfg.liveVarsAfter[block];
+ Contract.Assert(cce.NonNullElements(lv));
+ // Propagate backwards in the block
+ Set<Variable/*!*/>/*!*/ prop = new Set<Variable/*!*/>();
+ prop.AddRange(lv);
+ for (int i = block.Cmds.Length - 1; i >= 0; i--) {
+ Cmd/*!*/ cmd = block.Cmds[i];
+ Contract.Assert(cmd != null);
+ if (cmd is CallCmd) {
+ string/*!*/ procName = cce.NonNull(cce.NonNull((CallCmd)cmd).Proc).Name;
+ Contract.Assert(procName != null);
+ if (procICFG.ContainsKey(procName)) {
+ ICFG/*!*/ callee = procICFG[procName];
+ Contract.Assert(callee != null);
+ // Inter propagation
+ // Remove local variables; add return variables
+ Set<Variable/*!*/>/*!*/ elv = new Set<Variable/*!*/>();
+ foreach (Variable/*!*/ v in prop) {
+ Contract.Assert(v != null);
+ if (v is GlobalVariable)
+ elv.Add(v);
+ }
+ foreach (Variable/*!*/ v in callee.impl.OutParams) {
+ Contract.Assert(v != null);
+ elv.Add(v);
+ }
+
+ foreach (Block/*!*/ eb in callee.exitNodes) {
+ Contract.Assert(eb != null);
+ callee.liveVarsAfter[eb].AddRange(elv);
+ // TODO: check if modified before inserting
+ AddToWorkListReverse(new WorkItem(callee, eb));
+ }
+
+ // Continue with intra propagation
+ GenKillWeight/*!*/ summary = getWeightCall(cce.NonNull((CallCmd/*!*/)cmd));
+ prop = summary.getLiveVars(prop);
+ } else {
+ LiveVariableAnalysis.Propagate(cmd, prop);
}
- varsLiveAtEntry.Add(cfg.impl.Name, lv);
- varsLiveSummary.Add(cfg.impl.Name, cfg.summary);
- }
-
- /*
- foreach(Block! b in mainImpl.Blocks) {
- //Set<Variable!> lv = cfg.weightBefore[b].getLiveVars();
- b.liveVarsBefore = procICFG[mainImpl.Name].liveVarsAfter[b];
- //foreach(GlobalVariable! v in program.GlobalVariables()) {
- // b.liveVarsBefore.Add(v);
- //}
- }
- */
- }
-
- // Called when summaries have already been computed
- private void processLV(WorkItem! wi) {
- ICFG! cfg = wi.cfg;
- Block! block = wi.block;
-
- Set<Variable!>! lv = cfg.liveVarsAfter[block];
-
- // Propagate backwards in the block
- Set<Variable!>! prop = new Set<Variable!>();
- prop.AddRange(lv);
- for(int i = block.Cmds.Length - 1; i >= 0; i--) {
- Cmd! cmd = block.Cmds[i];
- if(cmd is CallCmd) {
- string! procName = ((!)((CallCmd!)cmd).Proc).Name;
- if(procICFG.ContainsKey(procName)) {
- ICFG! callee = procICFG[procName];
- // Inter propagation
- // Remove local variables; add return variables
- Set<Variable!>! elv = new Set<Variable!>();
- foreach(Variable! v in prop) {
- if(v is GlobalVariable) elv.Add(v);
- }
- foreach(Variable! v in callee.impl.OutParams) {
- elv.Add(v);
- }
-
- foreach(Block! eb in callee.exitNodes) {
- callee.liveVarsAfter[eb].AddRange(elv);
- // TODO: check if modified before inserting
- AddToWorkListReverse(new WorkItem(callee, eb));
- }
-
- // Continue with intra propagation
- GenKillWeight! summary = getWeightCall((CallCmd!)cmd);
- prop = summary.getLiveVars(prop);
- } else {
- LiveVariableAnalysis.Propagate(cmd, prop);
- }
- } else {
- LiveVariableAnalysis.Propagate(cmd, prop);
- }
+ } else {
+ LiveVariableAnalysis.Propagate(cmd, prop);
}
-
- cfg.liveVarsBefore[block].AddRange(prop);
-
- foreach(Block! b in cfg.predEdges[block]) {
- Set<Variable!>! prev = cfg.liveVarsAfter[b];
- Set<Variable!>! curr = (!)prev.Union(cfg.liveVarsBefore[block]);
- if(curr.Count != prev.Count) {
- cfg.liveVarsAfter[b] = curr;
- AddToWorkListReverse(new WorkItem(cfg, b));
- }
+ }
+
+ cfg.liveVarsBefore[block].AddRange(prop);
+
+ foreach (Block/*!*/ b in cfg.predEdges[block]) {
+ Contract.Assert(b != null);
+ Set<Variable/*!*/>/*!*/ prev = cfg.liveVarsAfter[b];
+ Contract.Assert(cce.NonNullElements(prev));
+ Set<Variable/*!*/>/*!*/ curr = cce.NonNull(prev.Union(cfg.liveVarsBefore[block]));
+ Contract.Assert(cce.NonNullElements(curr));
+ if (curr.Count != prev.Count) {
+ cfg.liveVarsAfter[b] = curr;
+ AddToWorkListReverse(new WorkItem(cfg, b));
}
- }
-
- private void process(WorkItem! wi)
- {
- GenKillWeight! w = wi.getWeightAfter();
-
- for(int i = wi.block.Cmds.Length - 1; i >= 0; i--) {
- Cmd! c = wi.block.Cmds[i];
- if(c is CallCmd && procICFG.ContainsKey( ((!)((CallCmd!)c).Proc).Name ) ){
- w = GenKillWeight.extend(getWeightCall((CallCmd!)c), w);
- } else {
- GenKillWeight! cweight = getWeight(c, wi.cfg.impl, program);
- w = GenKillWeight.extend(cweight, w);
- }
- }
-
- bool change = wi.setWeightBefore(w);
-
- if(change && wi.cfg.srcNodes.Contains(wi.block)) {
- GenKillWeight! prev = wi.cfg.summary;
- GenKillWeight! curr = GenKillWeight.combine(prev, wi.cfg.weightBefore[wi.block]);
- if(!GenKillWeight.isEqual(prev, curr)) {
- wi.cfg.summary = curr;
- // push callers onto the worklist
- if(callers.ContainsKey(wi.cfg.impl.Name)) {
- foreach(WorkItem! caller in callers[wi.cfg.impl.Name]) {
- AddToWorkList(caller);
- }
- }
- }
- }
-
- foreach(Block! b in wi.cfg.predEdges[wi.block]) {
- GenKillWeight! prev = wi.cfg.weightAfter[b];
- GenKillWeight! curr = GenKillWeight.combine(prev, w);
- if(!GenKillWeight.isEqual(prev, curr)) {
- wi.cfg.weightAfter[b] = curr;
- AddToWorkList(new WorkItem(wi.cfg, b));
+ }
+ }
+
+ private void process(WorkItem wi) {
+ Contract.Requires(wi != null);
+ GenKillWeight/*!*/ w = wi.getWeightAfter();
+ Contract.Assert(w != null);
+
+ for (int i = wi.block.Cmds.Length - 1; i >= 0; i--) {
+ Cmd/*!*/ c = wi.block.Cmds[i];
+ Contract.Assert(c != null);
+ if (c is CallCmd && procICFG.ContainsKey(cce.NonNull(cce.NonNull((CallCmd)c).Proc).Name)) {
+ w = GenKillWeight.extend(getWeightCall(cce.NonNull((CallCmd)c)), w);
+ } else {
+ GenKillWeight/*!*/ cweight = getWeight(c, wi.cfg.impl, program);
+ Contract.Assert(cweight != null);
+ w = GenKillWeight.extend(cweight, w);
+ }
+ }
+
+ bool change = wi.setWeightBefore(w);
+
+ if (change && wi.cfg.srcNodes.Contains(wi.block)) {
+ GenKillWeight/*!*/ prev = wi.cfg.summary;
+ Contract.Assert(prev != null);
+ GenKillWeight/*!*/ curr = GenKillWeight.combine(prev, wi.cfg.weightBefore[wi.block]);
+ Contract.Assert(curr != null);
+ if (!GenKillWeight.isEqual(prev, curr)) {
+ wi.cfg.summary = curr;
+ // push callers onto the worklist
+ if (callers.ContainsKey(wi.cfg.impl.Name)) {
+ foreach (WorkItem/*!*/ caller in callers[wi.cfg.impl.Name]) {
+ Contract.Assert(caller != null);
+ AddToWorkList(caller);
+ }
}
- }
-
- }
+ }
+ }
- static Dictionary<Cmd!, GenKillWeight!>! weightCache = new Dictionary<Cmd!, GenKillWeight!>();
+ foreach (Block/*!*/ b in wi.cfg.predEdges[wi.block]) {
+ Contract.Assert(b != null);
+ GenKillWeight/*!*/ prev = wi.cfg.weightAfter[b];
+ Contract.Assert(prev != null);
+ GenKillWeight/*!*/ curr = GenKillWeight.combine(prev, w);
+ Contract.Assert(curr != null);
+ if (!GenKillWeight.isEqual(prev, curr)) {
+ wi.cfg.weightAfter[b] = curr;
+ AddToWorkList(new WorkItem(wi.cfg, b));
+ }
+ }
- private static GenKillWeight! getWeight(Cmd! cmd) {
- return getWeight(cmd, null, null);
- }
+ }
- private GenKillWeight! getWeightCall(CallCmd! cmd) {
- GenKillWeight! w1 = getWeightBeforeCall(cmd);
- GenKillWeight! w2 = getSummary(cmd);
- GenKillWeight! w3 = getWeightAfterCall(cmd);
- return GenKillWeight.extend(w1, GenKillWeight.extend(w2, w3));
- }
+ static Dictionary<Cmd/*!*/, GenKillWeight/*!*/>/*!*/ weightCache = new Dictionary<Cmd/*!*/, GenKillWeight/*!*/>();
- private static GenKillWeight! getWeight(Cmd! cmd, Implementation impl, Program prog) {
+ private static GenKillWeight getWeight(Cmd cmd) {
+ Contract.Requires(cmd != null);
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+ return getWeight(cmd, null, null);
+ }
- if(weightCache.ContainsKey(cmd))
+ private GenKillWeight getWeightCall(CallCmd cmd) {
+ Contract.Requires(cmd != null);
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+ GenKillWeight/*!*/ w1 = getWeightBeforeCall(cmd);
+ GenKillWeight/*!*/ w2 = getSummary(cmd);
+ GenKillWeight/*!*/ w3 = getWeightAfterCall(cmd);
+ Contract.Assert(w1 != null);
+ Contract.Assert(w2 != null);
+ Contract.Assert(w3 != null);
+ return GenKillWeight.extend(w1, GenKillWeight.extend(w2, w3));
+ }
+
+ private static GenKillWeight getWeight(Cmd cmd, Implementation impl, Program prog) {
+ Contract.Requires(cmd != null);
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+
+ if (weightCache.ContainsKey(cmd))
return weightCache[cmd];
-
- Set<Variable!>! gen = new Set<Variable!>();
- Set<Variable!>! kill = new Set<Variable!>();
- GenKillWeight! ret;
-
- if (cmd is AssignCmd) {
- AssignCmd! assignCmd = (AssignCmd) cmd;
- // I must first iterate over all the targets and remove the live ones.
- // After the removals are done, I must add the variables referred on
- // the right side of the removed targets
- foreach (AssignLhs! lhs in assignCmd.Lhss) {
- Variable var = lhs.DeepAssignedVariable;
- if (var != null) {
- if (lhs is SimpleAssignLhs) {
- // we should only remove non-map target variables because there is an implicit
- // read of a map variable in an assignment to it
- kill.Add(var);
- }
- }
- }
- int index = 0;
- foreach (Expr! expr in assignCmd.Rhss) {
- VariableCollector! collector = new VariableCollector();
- collector.Visit(expr);
- gen.AddRange(collector.usedVars);
- AssignLhs lhs = assignCmd.Lhss[index];
- if (lhs is MapAssignLhs) {
- // If the target is a map, then all indices are also read
- MapAssignLhs malhs = (MapAssignLhs) lhs;
- foreach (Expr e in malhs.Indexes) {
- VariableCollector! c = new VariableCollector();
- c.Visit(e);
- gen.AddRange(c.usedVars);
- }
- }
- index++;
- }
- ret = new GenKillWeight(gen, kill);
- } else if (cmd is HavocCmd) {
- HavocCmd! havocCmd = (HavocCmd) cmd;
- foreach (IdentifierExpr! expr in havocCmd.Vars) {
- if (expr.Decl != null) {
- kill.Add(expr.Decl);
- }
- }
- ret = new GenKillWeight(gen, kill);
- } else if (cmd is PredicateCmd) {
- assert (cmd is AssertCmd || cmd is AssumeCmd);
- PredicateCmd! predicateCmd = (PredicateCmd) cmd;
- if (predicateCmd.Expr is LiteralExpr && prog != null && impl != null) {
- LiteralExpr le = (LiteralExpr) predicateCmd.Expr;
- if (le.IsFalse) {
- List<GlobalVariable!>! globals = prog.GlobalVariables();
- foreach(Variable! v in globals) {
- kill.Add(v);
- }
- foreach(Variable! v in impl.LocVars) {
- kill.Add(v);
- }
- foreach(Variable! v in impl.OutParams) {
- kill.Add(v);
- }
- }
- } else {
- VariableCollector! collector = new VariableCollector();
- collector.Visit(predicateCmd.Expr);
- gen.AddRange(collector.usedVars);
- }
- ret = new GenKillWeight(gen, kill);
- } else if (cmd is CommentCmd) {
- ret = new GenKillWeight(gen, kill);
+
+ Set<Variable/*!*/>/*!*/ gen = new Set<Variable/*!*/>();
+ Set<Variable/*!*/>/*!*/ kill = new Set<Variable/*!*/>();
+ GenKillWeight/*!*/ ret;
+
+ if (cmd is AssignCmd) {
+ AssignCmd/*!*/ assignCmd = (AssignCmd)cmd;
+ Contract.Assert(cmd != null);
+ // I must first iterate over all the targets and remove the live ones.
+ // After the removals are done, I must add the variables referred on
+ // the right side of the removed targets
+ foreach (AssignLhs/*!*/ lhs in assignCmd.Lhss) {
+ Contract.Assert(lhs != null);
+ Variable var = lhs.DeepAssignedVariable;
+ if (var != null) {
+ if (lhs is SimpleAssignLhs) {
+ // we should only remove non-map target variables because there is an implicit
+ // read of a map variable in an assignment to it
+ kill.Add(var);
+ }
+ }
+ }
+ int index = 0;
+ foreach (Expr/*!*/ expr in assignCmd.Rhss) {
+ Contract.Assert(expr != null);
+ VariableCollector/*!*/ collector = new VariableCollector();
+ collector.Visit(expr);
+ gen.AddRange(collector.usedVars);
+ AssignLhs lhs = assignCmd.Lhss[index];
+ if (lhs is MapAssignLhs) {
+ // If the target is a map, then all indices are also read
+ MapAssignLhs malhs = (MapAssignLhs)lhs;
+ foreach (Expr e in malhs.Indexes) {
+ VariableCollector/*!*/ c = new VariableCollector();
+ c.Visit(e);
+ gen.AddRange(c.usedVars);
+ }
+ }
+ index++;
+ }
+ ret = new GenKillWeight(gen, kill);
+ } else if (cmd is HavocCmd) {
+ HavocCmd/*!*/ havocCmd = (HavocCmd)cce.NonNull(cmd);
+ foreach (IdentifierExpr/*!*/ expr in havocCmd.Vars) {
+ Contract.Assert(expr != null);
+ if (expr.Decl != null) {
+ kill.Add(expr.Decl);
+ }
+ }
+ ret = new GenKillWeight(gen, kill);
+ } else if (cmd is PredicateCmd) {
+ Contract.Assert((cmd is AssertCmd || cmd is AssumeCmd));
+ PredicateCmd/*!*/ predicateCmd = (PredicateCmd)cce.NonNull(cmd);
+ if (predicateCmd.Expr is LiteralExpr && prog != null && impl != null) {
+ LiteralExpr le = (LiteralExpr)predicateCmd.Expr;
+ if (le.IsFalse) {
+ List<GlobalVariable/*!*/>/*!*/ globals = prog.GlobalVariables();
+ Contract.Assert(cce.NonNullElements(globals));
+ foreach (Variable/*!*/ v in globals) {
+ Contract.Assert(v != null);
+ kill.Add(v);
+ }
+ foreach (Variable/*!*/ v in impl.LocVars) {
+ Contract.Assert(v != null);
+ kill.Add(v);
+ }
+ foreach (Variable/*!*/ v in impl.OutParams) {
+ Contract.Assert(v != null);
+ kill.Add(v);
+ }
+ }
+ } else {
+ VariableCollector/*!*/ collector = new VariableCollector();
+ collector.Visit(predicateCmd.Expr);
+ gen.AddRange(collector.usedVars);
+ }
+ ret = new GenKillWeight(gen, kill);
+ } else if (cmd is CommentCmd) {
+ ret = new GenKillWeight(gen, kill);
// comments are just for debugging and don't affect verification
} else if (cmd is SugaredCmd) {
- SugaredCmd! sugCmd = (SugaredCmd) cmd;
+ SugaredCmd/*!*/ sugCmd = (SugaredCmd)cmd;
+ Contract.Assert(sugCmd != null);
ret = getWeight(sugCmd.Desugaring, impl, prog);
} else if (cmd is StateCmd) {
- StateCmd! stCmd = (StateCmd) cmd;
- CmdSeq! cmds = stCmd.Cmds;
+ StateCmd/*!*/ stCmd = (StateCmd)cmd;
+ Contract.Assert(stCmd != null);
+ CmdSeq/*!*/ cmds = stCmd.Cmds;
+ Contract.Assert(cmds != null);
int len = cmds.Length;
ret = GenKillWeight.one();
for (int i = len - 1; i >= 0; i--) {
- GenKillWeight! w = getWeight(cmds[i], impl, prog);
+ GenKillWeight/*!*/ w = getWeight(cmds[i], impl, prog);
+ Contract.Assert(w != null);
ret = GenKillWeight.extend(w, ret);
}
- foreach (Variable! v in stCmd.Locals) {
+ foreach (Variable/*!*/ v in stCmd.Locals) {
+ Contract.Assert(v != null);
kill.Add(v);
}
ret = GenKillWeight.extend(new GenKillWeight(gen, kill), ret);
} else {
- assert false;
+ {
+ Contract.Assert(false);
+ throw new cce.UnreachableException();
+ }
}
-
+
weightCache[cmd] = ret;
return ret;
- }
-
- static Dictionary<Cmd!, GenKillWeight!>! weightCacheAfterCall = new Dictionary<Cmd!, GenKillWeight!>();
- static Dictionary<Cmd!, GenKillWeight!>! weightCacheBeforeCall = new Dictionary<Cmd!, GenKillWeight!>();
-
- private static GenKillWeight! getWeightAfterCall(Cmd! cmd) {
-
- if(weightCacheAfterCall.ContainsKey(cmd))
- return weightCacheAfterCall[cmd];
-
- Set<Variable!>! gen = new Set<Variable!>();
- Set<Variable!>! kill = new Set<Variable!>();
-
- assert (cmd is CallCmd);
- CallCmd! ccmd = (CallCmd!)cmd;
-
- foreach(IdentifierExpr! ie in ccmd.Outs) {
- if(ie.Decl != null) kill.Add(ie.Decl);
- }
+ }
+
+ static Dictionary<Cmd/*!*/, GenKillWeight/*!*/>/*!*/ weightCacheAfterCall = new Dictionary<Cmd/*!*/, GenKillWeight/*!*/>();
+ static Dictionary<Cmd/*!*/, GenKillWeight/*!*/>/*!*/ weightCacheBeforeCall = new Dictionary<Cmd/*!*/, GenKillWeight/*!*/>();
+
+ private static GenKillWeight getWeightAfterCall(Cmd cmd) {
+ Contract.Requires(cmd != null);
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+
+ if (weightCacheAfterCall.ContainsKey(cmd))
+ return weightCacheAfterCall[cmd];
+
+ Set<Variable/*!*/>/*!*/ gen = new Set<Variable/*!*/>();
+ Set<Variable/*!*/>/*!*/ kill = new Set<Variable/*!*/>();
+
+ Contract.Assert(cmd is CallCmd);
+ CallCmd/*!*/ ccmd = cce.NonNull((CallCmd)cmd);
+
+ foreach (IdentifierExpr/*!*/ ie in ccmd.Outs) {
+ Contract.Assert(ie != null);
+ if (ie.Decl != null)
+ kill.Add(ie.Decl);
+ }
// Variables in ensures are considered as "read"
- foreach(Ensures! re in ((!)ccmd.Proc).Ensures) {
- VariableCollector! collector = new VariableCollector();
- collector.Visit(re.Condition);
- foreach(Variable! v in collector.usedVars) {
- if(v is GlobalVariable) {
- gen.Add(v);
- }
- }
- }
-
- GenKillWeight! ret = new GenKillWeight(gen, kill);
- weightCacheAfterCall[cmd] = ret;
- return ret;
- }
-
- private static GenKillWeight! getWeightBeforeCall(Cmd! cmd) {
- assert (cmd is CallCmd);
- if(weightCacheBeforeCall.ContainsKey(cmd))
- return weightCacheBeforeCall[cmd];
-
- Set<Variable!>! gen = new Set<Variable!>();
- Set<Variable!>! kill = new Set<Variable!>();
- CallCmd! ccmd = (CallCmd!)cmd;
-
- foreach (Expr! expr in ccmd.Ins) {
- VariableCollector! collector = new VariableCollector();
- collector.Visit(expr);
- gen.AddRange(collector.usedVars);
- }
-
- assert ccmd.Proc != null;
-
+ foreach (Ensures/*!*/ re in cce.NonNull(ccmd.Proc).Ensures) {
+ Contract.Assert(re != null);
+ VariableCollector/*!*/ collector = new VariableCollector();
+ collector.Visit(re.Condition);
+ foreach (Variable/*!*/ v in collector.usedVars) {
+ Contract.Assert(v != null);
+ if (v is GlobalVariable) {
+ gen.Add(v);
+ }
+ }
+ }
+
+ GenKillWeight/*!*/ ret = new GenKillWeight(gen, kill);
+ Contract.Assert(ret != null);
+ weightCacheAfterCall[cmd] = ret;
+ return ret;
+ }
+
+ private static GenKillWeight getWeightBeforeCall(Cmd cmd) {
+ Contract.Requires(cmd != null);
+ Contract.Ensures(Contract.Result<GenKillWeight>() != null);
+ Contract.Assert((cmd is CallCmd));
+ if (weightCacheBeforeCall.ContainsKey(cmd))
+ return weightCacheBeforeCall[cmd];
+
+ Set<Variable/*!*/>/*!*/ gen = new Set<Variable/*!*/>();
+ Set<Variable/*!*/>/*!*/ kill = new Set<Variable/*!*/>();
+ CallCmd/*!*/ ccmd = cce.NonNull((CallCmd/*!*/)cmd);
+
+ foreach (Expr/*!*/ expr in ccmd.Ins) {
+ Contract.Assert(expr != null);
+ VariableCollector/*!*/ collector = new VariableCollector();
+ collector.Visit(expr);
+ gen.AddRange(collector.usedVars);
+ }
+
+ Contract.Assert(ccmd.Proc != null);
+
// Variables in requires are considered as "read"
- foreach(Requires! re in ccmd.Proc.Requires) {
- VariableCollector! collector = new VariableCollector();
- collector.Visit(re.Condition);
- foreach(Variable! v in collector.usedVars) {
- if(v is GlobalVariable) {
- gen.Add(v);
- }
- }
+ foreach (Requires/*!*/ re in ccmd.Proc.Requires) {
+ Contract.Assert(re != null);
+ VariableCollector/*!*/ collector = new VariableCollector();
+ collector.Visit(re.Condition);
+ foreach (Variable/*!*/ v in collector.usedVars) {
+ Contract.Assert(v != null);
+ if (v is GlobalVariable) {
+ gen.Add(v);
+ }
+ }
}
// Old variables in ensures are considered as "read"
- foreach(Ensures! re in ccmd.Proc.Ensures) {
- VariableCollector! collector = new VariableCollector();
- collector.Visit(re.Condition);
- foreach(Variable! v in collector.oldVarsUsed) {
- if(v is GlobalVariable) {
- gen.Add(v);
- }
- }
- }
-
- GenKillWeight! ret = new GenKillWeight(gen, kill);
- weightCacheAfterCall[cmd] = ret;
- return ret;
- }
-
-
+ foreach (Ensures/*!*/ re in ccmd.Proc.Ensures) {
+ Contract.Assert(re != null);
+ VariableCollector/*!*/ collector = new VariableCollector();
+ collector.Visit(re.Condition);
+ foreach (Variable/*!*/ v in collector.oldVarsUsed) {
+ Contract.Assert(v != null);
+ if (v is GlobalVariable) {
+ gen.Add(v);
+ }
+ }
+ }
+
+ GenKillWeight/*!*/ ret = new GenKillWeight(gen, kill);
+ Contract.Assert(ret != null);
+ weightCacheAfterCall[cmd] = ret;
+ return ret;
+ }
}
-
} \ No newline at end of file
diff --git a/Source/Core/Duplicator.cs b/Source/Core/Duplicator.cs
index f265ee35..0445be1a 100644
--- a/Source/Core/Duplicator.cs
+++ b/Source/Core/Duplicator.cs
@@ -9,317 +9,392 @@
using System.Collections;
using System.Collections.Generic;
+using System.Diagnostics.Contracts;
-namespace Microsoft.Boogie
-{
- public class Duplicator : StandardVisitor
- {
- public override Absy! Visit(Absy! node)
- {
+namespace Microsoft.Boogie {
+ public class Duplicator : StandardVisitor {
+ public override Absy Visit(Absy node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
node = base.Visit(node);
return node;
}
- public override Cmd! VisitAssertCmd(AssertCmd! node)
- {
- return base.VisitAssertCmd ((AssertCmd)node.Clone());
- }
- public override Cmd! VisitAssignCmd(AssignCmd! node)
- {
+ public override Cmd VisitAssertCmd(AssertCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+ return base.VisitAssertCmd((AssertCmd)node.Clone());
+ }
+ public override Cmd VisitAssignCmd(AssignCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
AssignCmd clone = (AssignCmd)node.Clone();
- clone.Lhss = new List<AssignLhs!>(clone.Lhss);
- clone.Rhss = new List<Expr!>(clone.Rhss);
+ clone.Lhss = new List<AssignLhs/*!*/>(clone.Lhss);
+ clone.Rhss = new List<Expr/*!*/>(clone.Rhss);
return base.VisitAssignCmd(clone);
}
- public override Cmd! VisitAssumeCmd(AssumeCmd! node)
- {
- return base.VisitAssumeCmd ((AssumeCmd)node.Clone());
+ public override Cmd VisitAssumeCmd(AssumeCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+ return base.VisitAssumeCmd((AssumeCmd)node.Clone());
}
- public override AtomicRE! VisitAtomicRE(AtomicRE! node)
- {
- return base.VisitAtomicRE ((AtomicRE)node.Clone());
+ public override AtomicRE VisitAtomicRE(AtomicRE node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<AtomicRE>() != null);
+ return base.VisitAtomicRE((AtomicRE)node.Clone());
}
- public override Axiom! VisitAxiom(Axiom! node)
- {
- return base.VisitAxiom ((Axiom)node.Clone());
+ public override Axiom VisitAxiom(Axiom node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Axiom>() != null);
+ return base.VisitAxiom((Axiom)node.Clone());
}
- public override Type! VisitBasicType(BasicType! node)
- {
+ public override Type VisitBasicType(BasicType node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
// do /not/ clone the type recursively
return (BasicType)node.Clone();
}
- public override Block! VisitBlock(Block! node)
- {
- return base.VisitBlock ((Block)node.Clone());
+ public override Block VisitBlock(Block node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Block>() != null);
+ return base.VisitBlock((Block)node.Clone());
}
- public override Expr! VisitCodeExpr(CodeExpr! node)
- {
+ public override Expr VisitCodeExpr(CodeExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
CodeExpr clone = (CodeExpr)base.VisitCodeExpr((CodeExpr)node.Clone());
// Before returning, fix up the resolved goto targets
- assert node.Blocks.Count == clone.Blocks.Count;
- Dictionary<Block,Block> subst = new Dictionary<Block,Block>();
+ Contract.Assert(node.Blocks.Count == clone.Blocks.Count);
+ Dictionary<Block, Block> subst = new Dictionary<Block, Block>();
for (int i = 0; i < node.Blocks.Count; i++) {
subst.Add(node.Blocks[i], clone.Blocks[i]);
}
- foreach (Block! b in clone.Blocks) {
+ foreach (Block/*!*/ b in clone.Blocks) {
+ Contract.Assert(b != null);
GotoCmd g = b.TransferCmd as GotoCmd;
if (g != null) {
BlockSeq targets = new BlockSeq();
- foreach (Block t in (!)g.labelTargets) {
+ foreach (Block t in cce.NonNull(g.labelTargets)) {
Block nt = subst[t];
targets.Add(nt);
}
g.labelTargets = targets;
}
}
- return clone;
- }
- public override BlockSeq! VisitBlockSeq(BlockSeq! blockSeq)
- {
- return base.VisitBlockSeq (new BlockSeq(blockSeq));
- }
- public override List<Block!>! VisitBlockList(List<Block!>! blocks)
- {
- return base.VisitBlockList (new List<Block!>(blocks));
- }
- public override BoundVariable! VisitBoundVariable(BoundVariable! node)
- {
- return base.VisitBoundVariable ((BoundVariable)node.Clone());
- }
- public override Type! VisitBvType(BvType! node)
- {
+ return clone;
+ }
+ public override BlockSeq VisitBlockSeq(BlockSeq blockSeq) {
+ //Contract.Requires(blockSeq != null);
+ Contract.Ensures(Contract.Result<BlockSeq>() != null);
+ return base.VisitBlockSeq(new BlockSeq(blockSeq));
+ }
+ public override List<Block/*!*/>/*!*/ VisitBlockList(List<Block/*!*/>/*!*/ blocks) {
+ //Contract.Requires(cce.NonNullElements(blocks));
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Block>>()));
+ return base.VisitBlockList(new List<Block/*!*/>(blocks));
+ }
+ public override BoundVariable VisitBoundVariable(BoundVariable node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<BoundVariable>() != null);
+ return base.VisitBoundVariable((BoundVariable)node.Clone());
+ }
+ public override Type VisitBvType(BvType node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
// do /not/ clone the type recursively
return (BvType)node.Clone();
}
- public override Cmd! VisitCallCmd(CallCmd! node)
- {
- CallCmd! clone = (CallCmd)node.Clone();
+ public override Cmd VisitCallCmd(CallCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+ CallCmd/*!*/ clone = (CallCmd)node.Clone();
+ Contract.Assert(clone != null);
clone.Ins = new List<Expr>(clone.Ins);
clone.Outs = new List<IdentifierExpr>(clone.Outs);
return base.VisitCallCmd(clone);
}
- public override Cmd! VisitCallForallCmd(CallForallCmd! node)
- {
- CallForallCmd! clone = (CallForallCmd)node.Clone();
+ public override Cmd VisitCallForallCmd(CallForallCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+ CallForallCmd/*!*/ clone = (CallForallCmd)node.Clone();
+ Contract.Assert(clone != null);
clone.Ins = new List<Expr>(clone.Ins);
return base.VisitCallForallCmd(clone);
}
- public override Choice! VisitChoice(Choice! node)
- {
- return base.VisitChoice ((Choice)node.Clone());
+ public override Choice VisitChoice(Choice node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Choice>() != null);
+ return base.VisitChoice((Choice)node.Clone());
}
- public override CmdSeq! VisitCmdSeq(CmdSeq! cmdSeq)
- {
- return base.VisitCmdSeq (cmdSeq);
+ public override CmdSeq VisitCmdSeq(CmdSeq cmdSeq) {
+ //Contract.Requires(cmdSeq != null);
+ Contract.Ensures(Contract.Result<CmdSeq>() != null);
+ return base.VisitCmdSeq(cmdSeq);
}
- public override Constant! VisitConstant(Constant! node)
- {
- return base.VisitConstant ((Constant)node.Clone());
+ public override Constant VisitConstant(Constant node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Constant>() != null);
+ return base.VisitConstant((Constant)node.Clone());
}
- public override CtorType! VisitCtorType(CtorType! node)
- {
+ public override CtorType VisitCtorType(CtorType node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<CtorType>() != null);
// do /not/ clone the type recursively
return (CtorType)node.Clone();
}
- public override Declaration! VisitDeclaration(Declaration! node)
- {
- return base.VisitDeclaration ((Declaration)node.Clone());
+ public override Declaration VisitDeclaration(Declaration node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Declaration>() != null);
+ return base.VisitDeclaration((Declaration)node.Clone());
}
- public override List<Declaration!>! VisitDeclarationList(List<Declaration!>! declarationList)
- {
+ public override List<Declaration/*!*/>/*!*/ VisitDeclarationList(List<Declaration/*!*/>/*!*/ declarationList) {
+ //Contract.Requires(cce.NonNullElements(declarationList));
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Declaration>>()));
return base.VisitDeclarationList(declarationList);
}
- public override DeclWithFormals! VisitDeclWithFormals(DeclWithFormals! node)
- {
- return base.VisitDeclWithFormals ((DeclWithFormals)node.Clone());
- }
- public override ExistsExpr! VisitExistsExpr(ExistsExpr! node)
- {
- return base.VisitExistsExpr ((ExistsExpr)node.Clone());
- }
- public override Expr! VisitExpr(Expr! node)
- {
- return base.VisitExpr ((Expr)node.Clone());
- }
- public override ExprSeq! VisitExprSeq(ExprSeq! list)
- {
- return base.VisitExprSeq (new ExprSeq(list));
- }
- public override ForallExpr! VisitForallExpr(ForallExpr! node)
- {
- return base.VisitForallExpr ((ForallExpr)node.Clone());
- }
- public override Formal! VisitFormal(Formal! node)
- {
- return base.VisitFormal ((Formal)node.Clone());
- }
- public override Function! VisitFunction(Function! node)
- {
- return base.VisitFunction ((Function)node.Clone());
- }
- public override GlobalVariable! VisitGlobalVariable(GlobalVariable! node)
- {
- return base.VisitGlobalVariable ((GlobalVariable)node.Clone());
- }
- public override GotoCmd! VisitGotoCmd(GotoCmd! node)
- {
- return base.VisitGotoCmd ((GotoCmd)node.Clone());
- }
- public override Cmd! VisitHavocCmd(HavocCmd! node)
- {
- return base.VisitHavocCmd ((HavocCmd)node.Clone());
- }
- public override Expr! VisitIdentifierExpr(IdentifierExpr! node)
- {
- return base.VisitIdentifierExpr ((IdentifierExpr) node.Clone());
- }
- public override IdentifierExprSeq! VisitIdentifierExprSeq(IdentifierExprSeq! identifierExprSeq)
- {
- return base.VisitIdentifierExprSeq (new IdentifierExprSeq(identifierExprSeq));
- }
- public override Implementation! VisitImplementation(Implementation! node)
- {
- return base.VisitImplementation ((Implementation)node.Clone());
- }
- public override LiteralExpr! VisitLiteralExpr(LiteralExpr! node)
- {
- return base.VisitLiteralExpr ((LiteralExpr)node.Clone());
- }
- public override LocalVariable! VisitLocalVariable(LocalVariable! node)
- {
- return base.VisitLocalVariable ((LocalVariable)node.Clone());
- }
- public override AssignLhs! VisitMapAssignLhs(MapAssignLhs! node)
- {
+ public override DeclWithFormals VisitDeclWithFormals(DeclWithFormals node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<DeclWithFormals>() != null);
+ return base.VisitDeclWithFormals((DeclWithFormals)node.Clone());
+ }
+ public override ExistsExpr VisitExistsExpr(ExistsExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<ExistsExpr>() != null);
+ return base.VisitExistsExpr((ExistsExpr)node.Clone());
+ }
+ public override Expr VisitExpr(Expr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ return base.VisitExpr((Expr)node.Clone());
+ }
+ public override ExprSeq VisitExprSeq(ExprSeq list) {
+ //Contract.Requires(list != null);
+ Contract.Ensures(Contract.Result<ExprSeq>() != null);
+ return base.VisitExprSeq(new ExprSeq(list));
+ }
+ public override ForallExpr VisitForallExpr(ForallExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<ForallExpr>() != null);
+ return base.VisitForallExpr((ForallExpr)node.Clone());
+ }
+ public override Formal VisitFormal(Formal node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Formal>() != null);
+ return base.VisitFormal((Formal)node.Clone());
+ }
+ public override Function VisitFunction(Function node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Function>() != null);
+ return base.VisitFunction((Function)node.Clone());
+ }
+ public override GlobalVariable VisitGlobalVariable(GlobalVariable node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<GlobalVariable>() != null);
+ return base.VisitGlobalVariable((GlobalVariable)node.Clone());
+ }
+ public override GotoCmd VisitGotoCmd(GotoCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<GotoCmd>() != null);
+ return base.VisitGotoCmd((GotoCmd)node.Clone());
+ }
+ public override Cmd VisitHavocCmd(HavocCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+ return base.VisitHavocCmd((HavocCmd)node.Clone());
+ }
+ public override Expr VisitIdentifierExpr(IdentifierExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ return base.VisitIdentifierExpr((IdentifierExpr)node.Clone());
+ }
+ public override IdentifierExprSeq VisitIdentifierExprSeq(IdentifierExprSeq identifierExprSeq) {
+ //Contract.Requires(identifierExprSeq != null);
+ Contract.Ensures(Contract.Result<IdentifierExprSeq>() != null);
+ return base.VisitIdentifierExprSeq(new IdentifierExprSeq(identifierExprSeq));
+ }
+ public override Implementation VisitImplementation(Implementation node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Implementation>() != null);
+ return base.VisitImplementation((Implementation)node.Clone());
+ }
+ public override LiteralExpr VisitLiteralExpr(LiteralExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<LiteralExpr>() != null);
+ return base.VisitLiteralExpr((LiteralExpr)node.Clone());
+ }
+ public override LocalVariable VisitLocalVariable(LocalVariable node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<LocalVariable>() != null);
+ return base.VisitLocalVariable((LocalVariable)node.Clone());
+ }
+ public override AssignLhs VisitMapAssignLhs(MapAssignLhs node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<AssignLhs>() != null);
MapAssignLhs clone = (MapAssignLhs)node.Clone();
- clone.Indexes = new List<Expr!>(clone.Indexes);
+ clone.Indexes = new List<Expr/*!*/>(clone.Indexes);
return base.VisitMapAssignLhs(clone);
}
- public override MapType! VisitMapType(MapType! node)
- {
+ public override MapType VisitMapType(MapType node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<MapType>() != null);
// do /not/ clone the type recursively
return (MapType)node.Clone();
}
- public override Expr! VisitNAryExpr(NAryExpr! node)
- {
- return base.VisitNAryExpr ((NAryExpr)node.Clone());
- }
- public override Expr! VisitOldExpr(OldExpr! node)
- {
- return base.VisitOldExpr ((OldExpr) node.Clone());
- }
- public override Procedure! VisitProcedure(Procedure! node)
- {
- return base.VisitProcedure ((Procedure)node.Clone());
- }
- public override Program! VisitProgram(Program! node)
- {
- return base.VisitProgram ((Program) node.Clone());
- }
- public override BinderExpr! VisitBinderExpr(BinderExpr! node)
- {
- return base.VisitBinderExpr ((BinderExpr) node.Clone());
- }
- public override Cmd! VisitRE(RE! node)
- {
- return base.VisitRE ((RE) node.Clone());
- }
- public override RESeq! VisitRESeq(RESeq! reSeq)
- {
- return base.VisitRESeq (new RESeq(reSeq));
- }
- public override ReturnCmd! VisitReturnCmd(ReturnCmd! node)
- {
- return base.VisitReturnCmd ((ReturnCmd) node.Clone());
- }
- public override ReturnExprCmd! VisitReturnExprCmd(ReturnExprCmd! node)
- {
+ public override Expr VisitNAryExpr(NAryExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ return base.VisitNAryExpr((NAryExpr)node.Clone());
+ }
+ public override Expr VisitOldExpr(OldExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ return base.VisitOldExpr((OldExpr)node.Clone());
+ }
+ public override Procedure VisitProcedure(Procedure node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Procedure>() != null);
+ return base.VisitProcedure((Procedure)node.Clone());
+ }
+ public override Program VisitProgram(Program node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Program>() != null);
+ return base.VisitProgram((Program)node.Clone());
+ }
+ public override BinderExpr VisitBinderExpr(BinderExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<BinderExpr>() != null);
+ return base.VisitBinderExpr((BinderExpr)node.Clone());
+ }
+ public override Cmd VisitRE(RE node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+ return base.VisitRE((RE)node.Clone());
+ }
+ public override RESeq VisitRESeq(RESeq reSeq) {
+ //Contract.Requires(reSeq != null);
+ Contract.Ensures(Contract.Result<RESeq>() != null);
+ return base.VisitRESeq(new RESeq(reSeq));
+ }
+ public override ReturnCmd VisitReturnCmd(ReturnCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<ReturnCmd>() != null);
+ return base.VisitReturnCmd((ReturnCmd)node.Clone());
+ }
+ public override ReturnExprCmd VisitReturnExprCmd(ReturnExprCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<ReturnExprCmd>() != null);
return base.VisitReturnExprCmd((ReturnExprCmd)node.Clone());
}
- public override Sequential! VisitSequential(Sequential! node)
- {
- return base.VisitSequential ((Sequential) node.Clone());
- }
- public override AssignLhs! VisitSimpleAssignLhs(SimpleAssignLhs! node)
- {
- return base.VisitSimpleAssignLhs ((SimpleAssignLhs)node.Clone());
- }
- public override Cmd! VisitStateCmd(StateCmd! node)
- {
- return base.VisitStateCmd ((StateCmd)node.Clone());
- }
- public override TransferCmd! VisitTransferCmd(TransferCmd! node)
- {
- return base.VisitTransferCmd ((TransferCmd) node.Clone());
- }
- public override Trigger! VisitTrigger(Trigger! node)
- {
- return base.VisitTrigger ((Trigger) node.Clone());
- }
- public override Type! VisitType(Type! node)
- {
+ public override Sequential VisitSequential(Sequential node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Sequential>() != null);
+ return base.VisitSequential((Sequential)node.Clone());
+ }
+ public override AssignLhs VisitSimpleAssignLhs(SimpleAssignLhs node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<AssignLhs>() != null);
+ return base.VisitSimpleAssignLhs((SimpleAssignLhs)node.Clone());
+ }
+ public override Cmd VisitStateCmd(StateCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+ return base.VisitStateCmd((StateCmd)node.Clone());
+ }
+ public override TransferCmd VisitTransferCmd(TransferCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<TransferCmd>() != null);
+ return base.VisitTransferCmd((TransferCmd)node.Clone());
+ }
+ public override Trigger VisitTrigger(Trigger node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Trigger>() != null);
+ return base.VisitTrigger((Trigger)node.Clone());
+ }
+ public override Type VisitType(Type node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
// do /not/ clone the type recursively
return (Type)node.Clone();
}
- public override TypedIdent! VisitTypedIdent(TypedIdent! node)
- {
- return base.VisitTypedIdent ((TypedIdent) node.Clone());
+ public override TypedIdent VisitTypedIdent(TypedIdent node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<TypedIdent>() != null);
+ return base.VisitTypedIdent((TypedIdent)node.Clone());
}
- public override Variable! VisitVariable(Variable! node)
- {
+ public override Variable VisitVariable(Variable node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Variable>() != null);
return node;
}
- public override VariableSeq! VisitVariableSeq(VariableSeq! variableSeq)
- {
- return base.VisitVariableSeq (new VariableSeq(variableSeq));
+ public override VariableSeq VisitVariableSeq(VariableSeq variableSeq) {
+ //Contract.Requires(variableSeq != null);
+ Contract.Ensures(Contract.Result<VariableSeq>() != null);
+ return base.VisitVariableSeq(new VariableSeq(variableSeq));
}
- public override Cmd! VisitAssertRequiresCmd(AssertRequiresCmd! node)
- {
+ public override Cmd VisitAssertRequiresCmd(AssertRequiresCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
return base.VisitAssertRequiresCmd((AssertRequiresCmd)node.Clone());
}
- public override Cmd! VisitAssertEnsuresCmd(AssertEnsuresCmd! node)
- {
+ public override Cmd VisitAssertEnsuresCmd(AssertEnsuresCmd node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
return base.VisitAssertEnsuresCmd((AssertEnsuresCmd)node.Clone());
- }
- public override Ensures! VisitEnsures(Ensures! node)
- {
- return base.VisitEnsures((Ensures)node.Clone());
- }
- public override Requires! VisitRequires(Requires! node)
- {
- return base.VisitRequires((Requires)node.Clone());
+ }
+ public override Ensures VisitEnsures(Ensures node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Ensures>() != null);
+ return base.VisitEnsures((Ensures)node.Clone());
+ }
+ public override Requires VisitRequires(Requires node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Requires>() != null);
+ return base.VisitRequires((Requires)node.Clone());
}
}
-
-
- #region A duplicator that also does substitutions for a set of variables
+
+
+ #region A duplicator that also does substitutions for a set of variables
/// <summary>
/// A substitution is a partial mapping from Variables to Exprs.
/// </summary>
- public delegate Expr/*?*/ Substitution(Variable! v);
-
- public static class Substituter
- {
- public static Substitution! SubstitutionFromHashtable(Hashtable/*Variable!->Expr!*/! map)
- {
+ public delegate Expr/*?*/ Substitution(Variable/*!*/ v);
+
+ public static class Substituter {
+ public static Substitution SubstitutionFromHashtable(Hashtable/*Variable!->Expr!*/ map) {
+ Contract.Requires(map != null);
+ Contract.Ensures(Contract.Result<Substitution>() != null);
// TODO: With Whidbey, could use anonymous functions.
return new Substitution(new CreateSubstitutionClosure(map).Method);
}
- private sealed class CreateSubstitutionClosure
- {
- Hashtable/*Variable!->Expr!*/! map;
- public CreateSubstitutionClosure(Hashtable/*Variable!->Expr!*/! map) { this.map = map; base(); }
- public Expr/*?*/ Method(Variable! v) { return (Expr) map[v]; }
+ private sealed class CreateSubstitutionClosure {
+ Hashtable/*Variable!->Expr!*//*!*/ map;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(map != null);
+ }
+
+ public CreateSubstitutionClosure(Hashtable/*Variable!->Expr!*/ map)
+ : base() {//BASEMOVE DANGER
+ Contract.Requires(map != null);
+ this.map = map; //:base();
+ }
+ public Expr/*?*/ Method(Variable v) {
+ Contract.Requires(v != null);
+ return (Expr)map[v];
+ }
}
-
+
/// <summary>
/// Apply a substitution to an expression. Any variables not in domain(subst)
/// is not changed. The substitutions applies within the "old", but the "old"
/// expression remains.
/// </summary>
- public static Expr! Apply(Substitution! subst, Expr! expr)
- {
- return (Expr) new NormalSubstituter(subst).Visit(expr);
+ public static Expr Apply(Substitution subst, Expr expr) {
+ Contract.Requires(expr != null);
+ Contract.Requires(subst != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ return (Expr)new NormalSubstituter(subst).Visit(expr);
}
/// <summary>
@@ -327,9 +402,11 @@ namespace Microsoft.Boogie
/// is not changed. The substitutions applies within the "old", but the "old"
/// expression remains.
/// </summary>
- public static Cmd! Apply(Substitution! subst, Cmd! cmd)
- {
- return (Cmd) new NormalSubstituter(subst).Visit(cmd);
+ public static Cmd Apply(Substitution subst, Cmd cmd) {
+ Contract.Requires(cmd != null);
+ Contract.Requires(subst != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+ return (Cmd)new NormalSubstituter(subst).Visit(cmd);
}
/// <summary>
@@ -339,11 +416,14 @@ namespace Microsoft.Boogie
/// variables in domain(oldExpr), apply map "always" to variables in
/// domain(always)-domain(oldExpr), and leave variable unchanged otherwise.
/// </summary>
- public static Expr! ApplyReplacingOldExprs(Substitution! always, Substitution! forold, Expr! expr)
- {
- return (Expr) new ReplacingOldSubstituter(always, forold).Visit(expr);
+ public static Expr ApplyReplacingOldExprs(Substitution always, Substitution forold, Expr expr) {
+ Contract.Requires(expr != null);
+ Contract.Requires(forold != null);
+ Contract.Requires(always != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ return (Expr)new ReplacingOldSubstituter(always, forold).Visit(expr);
}
-
+
/// <summary>
/// Apply a substitution to a command replacing "old" expressions.
/// Outside "old" expressions, the substitution "always" is applied; any variable not in
@@ -351,58 +431,82 @@ namespace Microsoft.Boogie
/// variables in domain(oldExpr), apply map "always" to variables in
/// domain(always)-domain(oldExpr), and leave variable unchanged otherwise.
/// </summary>
- public static Cmd! ApplyReplacingOldExprs(Substitution! always, Substitution! forold, Cmd! cmd)
- {
- return (Cmd) new ReplacingOldSubstituter(always, forold).Visit(cmd);
- }
-
- private sealed class NormalSubstituter : Duplicator
- {
- private readonly Substitution! subst;
- public NormalSubstituter(Substitution! subst) { this.subst = subst; base(); }
-
- public override Expr! VisitIdentifierExpr(IdentifierExpr! node)
- {
- Expr/*?*/ e = subst((!)node.Decl);
+ public static Cmd ApplyReplacingOldExprs(Substitution always, Substitution forold, Cmd cmd) {
+ Contract.Requires(cmd != null);
+ Contract.Requires(forold != null);
+ Contract.Requires(always != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+ return (Cmd)new ReplacingOldSubstituter(always, forold).Visit(cmd);
+ }
+
+ private sealed class NormalSubstituter : Duplicator {
+ private readonly Substitution/*!*/ subst;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(subst != null);
+ }
+
+ public NormalSubstituter(Substitution subst)
+ : base() {//BASEMOVE DANGER
+ Contract.Requires(subst != null);
+ this.subst = subst;
+ //:base();
+ }
+
+ public override Expr VisitIdentifierExpr(IdentifierExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ Expr/*?*/ e = subst(cce.NonNull(node.Decl));
return e == null ? base.VisitIdentifierExpr(node) : e;
}
}
-
- private sealed class ReplacingOldSubstituter : Duplicator
- {
- private readonly Substitution! always;
- private readonly Substitution! forold;
- public ReplacingOldSubstituter(Substitution! always, Substitution! forold)
- { this.always = always; this.forold = forold; base(); }
-
+
+ private sealed class ReplacingOldSubstituter : Duplicator {
+ private readonly Substitution/*!*/ always;
+ private readonly Substitution/*!*/ forold;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(always != null);
+ Contract.Invariant(forold != null);
+ }
+
+ public ReplacingOldSubstituter(Substitution always, Substitution forold)
+ : base() {//BASEMOVE DANGER
+ Contract.Requires(forold != null);
+ Contract.Requires(always != null);
+ this.always = always;
+ this.forold = forold;
+ //:base();
+ }
+
private bool insideOldExpr = false;
-
- public override Expr! VisitIdentifierExpr(IdentifierExpr! node)
- {
+
+ public override Expr VisitIdentifierExpr(IdentifierExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
Expr/*?*/ e = null;
-
- if (insideOldExpr)
- {
- e = forold((!)node.Decl);
+
+ if (insideOldExpr) {
+ e = forold(cce.NonNull(node.Decl));
}
-
- if (e == null)
- {
- e = always((!)node.Decl);
+
+ if (e == null) {
+ e = always(cce.NonNull(node.Decl));
}
-
+
return e == null ? base.VisitIdentifierExpr(node) : e;
}
-
- public override Expr! VisitOldExpr(OldExpr! node)
- {
+
+ public override Expr VisitOldExpr(OldExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
bool previouslyInOld = insideOldExpr;
insideOldExpr = true;
- Expr! e = (Expr!)this.Visit(node.Expr);
+ Expr/*!*/ e = (Expr/*!*/)cce.NonNull(this.Visit(node.Expr));
insideOldExpr = previouslyInOld;
return e;
}
}
}
#endregion
-}
+} \ No newline at end of file
diff --git a/Source/Core/GraphAlgorithms.cs b/Source/Core/GraphAlgorithms.cs
index e1303316..e901005e 100644
--- a/Source/Core/GraphAlgorithms.cs
+++ b/Source/Core/GraphAlgorithms.cs
@@ -4,88 +4,145 @@
//
//-----------------------------------------------------------------------------
using System.Collections.Generic;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
-namespace Microsoft.Boogie
-{
- public delegate System.Collections.IEnumerable/*<Node!>*/! Adjacency<T>(T! node);
+namespace Microsoft.Boogie {
+ public delegate System.Collections.IEnumerable/*<Node!>*//*!*/ Adjacency<T>(T/*!*/ node);
// An SCC is a set of nodes
- public sealed class SCC<Node> : ICollection<Node>
- {
- private IDictionary<Node,object>! nodesMap = new Dictionary<Node,object>();
- private ICollection<Node>! nodes { get { return (!) nodesMap.Keys; } }
-
- [Pure] [GlobalAccess(false)] [Escapes(true,false)]
- System.Collections.IEnumerator! System.Collections.IEnumerable.GetEnumerator()
- {
+ public sealed class SCC<Node> : ICollection<Node> {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(nodesMap != null);
+ }
+
+ private IDictionary<Node, object>/*!*/ nodesMap = new Dictionary<Node, object>();
+ private ICollection<Node>/*!*/ nodes {
+ get {
+ return cce.NonNull(nodesMap.Keys);
+ }
+ }
+
+ [Pure]
+ [GlobalAccess(false)]
+ [Escapes(true, false)]
+ System.Collections.IEnumerator/*!*/ System.Collections.IEnumerable.GetEnumerator() {
+ Contract.Ensures(Contract.Result<System.Collections.IEnumerator>() != null);
+
return ((System.Collections.IEnumerable)nodes).GetEnumerator();
}
- [Pure] [GlobalAccess(false)] [Escapes(true,false)]
- IEnumerator<Node>! IEnumerable<Node>.GetEnumerator()
- {
+ [Pure]
+ [GlobalAccess(false)]
+ [Escapes(true, false)]
+ IEnumerator<Node>/*!*/ IEnumerable<Node>.GetEnumerator() {
+ Contract.Ensures(Contract.Result<IEnumerator<Node>>() != null);
+
return ((IEnumerable<Node>)nodes).GetEnumerator();
}
-
- public int Count { get { return nodes.Count; } }
- public bool IsReadOnly { get { return nodesMap.IsReadOnly; } }
- public void Add(Node item) { nodesMap.Add(item,null); }
- public void Clear() { nodesMap.Clear(); }
+
+ public int Count {
+ get {
+ return nodes.Count;
+ }
+ }
+ public bool IsReadOnly {
+ get {
+ return nodesMap.IsReadOnly;
+ }
+ }
+ public void Add(Node item) {
+ nodesMap.Add(item, null);
+ }
+ public void Clear() {
+ nodesMap.Clear();
+ }
[Pure]
- public bool Contains(Node item) { return nodesMap.ContainsKey(item); }
- public void CopyTo(Node[]! array, int arrayIndex) { nodes.CopyTo(array, arrayIndex); }
- public bool Remove(Node item) { return nodesMap.Remove(item); }
+ public bool Contains(Node item) {
+ return nodesMap.ContainsKey(item);
+ }
+ public void CopyTo(Node[] array, int arrayIndex) {
+ //Contract.Requires(array != null);
+ nodes.CopyTo(array, arrayIndex);
+ }
+ public bool Remove(Node item) {
+ return nodesMap.Remove(item);
+ }
}
- public sealed class StronglyConnectedComponents<Node> : IEnumerable<SCC<Node>!>
- {
- private readonly IDictionary<Node!,object>! graph;
- private readonly Adjacency<Node>! preds;
- private readonly Adjacency<Node>! succs;
+ public sealed class StronglyConnectedComponents<Node> : IEnumerable<SCC<Node>/*!*/> {
+ private readonly IDictionary<Node/*!*/, object/*!*/>/*!*/ graph;
+ [ContractInvariantMethod]
+ void graphInvariantMethod() {
+ Contract.Invariant(cce.NonNullElements(graph));
+ Contract.Invariant(preds != null);
+ Contract.Invariant(succs != null);
+ }
+ private readonly Adjacency<Node>/*!*/ preds;
+ private readonly Adjacency<Node>/*!*/ succs;
private bool computed = false;
- public bool Computed { get { return computed; } }
-
+ public bool Computed {
+ get {
+ return computed;
+ }
+ }
+
[NotDelayed]
- public StronglyConnectedComponents(System.Collections.IEnumerable/*<Node!>*/! graph, Adjacency<Node>! preds, Adjacency<Node>! succs)
- ensures !Computed;
- {
- IDictionary<Node!,object>! dict = new Dictionary<Node!,object>();
- foreach (Node! n in graph) { dict.Add(n,null); }
-
+ public StronglyConnectedComponents(System.Collections.IEnumerable/*<Node!>*/ graph, Adjacency<Node> preds, Adjacency<Node> succs)
+ : base() {//BASEMOVE DANGER
+ Contract.Requires(succs != null);
+ Contract.Requires(preds != null);
+ Contract.Requires(graph != null);
+ Contract.Ensures(!Computed);
+ IDictionary<Node/*!*/, object>/*!*/ dict = new Dictionary<Node/*!*/, object>();
+ foreach (Node/*!*/ n in graph) {
+ Contract.Assert(n != null);
+ dict.Add(n, null);
+ }
+
this.graph = dict;
this.preds = preds;
this.succs = succs;
- base();
+ //:base();
}
-
- [Pure] [GlobalAccess(false)] [Escapes(true,false)]
- System.Collections.IEnumerator! System.Collections.IEnumerable.GetEnumerator()
- {
+
+ [Pure]
+ [GlobalAccess(false)]
+ [Escapes(true, false)]
+ System.Collections.IEnumerator/*!*/ System.Collections.IEnumerable.GetEnumerator() {
+ Contract.Ensures(Contract.Result<System.Collections.IEnumerator>() != null);
+
return ((System.Collections.IEnumerable)sccs).GetEnumerator();
}
- [Pure] [GlobalAccess(false)] [Escapes(true,false)]
- IEnumerator<SCC<Node>!>! IEnumerable<SCC<Node>!>.GetEnumerator()
- {
- assume Computed;
- return ((IEnumerable<SCC<Node>!>)sccs).GetEnumerator();
+ [Pure]
+ [GlobalAccess(false)]
+ [Escapes(true, false)]
+ IEnumerator<SCC<Node>/*!*/>/*!*/ IEnumerable<SCC<Node>/*!*/>.GetEnumerator() {
+ Contract.Ensures(Contract.Result<IEnumerator<SCC<Node>>>() != null);
+
+ Contract.Assume(Computed);
+ Contract.Assert(cce.NonNullElements((IEnumerable<SCC<Node>/*!*/>)sccs));//REVIEW
+ return ((IEnumerable<SCC<Node>/*!*/>)sccs).GetEnumerator();
+ }
+
+ private readonly IList<SCC<Node>/*!*/>/*!*/ sccs = new List<SCC<Node>/*!*/>();
+ [ContractInvariantMethod]
+ void sccsInvariant() {
+ Contract.Invariant(cce.NonNullElements(sccs));
}
- private readonly IList<SCC<Node>!>! sccs = new List<SCC<Node>!>();
- public void Compute()
- requires !Computed;
- ensures Computed;
- {
+ public void Compute() {
+ Contract.Requires(!Computed);
+ Contract.Ensures(Computed);
// Compute post times on graph with edges reversed
this.dfsNext = this.preds;
- foreach (Node! n in (!)graph.Keys)
- {
- if (!seen.ContainsKey(n))
- {
+ foreach (Node/*!*/ n in cce.NonNull(graph.Keys)) {
+ Contract.Assert(n != null);
+ if (!seen.ContainsKey(n)) {
OrderNodes(n);
}
}
@@ -95,13 +152,12 @@ namespace Microsoft.Boogie
// Compute SCCs
this.dfsNext = this.succs;
- while (postOrder.Count > 0)
- {
- Node! n = postOrder.Pop();
+ while (postOrder.Count > 0) {
+ Node/*!*/ n = postOrder.Pop();
+ Contract.Assert(n != null);
- if (!seen.ContainsKey(n))
- {
- SCC<Node>! curr = new SCC<Node>();
+ if (!seen.ContainsKey(n)) {
+ SCC<Node>/*!*/ curr = new SCC<Node>();
FindSCCs(n, curr);
sccs.Add(curr);
}
@@ -109,61 +165,74 @@ namespace Microsoft.Boogie
// Clear seen
seen.Clear();
-
+
this.computed = true;
}
private Adjacency<Node>/*?*/ dfsNext = null;
- private readonly IDictionary<Node!,object>! seen = new Dictionary<Node!,object>();
- private readonly Stack<Node!>! postOrder = new Stack<Node!>();
-
+ private readonly IDictionary<Node/*!*/, object>/*!*/ seen = new Dictionary<Node/*!*/, object>();
+ private readonly Stack<Node/*!*/>/*!*/ postOrder = new Stack<Node/*!*/>();
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(seen != null && cce.NonNullElements(seen.Keys));
+ Contract.Invariant(cce.NonNullElements(postOrder));
+ }
+
+
// DFS to order nodes by post times
- private void OrderNodes(Node! node)
- {
- seen.Add(node,null);
-
- assert dfsNext != null;
- System.Collections.IEnumerable! nexts = dfsNext(node);
- foreach (Node! n in nexts)
- {
- if (graph.ContainsKey(n) && !seen.ContainsKey(n)) { OrderNodes(n); }
+ private void OrderNodes(Node node) {
+ Contract.Requires(node != null);
+ seen.Add(node, null);
+
+ Contract.Assert(dfsNext != null);
+ System.Collections.IEnumerable/*!*/ nexts = dfsNext(node);
+ Contract.Assert(nexts != null);
+ foreach (Node/*!*/ n in nexts) {
+ Contract.Assert(n != null);
+ if (graph.ContainsKey(n) && !seen.ContainsKey(n)) {
+ OrderNodes(n);
+ }
}
postOrder.Push(node);
}
// DFS to compute SCCs
- private void FindSCCs(Node! node, SCC<Node>! currSCC)
+ private void FindSCCs(Node node, SCC<Node> currSCC) {
+ Contract.Requires(currSCC != null);
+ Contract.Requires(node != null);
//modifies currSCC.*;
- {
- seen.Add(node,null);
+ seen.Add(node, null);
currSCC.Add(node);
- assert dfsNext != null;
- System.Collections.IEnumerable! nexts = dfsNext(node);
- foreach (Node! n in nexts)
- {
- if (graph.ContainsKey(n) && !seen.ContainsKey(n)) { FindSCCs(n,currSCC); }
+ Contract.Assert(dfsNext != null);
+ System.Collections.IEnumerable/*!*/ nexts = dfsNext(node);
+ Contract.Assert(nexts != null);
+ foreach (Node/*!*/ n in nexts) {
+ Contract.Assert(n != null);
+ if (graph.ContainsKey(n) && !seen.ContainsKey(n)) {
+ FindSCCs(n, currSCC);
+ }
}
}
[Pure]
- public override string! ToString()
- {
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
string outStr = "";
int i = 0;
- foreach(ICollection<Node> component in this)
- {
- string! tmp = System.String.Format("\nComponent #{0} = ", i++);
+ foreach (ICollection<Node> component in this) {
+ string/*!*/ tmp = System.String.Format("\nComponent #{0} = ", i++);
+ Contract.Assert(tmp != null);
outStr += tmp;
bool firstInRow = true;
- foreach(Node b in component)
- {
- string! tmpComponent = System.String.Format("{0}{1}", firstInRow? "" : ", ", b);
+ foreach (Node b in component) {
+ string/*!*/ tmpComponent = System.String.Format("{0}{1}", firstInRow ? "" : ", ", b);
+ Contract.Assert(tmpComponent != null);
outStr += tmpComponent;
firstInRow = false;
}
diff --git a/Source/Core/Inline.cs b/Source/Core/Inline.cs
index 0db27d6d..7ae3a098 100644
--- a/Source/Core/Inline.cs
+++ b/Source/Core/Inline.cs
@@ -4,29 +4,38 @@
//
//-----------------------------------------------------------------------------
namespace Microsoft.Boogie {
-
+
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
- using BoogiePL;
+ using System.Diagnostics.Contracts;
+ using BoogiePL=Microsoft.Boogie;
using System.Diagnostics;
using System.Text.RegularExpressions; // for procedure inlining
// this callback is called before inlining a procedure
- public delegate void InlineCallback(Implementation! impl);
+ public delegate void InlineCallback(Implementation/*!*/ impl);
- public class Inliner
- {
+ public class Inliner {
private InlineCallback inlineCallback;
-
- protected CodeCopier! codeCopier;
-
- protected Dictionary<string!,int>! /* Procedure.Name -> int */ recursiveProcUnrollMap;
-
- protected Dictionary<string!,int>! /* Procedure.Name -> int */ inlinedProcLblMap;
-
- protected void NextInlinedProcLabel(string! procName) {
+
+ protected CodeCopier/*!*/ codeCopier;
+
+ protected Dictionary<string/*!*/, int>/*!*/ /* Procedure.Name -> int */ recursiveProcUnrollMap;
+
+ protected Dictionary<string/*!*/, int>/*!*/ /* Procedure.Name -> int */ inlinedProcLblMap;
+
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(codeCopier != null);
+ Contract.Invariant(cce.NonNullElements(recursiveProcUnrollMap));
+ Contract.Invariant(cce.NonNullElements(inlinedProcLblMap));
+ }
+
+
+ protected void NextInlinedProcLabel(string procName) {
+ Contract.Requires(procName != null);
int currentId;
if (inlinedProcLblMap.TryGetValue(procName, out currentId)) {
inlinedProcLblMap[procName] = currentId + 1;
@@ -34,8 +43,10 @@ namespace Microsoft.Boogie {
inlinedProcLblMap.Add(procName, 0);
}
}
-
- protected string! GetInlinedProcLabel(string! procName) {
+
+ protected string GetInlinedProcLabel(string procName) {
+ Contract.Requires(procName != null);
+ Contract.Ensures(Contract.Result<string>() != null);
int currentId;
if (!inlinedProcLblMap.TryGetValue(procName, out currentId)) {
currentId = 0;
@@ -43,69 +54,81 @@ namespace Microsoft.Boogie {
}
return "inline$" + procName + "$" + currentId;
}
-
- protected string! GetProcVarName(string! procName, string! formalName) {
- string! prefix = GetInlinedProcLabel(procName);
+
+ protected string GetProcVarName(string procName, string formalName) {
+ Contract.Requires(formalName != null);
+ Contract.Requires(procName != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+ string/*!*/ prefix = GetInlinedProcLabel(procName);
+ Contract.Assert(prefix != null);
return prefix + "$" + formalName;
- }
-
- protected Inliner(InlineCallback cb) {
- inlinedProcLblMap = new Dictionary<string!,int>();
- recursiveProcUnrollMap = new Dictionary<string!,int>();
+ }
+
+ protected Inliner(InlineCallback cb) {
+ inlinedProcLblMap = new Dictionary<string/*!*/, int>();
+ recursiveProcUnrollMap = new Dictionary<string/*!*/, int>();
codeCopier = new CodeCopier();
inlineCallback = cb;
}
-
- public static void ProcessImplementation(Program! program, Implementation! impl, InlineCallback cb)
- requires impl.Proc != null;
- {
+
+ public static void ProcessImplementation(Program program, Implementation impl, InlineCallback cb) {
+ Contract.Requires(impl != null);
+ Contract.Requires(program != null);
+ Contract.Requires(impl.Proc != null);
Inliner inliner = new Inliner(cb);
-
- VariableSeq! newInParams = new VariableSeq(impl.InParams);
- VariableSeq! newOutParams = new VariableSeq(impl.OutParams);
- VariableSeq! newLocalVars = new VariableSeq(impl.LocVars);
-
- IdentifierExprSeq! newModifies = new IdentifierExprSeq(impl.Proc.Modifies);
-
+
+ VariableSeq/*!*/ newInParams = new VariableSeq(impl.InParams);
+ Contract.Assert(newInParams != null);
+ VariableSeq/*!*/ newOutParams = new VariableSeq(impl.OutParams);
+ Contract.Assert(newOutParams != null);
+ VariableSeq/*!*/ newLocalVars = new VariableSeq(impl.LocVars);
+ Contract.Assert(newLocalVars != null);
+ IdentifierExprSeq/*!*/ newModifies = new IdentifierExprSeq(impl.Proc.Modifies);
+ Contract.Assert(newModifies != null);
+
bool inlined = false;
- List<Block!>! newBlocks = inliner.DoInline(impl.Blocks, program, newLocalVars, newModifies, out inlined);
+ List<Block/*!*/>/*!*/ newBlocks = inliner.DoInline(impl.Blocks, program, newLocalVars, newModifies, out inlined);
+ Contract.Assert(cce.NonNullElements(newBlocks));
+
+ if (!inlined)
+ return;
- if (!inlined) return;
-
impl.InParams = newInParams;
impl.OutParams = newOutParams;
impl.LocVars = newLocalVars;
impl.Blocks = newBlocks;
impl.Proc.Modifies = newModifies;
-
+
impl.ResetImplFormalMap();
-
+
// we need to resolve the new code
inliner.ResolveImpl(program, impl);
-
- if(CommandLineOptions.Clo.PrintInlined) {
+
+ if (CommandLineOptions.Clo.PrintInlined) {
inliner.EmitImpl(impl);
}
}
-
-
- public static void ProcessImplementation(Program! program, Implementation! impl)
- requires impl.Proc != null;
- {
+
+
+ public static void ProcessImplementation(Program program, Implementation impl) {
+ Contract.Requires(impl != null);
+ Contract.Requires(program != null);
+ Contract.Requires(impl.Proc != null);
ProcessImplementation(program, impl, null);
}
-
- protected void EmitImpl(Implementation! impl)
- requires impl.Proc != null;
- {
+
+ protected void EmitImpl(Implementation impl) {
+ Contract.Requires(impl != null);
+ Contract.Requires(impl.Proc != null);
Console.WriteLine("after inlining procedure calls");
impl.Proc.Emit(new TokenTextWriter("<console>", Console.Out), 0);
impl.Emit(new TokenTextWriter("<console>", Console.Out), 0);
}
-
- private sealed class DummyErrorSink : IErrorSink
- {
- public void Error(IToken! tok, string! msg) {
+
+ private sealed class DummyErrorSink : IErrorSink {
+ public void Error(IToken tok, string msg) {
+ //Contract.Requires(msg != null);
+ //Contract.Requires(tok != null);
// FIXME
// noop.
// This is required because during the resolution, some resolution errors happen
@@ -113,28 +136,31 @@ namespace Microsoft.Boogie {
}
}
- protected void ResolveImpl(Program! program, Implementation! impl)
- ensures impl.Proc != null;
- {
+ protected void ResolveImpl(Program program, Implementation impl) {
+ Contract.Requires(impl != null);
+ Contract.Requires(program != null);
+ Contract.Ensures(impl.Proc != null);
ResolutionContext rc = new ResolutionContext(new DummyErrorSink());
-
- foreach(Declaration decl in program.TopLevelDeclarations) {
+
+ foreach (Declaration decl in program.TopLevelDeclarations) {
decl.Register(rc);
}
-
+
impl.Proc = null; // to force Resolve() redo the operation
impl.Resolve(rc);
-
+
TypecheckingContext tc = new TypecheckingContext(new DummyErrorSink());
-
+
impl.Typecheck(tc);
}
-
-
+
+
// returns true if it is ok to further unroll the procedure
// otherwise, the procedure is not inlined at the call site
- protected int GetInlineCount(Implementation! impl) {
- string! procName = impl.Name;
+ protected int GetInlineCount(Implementation impl) {
+ Contract.Requires(impl != null);
+ string/*!*/ procName = impl.Name;
+ Contract.Assert(procName != null);
int c;
if (recursiveProcUnrollMap.TryGetValue(procName, out c)) {
return c;
@@ -146,103 +172,115 @@ namespace Microsoft.Boogie {
if (impl.Proc != null) {
impl.Proc.CheckIntAttribute("inline", ref c);
}
-
+
recursiveProcUnrollMap[procName] = c;
return c;
}
-
- void CheckRecursion(Implementation! impl, Stack<Procedure!>! callStack) {
- foreach (Procedure! p in callStack) {
+
+ void CheckRecursion(Implementation impl, Stack<Procedure/*!*/>/*!*/ callStack) {
+ Contract.Requires(impl != null);
+ Contract.Requires(cce.NonNullElements(callStack));
+ foreach (Procedure/*!*/ p in callStack) {
+ Contract.Assert(p != null);
if (p == impl.Proc) {
string msg = "";
- foreach (Procedure! p in callStack) {
- msg = p.Name + " -> " + msg;
+ foreach (Procedure/*!*/ q in callStack) {
+ Contract.Assert(q != null);
+ msg = q.Name + " -> " + msg;
}
msg += p.Name;
//checkingCtx.Error(impl, "inlined procedure is recursive, call stack: {0}", msg);
}
}
}
-
- private List<Block!>! DoInlineBlocks(Stack<Procedure!>! callStack, List<Block!>! blocks, Program! program,
- VariableSeq! newLocalVars, IdentifierExprSeq! newModifies, ref bool inlinedSomething)
- {
- List<Block!>! newBlocks = new List<Block!>();
- foreach(Block block in blocks) {
- TransferCmd! transferCmd = (!) block.TransferCmd;
+ private List<Block/*!*/>/*!*/ DoInlineBlocks(Stack<Procedure/*!*/>/*!*/ callStack, List<Block/*!*/>/*!*/ blocks, Program/*!*/ program,
+ VariableSeq/*!*/ newLocalVars, IdentifierExprSeq/*!*/ newModifies, ref bool inlinedSomething) {
+ Contract.Requires(cce.NonNullElements(callStack));
+ Contract.Requires(cce.NonNullElements(blocks));
+ Contract.Requires(program != null);
+ Contract.Requires(newLocalVars != null);
+ Contract.Requires(newModifies != null);
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Block>>()));
+ List<Block/*!*/>/*!*/ newBlocks = new List<Block/*!*/>();
+
+
+ foreach (Block block in blocks) {
+ TransferCmd/*!*/ transferCmd = cce.NonNull(block.TransferCmd);
CmdSeq cmds = block.Cmds;
CmdSeq newCmds = new CmdSeq();
Block newBlock;
string label = block.Label;
int lblCount = 0;
-
- for(int i = 0; i < cmds.Length; ++i) {
- Cmd cmd = cmds[i];
+
+ for (int i = 0; i < cmds.Length; ++i) {
+ Cmd cmd = cmds[i];
CallCmd callCmd = cmd as CallCmd;
-
- if(callCmd == null) {
+
+ if (callCmd == null) {
// if not call command, leave it as is
- newCmds.Add(codeCopier.CopyCmd(cmd));
+ newCmds.Add(codeCopier.CopyCmd(cmd));
} else {
- assert(callCmd.Proc != null);
+ Contract.Assert(callCmd.Proc != null);
Procedure proc = null;
Implementation impl = null;
string calleeName = callCmd.Proc.Name;
-
+
int inline = -1;
// *** now we do not allow constructors to be inlined
if (!calleeName.Contains("..ctor")) {
// FIXME why on earth are we searching by name?!
bool implExists = FindProcImpl(program, calleeName, out proc, out impl);
- assume(!implExists || (proc != null && impl != null));
+ Contract.Assume(!implExists || (proc != null && impl != null));
if (implExists) {
- inline = GetInlineCount((!)impl);
+ inline = GetInlineCount(cce.NonNull(impl));
}
- }
+ }
+
+ Contract.Assert(inline == -1 || impl != null);
- assert(inline == -1 || impl != null);
-
if (inline > 0) { // at least one block should exist
- assume(impl != null && proc != null);
- assert(((!)impl.OriginalBlocks).Count > 0);
+ Contract.Assume(impl != null && proc != null);
+ Contract.Assert(cce.NonNull(impl.OriginalBlocks).Count > 0);
inlinedSomething = true;
-
+
// do inline now
int nextlblCount = lblCount + 1;
string nextBlockLabel = label + "$" + nextlblCount;
-
+
// run the callback before each inline
- if(inlineCallback != null) {
+ if (inlineCallback != null) {
inlineCallback(impl);
}
-
+
// increment the counter for the procedure to be used in constructing the locals and formals
NextInlinedProcLabel(proc.Name);
-
+
BeginInline(newLocalVars, newModifies, proc, impl);
-
- List<Block!>! inlinedBlocks = CreateInlinedBlocks(callCmd, proc, impl, nextBlockLabel);
-
+
+ List<Block/*!*/>/*!*/ inlinedBlocks = CreateInlinedBlocks(callCmd, proc, impl, nextBlockLabel);
+ Contract.Assert(cce.NonNullElements(inlinedBlocks));
+
EndInline();
- recursiveProcUnrollMap[impl.Name] = recursiveProcUnrollMap[impl.Name] - 1;
- callStack.Push((!)impl.Proc);
+ recursiveProcUnrollMap[impl.Name] = recursiveProcUnrollMap[impl.Name] - 1;
+ callStack.Push(cce.NonNull(impl.Proc));
inlinedBlocks = DoInlineBlocks(callStack, inlinedBlocks, program, newLocalVars, newModifies, ref inlinedSomething);
callStack.Pop();
recursiveProcUnrollMap[impl.Name] = recursiveProcUnrollMap[impl.Name] + 1;
-
- Block! startBlock = inlinedBlocks[0];
+
+ Block/*!*/ startBlock = inlinedBlocks[0];
+ Contract.Assert(startBlock != null);
GotoCmd gotoCmd = new GotoCmd(Token.NoToken, new StringSeq(startBlock.Label));
newBlock = new Block(block.tok, ((lblCount == 0) ? (label) : (label + "$" + lblCount)), newCmds, gotoCmd);
-
+
newBlocks.Add(newBlock);
newBlocks.AddRange(inlinedBlocks);
-
+
lblCount = nextlblCount;
- newCmds = new CmdSeq();
+ newCmds = new CmdSeq();
} else if (inline == 0) {
inlinedSomething = true;
if (CommandLineOptions.Clo.ProcedureInlining == CommandLineOptions.Inlining.Assert) {
@@ -256,11 +294,11 @@ namespace Microsoft.Boogie {
newCmds.Add(codeCopier.CopyCmd(callCmd));
}
} else {
- newCmds.Add(codeCopier.CopyCmd(callCmd));
- }
+ newCmds.Add(codeCopier.CopyCmd(callCmd));
+ }
}
}
-
+
newBlock = new Block(block.tok, ((lblCount == 0) ? (label) : (label + "$" + lblCount)), newCmds, codeCopier.CopyTransferCmd(transferCmd));
newBlocks.Add(newBlock);
}
@@ -268,271 +306,300 @@ namespace Microsoft.Boogie {
return newBlocks;
}
- protected List<Block!>! DoInline(List<Block!>! blocks, Program! program, VariableSeq! newLocalVars, IdentifierExprSeq! newModifies, out bool inlined)
- {
+ protected List<Block/*!*/>/*!*/ DoInline(List<Block/*!*/>/*!*/ blocks, Program program, VariableSeq newLocalVars, IdentifierExprSeq newModifies, out bool inlined) {
+ Contract.Requires(newModifies != null);
+ Contract.Requires(newLocalVars != null);
+ Contract.Requires(program != null);
+ Contract.Requires(cce.NonNullElements(blocks));
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Block>>()));
inlinedProcLblMap.Clear();
recursiveProcUnrollMap.Clear();
-
+
inlined = false;
- return DoInlineBlocks(new Stack<Procedure!>(), blocks, program, newLocalVars, newModifies, ref inlined);
+ return DoInlineBlocks(new Stack<Procedure/*!*/>(), blocks, program, newLocalVars, newModifies, ref inlined);
}
-
- protected void BeginInline(VariableSeq! newLocalVars, IdentifierExprSeq! newModifies, Procedure! proc, Implementation! impl) {
+
+ protected void BeginInline(VariableSeq newLocalVars, IdentifierExprSeq newModifies, Procedure proc, Implementation impl) {
+ Contract.Requires(impl != null);
+ Contract.Requires(proc != null);
+ Contract.Requires(newModifies != null);
+ Contract.Requires(newLocalVars != null);
Hashtable substMap = new Hashtable();
-
- foreach(Variable! locVar in (!)impl.OriginalLocVars) {
+
+ foreach (Variable/*!*/ locVar in cce.NonNull(impl.OriginalLocVars)) {
+ Contract.Assert(locVar != null);
LocalVariable localVar = new LocalVariable(Token.NoToken, new TypedIdent(Token.NoToken, GetProcVarName(proc.Name, locVar.Name), locVar.TypedIdent.Type, locVar.TypedIdent.WhereExpr));
newLocalVars.Add(localVar);
IdentifierExpr ie = new IdentifierExpr(Token.NoToken, localVar);
substMap.Add(locVar, ie);
}
-
+
for (int i = 0; i < impl.InParams.Length; i++) {
- Variable inVar = (!) impl.InParams[i];
+ Variable inVar = cce.NonNull(impl.InParams[i]);
LocalVariable localVar = new LocalVariable(Token.NoToken, new TypedIdent(Token.NoToken, GetProcVarName(proc.Name, inVar.Name), inVar.TypedIdent.Type, inVar.TypedIdent.WhereExpr));
newLocalVars.Add(localVar);
IdentifierExpr ie = new IdentifierExpr(Token.NoToken, localVar);
substMap.Add(inVar, ie);
// also add a substitution from the corresponding formal occurring in the PROCEDURE declaration
- Variable procInVar = (!)proc.InParams[i];
+ Variable procInVar = cce.NonNull(proc.InParams[i]);
if (procInVar != inVar) {
substMap.Add(procInVar, ie);
}
}
-
+
for (int i = 0; i < impl.OutParams.Length; i++) {
- Variable outVar = (!) impl.OutParams[i];
+ Variable outVar = cce.NonNull(impl.OutParams[i]);
LocalVariable localVar = new LocalVariable(Token.NoToken, new TypedIdent(Token.NoToken, GetProcVarName(proc.Name, outVar.Name), outVar.TypedIdent.Type, outVar.TypedIdent.WhereExpr));
newLocalVars.Add(localVar);
IdentifierExpr ie = new IdentifierExpr(Token.NoToken, localVar);
substMap.Add(outVar, ie);
// also add a substitution from the corresponding formal occurring in the PROCEDURE declaration
- Variable procOutVar = (!)proc.OutParams[i];
+ Variable procOutVar = cce.NonNull(proc.OutParams[i]);
if (procOutVar != outVar) {
substMap.Add(procOutVar, ie);
}
}
-
+
Hashtable /*Variable -> Expr*/ substMapOld = new Hashtable/*Variable -> Expr*/();
-
- foreach (IdentifierExpr! mie in proc.Modifies) {
- Variable! mVar = (!) mie.Decl;
+
+ foreach (IdentifierExpr/*!*/ mie in proc.Modifies) {
+ Contract.Assert(mie != null);
+ Variable/*!*/ mVar = cce.NonNull(mie.Decl);
LocalVariable localVar = new LocalVariable(Token.NoToken, new TypedIdent(Token.NoToken, GetProcVarName(proc.Name, mVar.Name), mVar.TypedIdent.Type));
newLocalVars.Add(localVar);
IdentifierExpr ie = new IdentifierExpr(Token.NoToken, localVar);
substMapOld.Add(mVar, ie);
// FIXME why are we doing this? the modifies list should already include them.
// add the modified variable to the modifies list of the procedure
- if(!newModifies.Has(mie)) {
+ if (!newModifies.Has(mie)) {
newModifies.Add(mie);
}
}
-
- codeCopier.Subst = Substituter.SubstitutionFromHashtable(substMap);
- codeCopier.OldSubst = Substituter.SubstitutionFromHashtable(substMapOld);
+
+ codeCopier.Subst = Substituter.SubstitutionFromHashtable(substMap);
+ codeCopier.OldSubst = Substituter.SubstitutionFromHashtable(substMapOld);
}
-
+
protected void EndInline() {
codeCopier.Subst = null;
codeCopier.OldSubst = null;
}
-
-
+
+
// result[0] is the entry block
- protected List<Block!>! CreateInlinedBlocks(CallCmd! callCmd, Procedure! proc, Implementation! impl, string! nextBlockLabel)
- requires (codeCopier.Subst != null);
- requires (codeCopier.OldSubst != null);
- {
-
- List<Block!>! implBlocks = (!)impl.OriginalBlocks;
- assert (implBlocks.Count > 0);
-
+ protected List<Block/*!*/>/*!*/ CreateInlinedBlocks(CallCmd callCmd, Procedure proc, Implementation impl, string nextBlockLabel) {
+ Contract.Requires(nextBlockLabel != null);
+ Contract.Requires(impl != null);
+ Contract.Requires(proc != null);
+ Contract.Requires(callCmd != null);
+ Contract.Requires(((codeCopier.Subst != null)));
+
+ Contract.Requires((codeCopier.OldSubst != null));
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Block>>()));
+ List<Block/*!*/>/*!*/ implBlocks = cce.NonNull(impl.OriginalBlocks);
+ Contract.Assert(implBlocks.Count > 0);
+
string startLabel = implBlocks[0].Label;
-
- List<Block!>! inlinedBlocks = new List<Block!>();
-
+
+ List<Block/*!*/>/*!*/ inlinedBlocks = new List<Block/*!*/>();
+
// create in block
CmdSeq inCmds = new CmdSeq();
-
+
// assign in parameters
- for(int i = 0; i < impl.InParams.Length; ++i) {
+ for (int i = 0; i < impl.InParams.Length; ++i) {
Cmd cmd = Cmd.SimpleAssign(impl.tok,
- (IdentifierExpr) (!) codeCopier.Subst( (!)impl.InParams[i]),
- (!)callCmd.Ins[i]);
+ (IdentifierExpr)cce.NonNull(codeCopier.Subst)(cce.NonNull(impl.InParams[i])),
+ cce.NonNull(callCmd.Ins[i]));
inCmds.Add(cmd);
}
-
+
// inject non-free requires
for (int i = 0; i < proc.Requires.Length; i++) {
- Requires! req = (!) proc.Requires[i];
+ Requires/*!*/ req = cce.NonNull(proc.Requires[i]);
if (!req.Free) {
- Requires! reqCopy = (Requires!) req.Clone();
+ Requires/*!*/ reqCopy = (Requires/*!*/)cce.NonNull(req.Clone());
reqCopy.Condition = codeCopier.CopyExpr(req.Condition);
- AssertCmd! a = new AssertRequiresCmd(callCmd, reqCopy);
+ AssertCmd/*!*/ a = new AssertRequiresCmd(callCmd, reqCopy);
+ Contract.Assert(a != null);
a.ErrorDataEnhanced = reqCopy.ErrorDataEnhanced;
inCmds.Add(a);
}
}
- VariableSeq locVars = (!)impl.OriginalLocVars;
-
+ VariableSeq locVars = cce.NonNull(impl.OriginalLocVars);
+
// add where clauses of local vars as assume
- for(int i = 0; i < locVars.Length; ++i) {
- Expr whereExpr = ((!)locVars[i]).TypedIdent.WhereExpr;
- if(whereExpr != null) {
+ for (int i = 0; i < locVars.Length; ++i) {
+ Expr whereExpr = (cce.NonNull(locVars[i])).TypedIdent.WhereExpr;
+ if (whereExpr != null) {
whereExpr = Substituter.Apply(codeCopier.Subst, whereExpr);
// FIXME we cannot overwrite it, can we?!
- ((!)locVars[i]).TypedIdent.WhereExpr = whereExpr;
- AssumeCmd! a = new AssumeCmd(Token.NoToken, whereExpr);
+ (cce.NonNull(locVars[i])).TypedIdent.WhereExpr = whereExpr;
+ AssumeCmd/*!*/ a = new AssumeCmd(Token.NoToken, whereExpr);
+ Contract.Assert(a != null);
inCmds.Add(a);
}
}
-
+
// add where clauses of output params as assume
- for(int i = 0; i < impl.OutParams.Length; ++i) {
- Expr whereExpr = ((!)impl.OutParams[i]).TypedIdent.WhereExpr;
- if(whereExpr != null) {
+ for (int i = 0; i < impl.OutParams.Length; ++i) {
+ Expr whereExpr = (cce.NonNull(impl.OutParams[i])).TypedIdent.WhereExpr;
+ if (whereExpr != null) {
whereExpr = Substituter.Apply(codeCopier.Subst, whereExpr);
// FIXME likewise
- ((!)impl.OutParams[i]).TypedIdent.WhereExpr = whereExpr;
- AssumeCmd! a = new AssumeCmd(Token.NoToken, whereExpr);
+ (cce.NonNull(impl.OutParams[i])).TypedIdent.WhereExpr = whereExpr;
+ AssumeCmd/*!*/ a = new AssumeCmd(Token.NoToken, whereExpr);
+ Contract.Assert(a != null);
inCmds.Add(a);
}
}
-
+
// assign modifies old values
- foreach (IdentifierExpr! mie in proc.Modifies)
- {
- Variable! mvar = (!) mie.Decl;
- AssignCmd assign = Cmd.SimpleAssign(impl.tok, (IdentifierExpr) (!) codeCopier.OldSubst(mvar), mie);
+ foreach (IdentifierExpr/*!*/ mie in proc.Modifies) {
+ Contract.Assert(mie != null);
+ Variable/*!*/ mvar = cce.NonNull(mie.Decl);
+ AssignCmd assign = Cmd.SimpleAssign(impl.tok, (IdentifierExpr)cce.NonNull(codeCopier.OldSubst(mvar)), mie);
inCmds.Add(assign);
}
-
+
GotoCmd inGotoCmd = new GotoCmd(callCmd.tok, new StringSeq(GetInlinedProcLabel(proc.Name) + "$" + startLabel));
Block inBlock = new Block(impl.tok, GetInlinedProcLabel(proc.Name) + "$Entry", inCmds, inGotoCmd);
- inlinedBlocks.Add(inBlock);
-
+ inlinedBlocks.Add(inBlock);
+
// inject the blocks of the implementation
Block intBlock;
foreach (Block block in implBlocks) {
- CmdSeq copyCmds = codeCopier.CopyCmdSeq(block.Cmds);
- TransferCmd transferCmd = CreateInlinedTransferCmd((!) block.TransferCmd, GetInlinedProcLabel(proc.Name));
+ CmdSeq copyCmds = codeCopier.CopyCmdSeq(block.Cmds);
+ TransferCmd transferCmd = CreateInlinedTransferCmd(cce.NonNull(block.TransferCmd), GetInlinedProcLabel(proc.Name));
intBlock = new Block(block.tok, GetInlinedProcLabel(proc.Name) + "$" + block.Label, copyCmds, transferCmd);
- inlinedBlocks.Add(intBlock);
+ inlinedBlocks.Add(intBlock);
}
-
+
// create out block
CmdSeq outCmds = new CmdSeq();
-
+
// inject non-free ensures
for (int i = 0; i < proc.Ensures.Length; i++) {
- Ensures! ens = (!) proc.Ensures[i];
+ Ensures/*!*/ ens = cce.NonNull(proc.Ensures[i]);
if (!ens.Free) {
- Ensures! ensCopy = (Ensures!) ens.Clone();
+ Ensures/*!*/ ensCopy = (Ensures/*!*/)cce.NonNull(ens.Clone());
ensCopy.Condition = codeCopier.CopyExpr(ens.Condition);
- AssertCmd! a = new AssertEnsuresCmd(ensCopy);
+ AssertCmd/*!*/ a = new AssertEnsuresCmd(ensCopy);
+ Contract.Assert(a != null);
outCmds.Add(a);
}
}
-
+
// assign out params
- for(int i = 0; i < impl.OutParams.Length; ++i) {
- Expr! cout_exp = (IdentifierExpr) (!) codeCopier.Subst((!)impl.OutParams[i]);
- Cmd cmd = Cmd.SimpleAssign(impl.tok, (!)callCmd.Outs[i], cout_exp);
+ for (int i = 0; i < impl.OutParams.Length; ++i) {
+ Expr/*!*/ cout_exp = (IdentifierExpr)cce.NonNull(codeCopier.Subst(cce.NonNull(impl.OutParams[i])));
+ Cmd cmd = Cmd.SimpleAssign(impl.tok, cce.NonNull(callCmd.Outs[i]), cout_exp);
outCmds.Add(cmd);
}
-
+
// create out block
GotoCmd outGotoCmd = new GotoCmd(Token.NoToken, new StringSeq(nextBlockLabel));
Block outBlock = new Block(impl.tok, GetInlinedProcLabel(proc.Name) + "$Return", outCmds, outGotoCmd);
inlinedBlocks.Add(outBlock);
-
+
return inlinedBlocks;
}
-
- protected TransferCmd CreateInlinedTransferCmd(TransferCmd! transferCmd, string! procLabel) {
+
+ protected TransferCmd CreateInlinedTransferCmd(TransferCmd transferCmd, string procLabel) {
+ Contract.Requires(procLabel != null);
+ Contract.Requires(transferCmd != null);
TransferCmd newTransferCmd;
-
+
GotoCmd gotoCmd = transferCmd as GotoCmd;
- if(gotoCmd != null) {
+ if (gotoCmd != null) {
StringSeq gotoSeq = gotoCmd.labelNames;
StringSeq newGotoSeq = new StringSeq();
- foreach(string! blockLabel in (!) gotoSeq) {
+ foreach (string/*!*/ blockLabel in cce.NonNull(gotoSeq)) {
+ Contract.Assert(blockLabel != null);
newGotoSeq.Add(procLabel + "$" + blockLabel);
}
newTransferCmd = new GotoCmd(transferCmd.tok, newGotoSeq);
} else {
newTransferCmd = new GotoCmd(transferCmd.tok, new StringSeq(procLabel + "$Return"));
}
-
+
return newTransferCmd;
}
-
- protected static bool FindProcImpl(Program! program, string! procName, out Procedure outProc, out Implementation outImpl)
- {
+
+ protected static bool FindProcImpl(Program program, string procName, out Procedure outProc, out Implementation outImpl) {
+ Contract.Requires(procName != null);
+ Contract.Requires(program != null);
// this assumes that there is at most one procedure and only one associated implementation in the current context
-
- foreach(Declaration decl in program.TopLevelDeclarations) {
+
+ foreach (Declaration decl in program.TopLevelDeclarations) {
Implementation impl = decl as Implementation;
- if(impl != null) {
- if(impl.Name.Equals(procName)) {
- assert(impl.Proc != null);
+ if (impl != null) {
+ if (impl.Name.Equals(procName)) {
+ Contract.Assert(impl.Proc != null);
outProc = impl.Proc;
outImpl = impl;
return true;
}
}
}
-
- foreach(Declaration decl in program.TopLevelDeclarations) {
+
+ foreach (Declaration decl in program.TopLevelDeclarations) {
Procedure proc = decl as Procedure;
- if(proc != null) {
- if(proc.Name.Equals(procName)) {
+ if (proc != null) {
+ if (proc.Name.Equals(procName)) {
outProc = proc;
outImpl = null;
return false;
}
}
}
-
+
outProc = null;
outImpl = null;
return false;
}
}
-
+
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
-
- public class CodeCopier
- {
+
+ public class CodeCopier {
public Substitution Subst;
public Substitution OldSubst;
- public CodeCopier(Hashtable! substMap) {
+ public CodeCopier(Hashtable substMap) {
+ Contract.Requires(substMap != null);
Subst = Substituter.SubstitutionFromHashtable(substMap);
}
-
- public CodeCopier(Hashtable! substMap, Hashtable! oldSubstMap) {
+
+ public CodeCopier(Hashtable substMap, Hashtable oldSubstMap) {
+ Contract.Requires(oldSubstMap != null);
+ Contract.Requires(substMap != null);
Subst = Substituter.SubstitutionFromHashtable(substMap);
OldSubst = Substituter.SubstitutionFromHashtable(oldSubstMap);
}
-
+
public CodeCopier() {
}
-
- public CmdSeq! CopyCmdSeq(CmdSeq! cmds) {
+
+ public CmdSeq CopyCmdSeq(CmdSeq cmds) {
+ Contract.Requires(cmds != null);
+ Contract.Ensures(Contract.Result<CmdSeq>() != null);
CmdSeq newCmds = new CmdSeq();
- foreach (Cmd! cmd in cmds) {
+ foreach (Cmd/*!*/ cmd in cmds) {
+ Contract.Assert(cmd != null);
newCmds.Add(CopyCmd(cmd));
}
return newCmds;
}
-
- public TransferCmd! CopyTransferCmd(TransferCmd! cmd) {
+
+ public TransferCmd CopyTransferCmd(TransferCmd cmd) {
+ Contract.Requires(cmd != null);
+ Contract.Ensures(Contract.Result<TransferCmd>() != null);
TransferCmd transferCmd;
GotoCmd gotocmd = cmd as GotoCmd;
- if(gotocmd != null) {
- assert(gotocmd.labelNames != null);
+ if (gotocmd != null) {
+ Contract.Assert(gotocmd.labelNames != null);
StringSeq labels = new StringSeq();
labels.AddRange(gotocmd.labelNames);
transferCmd = new GotoCmd(cmd.tok, labels);
@@ -541,8 +608,10 @@ namespace Microsoft.Boogie {
}
return transferCmd;
}
-
- public Cmd! CopyCmd(Cmd! cmd) {
+
+ public Cmd CopyCmd(Cmd cmd) {
+ Contract.Requires(cmd != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
if (Subst == null) {
return cmd;
} else if (OldSubst == null) {
@@ -551,8 +620,10 @@ namespace Microsoft.Boogie {
return Substituter.ApplyReplacingOldExprs(Subst, OldSubst, cmd);
}
}
-
- public Expr! CopyExpr(Expr! expr) {
+
+ public Expr CopyExpr(Expr expr) {
+ Contract.Requires(expr != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
if (Subst == null) {
return expr;
} else if (OldSubst == null) {
@@ -564,20 +635,26 @@ namespace Microsoft.Boogie {
} // end class CodeCopier
- public class AxiomExpander : Duplicator
- {
- readonly Program! program;
- readonly TypecheckingContext! tc;
+ public class AxiomExpander : Duplicator {
+ readonly Program/*!*/ program;
+ readonly TypecheckingContext/*!*/ tc;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(program != null);
+ Contract.Invariant(tc != null);
+ }
+
- public AxiomExpander(Program! prog, TypecheckingContext! t)
- {
+ public AxiomExpander(Program prog, TypecheckingContext t) {
+ Contract.Requires(t != null);
+ Contract.Requires(prog != null);
program = prog;
tc = t;
}
- public void CollectExpansions()
- {
- foreach (Declaration! decl in program.TopLevelDeclarations) {
+ public void CollectExpansions() {
+ foreach (Declaration/*!*/ decl in program.TopLevelDeclarations) {
+ Contract.Assert(decl != null);
Axiom ax = decl as Axiom;
if (ax != null) {
bool expand = false;
@@ -590,23 +667,24 @@ namespace Microsoft.Boogie {
}
Function f = decl as Function;
if (f != null && f.Body != null) {
- Variable[]! formals = new Variable [f.InParams.Length];
+ Variable[]/*!*/ formals = new Variable[f.InParams.Length];
+ Contract.Assert(formals != null);
for (int i = 0; i < formals.Length; ++i)
formals[i] = f.InParams[i];
AddExpansion(f, new Expansion(null, f.Body,
- new TypeVariableSeq (f.TypeParameters),
+ new TypeVariableSeq(f.TypeParameters),
formals));
}
}
}
- void Error(IToken! tok, string msg)
- {
+ void Error(IToken tok, string msg) {
+ Contract.Requires(tok != null);
tc.Error(tok, "expansion: " + msg);
}
- void AddExpansion(Expr! axiomBody, string? ignore)
- {
+ void AddExpansion(Expr axiomBody, string ignore) {
+ Contract.Requires(axiomBody != null);
// it would be sooooooooo much easier with pattern matching
ForallExpr all = axiomBody as ForallExpr;
if (all != null) {
@@ -614,18 +692,20 @@ namespace Microsoft.Boogie {
BinaryOperator bin = nary == null ? null : nary.Fun as BinaryOperator;
//System.Console.WriteLine("{0} {1} {2}", nary==null, bin==null, bin==null?0 : bin.Op);
if (nary != null && bin != null && (bin.Op == BinaryOperator.Opcode.Eq || bin.Op == BinaryOperator.Opcode.Iff)) {
- NAryExpr? func = nary.Args[0] as NAryExpr;
+
+ NAryExpr func = nary.Args[0] as NAryExpr;
//System.Console.WriteLine("{0} {1}", func == null, func == null ? null : func.Fun.GetType());
while (func != null && func.Fun is TypeCoercion)
func = func.Args[0] as NAryExpr;
if (func != null && func.Fun is FunctionCall) {
- Function fn = (!)((FunctionCall)func.Fun).Func;
- Expansion exp = new Expansion(ignore, (!)nary.Args[1],
- new TypeVariableSeq (),
+ Function fn = cce.NonNull((FunctionCall)func.Fun).Func;
+ Expansion exp = new Expansion(ignore, cce.NonNull(nary.Args[1]),
+ new TypeVariableSeq(),
new Variable[func.Args.Length]);
int pos = 0;
Dictionary<Declaration, bool> parms = new Dictionary<Declaration, bool>();
- foreach (Expr! e in func.Args) {
+ foreach (Expr/*!*/ e in func.Args) {
+ Contract.Assert(e != null);
IdentifierExpr id = e as IdentifierExpr;
if (id == null) {
Error(e.tok, "only identifiers supported as function arguments");
@@ -647,13 +727,15 @@ namespace Microsoft.Boogie {
return;
}
- Dictionary<TypeVariable!, bool> typeVars = new Dictionary<TypeVariable!, bool>();
- foreach (TypeVariable! v in ((!)func.TypeParameters).FormalTypeParams) {
+ Dictionary<TypeVariable/*!*/, bool> typeVars = new Dictionary<TypeVariable/*!*/, bool>();
+ foreach (TypeVariable/*!*/ v in cce.NonNull(func.TypeParameters).FormalTypeParams) {
+ Contract.Assert(v != null);
if (!func.TypeParameters[v].IsVariable) {
Error(all.tok, "only identifiers supported as type parameters");
return;
}
- TypeVariable! formal = func.TypeParameters[v].AsVariable;
+ TypeVariable/*!*/ formal = func.TypeParameters[v].AsVariable;
+ Contract.Assert(formal != null);
exp.TypeParameters.Add(formal);
if (typeVars.ContainsKey(formal)) {
Error(all.tok, "an identifier was used more than once");
@@ -678,12 +760,13 @@ namespace Microsoft.Boogie {
Error(axiomBody.tok, "axiom to be expanded must have form (forall VARS :: f(VARS) == expr(VARS))");
}
- void AddExpansion(Function! fn, Expansion! x) {
+ void AddExpansion(Function fn, Expansion x) {
+ Contract.Requires(x != null);
+ Contract.Requires(fn != null);
if (fn.expansions == null) {
- fn.expansions = new List<Expansion!>();
+ fn.expansions = new List<Expansion/*!*/>();
}
fn.expansions.Add(x);
}
}
-} // end namespace
-
+} // end namespace \ No newline at end of file
diff --git a/Source/Core/LambdaHelper.cs b/Source/Core/LambdaHelper.cs
index 83b66ce0..04bf0222 100644
--- a/Source/Core/LambdaHelper.cs
+++ b/Source/Core/LambdaHelper.cs
@@ -4,17 +4,20 @@
//
//-----------------------------------------------------------------------------
namespace Microsoft.Boogie {
-
+
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
+ using System.Diagnostics.Contracts;
- public static class LambdaHelper
- {
- public static Absy! Desugar(Absy! node, out List<Expr!>! axioms, out List<Function!>! functions)
- {
+ public static class LambdaHelper {
+ public static Absy Desugar(Absy node, out List<Expr/*!*/>/*!*/ axioms, out List<Function/*!*/>/*!*/ functions) {
+ Contract.Requires(node != null);
+ Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out functions)));
+ Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out axioms)));
+ Contract.Ensures(Contract.Result<Absy>() != null);
LambdaVisitor v = new LambdaVisitor();
node = v.Visit(node);
axioms = v.lambdaAxioms;
@@ -33,10 +36,11 @@ namespace Microsoft.Boogie {
return node;
}
- public static void ExpandLambdas(Program! prog)
- {
- List<Expr!>! axioms;
- List<Function!>! functions;
+ public static void ExpandLambdas(Program prog) {
+ Contract.Requires(prog != null);
+ List<Expr/*!*/>/*!*/ axioms;
+ List<Function/*!*/>/*!*/ functions;
+
Desugar(prog, out axioms, out functions);
foreach (var f in functions) {
prog.TopLevelDeclarations.Add(f);
@@ -46,15 +50,22 @@ namespace Microsoft.Boogie {
}
}
- private class LambdaVisitor : StandardVisitor
- {
- internal List<Expr!>! lambdaAxioms = new List<Expr!>();
- internal List<Function!>! lambdaFunctions = new List<Function!>();
+ private class LambdaVisitor : StandardVisitor {
+ internal List<Expr/*!*/>/*!*/ lambdaAxioms = new List<Expr/*!*/>();
+ internal List<Function/*!*/>/*!*/ lambdaFunctions = new List<Function/*!*/>();
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(cce.NonNullElements(lambdaAxioms));
+ Contract.Invariant(cce.NonNullElements(lambdaFunctions));
+ }
+
static int lambdaid = 0;
- public override Program! VisitProgram(Program! prog)
- {
- foreach (Declaration! decl in prog.TopLevelDeclarations) {
+ public override Program VisitProgram(Program prog) {
+ //Contract.Requires(prog != null);
+ Contract.Ensures(Contract.Result<Program>() != null);
+ foreach (Declaration/*!*/ decl in prog.TopLevelDeclarations) {
+ Contract.Assert(decl != null);
if (decl is Axiom || decl is Function) {
this.Visit(decl);
}
@@ -62,20 +73,23 @@ namespace Microsoft.Boogie {
return prog;
}
-
- public override Procedure! VisitProcedure(Procedure! node)
- {
+
+ public override Procedure VisitProcedure(Procedure node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Procedure>() != null);
// do not visit requires/ensures when calling this on Implementation
return node;
- }
+ }
- public override Absy! Visit(Absy! node)
- {
+ public override Absy Visit(Absy node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
node = base.Visit(node);
LambdaExpr lambda = node as LambdaExpr;
if (lambda != null) {
- IToken! tok = lambda.tok;
+ IToken/*!*/ tok = lambda.tok;
+ Contract.Assert(tok != null);
Set freeVars = new Set();
lambda.ComputeFreeVariables(freeVars);
@@ -86,7 +100,7 @@ namespace Microsoft.Boogie {
ExprSeq axCallArgs = new ExprSeq();
VariableSeq dummies = new VariableSeq(lambda.Dummies);
TypeVariableSeq freeTypeVars = new TypeVariableSeq();
- List<Type!> fnTypeVarActuals = new List<Type!>();
+ List<Type/*!*/> fnTypeVarActuals = new List<Type/*!*/>();
TypeVariableSeq freshTypeVars = new TypeVariableSeq(); // these are only used in the lambda@n function's definition
foreach (object o in freeVars) {
// 'o' is either a Variable or a TypeVariable. Since the lambda desugaring happens only
@@ -102,7 +116,8 @@ namespace Microsoft.Boogie {
BoundVariable b = new BoundVariable(v.tok, ti);
dummies.Add(b);
callArgs.Add(new IdentifierExpr(v.tok, v));
- Expr! id = new IdentifierExpr(f.tok, b);
+ Expr/*!*/ id = new IdentifierExpr(f.tok, b);
+ Contract.Assert(id != null);
subst.Add(v, id);
axCallArgs.Add(id);
} else if (o is TypeVariable) {
@@ -112,16 +127,17 @@ namespace Microsoft.Boogie {
freshTypeVars.Add(new TypeVariable(tv.tok, tv.Name));
}
}
-
- Formal res = new Formal(tok, new TypedIdent(tok, TypedIdent.NoName, (!)lambda.Type), false);
+
+ Formal res = new Formal(tok, new TypedIdent(tok, TypedIdent.NoName, cce.NonNull(lambda.Type)), false);
Function fn = new Function(tok, "lambda@" + lambdaid++, freshTypeVars, formals, res, "auto-generated lambda function", lambda.Attributes);
lambdaFunctions.Add(fn);
FunctionCall fcall = new FunctionCall(new IdentifierExpr(tok, fn.Name));
fcall.Func = fn; // resolve here
- List<Expr!> selectArgs = new List<Expr!>();
- foreach (Variable! v in lambda.Dummies) {
+ List<Expr/*!*/> selectArgs = new List<Expr/*!*/>();
+ foreach (Variable/*!*/ v in lambda.Dummies) {
+ Contract.Assert(v != null);
selectArgs.Add(new IdentifierExpr(v.tok, v));
}
NAryExpr axcall = new NAryExpr(tok, fcall, axCallArgs);
@@ -129,9 +145,10 @@ namespace Microsoft.Boogie {
axcall.TypeParameters = SimpleTypeParamInstantiation.From(freeTypeVars, fnTypeVarActuals);
NAryExpr select = Expr.Select(axcall, selectArgs);
select.Type = lambda.Body.Type;
- List<Type!> selectTypeParamActuals = new List<Type!>();
+ List<Type/*!*/> selectTypeParamActuals = new List<Type/*!*/>();
TypeVariableSeq forallTypeVariables = new TypeVariableSeq();
- foreach (TypeVariable! tp in lambda.TypeParameters) {
+ foreach (TypeVariable/*!*/ tp in lambda.TypeParameters) {
+ Contract.Assert(tp != null);
selectTypeParamActuals.Add(tp);
forallTypeVariables.Add(tp);
}
@@ -156,6 +173,5 @@ namespace Microsoft.Boogie {
}
}
}
-
-} // end namespace
+} // end namespace \ No newline at end of file
diff --git a/Source/Core/LoopUnroll.cs b/Source/Core/LoopUnroll.cs
index 68bc8847..cfadd2b2 100644
--- a/Source/Core/LoopUnroll.cs
+++ b/Source/Core/LoopUnroll.cs
@@ -3,68 +3,93 @@
// Copyright (C) Microsoft Corporation. All Rights Reserved.
//
//-----------------------------------------------------------------------------
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
using System.Collections.Generic;
using Cci = System.Compiler;
using Bpl = Microsoft.Boogie;
-namespace Microsoft.Boogie
-{
+namespace Microsoft.Boogie {
public class LoopUnroll {
- public static List<Block!>! UnrollLoops(Block! start, int unrollMaxDepth)
- requires 0 <= unrollMaxDepth;
- {
- Dictionary<Block,GraphNode!> gd = new Dictionary<Block,GraphNode!>();
- Cci.HashSet/*Block*/! beingVisited = new Cci.HashSet/*Block*/();
+ public static List<Block/*!*/>/*!*/ UnrollLoops(Block start, int unrollMaxDepth) {
+ Contract.Requires(start != null);
+
+ Contract.Requires(0 <= unrollMaxDepth);
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Block>>()));
+ Dictionary<Block, GraphNode/*!*/> gd = new Dictionary<Block, GraphNode/*!*/>();
+ Cci.HashSet/*Block*//*!*/ beingVisited = new Cci.HashSet/*Block*/();
GraphNode gStart = GraphNode.ComputeGraphInfo(null, start, gd, beingVisited);
-
+
// Compute SCCs
- StronglyConnectedComponents<GraphNode!> sccs =
- new StronglyConnectedComponents<GraphNode!>(gd.Values, Preds, Succs);
+ StronglyConnectedComponents<GraphNode/*!*/> sccs =
+ new StronglyConnectedComponents<GraphNode/*!*/>(gd.Values, Preds, Succs);
+ Contract.Assert(sccs != null);
sccs.Compute();
- Dictionary<GraphNode!, SCC<GraphNode!>> containingSCC = new Dictionary<GraphNode!, SCC<GraphNode!>>();
- foreach (SCC<GraphNode!> scc in sccs)
- {
- foreach (GraphNode! n in scc)
- {
+ Dictionary<GraphNode/*!*/, SCC<GraphNode/*!*/>> containingSCC = new Dictionary<GraphNode/*!*/, SCC<GraphNode/*!*/>>();
+ foreach (SCC<GraphNode/*!*/> scc in sccs) {
+ foreach (GraphNode/*!*/ n in scc) {
+ Contract.Assert(n != null);
containingSCC[n] = scc;
}
}
-
- LoopUnroll lu = new LoopUnroll(unrollMaxDepth, containingSCC, new List<Block!>());
+
+ LoopUnroll lu = new LoopUnroll(unrollMaxDepth, containingSCC, new List<Block/*!*/>());
lu.Visit(gStart);
lu.newBlockSeqGlobal.Reverse();
return lu.newBlockSeqGlobal;
}
-
- private static System.Collections.IEnumerable/*<GraphNode!>*/! Succs(GraphNode! n)
- {
- List<GraphNode!>! AllEdges = new List<GraphNode!>();
+
+ private static System.Collections.IEnumerable/*<GraphNode/*!>/*!*/ Succs(GraphNode n) {
+ Contract.Requires(n != null);
+ Contract.Ensures(Contract.Result<System.Collections.IEnumerable>() != null);
+
+ List<GraphNode/*!*/>/*!*/ AllEdges = new List<GraphNode/*!*/>();
AllEdges.AddRange(n.ForwardEdges);
AllEdges.AddRange(n.BackEdges);
return AllEdges;
}
- private static System.Collections.IEnumerable/*<GraphNode!>*/! Preds(GraphNode! n)
- {
+ private static System.Collections.IEnumerable/*<GraphNode!>*//*!*/ Preds(GraphNode n) {
+ Contract.Requires(n != null);
+ Contract.Ensures(Contract.Result<System.Collections.IEnumerable>() != null);
+
return n.Predecessors;
}
-
+
class GraphNode {
- public readonly Block! Block;
- public readonly CmdSeq! Body;
+ public readonly Block/*!*/ Block;
+ public readonly CmdSeq/*!*/ Body;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Block != null);
+ Contract.Invariant(Body != null);
+ Contract.Invariant(cce.NonNullElements(ForwardEdges));
+ Contract.Invariant(cce.NonNullElements(BackEdges));
+ Contract.Invariant(cce.NonNullElements(Predecessors));
+ Contract.Invariant(isCutPoint == (BackEdges.Count != 0));
+ }
+
bool isCutPoint; // is set during ComputeGraphInfo
- public bool IsCutPoint { get { return isCutPoint; } }
- [Rep] public readonly List<GraphNode!>! ForwardEdges = new List<GraphNode!>();
- [Rep] public readonly List<GraphNode!>! BackEdges = new List<GraphNode!>();
- [Rep] public readonly List<GraphNode!>! Predecessors = new List<GraphNode!>();
- invariant isCutPoint <==> BackEdges.Count != 0;
-
- GraphNode(Block! b, CmdSeq! body) {
+ public bool IsCutPoint {
+ get {
+ return isCutPoint;
+ }
+ }
+ [Rep]
+ public readonly List<GraphNode/*!*/>/*!*/ ForwardEdges = new List<GraphNode/*!*/>();
+ [Rep]
+ public readonly List<GraphNode/*!*/>/*!*/ BackEdges = new List<GraphNode/*!*/>();
+ [Rep]
+ public readonly List<GraphNode/*!*/>/*!*/ Predecessors = new List<GraphNode/*!*/>();
+
+ GraphNode(Block b, CmdSeq body) {
+ Contract.Requires(body != null);
+ Contract.Requires(b != null);
this.Block = b;
this.Body = body;
}
-
- static CmdSeq! GetOptimizedBody(CmdSeq! cmds) {
+
+ static CmdSeq GetOptimizedBody(CmdSeq cmds) {
+ Contract.Requires(cmds != null);
+ Contract.Ensures(Contract.Result<CmdSeq>() != null);
int n = 0;
foreach (Cmd c in cmds) {
n++;
@@ -81,11 +106,15 @@ namespace Microsoft.Boogie
return cmds;
}
- public static GraphNode! ComputeGraphInfo(GraphNode from, Block! b, Dictionary<Block,GraphNode!>! gd, Cci.HashSet/*Block*/! beingVisited) {
+ public static GraphNode ComputeGraphInfo(GraphNode from, Block b, Dictionary<Block/*!*/, GraphNode/*!*/>/*!*/ gd, Cci.HashSet/*Block*/ beingVisited) {
+ Contract.Requires(beingVisited != null);
+ Contract.Requires(b != null);
+ Contract.Requires(cce.NonNullElements(gd));
+ Contract.Ensures(Contract.Result<GraphNode>() != null);
GraphNode g;
if (gd.TryGetValue(b, out g)) {
- assume from != null;
- assert g != null;
+ Contract.Assume(from != null);
+ Contract.Assert(g != null);
if (beingVisited.Contains(b)) {
// it's a cut point
g.isCutPoint = true;
@@ -95,7 +124,7 @@ namespace Microsoft.Boogie
from.ForwardEdges.Add(g);
g.Predecessors.Add(from);
}
-
+
} else {
CmdSeq body = GetOptimizedBody(b.Cmds);
g = new GraphNode(b, body);
@@ -104,52 +133,64 @@ namespace Microsoft.Boogie
from.ForwardEdges.Add(g);
g.Predecessors.Add(from);
}
-
+
if (body != b.Cmds) {
// the body was optimized -- there is no way through this block
} else {
beingVisited.Add(b);
-
+
GotoCmd gcmd = b.TransferCmd as GotoCmd;
if (gcmd != null) {
- assume gcmd.labelTargets != null;
- foreach (Block! succ in gcmd.labelTargets) {
+ Contract.Assume(gcmd.labelTargets != null);
+ foreach (Block/*!*/ succ in gcmd.labelTargets) {
+ Contract.Assert(succ != null);
ComputeGraphInfo(g, succ, gd, beingVisited);
}
}
-
+
beingVisited.Remove(b);
}
}
return g;
}
}
-
- readonly List<Block!>! newBlockSeqGlobal;
- readonly Dictionary<GraphNode!, SCC<GraphNode!>>! containingSCC;
+
+ readonly List<Block/*!*/>/*!*/ newBlockSeqGlobal;
+ readonly Dictionary<GraphNode/*!*/, SCC<GraphNode/*!*/>>/*!*/ containingSCC;
readonly int c;
readonly LoopUnroll next;
- readonly LoopUnroll head;
- invariant head != null;
- Dictionary<Block,Block!>! newBlocks = new Dictionary<Block,Block!>();
-
+ readonly LoopUnroll/*!*/ head;
+
+ Dictionary<Block, Block/*!*/>/*!*/ newBlocks = new Dictionary<Block, Block/*!*/>();
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(head != null);
+ Contract.Invariant(cce.NonNullElements(newBlockSeqGlobal));
+ Contract.Invariant(newBlocks != null && cce.NonNullElements(newBlocks.Values));
+ }
+
+
[NotDelayed]
- private LoopUnroll(int unrollMaxDepth, Dictionary<GraphNode!, SCC<GraphNode!>>! scc, List<Block!>! newBlockSeqGlobal)
- requires 0 <= unrollMaxDepth;
- {
+ private LoopUnroll(int unrollMaxDepth, Dictionary<GraphNode/*!*/, SCC<GraphNode/*!*/>>/*!*/ scc, List<Block/*!*/>/*!*/ newBlockSeqGlobal)
+ : base() {//BASEMOVE DANGER
+ Contract.Requires(cce.NonNullElements(newBlockSeqGlobal));
+ Contract.Requires(cce.NonNullElements(scc) && Contract.ForAll(scc.Values, v => cce.NonNullElements(v)));
+ Contract.Requires(0 <= unrollMaxDepth);
this.newBlockSeqGlobal = newBlockSeqGlobal;
this.c = unrollMaxDepth;
this.containingSCC = scc;
- base();
+ //:base();
this.head = this;
if (unrollMaxDepth != 0) {
next = new LoopUnroll(unrollMaxDepth - 1, scc, newBlockSeqGlobal, this);
}
}
-
- private LoopUnroll(int unrollMaxDepth, Dictionary<GraphNode!, SCC<GraphNode!>>! scc, List<Block!>! newBlockSeqGlobal, LoopUnroll! head)
- requires 0 <= unrollMaxDepth;
- {
+
+ private LoopUnroll(int unrollMaxDepth, Dictionary<GraphNode/*!*/, SCC<GraphNode/*!*/>> scc, List<Block/*!*/>/*!*/ newBlockSeqGlobal, LoopUnroll head) {
+ Contract.Requires(head != null);
+ Contract.Requires(cce.NonNullElements(scc));
+ Contract.Requires(cce.NonNullElements(newBlockSeqGlobal));
+ Contract.Requires(0 <= unrollMaxDepth);
this.newBlockSeqGlobal = newBlockSeqGlobal;
this.c = unrollMaxDepth;
this.containingSCC = scc;
@@ -158,22 +199,25 @@ namespace Microsoft.Boogie
next = new LoopUnroll(unrollMaxDepth - 1, scc, newBlockSeqGlobal, head);
}
}
-
- Block! Visit(GraphNode! node) {
+
+ Block Visit(GraphNode node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Block>() != null);
Block orig = node.Block;
Block nw;
if (newBlocks.TryGetValue(orig, out nw)) {
- assert nw != null;
-
+ Contract.Assert(nw != null);
+
} else {
CmdSeq body;
TransferCmd tcmd;
- assert orig.TransferCmd != null;
-
+ Contract.Assert(orig.TransferCmd != null);
+
if (next == null && node.IsCutPoint) {
// as the body, use the assert/assume commands that make up the loop invariant
body = new CmdSeq();
- foreach (Cmd! c in node.Body) {
+ foreach (Cmd/*!*/ c in node.Body) {
+ Contract.Assert(c != null);
if (c is PredicateCmd || c is CommentCmd) {
body.Add(c);
} else {
@@ -181,31 +225,31 @@ namespace Microsoft.Boogie
}
}
body.Add(new AssumeCmd(orig.tok, Bpl.Expr.False));
-
+
tcmd = new ReturnCmd(orig.TransferCmd.tok);
} else {
body = node.Body;
BlockSeq newSuccs = new BlockSeq();
-
+
foreach (GraphNode succ in node.ForwardEdges) {
Block s;
if (containingSCC[node] == containingSCC[succ]) {
s = Visit(succ);
} else {
- assert head != null; // follows from object invariant
+ Contract.Assert(head != null); // follows from object invariant
s = head.Visit(succ);
}
newSuccs.Add(s);
}
-
- assert next == null ==> node.BackEdges.Count == 0; // follows from if-else test above and the GraphNode invariant
+
+ Contract.Assert(next != null || node.BackEdges.Count == 0); // follows from if-else test above and the GraphNode invariant
foreach (GraphNode succ in node.BackEdges) {
- assert next != null; // since if we get here, node.BackEdges.Count != 0
+ Contract.Assert(next != null); // since if we get here, node.BackEdges.Count != 0
Block s = next.Visit(succ);
newSuccs.Add(s);
}
-
+
if (newSuccs.Length == 0) {
tcmd = new ReturnCmd(orig.TransferCmd.tok);
} else {
@@ -217,7 +261,7 @@ namespace Microsoft.Boogie
newBlocks.Add(orig, nw);
newBlockSeqGlobal.Add(nw);
}
-
+
return nw;
}
}
diff --git a/Source/Core/Makefile b/Source/Core/Makefile
index a549dd81..a5061138 100644
--- a/Source/Core/Makefile
+++ b/Source/Core/Makefile
@@ -1,5 +1,4 @@
COCO = ..\..\Binaries\Coco.exe
-ASML = ..\..\Binaries\asmlc.boot.exe
# ###############################################################################
# The frame files are no longer in this directory. They must be downloaded
@@ -13,13 +12,8 @@ FRAME_DIR = c:\BoogiePartners\CocoR\Modified
# nmake that. --KRML
all: Parser.ssc
-#Graph.dll: Graph.as
-# $(ASML) /target:library Graph.as
-
Parser.ssc: $(FRAME_DIR)\Scanner.frame $(FRAME_DIR)\Parser.frame BoogiePL.atg
$(COCO) BoogiePL.atg -namespace Microsoft.Boogie -frames $(FRAME_DIR)
- copy Parser.cs Parser.ssc
- copy Scanner.cs Scanner.ssc
clean:
- rm -f Scanner.ssc Parser.ssc
+ rm -f Scanner.cs Parser.cs
diff --git a/Source/Core/OOLongUtil.cs b/Source/Core/OOLongUtil.cs
index e87666f3..1b3a68ad 100644
--- a/Source/Core/OOLongUtil.cs
+++ b/Source/Core/OOLongUtil.cs
@@ -6,14 +6,22 @@
using System;
using System.Collections.Generic;
using System.IO;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
namespace Boogie.Util {
public class TeeWriter : TextWriter {
- readonly TextWriter! a;
- readonly TextWriter! b;
+ readonly TextWriter/*!*/ a;
+ readonly TextWriter/*!*/ b;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(a != null);
+ Contract.Invariant(b != null);
+ }
+
- public TeeWriter(TextWriter! a, TextWriter! b) {
+ public TeeWriter(TextWriter a, TextWriter b) {
+ Contract.Requires(b != null);
+ Contract.Requires(a != null);
this.a = a;
this.b = b;
}
@@ -28,14 +36,15 @@ namespace Boogie.Util {
a.Close();
b.Close();
}
-
+
public override void Flush() {
a.Flush();
b.Flush();
}
[Pure]
- public override string! ToString() {
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
return "<TeeWriter: " + a.ToString() + ", " + b.ToString() + ">";
}
@@ -55,21 +64,32 @@ namespace Boogie.Util {
/// It simply reads from the given "reader".
/// </summary>
public class LineReader : TextReader {
- [Rep] readonly TextReader! reader;
+ [Rep]
+ readonly TextReader/*!*/ reader;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(reader != null);
+ Contract.Invariant(readAhead == null || (0 <= readAheadConsumed && readAheadConsumed < readAhead.Length));
+ }
+
string readAhead;
int readAheadConsumed;
- invariant readAhead == null || (0 <= readAheadConsumed && readAheadConsumed < readAhead.Length);
- public LineReader([Captured] TextReader! reader) {
+
+ public LineReader([Captured] TextReader reader) {
+ Contract.Requires(reader != null);
this.reader = reader;
}
public override void Close() {
- expose (this) {
+ cce.BeginExpose(this);
+ {
reader.Close();
}
+ cce.EndExpose();
}
public override int Read() {
- expose (this) {
+ cce.BeginExpose(this);
+ {
while (readAhead == null) {
readAhead = reader.ReadLine();
if (readAhead == null) {
@@ -86,8 +106,10 @@ namespace Boogie.Util {
}
return res;
}
+ cce.EndExpose();
}
- public override int Read(char[]! buffer, int index, int count) {
+ public override int Read(char[] buffer, int index, int count) {
+
int n = 0;
for (; n < count; n++) {
int ch = Read();
@@ -101,10 +123,12 @@ namespace Boogie.Util {
public override string ReadLine() {
string res;
if (readAhead != null) {
- expose (this) {
+ cce.BeginExpose(this);
+ {
res = readAhead.Substring(readAheadConsumed);
readAhead = null;
}
+ cce.EndExpose();
} else {
res = reader.ReadLine();
}
@@ -113,16 +137,28 @@ namespace Boogie.Util {
}
public class IfdefReader : LineReader {
- [Rep] readonly List<string!>! defines;
- [Rep] readonly List<bool>! readState = new List<bool>();
+ [Rep]
+ readonly List<string/*!*/>/*!*/ defines;
+ [Rep]
+ readonly List<bool>/*!*/ readState = new List<bool>();
int ignoreCutoff = 0; // 0 means we're not ignoring
- invariant 0 <= ignoreCutoff && ignoreCutoff <= readState.Count;
-
- public IfdefReader([Captured] TextReader! reader, [Captured] List<string!>! defines) {
- base(reader);
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(readState != null);
+ Contract.Invariant(cce.NonNullElements(defines));
+ Contract.Invariant(0 <= ignoreCutoff && ignoreCutoff <= readState.Count);
+ }
+
+
+
+ public IfdefReader([Captured] TextReader reader, [Captured] List<string/*!*/>/*!*/ defines)
+ : base(reader) {//BASEMOVEA
+ Contract.Requires(reader != null);
+ Contract.Requires(cce.NonNullElements(defines));
+ //:base(reader);
this.defines = defines;
}
-
+
public override string ReadLine() {
while (true) {
string s = base.ReadLine();
@@ -143,11 +179,11 @@ namespace Boogie.Util {
ignoreCutoff = readState.Count; // start ignoring
}
} else if (t == "#else") {
- if (readState.Count == 0 || !readState[readState.Count-1]) {
+ if (readState.Count == 0 || !readState[readState.Count - 1]) {
return s; // malformed input; return the read line as if it were not special
}
// change the "true" to a "false" on top of the state, since we're now going into the "else" branch
- readState[readState.Count-1] = false;
+ readState[readState.Count - 1] = false;
if (ignoreCutoff == 0) {
// the "then" branch had been included, so we'll ignore the "else" branch
ignoreCutoff = readState.Count;
@@ -164,7 +200,7 @@ namespace Boogie.Util {
ignoreCutoff = 0;
}
// pop
- readState.RemoveAt(readState.Count-1);
+ readState.RemoveAt(readState.Count - 1);
} else if (ignoreCutoff == 0) {
return s;
}
diff --git a/Source/Core/Parser.cs b/Source/Core/Parser.cs
index 86f792bb..0fedc95f 100644
--- a/Source/Core/Parser.cs
+++ b/Source/Core/Parser.cs
@@ -12,7 +12,7 @@ using AI = Microsoft.AbstractInterpretationFramework;
using System;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
namespace Microsoft.Boogie {
@@ -38,36 +38,33 @@ public class Parser {
public Token/*!*/ la; // lookahead token
int errDist = minErrDist;
-static Program! Pgm = new Program();
+static Program/*!*/ Pgm = new Program();
-static Expr! dummyExpr = new LiteralExpr(Token.NoToken, false);
-static Cmd! dummyCmd = new AssumeCmd(Token.NoToken, dummyExpr);
-static Block! dummyBlock = new Block(Token.NoToken, "dummyBlock", new CmdSeq(),
+static Expr/*!*/ dummyExpr = new LiteralExpr(Token.NoToken, false);
+static Cmd/*!*/ dummyCmd = new AssumeCmd(Token.NoToken, dummyExpr);
+static Block/*!*/ dummyBlock = new Block(Token.NoToken, "dummyBlock", new CmdSeq(),
new ReturnCmd(Token.NoToken));
-static Bpl.Type! dummyType = new BasicType(Token.NoToken, SimpleType.Bool);
-static Bpl.ExprSeq! dummyExprSeq = new ExprSeq ();
-static TransferCmd! dummyTransferCmd = new ReturnCmd(Token.NoToken);
-static StructuredCmd! dummyStructuredCmd = new BreakCmd(Token.NoToken, null);
+static Bpl.Type/*!*/ dummyType = new BasicType(Token.NoToken, SimpleType.Bool);
+static Bpl.ExprSeq/*!*/ dummyExprSeq = new ExprSeq ();
+static TransferCmd/*!*/ dummyTransferCmd = new ReturnCmd(Token.NoToken);
+static StructuredCmd/*!*/ dummyStructuredCmd = new BreakCmd(Token.NoToken, null);
///<summary>
///Returns the number of parsing errors encountered. If 0, "program" returns as
///the parsed program.
///</summary>
-public static int Parse (string! filename, /*maybe null*/ List<string!> defines, out /*maybe null*/ Program program) /* throws System.IO.IOException */ {
+public static int Parse (string/*!*/ filename, /*maybe null*/ List<string/*!*/> defines, out /*maybe null*/ Program program) /* throws System.IO.IOException */ {
+Contract.Requires(filename != null);
+Contract.Requires(cce.NonNullElements(defines,true));
FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
- return Parse(stream, filename, defines, out program);
-}
-
-// Read the program from a stream. This allows the program to be stored in memory.
-public static int Parse (Stream! stream, string! filename, /*maybe null*/ List<string!> defines, out /*maybe null*/ Program program) /* throws System.IO.IOException */ {
if (defines == null) {
- defines = new List<string!>();
+ defines = new List<string/*!*/>();
}
string s = ParserHelper.Fill(stream, defines);
- 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);
@@ -93,21 +90,24 @@ public static int Parse (Stream! stream, string! filename, /*maybe null*/ List<s
private class BvBounds : Expr {
public BigNum Lower;
public BigNum Upper;
- public BvBounds(IToken! tok, BigNum lower, BigNum upper) {
- base(tok);
+ public BvBounds(IToken/*!*/ tok, BigNum lower, BigNum upper) :base(tok){//BASEMOVEA
+ Contract.Requires(tok != null);
+ //:base(tok);
this.Lower = lower;
this.Upper = upper;
}
- public override Type! ShallowType { get { return Bpl.Type.Int; } }
- public override void Resolve(ResolutionContext! rc) {
+ public override Type/*!*/ ShallowType { get {Contract.Ensures(Contract.Result<Type>() != null); return Bpl.Type.Int; } }
+ public override void Resolve(ResolutionContext/*!*/ rc) {
+ //Contract.Requires(rc != null);
rc.Error(this, "bitvector bounds in illegal position");
}
- public override void Emit(TokenTextWriter! stream,
+ public override void Emit(TokenTextWriter/*!*/ stream,
int contextBindingStrength, bool fragileContext) {
- assert false;
+ //Contract.Requires(stream != null);
+ {Contract.Assert(false);throw new cce.UnreachableException();}
}
- public override void ComputeFreeVariables(Set! freeVars) { assert false; }
- public override AI.IExpr! IExpr { get { assert false; } }
+ public override void ComputeFreeVariables(Set/*!*/ freeVars) {/*Contract.Requires(freeVars != null);*/ {Contract.Assert(false);throw new cce.UnreachableException();} }
+ public override AI.IExpr/*!*/ IExpr { get { Contract.Ensures(Contract.Result<AI.IExpr>()!=null); {Contract.Assert(false);throw new cce.UnreachableException();} } }
}
/*--------------------------------------------------------------------------*/
@@ -116,7 +116,7 @@ private class BvBounds : Expr {
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
@@ -127,12 +127,15 @@ private class BvBounds : Expr {
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);
}
@@ -179,24 +182,28 @@ private class BvBounds : Expr {
void BoogiePL() {
- VariableSeq! vs;
- DeclarationSeq! ds;
- Axiom! ax;
- List<Declaration!>! ts;
- Procedure! pr;
+ VariableSeq/*!*/ vs;
+ DeclarationSeq/*!*/ ds;
+ Axiom/*!*/ ax;
+ List<Declaration/*!*/>/*!*/ ts;
+ Procedure/*!*/ pr;
Implementation im;
- Implementation! nnim;
+ Implementation/*!*/ nnim;
while (StartOf(1)) {
switch (la.kind) {
case 19: {
Consts(out vs);
- foreach (Bpl.Variable! v in vs) { Pgm.TopLevelDeclarations.Add(v); }
+ foreach(Bpl.Variable/*!*/ v in vs){
+ Contract.Assert(v != null);
+ Pgm.TopLevelDeclarations.Add(v); }
break;
}
case 23: {
Function(out ds);
- foreach (Bpl.Declaration! d in ds) { Pgm.TopLevelDeclarations.Add(d); }
+ foreach(Bpl.Declaration/*!*/ d in ds){
+ Contract.Assert(d != null);
+ Pgm.TopLevelDeclarations.Add(d); }
break;
}
case 27: {
@@ -206,14 +213,17 @@ private class BvBounds : Expr {
}
case 28: {
UserDefinedTypes(out ts);
- foreach (Declaration! td in ts) {
- Pgm.TopLevelDeclarations.Add(td);
- }
+ foreach(Declaration/*!*/ td in ts){
+ Contract.Assert(td != null);
+ Pgm.TopLevelDeclarations.Add(td);
+ }
break;
}
case 6: {
GlobalVars(out vs);
- foreach (Bpl.Variable! v in vs) { Pgm.TopLevelDeclarations.Add(v); }
+ foreach(Bpl.Variable/*!*/ v in vs){
+ Contract.Assert(v != null);
+ Pgm.TopLevelDeclarations.Add(v); }
break;
}
case 30: {
@@ -235,12 +245,12 @@ private class BvBounds : Expr {
Expect(0);
}
- void Consts(out VariableSeq! ds) {
- IToken! y; TypedIdentSeq! xs;
+ void Consts(out VariableSeq/*!*/ ds) {
+ Contract.Ensures(Contract.ValueAtReturn(out ds) != null); IToken/*!*/ y; TypedIdentSeq/*!*/ xs;
ds = new VariableSeq();
bool u = false; QKeyValue kv = null;
bool ChildrenComplete = false;
- List<ConstantParent!> Parents = null;
+ List<ConstantParent/*!*/> Parents = null;
Expect(19);
y = t;
while (la.kind == 25) {
@@ -255,16 +265,17 @@ private class BvBounds : Expr {
OrderSpec(out ChildrenComplete, out Parents);
}
bool makeClone = false;
- foreach(TypedIdent! x in xs) {
+ foreach(TypedIdent/*!*/ x in xs){
+ Contract.Assert(x != null);
// ensure that no sharing is introduced
- List<ConstantParent!> ParentsClone;
+ List<ConstantParent/*!*/> ParentsClone;
if (makeClone && Parents != null) {
- ParentsClone = new List<ConstantParent!> ();
- foreach (ConstantParent! p in Parents)
+ ParentsClone = new List<ConstantParent/*!*/> ();
+ foreach (ConstantParent/*!*/ p in Parents){Contract.Assert(p != null);
ParentsClone.Add(new ConstantParent (
new IdentifierExpr (p.Parent.tok, p.Parent.Name),
- p.Unique));
+ p.Unique));}
} else {
ParentsClone = Parents;
}
@@ -276,18 +287,19 @@ private class BvBounds : Expr {
Expect(7);
}
- void Function(out DeclarationSeq! ds) {
- ds = new DeclarationSeq(); IToken! z;
- IToken! typeParamTok;
- TypeVariableSeq! typeParams = new TypeVariableSeq();
- VariableSeq arguments = new VariableSeq();
- TypedIdent! tyd;
- TypedIdent retTyd = null;
- Type! retTy;
- QKeyValue kv = null;
- Expr definition = null;
- Expr! tmp;
-
+ void Function(out DeclarationSeq/*!*/ ds) {
+ Contract.Ensures(Contract.ValueAtReturn(out ds) != null);
+ ds = new DeclarationSeq(); IToken/*!*/ z;
+ IToken/*!*/ typeParamTok;
+ TypeVariableSeq/*!*/ typeParams = new TypeVariableSeq();
+ VariableSeq arguments = new VariableSeq();
+ TypedIdent/*!*/ tyd;
+ TypedIdent retTyd = null;
+ Type/*!*/ retTy;
+ QKeyValue kv = null;
+ Expr definition = null;
+ Expr/*!*/ tmp;
+
Expect(23);
while (la.kind == 25) {
Attribute(ref kv);
@@ -332,55 +344,59 @@ private class BvBounds : Expr {
} else {
tyd = retTyd;
}
- Function! func = new Function(z, z.val, typeParams, arguments,
+ Function/*!*/ func = new Function(z, z.val, typeParams, arguments,
new Formal(tyd.tok, tyd, false), null, kv);
+ Contract.Assert(func != null);
ds.Add(func);
bool allUnnamed = true;
- foreach (Formal! f in arguments) {
- if (f.TypedIdent.Name != "") {
- allUnnamed = false;
- break;
- }
- }
- if (!allUnnamed) {
- Type prevType = null;
- for (int i = arguments.Length - 1; i >= 0; i--) {
- TypedIdent! curr = ((!)arguments[i]).TypedIdent;
- if (curr.Name == "") {
- if (prevType == null) {
- this.errors.SemErr(curr.tok, "the type of the last parameter is unspecified");
- break;
- }
- Type ty = curr.Type;
- if (ty is UnresolvedTypeIdentifier &&
- ((!)(ty as UnresolvedTypeIdentifier)).Arguments.Length == 0) {
- curr.Name = ((!)(ty as UnresolvedTypeIdentifier)).Name;
- curr.Type = prevType;
- } else {
- this.errors.SemErr(curr.tok, "expecting an identifier as parameter name");
- }
- } else {
- prevType = curr.Type;
- }
- }
- }
- if (definition != null) {
- // generate either an axiom or a function body
- if (QKeyValue.FindBoolAttribute(kv, "inline")) {
- func.Body = definition;
- } else {
- VariableSeq dummies = new VariableSeq();
- ExprSeq callArgs = new ExprSeq();
- int i = 0;
- foreach (Formal! f in arguments) {
- string nm = f.TypedIdent.HasName ? f.TypedIdent.Name : "_" + i;
- dummies.Add(new BoundVariable(f.tok, new TypedIdent(f.tok, nm, f.TypedIdent.Type)));
- callArgs.Add(new IdentifierExpr(f.tok, nm));
- i++;
- }
- TypeVariableSeq! quantifiedTypeVars = new TypeVariableSeq ();
- foreach (TypeVariable! t in typeParams)
- quantifiedTypeVars.Add(new TypeVariable (Token.NoToken, t.Name));
+ foreach(Formal/*!*/ f in arguments){
+ Contract.Assert(f != null);
+ if (f.TypedIdent.Name != "") {
+ allUnnamed = false;
+ break;
+ }
+ }
+ if (!allUnnamed) {
+ Type prevType = null;
+ for (int i = arguments.Length - 1; i >= 0; i--) {
+ TypedIdent/*!*/ curr = cce.NonNull(arguments[i]).TypedIdent;
+ if (curr.Name == "") {
+ if (prevType == null) {
+ this.errors.SemErr(curr.tok, "the type of the last parameter is unspecified");
+ break;
+ }
+ Type ty = curr.Type;
+ if (ty is UnresolvedTypeIdentifier &&
+ cce.NonNull(ty as UnresolvedTypeIdentifier).Arguments.Length == 0) {
+ curr.Name = cce.NonNull(ty as UnresolvedTypeIdentifier).Name;
+ curr.Type = prevType;
+ } else {
+ this.errors.SemErr(curr.tok, "expecting an identifier as parameter name");
+ }
+ } else {
+ prevType = curr.Type;
+ }
+ }
+ }
+ if (definition != null) {
+ // generate either an axiom or a function body
+ if (QKeyValue.FindBoolAttribute(kv, "inline")) {
+ func.Body = definition;
+ } else {
+ VariableSeq dummies = new VariableSeq();
+ ExprSeq callArgs = new ExprSeq();
+ int i = 0;
+ foreach(Formal/*!*/ f in arguments){
+ Contract.Assert(f != null);
+ string nm = f.TypedIdent.HasName ? f.TypedIdent.Name : "_" + i;
+ dummies.Add(new BoundVariable(f.tok, new TypedIdent(f.tok, nm, f.TypedIdent.Type)));
+ callArgs.Add(new IdentifierExpr(f.tok, nm));
+ i++;
+ }
+ TypeVariableSeq/*!*/ quantifiedTypeVars = new TypeVariableSeq ();
+ foreach(TypeVariable/*!*/ t in typeParams){
+ Contract.Assert(t != null);
+ quantifiedTypeVars.Add(new TypeVariable (Token.NoToken, t.Name));}
Expr call = new NAryExpr(z, new FunctionCall(new IdentifierExpr(z, z.val)), callArgs);
// specify the type of the function, because it might be that
@@ -399,20 +415,20 @@ private class BvBounds : Expr {
}
- void Axiom(out Axiom! m) {
- Expr! e; QKeyValue kv = null;
+ void Axiom(out Axiom/*!*/ m) {
+ Contract.Ensures(Contract.ValueAtReturn(out m) != null); Expr/*!*/ e; QKeyValue kv = null;
Expect(27);
while (la.kind == 25) {
Attribute(ref kv);
}
- IToken! x = t;
+ IToken/*!*/ x = t;
Proposition(out e);
Expect(7);
m = new Axiom(x,e, null, kv);
}
- void UserDefinedTypes(out List<Declaration!>! ts) {
- Declaration! decl; QKeyValue kv = null; ts = new List<Declaration!> ();
+ void UserDefinedTypes(out List<Declaration/*!*/>/*!*/ ts) {
+ Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out ts))); Declaration/*!*/ decl; QKeyValue kv = null; ts = new List<Declaration/*!*/> ();
Expect(28);
while (la.kind == 25) {
Attribute(ref kv);
@@ -427,30 +443,31 @@ private class BvBounds : Expr {
Expect(7);
}
- void GlobalVars(out VariableSeq! ds) {
- TypedIdentSeq! tyds = new TypedIdentSeq(); ds = new VariableSeq(); QKeyValue kv = null;
+ void GlobalVars(out VariableSeq/*!*/ ds) {
+ Contract.Ensures(Contract.ValueAtReturn(out ds) != null); TypedIdentSeq/*!*/ tyds = new TypedIdentSeq(); ds = new VariableSeq(); QKeyValue kv = null;
Expect(6);
while (la.kind == 25) {
Attribute(ref kv);
}
IdsTypeWheres(true, tyds);
Expect(7);
- foreach(TypedIdent! tyd in tyds) {
- ds.Add(new GlobalVariable(tyd.tok, tyd, kv));
- }
-
+ foreach(TypedIdent/*!*/ tyd in tyds){
+ Contract.Assert(tyd != null);
+ ds.Add(new GlobalVariable(tyd.tok, tyd, kv));
+ }
+
}
- void Procedure(out Procedure! proc, out /*maybe null*/ Implementation impl) {
- IToken! x;
- TypeVariableSeq! typeParams;
- VariableSeq! ins, outs;
- RequiresSeq! pre = new RequiresSeq();
- IdentifierExprSeq! mods = new IdentifierExprSeq();
- EnsuresSeq! post = new EnsuresSeq();
+ void Procedure(out Procedure/*!*/ proc, out /*maybe null*/ Implementation impl) {
+ Contract.Ensures(Contract.ValueAtReturn(out proc) != null); IToken/*!*/ x;
+ TypeVariableSeq/*!*/ typeParams;
+ VariableSeq/*!*/ ins, outs;
+ RequiresSeq/*!*/ pre = new RequiresSeq();
+ IdentifierExprSeq/*!*/ mods = new IdentifierExprSeq();
+ EnsuresSeq/*!*/ post = new EnsuresSeq();
- VariableSeq! locals = new VariableSeq();
- StmtList! stmtList;
+ VariableSeq/*!*/ locals = new VariableSeq();
+ StmtList/*!*/ stmtList;
QKeyValue kv = null;
impl = null;
@@ -473,12 +490,12 @@ private class BvBounds : Expr {
proc = new Procedure(x, x.val, typeParams, ins, outs, pre, mods, post, kv);
}
- void Implementation(out Implementation! impl) {
- IToken! x;
- TypeVariableSeq! typeParams;
- VariableSeq! ins, outs;
- VariableSeq! locals;
- StmtList! stmtList;
+ void Implementation(out Implementation/*!*/ impl) {
+ Contract.Ensures(Contract.ValueAtReturn(out impl) != null); IToken/*!*/ x;
+ TypeVariableSeq/*!*/ typeParams;
+ VariableSeq/*!*/ ins, outs;
+ VariableSeq/*!*/ locals;
+ StmtList/*!*/ stmtList;
QKeyValue kv;
Expect(31);
@@ -493,7 +510,8 @@ private class BvBounds : Expr {
if (trig != null) this.SemErr("only attributes, not triggers, allowed here");
}
- void IdsTypeWheres(bool allowWhereClauses, TypedIdentSeq! tyds) {
+ void IdsTypeWheres(bool allowWhereClauses, TypedIdentSeq/*!*/ tyds) {
+ Contract.Requires(tyds != null);
IdsTypeWhere(allowWhereClauses, tyds);
while (la.kind == 11) {
Get();
@@ -501,56 +519,60 @@ private class BvBounds : Expr {
}
}
- void LocalVars(VariableSeq! ds) {
- TypedIdentSeq! tyds = new TypedIdentSeq(); QKeyValue kv = null;
+ void LocalVars(VariableSeq/*!*/ ds) {
+ Contract.Ensures(Contract.ValueAtReturn(out ds) != null); TypedIdentSeq/*!*/ tyds = new TypedIdentSeq(); QKeyValue kv = null;
Expect(6);
while (la.kind == 25) {
Attribute(ref kv);
}
IdsTypeWheres(true, tyds);
Expect(7);
- foreach(TypedIdent! tyd in tyds) {
- ds.Add(new LocalVariable(tyd.tok, tyd, kv));
- }
-
+ foreach(TypedIdent/*!*/ tyd in tyds){
+ Contract.Assert(tyd != null);
+ ds.Add(new LocalVariable(tyd.tok, tyd, kv));
+ }
+
}
- void ProcFormals(bool incoming, bool allowWhereClauses, out VariableSeq! ds) {
- TypedIdentSeq! tyds = new TypedIdentSeq(); ds = new VariableSeq();
+ void ProcFormals(bool incoming, bool allowWhereClauses, out VariableSeq/*!*/ ds) {
+ Contract.Ensures(Contract.ValueAtReturn(out ds) != null); TypedIdentSeq/*!*/ tyds = new TypedIdentSeq(); ds = new VariableSeq();
Expect(8);
if (la.kind == 1) {
IdsTypeWheres(allowWhereClauses, tyds);
}
Expect(9);
- foreach (TypedIdent! tyd in tyds) {
- ds.Add(new Formal(tyd.tok, tyd, incoming));
- }
-
+ foreach(TypedIdent/*!*/ tyd in tyds){
+ Contract.Assert(tyd != null);
+ ds.Add(new Formal(tyd.tok, tyd, incoming));
+ }
+
}
- void BoundVars(IToken! x, out VariableSeq! ds) {
- TypedIdentSeq! tyds = new TypedIdentSeq(); ds = new VariableSeq();
+ void BoundVars(IToken/*!*/ x, out VariableSeq/*!*/ ds) {
+ Contract.Requires(x != null); Contract.Ensures(Contract.ValueAtReturn(out ds) != null); TypedIdentSeq/*!*/ tyds = new TypedIdentSeq(); ds = new VariableSeq();
IdsTypeWheres(false, tyds);
- foreach (TypedIdent! tyd in tyds) {
- ds.Add(new BoundVariable(tyd.tok, tyd));
- }
-
+ foreach(TypedIdent/*!*/ tyd in tyds){
+ Contract.Assert(tyd != null);
+ ds.Add(new BoundVariable(tyd.tok, tyd));
+ }
+
}
- void IdsType(out TypedIdentSeq! tyds) {
- TokenSeq! ids; Bpl.Type! ty;
+ void IdsType(out TypedIdentSeq/*!*/ tyds) {
+ Contract.Ensures(Contract.ValueAtReturn(out tyds) != null); TokenSeq/*!*/ ids; Bpl.Type/*!*/ ty;
Idents(out ids);
Expect(10);
Type(out ty);
tyds = new TypedIdentSeq();
- foreach (Token! id in ids) {
- tyds.Add(new TypedIdent(id, id.val, ty, null));
- }
-
+ foreach(Token/*!*/ id in ids){
+ Contract.Assert(id != null);
+ tyds.Add(new TypedIdent(id, id.val, ty, null));
+ }
+
}
- void Idents(out TokenSeq! xs) {
- IToken! id; xs = new TokenSeq();
+ void Idents(out TokenSeq/*!*/ xs) {
+ Contract.Ensures(Contract.ValueAtReturn(out xs) != null); IToken/*!*/ id; xs = new TokenSeq();
Ident(out id);
xs.Add(id);
while (la.kind == 11) {
@@ -560,13 +582,13 @@ private class BvBounds : Expr {
}
}
- void Type(out Bpl.Type! ty) {
- IToken! tok; ty = dummyType;
+ void Type(out Bpl.Type/*!*/ ty) {
+ Contract.Ensures(Contract.ValueAtReturn(out ty) != null); IToken/*!*/ tok; ty = dummyType;
if (la.kind == 8 || la.kind == 13 || la.kind == 14) {
TypeAtom(out ty);
} else if (la.kind == 1) {
Ident(out tok);
- TypeSeq! args = new TypeSeq ();
+ TypeSeq/*!*/ args = new TypeSeq ();
if (StartOf(2)) {
TypeArgs(args);
}
@@ -576,8 +598,8 @@ private class BvBounds : Expr {
} else SynErr(92);
}
- void IdsTypeWhere(bool allowWhereClauses, TypedIdentSeq! tyds) {
- TokenSeq! ids; Bpl.Type! ty; Expr wh = null; Expr! nne;
+ void IdsTypeWhere(bool allowWhereClauses, TypedIdentSeq/*!*/ tyds) {
+ Contract.Requires(tyds != null); TokenSeq/*!*/ ids; Bpl.Type/*!*/ ty; Expr wh = null; Expr/*!*/ nne;
Idents(out ids);
Expect(10);
Type(out ty);
@@ -591,14 +613,15 @@ private class BvBounds : Expr {
}
}
- foreach (Token! id in ids) {
- tyds.Add(new TypedIdent(id, id.val, ty, wh));
- }
-
+ foreach(Token/*!*/ id in ids){
+ Contract.Assert(id != null);
+ tyds.Add(new TypedIdent(id, id.val, ty, wh));
+ }
+
}
- void Expression(out Expr! e0) {
- IToken! x; Expr! e1;
+ void Expression(out Expr/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1;
ImpliesExpression(false, out e0);
while (la.kind == 50 || la.kind == 51) {
EquivOp();
@@ -608,8 +631,8 @@ private class BvBounds : Expr {
}
}
- void TypeAtom(out Bpl.Type! ty) {
- ty = dummyType;
+ void TypeAtom(out Bpl.Type/*!*/ ty) {
+ Contract.Ensures(Contract.ValueAtReturn(out ty) != null); ty = dummyType;
if (la.kind == 13) {
Get();
ty = new BasicType(t, SimpleType.Int);
@@ -623,7 +646,8 @@ private class BvBounds : Expr {
} else SynErr(93);
}
- void Ident(out IToken! x) {
+ void Ident(out IToken/*!*/ x) {
+ Contract.Ensures(Contract.ValueAtReturn(out x) != null);
Expect(1);
x = t;
if (x.val.StartsWith("\\"))
@@ -631,8 +655,8 @@ private class BvBounds : Expr {
}
- void TypeArgs(TypeSeq! ts) {
- IToken! tok; Type! ty;
+ void TypeArgs(TypeSeq/*!*/ ts) {
+ Contract.Requires(ts != null); IToken/*!*/ tok; Type/*!*/ ty;
if (la.kind == 8 || la.kind == 13 || la.kind == 14) {
TypeAtom(out ty);
ts.Add(ty);
@@ -641,7 +665,7 @@ private class BvBounds : Expr {
}
} else if (la.kind == 1) {
Ident(out tok);
- TypeSeq! args = new TypeSeq ();
+ TypeSeq/*!*/ args = new TypeSeq ();
ts.Add(new UnresolvedTypeIdentifier (tok, tok.val, args));
if (StartOf(2)) {
TypeArgs(ts);
@@ -652,12 +676,12 @@ private class BvBounds : Expr {
} else SynErr(94);
}
- void MapType(out Bpl.Type! ty) {
- IToken tok = null;
- IToken! nnTok;
- TypeSeq! arguments = new TypeSeq();
- Type! result;
- TypeVariableSeq! typeParameters = new TypeVariableSeq();
+ void MapType(out Bpl.Type/*!*/ ty) {
+ Contract.Ensures(Contract.ValueAtReturn(out ty) != null); IToken tok = null;
+ IToken/*!*/ nnTok;
+ TypeSeq/*!*/ arguments = new TypeSeq();
+ Type/*!*/ result;
+ TypeVariableSeq/*!*/ typeParameters = new TypeVariableSeq();
if (la.kind == 17) {
TypeParams(out nnTok, out typeParameters);
@@ -674,20 +698,21 @@ private class BvBounds : Expr {
}
- void TypeParams(out IToken! tok, out Bpl.TypeVariableSeq! typeParams) {
- TokenSeq! typeParamToks;
+ void TypeParams(out IToken/*!*/ tok, out Bpl.TypeVariableSeq/*!*/ typeParams) {
+ Contract.Ensures(Contract.ValueAtReturn(out tok) != null); Contract.Ensures(Contract.ValueAtReturn(out typeParams) != null); TokenSeq/*!*/ typeParamToks;
Expect(17);
tok = t;
Idents(out typeParamToks);
Expect(18);
typeParams = new TypeVariableSeq ();
- foreach (Token! id in typeParamToks)
- typeParams.Add(new TypeVariable(id, id.val));
-
+ foreach(Token/*!*/ id in typeParamToks){
+ Contract.Assert(id != null);
+ typeParams.Add(new TypeVariable(id, id.val));}
+
}
- void Types(TypeSeq! ts) {
- Bpl.Type! ty;
+ void Types(TypeSeq/*!*/ ts) {
+ Contract.Requires(ts != null); Bpl.Type/*!*/ ty;
Type(out ty);
ts.Add(ty);
while (la.kind == 11) {
@@ -697,13 +722,13 @@ private class BvBounds : Expr {
}
}
- void OrderSpec(out bool ChildrenComplete, out List<ConstantParent!> Parents) {
- ChildrenComplete = false;
+ void OrderSpec(out bool ChildrenComplete, out List<ConstantParent/*!*/> Parents) {
+ Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out Parents),true)); ChildrenComplete = false;
Parents = null;
bool u;
- IToken! parent;
+ IToken/*!*/ parent;
Expect(21);
- Parents = new List<ConstantParent!> ();
+ Parents = new List<ConstantParent/*!*/> ();
u = false;
if (la.kind == 1 || la.kind == 20) {
if (la.kind == 20) {
@@ -731,15 +756,15 @@ private class BvBounds : Expr {
}
}
- void VarOrType(out TypedIdent! tyd) {
- string! varName = ""; Bpl.Type! ty; IToken! tok;
+ void VarOrType(out TypedIdent/*!*/ tyd) {
+ Contract.Ensures(Contract.ValueAtReturn(out tyd) != null); string/*!*/ varName = ""; Bpl.Type/*!*/ ty; IToken/*!*/ tok;
Type(out ty);
tok = ty.tok;
if (la.kind == 10) {
Get();
if (ty is UnresolvedTypeIdentifier &&
- ((!)(ty as UnresolvedTypeIdentifier)).Arguments.Length == 0) {
- varName = ((!)(ty as UnresolvedTypeIdentifier)).Name;
+ cce.NonNull(ty as UnresolvedTypeIdentifier).Arguments.Length == 0) {
+ varName = cce.NonNull(ty as UnresolvedTypeIdentifier).Name;
} else {
this.SemErr("expected identifier before ':'");
}
@@ -749,13 +774,14 @@ private class BvBounds : Expr {
tyd = new TypedIdent(tok, varName, ty);
}
- void Proposition(out Expr! e) {
+ void Proposition(out Expr/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null);
Expression(out e);
}
- void UserDefinedType(out Declaration! decl, QKeyValue kv) {
- IToken! id; IToken! id2; TokenSeq! paramTokens = new TokenSeq ();
- Type! body = dummyType; bool synonym = false;
+ void UserDefinedType(out Declaration/*!*/ decl, QKeyValue kv) {
+ Contract.Ensures(Contract.ValueAtReturn(out decl) != null); IToken/*!*/ id; IToken/*!*/ id2; TokenSeq/*!*/ paramTokens = new TokenSeq ();
+ Type/*!*/ body = dummyType; bool synonym = false;
Ident(out id);
if (la.kind == 1) {
WhiteSpaceIdents(out paramTokens);
@@ -766,18 +792,19 @@ private class BvBounds : Expr {
synonym = true;
}
if (synonym) {
- TypeVariableSeq! typeParams = new TypeVariableSeq();
- foreach (Token! t in paramTokens)
- typeParams.Add(new TypeVariable(t, t.val));
- decl = new TypeSynonymDecl(id, id.val, typeParams, body, kv);
- } else {
- decl = new TypeCtorDecl(id, id.val, paramTokens.Length, kv);
- }
-
+ TypeVariableSeq/*!*/ typeParams = new TypeVariableSeq();
+ foreach(Token/*!*/ t in paramTokens){
+ Contract.Assert(t != null);
+ typeParams.Add(new TypeVariable(t, t.val));}
+ decl = new TypeSynonymDecl(id, id.val, typeParams, body, kv);
+ } else {
+ decl = new TypeCtorDecl(id, id.val, paramTokens.Length, kv);
+ }
+
}
- void WhiteSpaceIdents(out TokenSeq! xs) {
- IToken! id; xs = new TokenSeq();
+ void WhiteSpaceIdents(out TokenSeq/*!*/ xs) {
+ Contract.Ensures(Contract.ValueAtReturn(out xs) != null); IToken/*!*/ id; xs = new TokenSeq();
Ident(out id);
xs.Add(id);
while (la.kind == 1) {
@@ -786,9 +813,10 @@ private class BvBounds : Expr {
}
}
- void ProcSignature(bool allowWhereClausesOnFormals, out IToken! name, out TypeVariableSeq! typeParams,
-out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
- IToken! typeParamTok; typeParams = new TypeVariableSeq();
+ void ProcSignature(bool allowWhereClausesOnFormals, out IToken/*!*/ name, out TypeVariableSeq/*!*/ typeParams,
+out VariableSeq/*!*/ ins, out VariableSeq/*!*/ outs, out QKeyValue kv) {
+ Contract.Ensures(Contract.ValueAtReturn(out name) != null); Contract.Ensures(Contract.ValueAtReturn(out typeParams) != null); Contract.Ensures(Contract.ValueAtReturn(out ins) != null); Contract.Ensures(Contract.ValueAtReturn(out outs) != null);
+ IToken/*!*/ typeParamTok; typeParams = new TypeVariableSeq();
outs = new VariableSeq(); kv = null;
while (la.kind == 25) {
Attribute(ref kv);
@@ -804,16 +832,17 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
}
- void Spec(RequiresSeq! pre, IdentifierExprSeq! mods, EnsuresSeq! post) {
- TokenSeq! ms;
+ void Spec(RequiresSeq/*!*/ pre, IdentifierExprSeq/*!*/ mods, EnsuresSeq/*!*/ post) {
+ Contract.Requires(pre != null); Contract.Requires(mods != null); Contract.Requires(post != null); TokenSeq/*!*/ ms;
if (la.kind == 32) {
Get();
if (la.kind == 1) {
Idents(out ms);
- foreach (IToken! m in ms) {
- mods.Add(new IdentifierExpr(m, m.val));
- }
-
+ foreach(IToken/*!*/ m in ms){
+ Contract.Assert(m != null);
+ mods.Add(new IdentifierExpr(m, m.val));
+ }
+
}
Expect(7);
} else if (la.kind == 33) {
@@ -824,8 +853,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(95);
}
- void ImplBody(out VariableSeq! locals, out StmtList! stmtList) {
- locals = new VariableSeq();
+ void ImplBody(out VariableSeq/*!*/ locals, out StmtList/*!*/ stmtList) {
+ Contract.Ensures(Contract.ValueAtReturn(out locals) != null); Contract.Ensures(Contract.ValueAtReturn(out stmtList) != null); locals = new VariableSeq();
Expect(25);
while (la.kind == 6) {
LocalVars(locals);
@@ -833,8 +862,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
StmtList(out stmtList);
}
- void SpecPrePost(bool free, RequiresSeq! pre, EnsuresSeq! post) {
- Expr! e; VariableSeq! locals; BlockSeq! blocks; Token tok = null; QKeyValue kv = null;
+ void SpecPrePost(bool free, RequiresSeq/*!*/ pre, EnsuresSeq/*!*/ post) {
+ Contract.Requires(pre != null); Contract.Requires(post != null); Expr/*!*/ e; VariableSeq/*!*/ locals; BlockSeq/*!*/ blocks; Token tok = null; QKeyValue kv = null;
if (la.kind == 34) {
Get();
tok = t;
@@ -856,30 +885,30 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(96);
}
- void StmtList(out StmtList! stmtList) {
- List<BigBlock!> bigblocks = new List<BigBlock!>();
+ void StmtList(out StmtList/*!*/ stmtList) {
+ Contract.Ensures(Contract.ValueAtReturn(out stmtList) != null); List<BigBlock/*!*/> bigblocks = new List<BigBlock/*!*/>();
/* built-up state for the current BigBlock: */
IToken startToken = null; string currentLabel = null;
CmdSeq cs = null; /* invariant: startToken != null ==> cs != null */
/* temporary variables: */
IToken label; Cmd c; BigBlock b;
- StructuredCmd ec = null; StructuredCmd! ecn;
- TransferCmd tc = null; TransferCmd! tcn;
+ StructuredCmd ec = null; StructuredCmd/*!*/ ecn;
+ TransferCmd tc = null; TransferCmd/*!*/ tcn;
while (StartOf(5)) {
if (StartOf(6)) {
LabelOrCmd(out c, out label);
if (c != null) {
// LabelOrCmd read a Cmd
- assert label == null;
+ Contract.Assert(label == null);
if (startToken == null) { startToken = c.tok; cs = new CmdSeq(); }
- assert cs != null;
+ Contract.Assert(cs != null);
cs.Add(c);
} else {
// LabelOrCmd read a label
- assert label != null;
+ Contract.Assert(label != null);
if (startToken != null) {
- assert cs != null;
+ Contract.Assert(cs != null);
// dump the built-up state into a BigBlock
b = new BigBlock(startToken, currentLabel, cs, null, null);
bigblocks.Add(b);
@@ -894,7 +923,7 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
StructuredCmd(out ecn);
ec = ecn;
if (startToken == null) { startToken = ec.tok; cs = new CmdSeq(); }
- assert cs != null;
+ Contract.Assert(cs != null);
b = new BigBlock(startToken, currentLabel, cs, ec, null);
bigblocks.Add(b);
startToken = null; currentLabel = null; cs = null;
@@ -903,7 +932,7 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
TransferCmd(out tcn);
tc = tcn;
if (startToken == null) { startToken = tc.tok; cs = new CmdSeq(); }
- assert cs != null;
+ Contract.Assert(cs != null);
b = new BigBlock(startToken, currentLabel, cs, null, tc);
bigblocks.Add(b);
startToken = null; currentLabel = null; cs = null;
@@ -911,12 +940,12 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
}
Expect(26);
- IToken! endCurly = t;
+ IToken/*!*/ endCurly = t;
if (startToken == null && bigblocks.Count == 0) {
startToken = t; cs = new CmdSeq();
}
if (startToken != null) {
- assert cs != null;
+ Contract.Assert(cs != null);
b = new BigBlock(startToken, currentLabel, cs, null, null);
bigblocks.Add(b);
}
@@ -926,11 +955,11 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
void LabelOrCmd(out Cmd c, out IToken label) {
- IToken! x; Expr! e;
- TokenSeq! xs;
+ IToken/*!*/ x; Expr/*!*/ e;
+ TokenSeq/*!*/ xs;
IdentifierExprSeq ids;
c = dummyCmd; label = null;
- Cmd! cn;
+ Cmd/*!*/ cn;
QKeyValue kv = null;
if (la.kind == 1) {
@@ -956,11 +985,12 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
Idents(out xs);
Expect(7);
ids = new IdentifierExprSeq();
- foreach (IToken! y in xs) {
- ids.Add(new IdentifierExpr(y, y.val));
- }
- c = new HavocCmd(x,ids);
-
+ foreach(IToken/*!*/ y in xs){
+ Contract.Assert(y != null);
+ ids.Add(new IdentifierExpr(y, y.val));
+ }
+ c = new HavocCmd(x,ids);
+
} else if (la.kind == 48) {
CallCmd(out cn);
Expect(7);
@@ -968,9 +998,9 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(97);
}
- void StructuredCmd(out StructuredCmd! ec) {
- ec = dummyStructuredCmd; assume ec.IsPeerConsistent;
- IfCmd! ifcmd; WhileCmd! wcmd; BreakCmd! bcmd;
+ void StructuredCmd(out StructuredCmd/*!*/ ec) {
+ Contract.Ensures(Contract.ValueAtReturn(out ec) != null); ec = dummyStructuredCmd; Contract.Assume(cce.IsPeerConsistent(ec));
+ IfCmd/*!*/ ifcmd; WhileCmd/*!*/ wcmd; BreakCmd/*!*/ bcmd;
if (la.kind == 38) {
IfCmd(out ifcmd);
@@ -984,18 +1014,20 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(98);
}
- void TransferCmd(out TransferCmd! tc) {
- tc = dummyTransferCmd;
- Token y; TokenSeq! xs;
+ void TransferCmd(out TransferCmd/*!*/ tc) {
+ Contract.Ensures(Contract.ValueAtReturn(out tc) != null); tc = dummyTransferCmd;
+ Token y; TokenSeq/*!*/ xs;
StringSeq ss = new StringSeq();
if (la.kind == 36) {
Get();
y = t;
Idents(out xs);
- foreach (IToken! s in xs) { ss.Add(s.val); }
- tc = new GotoCmd(y, ss);
-
+ foreach(IToken/*!*/ s in xs){
+ Contract.Assert(s != null);
+ ss.Add(s.val); }
+ tc = new GotoCmd(y, ss);
+
} else if (la.kind == 37) {
Get();
tc = new ReturnCmd(t);
@@ -1003,12 +1035,12 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
Expect(7);
}
- void IfCmd(out IfCmd! ifcmd) {
- IToken! x;
+ void IfCmd(out IfCmd/*!*/ ifcmd) {
+ Contract.Ensures(Contract.ValueAtReturn(out ifcmd) != null); IToken/*!*/ x;
Expr guard;
- StmtList! thn;
- IfCmd! elseIf; IfCmd elseIfOption = null;
- StmtList! els; StmtList elseOption = null;
+ StmtList/*!*/ thn;
+ IfCmd/*!*/ elseIf; IfCmd elseIfOption = null;
+ StmtList/*!*/ els; StmtList elseOption = null;
Expect(38);
x = t;
@@ -1029,16 +1061,16 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
ifcmd = new IfCmd(x, guard, thn, elseIfOption, elseOption);
}
- void WhileCmd(out WhileCmd! wcmd) {
- IToken! x; Token z;
- Expr guard; Expr! e; bool isFree;
- List<PredicateCmd!> invariants = new List<PredicateCmd!>();
- StmtList! body;
+ void WhileCmd(out WhileCmd/*!*/ wcmd) {
+ Contract.Ensures(Contract.ValueAtReturn(out wcmd) != null); IToken/*!*/ x; Token z;
+ Expr guard; Expr/*!*/ e; bool isFree;
+ List<PredicateCmd/*!*/> invariants = new List<PredicateCmd/*!*/>();
+ StmtList/*!*/ body;
Expect(40);
x = t;
Guard(out guard);
- assume guard == null || Owner.None(guard);
+ Contract.Assume(guard == null || cce.Owner.None(guard));
while (la.kind == 33 || la.kind == 41) {
isFree = false; z = la/*lookahead token*/;
if (la.kind == 33) {
@@ -1060,8 +1092,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
wcmd = new WhileCmd(x, guard, invariants, body);
}
- void BreakCmd(out BreakCmd! bcmd) {
- IToken! x; IToken! y;
+ void BreakCmd(out BreakCmd/*!*/ bcmd) {
+ Contract.Ensures(Contract.ValueAtReturn(out bcmd) != null); IToken/*!*/ x; IToken/*!*/ y;
string breakLabel = null;
Expect(43);
@@ -1075,7 +1107,7 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
void Guard(out Expr e) {
- Expr! ee; e = null;
+ Expr/*!*/ ee; e = null;
Expect(8);
if (la.kind == 42) {
Get();
@@ -1088,12 +1120,12 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
void LabelOrAssign(out Cmd c, out IToken label) {
- IToken! id; IToken! x, y; Expr! e, e0;
+ IToken/*!*/ id; IToken/*!*/ x, y; Expr/*!*/ e, e0;
c = dummyCmd; label = null;
- AssignLhs! lhs;
- List<AssignLhs!>! lhss;
- List<Expr!>! rhss;
- List<Expr!>! indexes;
+ AssignLhs/*!*/ lhs;
+ List<AssignLhs/*!*/>/*!*/ lhss;
+ List<Expr/*!*/>/*!*/ rhss;
+ List<Expr/*!*/>/*!*/ indexes;
Ident(out id);
x = t;
@@ -1101,7 +1133,7 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
Get();
c = null; label = x;
} else if (la.kind == 11 || la.kind == 15 || la.kind == 47) {
- lhss = new List<AssignLhs!>();
+ lhss = new List<AssignLhs/*!*/>();
lhs = new SimpleAssignLhs(id, new IdentifierExpr(id, id.val));
while (la.kind == 15) {
MapAssignIndex(out y, out indexes);
@@ -1121,7 +1153,7 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
Expect(47);
x = t; /* use location of := */
Expression(out e0);
- rhss = new List<Expr!> ();
+ rhss = new List<Expr/*!*/> ();
rhss.Add(e0);
while (la.kind == 11) {
Get();
@@ -1133,10 +1165,10 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(102);
}
- void CallCmd(out Cmd! c) {
- IToken! x; IToken! first; IToken p;
- List<IdentifierExpr>! ids = new List<IdentifierExpr>();
- List<Expr>! es = new List<Expr>();
+ void CallCmd(out Cmd/*!*/ c) {
+ Contract.Ensures(Contract.ValueAtReturn(out c) != null); IToken/*!*/ x; IToken/*!*/ first; IToken p;
+ List<IdentifierExpr>/*!*/ ids = new List<IdentifierExpr>();
+ List<Expr>/*!*/ es = new List<Expr>();
QKeyValue kv = null;
Expr en; List<Expr> args;
c = dummyCmd;
@@ -1254,9 +1286,9 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(104);
}
- void MapAssignIndex(out IToken! x, out List<Expr!>! indexes) {
- indexes = new List<Expr!> ();
- Expr! e;
+ void MapAssignIndex(out IToken/*!*/ x, out List<Expr/*!*/>/*!*/ indexes) {
+ Contract.Ensures(Contract.ValueAtReturn(out x) != null); Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out indexes))); indexes = new List<Expr/*!*/> ();
+ Expr/*!*/ e;
Expect(15);
x = t;
@@ -1274,7 +1306,7 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
void CallForallArg(out Expr exprOptional) {
exprOptional = null;
- Expr! e;
+ Expr/*!*/ e;
if (la.kind == 42) {
Get();
@@ -1286,7 +1318,7 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
void CallOutIdent(out IToken id) {
id = null;
- IToken! p;
+ IToken/*!*/ p;
if (la.kind == 42) {
Get();
@@ -1296,8 +1328,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(106);
}
- void Expressions(out ExprSeq! es) {
- Expr! e; es = new ExprSeq();
+ void Expressions(out ExprSeq/*!*/ es) {
+ Contract.Ensures(Contract.ValueAtReturn(out es) != null); Expr/*!*/ e; es = new ExprSeq();
Expression(out e);
es.Add(e);
while (la.kind == 11) {
@@ -1307,8 +1339,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
}
- void ImpliesExpression(bool noExplies, out Expr! e0) {
- IToken! x; Expr! e1;
+ void ImpliesExpression(bool noExplies, out Expr/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1;
LogicalExpression(out e0);
if (StartOf(9)) {
if (la.kind == 52 || la.kind == 53) {
@@ -1341,8 +1373,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(107);
}
- void LogicalExpression(out Expr! e0) {
- IToken! x; Expr! e1; BinaryOperator.Opcode op;
+ void LogicalExpression(out Expr/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; BinaryOperator.Opcode op;
RelationalExpression(out e0);
if (StartOf(10)) {
if (la.kind == 56 || la.kind == 57) {
@@ -1387,8 +1419,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(109);
}
- void RelationalExpression(out Expr! e0) {
- IToken! x; Expr! e1; BinaryOperator.Opcode op;
+ void RelationalExpression(out Expr/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; BinaryOperator.Opcode op;
BvTerm(out e0);
if (StartOf(11)) {
RelOp(out x, out op);
@@ -1413,8 +1445,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(111);
}
- void BvTerm(out Expr! e0) {
- IToken! x; Expr! e1;
+ void BvTerm(out Expr/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1;
Term(out e0);
while (la.kind == 68) {
Get();
@@ -1424,8 +1456,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
}
- void RelOp(out IToken! x, out BinaryOperator.Opcode op) {
- x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/;
+ void RelOp(out IToken/*!*/ x, out BinaryOperator.Opcode op) {
+ Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/;
switch (la.kind) {
case 60: {
Get();
@@ -1481,8 +1513,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
}
- void Term(out Expr! e0) {
- IToken! x; Expr! e1; BinaryOperator.Opcode op;
+ void Term(out Expr/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; BinaryOperator.Opcode op;
Factor(out e0);
while (la.kind == 69 || la.kind == 70) {
AddOp(out x, out op);
@@ -1491,8 +1523,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
}
- void Factor(out Expr! e0) {
- IToken! x; Expr! e1; BinaryOperator.Opcode op;
+ void Factor(out Expr/*!*/ e0) {
+ Contract.Ensures(Contract.ValueAtReturn(out e0) != null); IToken/*!*/ x; Expr/*!*/ e1; BinaryOperator.Opcode op;
UnaryExpression(out e0);
while (la.kind == 42 || la.kind == 71 || la.kind == 72) {
MulOp(out x, out op);
@@ -1501,8 +1533,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
}
- void AddOp(out IToken! x, out BinaryOperator.Opcode op) {
- x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/;
+ void AddOp(out IToken/*!*/ x, out BinaryOperator.Opcode op) {
+ Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/;
if (la.kind == 69) {
Get();
x = t; op=BinaryOperator.Opcode.Add;
@@ -1512,8 +1544,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(113);
}
- void UnaryExpression(out Expr! e) {
- IToken! x;
+ void UnaryExpression(out Expr/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x;
e = dummyExpr;
if (la.kind == 70) {
@@ -1531,8 +1563,8 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(114);
}
- void MulOp(out IToken! x, out BinaryOperator.Opcode op) {
- x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/;
+ void MulOp(out IToken/*!*/ x, out BinaryOperator.Opcode op) {
+ Contract.Ensures(Contract.ValueAtReturn(out x) != null); x = Token.NoToken; op=BinaryOperator.Opcode.Add/*(dummy)*/;
if (la.kind == 42) {
Get();
x = t; op=BinaryOperator.Opcode.Mul;
@@ -1553,9 +1585,9 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(116);
}
- void CoercionExpression(out Expr! e) {
- IToken! x;
- Type! coercedTo;
+ void CoercionExpression(out Expr/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x;
+ Type/*!*/ coercedTo;
BigNum bn;
ArrayExpression(out e);
@@ -1578,11 +1610,11 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
}
- void ArrayExpression(out Expr! e) {
- IToken! x;
- Expr! index0 = dummyExpr; Expr! e1;
+ void ArrayExpression(out Expr/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x;
+ Expr/*!*/ index0 = dummyExpr; Expr/*!*/ e1;
bool store; bool bvExtract;
- ExprSeq! allArgs = dummyExprSeq;
+ ExprSeq/*!*/ allArgs = dummyExprSeq;
AtomExpression(out e);
while (la.kind == 15) {
@@ -1644,16 +1676,16 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
}
- void AtomExpression(out Expr! e) {
- IToken! x; int n; BigNum bn;
- ExprSeq! es; VariableSeq! ds; Trigger trig;
- TypeVariableSeq! typeParams;
- IdentifierExpr! id;
- Bpl.Type! ty;
+ void AtomExpression(out Expr/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null); IToken/*!*/ x; int n; BigNum bn;
+ ExprSeq/*!*/ es; VariableSeq/*!*/ ds; Trigger trig;
+ TypeVariableSeq/*!*/ typeParams;
+ IdentifierExpr/*!*/ id;
+ Bpl.Type/*!*/ ty;
QKeyValue kv;
e = dummyExpr;
- VariableSeq! locals;
- List<Block!>! blocks;
+ VariableSeq/*!*/ locals;
+ List<Block/*!*/>/*!*/ blocks;
switch (la.kind) {
case 75: {
@@ -1768,13 +1800,14 @@ out VariableSeq! ins, out VariableSeq! outs, out QKeyValue kv) {
} else SynErr(121);
}
- void QuantifierBody(IToken! q, out TypeVariableSeq! typeParams, out VariableSeq! ds,
-out QKeyValue kv, out Trigger trig, out Expr! body) {
+ void QuantifierBody(IToken/*!*/ q, out TypeVariableSeq/*!*/ typeParams, out VariableSeq/*!*/ ds,
+out QKeyValue kv, out Trigger trig, out Expr/*!*/ body) {
+ Contract.Requires(q != null); Contract.Ensures(Contract.ValueAtReturn(out typeParams) != null); Contract.Ensures(Contract.ValueAtReturn(out ds) != null); Contract.Ensures(Contract.ValueAtReturn(out body) != null);
trig = null; typeParams = new TypeVariableSeq ();
- IToken! tok; Expr! e; ExprSeq! es;
- kv = null; string key; string value;
- ds = new VariableSeq ();
-
+ IToken/*!*/ tok; Expr/*!*/ e; ExprSeq/*!*/ es;
+ kv = null; string key; string value;
+ ds = new VariableSeq ();
+
if (la.kind == 17) {
TypeParams(out tok, out typeParams);
if (la.kind == 1) {
@@ -1806,9 +1839,10 @@ out QKeyValue kv, out Trigger trig, out Expr! body) {
} else SynErr(124);
}
- void IfThenElseExpression(out Expr! e) {
- IToken! tok;
- Expr! e0, e1, e2;
+ void IfThenElseExpression(out Expr/*!*/ e) {
+ Contract.Ensures(Contract.ValueAtReturn(out e) != null);
+ IToken/*!*/ tok;
+ Expr/*!*/ e0, e1, e2;
e = dummyExpr;
Expect(38);
tok = t;
@@ -1820,9 +1854,9 @@ out QKeyValue kv, out Trigger trig, out Expr! body) {
e = new NAryExpr(tok, new IfThenElse(tok), new ExprSeq(e0, e1, e2));
}
- void CodeExpression(out VariableSeq! locals, out List<Block!>! blocks) {
- locals = new VariableSeq(); Block! b;
- blocks = new List<Block!>();
+ void CodeExpression(out VariableSeq/*!*/ locals, out List<Block/*!*/>/*!*/ blocks) {
+ Contract.Ensures(Contract.ValueAtReturn(out locals) != null); Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out blocks))); locals = new VariableSeq(); Block/*!*/ b;
+ blocks = new List<Block/*!*/>();
Expect(78);
while (la.kind == 6) {
@@ -1837,24 +1871,24 @@ out QKeyValue kv, out Trigger trig, out Expr! body) {
Expect(79);
}
- void SpecBlock(out Block! b) {
- IToken! x; IToken! y;
+ void SpecBlock(out Block/*!*/ b) {
+ Contract.Ensures(Contract.ValueAtReturn(out b) != null); IToken/*!*/ x; IToken/*!*/ y;
Cmd c; IToken label;
CmdSeq cs = new CmdSeq();
- TokenSeq! xs;
+ TokenSeq/*!*/ xs;
StringSeq ss = new StringSeq();
b = dummyBlock;
- Expr! e;
+ Expr/*!*/ e;
Ident(out x);
Expect(10);
while (StartOf(6)) {
LabelOrCmd(out c, out label);
if (c != null) {
- assert label == null;
+ Contract.Assert(label == null);
cs.Add(c);
} else {
- assert label != null;
+ Contract.Assert(label != null);
SemErr("SpecBlock's can only have one label");
}
@@ -1863,9 +1897,11 @@ out QKeyValue kv, out Trigger trig, out Expr! body) {
Get();
y = t;
Idents(out xs);
- foreach (IToken! s in xs) { ss.Add(s.val); }
- b = new Block(x,x.val,cs,new GotoCmd(y,ss));
-
+ foreach(IToken/*!*/ s in xs){
+ Contract.Assert(s != null);
+ ss.Add(s.val); }
+ b = new Block(x,x.val,cs,new GotoCmd(y,ss));
+
} else if (la.kind == 37) {
Get();
Expression(out e);
@@ -1875,16 +1911,16 @@ out QKeyValue kv, out Trigger trig, out Expr! body) {
}
void AttributeOrTrigger(ref QKeyValue kv, ref Trigger trig) {
- IToken! tok; Expr! e; ExprSeq! es;
+ IToken/*!*/ tok; Expr/*!*/ e; ExprSeq/*!*/ es;
string key; string value;
- List<object!> parameters; object! param;
+ List<object/*!*/> parameters; object/*!*/ param;
Expect(25);
tok = t;
if (la.kind == 10) {
Get();
Expect(1);
- key = t.val; parameters = new List<object!>();
+ key = t.val; parameters = new List<object/*!*/>();
if (StartOf(14)) {
AttributeParameter(out param);
parameters.Add(param);
@@ -1931,9 +1967,10 @@ out QKeyValue kv, out Trigger trig, out Expr! body) {
Expect(26);
}
- void AttributeParameter(out object! o) {
+ void AttributeParameter(out object/*!*/ o) {
+ Contract.Ensures(Contract.ValueAtReturn(out o) != null);
o = "error";
- Expr! e;
+ Expr/*!*/ e;
if (la.kind == 4) {
Get();
@@ -1963,7 +2000,7 @@ out QKeyValue kv, out Trigger trig, out Expr! body) {
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,T,x, x,x,x,x, x,x,x,x, x,x,x,T, x,x,x,T, x,x,x,T, T,x,T,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,T,x,x, x,x,x,x, T,x,x,x, x,T,T,T, 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},
@@ -1986,10 +2023,10 @@ out QKeyValue kv, out Trigger trig, out Expr! body) {
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;
@@ -2132,12 +2169,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++;
}
@@ -2147,7 +2186,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/Core/ParserHelper.cs b/Source/Core/ParserHelper.cs
index 67cd261a..465b9245 100644
--- a/Source/Core/ParserHelper.cs
+++ b/Source/Core/ParserHelper.cs
@@ -1,188 +1,250 @@
using System.Text;
using System.Collections.Generic;
using System.IO;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
namespace Microsoft.Boogie {
[Immutable]
public interface IToken {
- int kind {get; set; } // token kind
- string filename {get; set; } // token file
- int pos {get; set; } // token position in the source text (starting at 0)
- int col {get; set; } // token column (starting at 0)
- int line {get; set; } // token line (starting at 1)
- string/*!*/ val {get; set; } // token value
-
- bool IsValid { get; }
+ int kind {
+ get;
+ set;
+ } // token kind
+ string filename {
+ get;
+ set;
+ } // token file
+ int pos {
+ get;
+ set;
+ } // token position in the source text (starting at 0)
+ int col {
+ get;
+ set;
+ } // token column (starting at 0)
+ int line {
+ get;
+ set;
+ } // token line (starting at 1)
+ string/*!*/ val {
+ get;
+ set;
+ } // token value
+
+ bool IsValid {
+ get;
+ }
}
[Immutable]
public class Token : IToken {
- public int _kind; // token kind
+ public int _kind; // token kind
string _filename; // token file
- public int _pos; // token position in the source text (starting at 0)
- public int _col; // token column (starting at 1)
- public int _line; // token line (starting at 1)
- public string/*!*/ _val; // token value
- public Token next; // ML 2005-03-11 Tokens are kept in linked list
-
- public static IToken! NoToken = new Token();
+ public int _pos; // token position in the source text (starting at 0)
+ public int _col; // token column (starting at 1)
+ public int _line; // token line (starting at 1)
+ public string/*!*/ _val; // token value
+ public Token next; // ML 2005-03-11 Tokens are kept in linked list
+
+ public static IToken/*!*/ NoToken = new Token();
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(NoToken != null);
+ }
+
public Token() {
this._val = "anything so that it is nonnull";
}
- public Token(int linenum, int colnum) {
+ public Token(int linenum, int colnum)
+ : base() {//BASEMOVE DANGER
this._line = linenum;
this._col = colnum;
this._val = "anything so that it is nonnull";
- base();
+ //:base();
}
- public int kind {
- get { return this._kind; }
- set { this._kind = value; }
+ public int kind {
+ get {
+ return this._kind;
+ }
+ set {
+ this._kind = value;
+ }
}
-
- public string filename{
- get { return this._filename; }
- set { this._filename = value; }
+
+ public string filename {
+ get {
+ return this._filename;
+ }
+ set {
+ this._filename = value;
+ }
}
- public int pos{
- get { return this._pos; }
- set { this._pos = value; }
+ public int pos {
+ get {
+ return this._pos;
+ }
+ set {
+ this._pos = value;
+ }
}
-
- public int col{
- get { return this._col; }
- set { this._col = value; }
+
+ public int col {
+ get {
+ return this._col;
+ }
+ set {
+ this._col = value;
+ }
}
-
- public int line{
- get { return this._line; }
- set { this._line = value; }
+
+ public int line {
+ get {
+ return this._line;
+ }
+ set {
+ this._line = value;
+ }
}
-
- public string/*!*/ val{
- get { return this._val; }
- set { this._val = value; }
+
+ public string/*!*/ val {
+ get {
+ return this._val;
+ }
+ set {
+ this._val = value;
+ }
}
- public bool IsValid { get { return this._filename != null; } }
+ public bool IsValid {
+ get {
+ return this._filename != null;
+ }
+ }
-
-}
-public static class ParserHelper {
- struct ReadState {
- public bool hasSeenElse;
- public bool mayStillIncludeAnotherAlternative;
- public ReadState(bool hasSeenElse, bool mayStillIncludeAnotherAlternative) {
- this.hasSeenElse = hasSeenElse;
- this.mayStillIncludeAnotherAlternative = mayStillIncludeAnotherAlternative;
- }
}
- // "arg" is assumed to be trimmed
- private static bool IfdefConditionSaysToInclude(string! arg, List<string!>! defines) {
- bool sense = true;
- while (arg.StartsWith("!")) {
- sense = !sense;
- arg = arg.Substring(1).TrimStart();
+
+ public static class ParserHelper {
+ struct ReadState {
+ public bool hasSeenElse;
+ public bool mayStillIncludeAnotherAlternative;
+ public ReadState(bool hasSeenElse, bool mayStillIncludeAnotherAlternative) {
+ this.hasSeenElse = hasSeenElse;
+ this.mayStillIncludeAnotherAlternative = mayStillIncludeAnotherAlternative;
+ }
}
- return defines.Contains(arg) == sense;
- }
-
- public static string! Fill(Stream! stream, List<string!>! defines) {
- StreamReader! reader = new StreamReader(stream);
- return Fill(reader, defines);
- }
- public static string! Fill(TextReader! reader, List<string!>! defines) {
- StringBuilder sb = new StringBuilder();
- List<ReadState>! readState = new List<ReadState>(); // readState.Count is the current nesting level of #if's
- int ignoreCutoff = -1; // -1 means we're not ignoring; for 0<=n, n means we're ignoring because of something at nesting level n
- while (true)
+ // "arg" is assumed to be trimmed
+ private static bool IfdefConditionSaysToInclude(string arg, List<string/*!*/>/*!*/ defines) {
+ Contract.Requires(arg != null);
+ Contract.Requires(cce.NonNullElements(defines));
+ bool sense = true;
+ while (arg.StartsWith("!")) {
+ sense = !sense;
+ arg = arg.Substring(1).TrimStart();
+ }
+ return defines.Contains(arg) == sense;
+ }
+
+ public static string Fill(Stream stream, List<string/*!*/>/*!*/ defines) {
+ Contract.Requires(stream != null);
+ Contract.Requires(cce.NonNullElements(defines));
+ Contract.Ensures(Contract.Result<string>() != null);
+ StreamReader/*!*/ reader = new StreamReader(stream);
+ return Fill(reader, defines);
+ }
+ public static string Fill(TextReader reader, List<string/*!*/>/*!*/ defines) {
+ Contract.Requires(reader != null);
+ Contract.Requires(cce.NonNullElements(defines));
+ Contract.Ensures(Contract.Result<string>() != null);
+ StringBuilder sb = new StringBuilder();
+ List<ReadState>/*!*/ readState = new List<ReadState>(); // readState.Count is the current nesting level of #if's
+ int ignoreCutoff = -1; // -1 means we're not ignoring; for 0<=n, n means we're ignoring because of something at nesting level n
+ while (true)
//invariant -1 <= ignoreCutoff && ignoreCutoff < readState.Count;
{
- string s = reader.ReadLine();
- if (s == null) {
- if (readState.Count != 0) {
- sb.AppendLine("#MalformedInput: missing #endif");
- }
- break;
- }
- string t = s.Trim();
- if (t.StartsWith("#if")) {
- ReadState rs = new ReadState(false, false);
- if (ignoreCutoff != -1) {
- // we're already in a state of ignoring, so continue to ignore
- } else if (IfdefConditionSaysToInclude(t.Substring(3).TrimStart(), defines)) {
- // include this branch
- } else {
- ignoreCutoff = readState.Count; // start ignoring
- rs.mayStillIncludeAnotherAlternative = true; // allow some later "elsif" or "else" branch to be included
- }
- readState.Add(rs);
- sb.AppendLine(); // ignore the #if line
-
- } else if (t.StartsWith("#elsif")) {
- ReadState rs;
- if (readState.Count == 0 || (rs = readState[readState.Count-1]).hasSeenElse) {
- sb.AppendLine("#MalformedInput: misplaced #elsif"); // malformed input
+ string s = reader.ReadLine();
+ if (s == null) {
+ if (readState.Count != 0) {
+ sb.AppendLine("#MalformedInput: missing #endif");
+ }
break;
}
- if (ignoreCutoff == -1) {
- // we had included the previous branch
- //assert !rs.mayStillIncludeAnotherAlternative;
- ignoreCutoff = readState.Count-1; // start ignoring
- } else if (rs.mayStillIncludeAnotherAlternative && IfdefConditionSaysToInclude(t.Substring(6).TrimStart(), defines)) {
- // include this branch, but no subsequent branch at this level
- ignoreCutoff = -1;
- rs.mayStillIncludeAnotherAlternative = false;
- readState[readState.Count-1] = rs;
- }
- sb.AppendLine(); // ignore the #elsif line
+ string t = s.Trim();
+ if (t.StartsWith("#if")) {
+ ReadState rs = new ReadState(false, false);
+ if (ignoreCutoff != -1) {
+ // we're already in a state of ignoring, so continue to ignore
+ } else if (IfdefConditionSaysToInclude(t.Substring(3).TrimStart(), defines)) {
+ // include this branch
+ } else {
+ ignoreCutoff = readState.Count; // start ignoring
+ rs.mayStillIncludeAnotherAlternative = true; // allow some later "elsif" or "else" branch to be included
+ }
+ readState.Add(rs);
+ sb.AppendLine(); // ignore the #if line
- } else if (t == "#else") {
- ReadState rs;
- if (readState.Count == 0 || (rs = readState[readState.Count-1]).hasSeenElse) {
- sb.AppendLine("#MalformedInput: misplaced #else"); // malformed input
- break;
- }
- rs.hasSeenElse = true;
- if (ignoreCutoff == -1) {
- // we had included the previous branch
- //assert !rs.mayStillIncludeAnotherAlternative;
- ignoreCutoff = readState.Count-1; // start ignoring
- } else if (rs.mayStillIncludeAnotherAlternative) {
- // include this branch
- ignoreCutoff = -1;
- rs.mayStillIncludeAnotherAlternative = false;
- }
- readState[readState.Count-1] = rs;
- sb.AppendLine(); // ignore the #else line
+ } else if (t.StartsWith("#elsif")) {
+ ReadState rs;
+ if (readState.Count == 0 || (rs = readState[readState.Count - 1]).hasSeenElse) {
+ sb.AppendLine("#MalformedInput: misplaced #elsif"); // malformed input
+ break;
+ }
+ if (ignoreCutoff == -1) {
+ // we had included the previous branch
+ //Contract.Assert(!rs.mayStillIncludeAnotherAlternative);
+ ignoreCutoff = readState.Count - 1; // start ignoring
+ } else if (rs.mayStillIncludeAnotherAlternative && IfdefConditionSaysToInclude(t.Substring(6).TrimStart(), defines)) {
+ // include this branch, but no subsequent branch at this level
+ ignoreCutoff = -1;
+ rs.mayStillIncludeAnotherAlternative = false;
+ readState[readState.Count - 1] = rs;
+ }
+ sb.AppendLine(); // ignore the #elsif line
- } else if (t == "#endif") {
- if (readState.Count == 0) {
- sb.AppendLine("#MalformedInput: misplaced #endif"); // malformed input
- break;
- }
- readState.RemoveAt(readState.Count-1); // pop
- if (ignoreCutoff == readState.Count) {
- // we had ignored the branch that ends here; so, now we start including again
- ignoreCutoff = -1;
- }
- sb.AppendLine(); // ignore the #endif line
+ } else if (t == "#else") {
+ ReadState rs;
+ if (readState.Count == 0 || (rs = readState[readState.Count - 1]).hasSeenElse) {
+ sb.AppendLine("#MalformedInput: misplaced #else"); // malformed input
+ break;
+ }
+ rs.hasSeenElse = true;
+ if (ignoreCutoff == -1) {
+ // we had included the previous branch
+ //Contract.Assert(!rs.mayStillIncludeAnotherAlternative);
+ ignoreCutoff = readState.Count - 1; // start ignoring
+ } else if (rs.mayStillIncludeAnotherAlternative) {
+ // include this branch
+ ignoreCutoff = -1;
+ rs.mayStillIncludeAnotherAlternative = false;
+ }
+ readState[readState.Count - 1] = rs;
+ sb.AppendLine(); // ignore the #else line
+
+ } else if (t == "#endif") {
+ if (readState.Count == 0) {
+ sb.AppendLine("#MalformedInput: misplaced #endif"); // malformed input
+ break;
+ }
+ readState.RemoveAt(readState.Count - 1); // pop
+ if (ignoreCutoff == readState.Count) {
+ // we had ignored the branch that ends here; so, now we start including again
+ ignoreCutoff = -1;
+ }
+ sb.AppendLine(); // ignore the #endif line
- } else if (ignoreCutoff == -1) {
- sb.AppendLine(s); // included line
+ } else if (ignoreCutoff == -1) {
+ sb.AppendLine(s); // included line
- } else {
- sb.AppendLine(); // ignore the line
+ } else {
+ sb.AppendLine(); // ignore the line
+ }
}
+
+ return sb.ToString();
}
-
- return sb.ToString();
}
-}
} \ No newline at end of file
diff --git a/Source/Core/PureCollections.cs b/Source/Core/PureCollections.cs
index e6d68a34..a77f59a1 100644
--- a/Source/Core/PureCollections.cs
+++ b/Source/Core/PureCollections.cs
@@ -13,140 +13,184 @@
using System;
using System.Collections;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
namespace PureCollections {
//-------------------------------------------------------------------
// General types
//-------------------------------------------------------------------
- public class MissingCase :Exception{}
+ public class MissingCase : Exception {
+ }
- public struct Capacity{
+ public struct Capacity {
public int capacity;
- public Capacity (int i) {capacity = i;}
+ public Capacity(int i) {
+ capacity = i;
+ }
}
abstract public class Coll {
public object[] elems; // null is used to show empty spots!
protected int card;
- protected Coll() {}
- protected Coll(object[] elems, int card) {this.elems = elems; this.card = card; }
- protected Coll(Coll! c)
- requires c.elems != null;
- {
- this.elems = (object[])c.elems.Clone();
- this.card = c.card;
- }
- }
+ protected Coll() {
+ }
+ protected Coll(object[] elems, int card) {
+ this.elems = elems;
+ this.card = card;
+ }
+ protected Coll(Coll c) {
+ Contract.Requires(c != null);
+ Contract.Requires(c.elems != null);
+ this.elems = (object[])c.elems.Clone();
+ this.card = c.card;
+ }
+ }
// ------------------------------------------------------------------
// Tuple
// ------------------------------------------------------------------
- public class Tuple : Coll, IComparable
- {
+ public class Tuple : Coll, IComparable {
//public object[] elems;
-
+
//invariant this.elems != null;
// Constructor - - - - - - - - - - - - - - - - - - - - - - - - - -
- public Tuple(params object []! ts) {
- elems = ts;
- card = ts.Length;}
+ public Tuple(params object[] ts) {
+ Contract.Requires(ts != null);
+ elems = ts;
+ card = ts.Length;
+ }
public Tuple(Capacity c) {
- elems = new object[c.capacity];
- card = c.capacity;
- }
+ elems = new object[c.capacity];
+ card = c.capacity;
+ }
//Equality - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals (object o){
- assert this.elems != null;
- if (o == null || !(o is Tuple) || elems.Length != ((!)((Tuple)o).elems).Length)
+
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object o) {
+ Contract.Assert(this.elems != null);
+ if (o == null || !(o is Tuple) || elems.Length != (cce.NonNull((Tuple)o).elems).Length)
return false;
- Tuple s = (Tuple) o;
- for(int i = 0; i < elems.Length; i ++)
- if ( ! Equals(this.elems[i], s.elems[i]))
+ Tuple s = (Tuple)o;
+ for (int i = 0; i < elems.Length; i++)
+ if (!Equals(this.elems[i], s.elems[i]))
return false;
return true;
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
- public static bool operator == (Tuple s, Tuple t) {return s == null ? t == null : s.Equals(t);}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
- public static bool operator != (Tuple s, Tuple t) { return ! (t == s); }
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
+ public static bool operator ==(Tuple s, Tuple t) {
+ return s == null ? t == null : s.Equals(t);
+ }
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
+ public static bool operator !=(Tuple s, Tuple t) {
+ return !(t == s);
+ }
[Pure]
- public override int GetHashCode (){
- int h =0;
- assume this.elems != null;
- for(int i = 0; i < elems.Length; i++)
- {
+ public override int GetHashCode() {
+ int h = 0;
+ Contract.Assume(this.elems != null);
+ for (int i = 0; i < elems.Length; i++) {
object elem = elems[i];
- if (elem != null)
+ if (elem != null)
h += elem.GetHashCode();
}
- return h;
+ return h;
}
//Compare - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- int IComparable.CompareTo(object o) {
- assert this.elems != null;
- if (o == null || !(o is Tuple) || elems.Length != ((!)((Tuple)o).elems).Length)
+ int IComparable.CompareTo(object o) {
+ Contract.Assert(this.elems != null);
+ if (o == null || !(o is Tuple) || elems.Length != (cce.NonNull((Tuple)o).elems).Length)
throw new MissingCase();
-
- Tuple t = (Tuple) o;
- for(int i = 0; i < elems.Length; i ++) {
- int c = ((IComparable!) elems[i]).CompareTo(t.elems[i]);
- if (c < 0) return -1;
- else if (c > 0) return +1;
+
+ Tuple t = (Tuple)o;
+ for (int i = 0; i < elems.Length; i++) {
+ int c = cce.NonNull((IComparable)elems[i]).CompareTo(t.elems[i]);
+ if (c < 0)
+ return -1;
+ else if (c > 0)
+ return +1;
}
return 0;
}
- public static bool operator <= (Tuple s, Tuple t) {return s == null ? t == null : ((IComparable) s).CompareTo(t) <= 0;}
- public static bool operator < (Tuple s, Tuple t) {return s == null ? false : ((IComparable) s).CompareTo(t) < 0;}
- public static bool operator >= (Tuple s, Tuple t) {return t <= s; }
- public static bool operator > (Tuple s, Tuple t) { return t < s; }
+ public static bool operator <=(Tuple s, Tuple t) {
+ return s == null ? t == null : ((IComparable)s).CompareTo(t) <= 0;
+ }
+ public static bool operator <(Tuple s, Tuple t) {
+ return s == null ? false : ((IComparable)s).CompareTo(t) < 0;
+ }
+ public static bool operator >=(Tuple s, Tuple t) {
+ return t <= s;
+ }
+ public static bool operator >(Tuple s, Tuple t) {
+ return t < s;
+ }
//Select and Update - - - - - - - - - - - - - - - - - - - - - - - -
- public object this[int index]{
- get{assert this.elems != null; return elems[index];}
- set{assert this.elems != null; elems[index] = value;}
+ public object this[int index] {
+ get {
+ Contract.Assert(this.elems != null);
+ return elems[index];
+ }
+ set {
+ Contract.Assert(this.elems != null);
+ elems[index] = value;
+ }
}
-
+
//ToString - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[Pure]
- public override string! ToString() {
- assert this.elems != null;
- if (elems.Length==0)
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ Contract.Assert(this.elems != null);
+ if (elems.Length == 0)
return "()";
-
+
string s = "(";
- for (int i= 0; i< elems.Length-1; i++)
- s += ((!)elems[i]).ToString() + ", ";
- return s + ((!)elems[elems.Length-1]).ToString() + ")";
- }
+ for (int i = 0; i < elems.Length - 1; i++)
+ s += cce.NonNull(elems[i]).ToString() + ", ";
+ return s + cce.NonNull(elems[elems.Length - 1]).ToString() + ")";
+ }
}
// ------------------------------------------------------------------
// Pair
- public class Pair : Tuple{
- protected Pair(){}
+ public class Pair : Tuple {
+ protected Pair() {
+ }
public Pair(object first, object second) {
- elems = new object[]{first,second};
+ elems = new object[] { first, second };
}
- public object First{
- get{assert this.elems != null; return elems[0];}
- set{assert this.elems != null; elems[0]=value;}
+ public object First {
+ get {
+ Contract.Assert(this.elems != null);
+ return elems[0];
+ }
+ set {
+ Contract.Assert(this.elems != null);
+ elems[0] = value;
+ }
}
- public object Second{
- get{assert this.elems != null; return elems[1];}
- set{assert this.elems != null; elems[1]=value;}
+ public object Second {
+ get {
+ Contract.Assert(this.elems != null);
+ return elems[1];
+ }
+ set {
+ Contract.Assert(this.elems != null);
+ elems[1] = value;
+ }
}
}
@@ -154,106 +198,137 @@ namespace PureCollections {
// Map
// --------------------------------------------------------------------
- public class MapEnumerator: IEnumerator{
- private Map! map;
+ public class MapEnumerator : IEnumerator {
+ private Map/*!*/ map;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(map != null);
+ }
+
private int index = -1;
- public MapEnumerator(Map! m) { map = m;}
+ public MapEnumerator(Map m) {
+ Contract.Requires(m != null);
+ map = m;
+ }
public bool MoveNext() {
- do{
+ do {
index++;
- assert map.elems != null;
+ Contract.Assert(map.elems != null);
} while (index < map.elems.Length && map.elems[index] == null);
return index < map.elems.Length;
}
- public object Current{ get { assert map.elems != null; return new Pair(map.elems[index],map.vals[index]); }}
- public void Reset() {index = -1; }
+ public object Current {
+ get {
+ Contract.Assert(map.elems != null);
+ return new Pair(map.elems[index], map.vals[index]);
+ }
+ }
+ public void Reset() {
+ index = -1;
+ }
}
-
- public class Map:Coll, IEnumerable, IComparable
- {
- public Object[]! vals;
-
+
+ public class Map : Coll, IEnumerable, IComparable {
+ public Object[]/*!*/ vals;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(vals != null);
+ }
+
+
//invariant this.elems != null;
-
+
// constructors - - - - - - - - - - - - - - - - - - - - - - - - - - -
- public Map(Capacity c){
- elems = new Object[c.capacity*2];
- vals = new Object[c.capacity*2];
+ public Map(Capacity c) {
+ elems = new Object[c.capacity * 2];
+ vals = new Object[c.capacity * 2];
card = 0;
}
-
+
[NotDelayed]
- public Map(params Pair []! ps){
- elems = new Object[ps.Length*2];
- vals = new Object[ps.Length*2];
- base();
+ public Map(params Pair[] ps)
+ : base() {//BASEMOVE DANGER
+ Contract.Requires(ps != null);
+ elems = new Object[ps.Length * 2];
+ vals = new Object[ps.Length * 2];
+ //base();
card = 0;
- for(int i = 0; i < ps.Length; i++)
- Insert( ((!)ps[i]).First, ((!)ps[i]).Second);
+ for (int i = 0; i < ps.Length; i++)
+ Insert(cce.NonNull(ps[i]).First, cce.NonNull(ps[i]).Second);
}
// iterators - - - - - - - - - - - - - - - - - - - - - - - - - - -
- [Pure] [GlobalAccess(false)] [Escapes(true,false)]
- public IEnumerator! GetEnumerator() {
+ [Pure]
+ [GlobalAccess(false)]
+ [Escapes(true, false)]
+ public IEnumerator GetEnumerator() {
+ Contract.Ensures(Contract.Result<IEnumerator>() != null);
return new MapEnumerator(this);
}
public Pair[] ToArray() {
- Pair [] n = new Pair[card];
+ Pair[] n = new Pair[card];
int ct = 0;
- assert this.elems != null;
- for(int i =0; i < elems.Length ; i++)
+ Contract.Assert(this.elems != null);
+ for (int i = 0; i < elems.Length; i++)
if (elems[i] != null)
n[ct++] = new Pair(elems[i], vals[i]);
return n;
}
-
+
//(ASM) Update- - - - - - - - - - - - - - - - - - - - - - - - - - -
public Map Update(object k, object v) {
- Map n = new Map(new Capacity(card+1));
- assert this.elems != null;
- for (int i = 0; i < elems.Length; i++ )
- if (elems[i] != null && ! Equals(elems[i], k))
+ Map n = new Map(new Capacity(card + 1));
+ Contract.Assert(this.elems != null);
+ for (int i = 0; i < elems.Length; i++)
+ if (elems[i] != null && !Equals(elems[i], k))
n.Insert(elems[i], vals[i]);
- n.Insert(k,v);
+ n.Insert(k, v);
return n;
}
//In place Update (and Remove)- - - - - - - - - - - - - - - - - - -
- public object this[object index]{
- get{return this.Apply(index);}
- set{this.Insert(index,value);}
- }
-
- public void Remove(object! o) {
- assert this.elems != null;
- int h = Math.Abs(o.GetHashCode()) % elems.Length;
- for (int i = 0; i < elems.Length; i++ ) {
- int j = (i+ h) % elems.Length;
- if (elems[j] == null) {
- break;
- } else if (Equals(elems[j], o)){
- elems[j] = null;
- vals[j] = null;
- break;
- }
- }
+ public object this[object index] {
+ get {
+ return this.Apply(index);
+ }
+ set {
+ this.Insert(index, value);
+ }
+ }
+
+ public void Remove(object o) {
+ Contract.Requires(o != null);
+ Contract.Assert(this.elems != null);
+ int h = Math.Abs(o.GetHashCode()) % elems.Length;
+ for (int i = 0; i < elems.Length; i++) {
+ int j = (i + h) % elems.Length;
+ if (elems[j] == null) {
+ break;
+ } else if (Equals(elems[j], o)) {
+ elems[j] = null;
+ vals[j] = null;
+ break;
}
-
+ }
+ }
+
public void Insert(Object key, Object val) {
if (key == null)
- throw new MissingCase();
-
- assert this.elems != null;
- if (elems.Length == 0 || 2*card >= elems.Length){
- int m = card*2; if (m < 4) m = 4;
- object [] newElems = new object [m];
- object [] newVals = new object [m];
+ throw new MissingCase();
+
+ Contract.Assert(this.elems != null);
+ if (elems.Length == 0 || 2 * card >= elems.Length) {
+ int m = card * 2;
+ if (m < 4)
+ m = 4;
+ object[] newElems = new object[m];
+ object[] newVals = new object[m];
for (int k = 0; k < elems.Length; k++) {
object elem = elems[k];
if (elem != null) {
int newHash = Math.Abs(elem.GetHashCode()) % newElems.Length;
- for (int i = 0; i < newElems.Length; i++ ) {
- int j = (i+ newHash) % newElems.Length;
+ for (int i = 0; i < newElems.Length; i++) {
+ int j = (i + newHash) % newElems.Length;
if (newElems[j] == null) {
newElems[j] = elem;
newVals[j] = vals[k];
@@ -264,17 +339,17 @@ namespace PureCollections {
}
elems = newElems;
vals = newVals;
- }
+ }
int h = Math.Abs(key.GetHashCode()) % elems.Length;
- for (int i = 0; i < elems.Length; i++ ) {
- int j = (i+ h) % elems.Length;
+ for (int i = 0; i < elems.Length; i++) {
+ int j = (i + h) % elems.Length;
if (elems[j] == null) {
elems[j] = key;
vals[j] = val;
- card ++;
+ card++;
return;
} else if (key.Equals(elems[j])) {
- vals[j] = val;
+ vals[j] = val;
return;
}
}
@@ -282,24 +357,26 @@ namespace PureCollections {
//ToString - - - - - - - - - - - - - - - - - - - - - - - - -
[Pure]
- public override string! ToString() {
- if (card ==0)
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ if (card == 0)
return "{|->}";
else {
- string s = "{"; int ct = 0;
- assert this.elems != null;
- for(int i =0; i < elems.Length ; i++) {
+ string s = "{";
+ int ct = 0;
+ Contract.Assert(this.elems != null);
+ for (int i = 0; i < elems.Length; i++) {
object elem = elems[i];
- if (elem != null){
- s += elem.ToString() +"|->" + ((!)vals[i]).ToString() ;
- s +=(ct!=card-1) ? ", " : "";
- ct ++;
+ if (elem != null) {
+ s += elem.ToString() + "|->" + cce.NonNull(vals[i]).ToString();
+ s += (ct != card - 1) ? ", " : "";
+ ct++;
}
- }
- return s+"}";
+ }
+ return s + "}";
}
}
-
+
// Subset operations - - - - - - - - - - - - - - - - - - - - - - -
// View Map as Set of Pairs
@@ -307,175 +384,212 @@ namespace PureCollections {
if (o == null || !(o is Map))
throw new MissingCase();
// WS Improve performance!
- Map t = (Map) o;
- if (this < t) return -1;
- else if(this > t) return +1;
- else return 0;
- }
- public static bool operator <= (Map s, Map t){
- if (s==null) return t==null;
- if (t==null) return false;
- assert s.elems != null;
- for(int i = 0; i < s.elems.Length; i++)
- if (s.elems[i]!= null) {
+ Map t = (Map)o;
+ if (this < t)
+ return -1;
+ else if (this > t)
+ return +1;
+ else
+ return 0;
+ }
+ public static bool operator <=(Map s, Map t) {
+ if (s == null)
+ return t == null;
+ if (t == null)
+ return false;
+ Contract.Assert(s.elems != null);
+ for (int i = 0; i < s.elems.Length; i++)
+ if (s.elems[i] != null) {
object o = t.Apply(s.elems[i]);
if (o == null || !o.Equals(s.vals[i]))
return false;
}
- return true;
+ return true;
}
- public static bool operator < (Map s, Map t){
- return s == null || t == null ? false : s.card < t.card && s <= t;
+ public static bool operator <(Map s, Map t) {
+ return s == null || t == null ? false : s.card < t.card && s <= t;
}
- public static bool operator >= (Map s, Map t){
- return t <= s;
- }
- public static bool operator > (Map s, Map t){
- return t < s;
+ public static bool operator >=(Map s, Map t) {
+ return t <= s;
+ }
+ public static bool operator >(Map s, Map t) {
+ return t < s;
}
// Equality - - - - - - - - - - - - - - - - - - - - - - -
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals (Object t){
- return t != null && t is Map && card == ((Map) t).card && this<= ((Map) t);
- }
- [Pure][Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
- public static bool operator == (Map s, Map t){
- if ((object)s==null)
- if ((object)t==null) return true;
- else return t.Equals(s);
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(Object t) {
+ return t != null && t is Map && card == ((Map)t).card && this <= ((Map)t);
+ }
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
+ public static bool operator ==(Map s, Map t) {
+ if ((object)s == null)
+ if ((object)t == null)
+ return true;
+ else
+ return t.Equals(s);
else
return s.Equals(t);
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
- public static bool operator != (Map s, Map t){
- return ! (t == s);
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
+ public static bool operator !=(Map s, Map t) {
+ return !(t == s);
}
[Pure]
- public override int GetHashCode (){
- int h =0;
- assert this.elems != null;
- for(int i = 0; i < elems.Length; i++)
- {
+ public override int GetHashCode() {
+ int h = 0;
+ Contract.Assert(this.elems != null);
+ for (int i = 0; i < elems.Length; i++) {
object elem = elems[i];
- if (elem != null)
- {
- h += elem.GetHashCode() + ((!)vals[i]).GetHashCode();
+ if (elem != null) {
+ h += elem.GetHashCode() + cce.NonNull(vals[i]).GetHashCode();
}
}
- return h;
+ return h;
}
-
+
//Ordinary map operations- - - - - - - - - - - - - - - - - - - - - - - -
-
+
[Pure]
- public bool Has(Object x) {
- if (x == null)
- throw new MissingCase();
+ public bool Has(Object x) {
+ if (x == null)
+ throw new MissingCase();
- assert this.elems != null;
- if (elems.Length == 0)
+ Contract.Assert(this.elems != null);
+ if (elems.Length == 0)
return false;
int h = Math.Abs(x.GetHashCode()) % elems.Length;
- for (int i = 0; i < elems.Length; i++ ) {
- int j = (i+ h) % elems.Length;
+ for (int i = 0; i < elems.Length; i++) {
+ int j = (i + h) % elems.Length;
if (x.Equals(elems[j]))
return true;
}
return false;
}
- public object Apply(object x) {
+ public object Apply(object x) {
if (x == null)
throw new MissingCase();
- assert this.elems != null;
- if (elems.Length == 0)
+ Contract.Assert(this.elems != null);
+ if (elems.Length == 0)
return null;
int h = Math.Abs(x.GetHashCode()) % elems.Length;
- for (int i = 0; i < elems.Length; i++ ) {
- int j = (i+ h) % elems.Length;
+ for (int i = 0; i < elems.Length; i++) {
+ int j = (i + h) % elems.Length;
if (elems[j] != null && x.Equals(elems[j]))
return vals[j];
}
- return null;
+ return null;
}
- public static Map Override(Map! s, Map! t) {
- Map m = new Map(new Capacity(s.card+t.card));
- assert s.elems != null;
- for(int i = 0; i< s.elems.Length; i++)
- if (s.elems[i] != null)
+ public static Map Override(Map s, Map t) {
+ Contract.Requires(t != null);
+ Contract.Requires(s != null);
+ Map m = new Map(new Capacity(s.card + t.card));
+ Contract.Assert(s.elems != null);
+ for (int i = 0; i < s.elems.Length; i++)
+ if (s.elems[i] != null)
m.Insert(s.elems[i], s.vals[i]);
- assert t.elems != null;
- for(int i = 0; i< t.elems.Length; i++)
- if (t.elems[i] != null)
+ Contract.Assert(t.elems != null);
+ for (int i = 0; i < t.elems.Length; i++)
+ if (t.elems[i] != null)
m.Insert(t.elems[i], t.vals[i]);
- return m;
- }
+ return m;
+ }
}
// --------------------------------------------------------------------
// Sequence
- public class SequenceEnumerator: IEnumerator{
- [Peer] private Sequence! seq;
+ public class SequenceEnumerator : IEnumerator {
+ [Peer]
+ private Sequence/*!*/ seq;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(seq != null);
+ }
+
private int index = -1;
[Captured]
- public SequenceEnumerator(Sequence! s) { seq = s;}
+ public SequenceEnumerator(Sequence s) {
+ Contract.Requires(s != null);
+ seq = s;
+ }
public bool MoveNext() {
index++;
//while (index < seq.elems.Length); // Sequences allow nils ... && seq.elems[index] == null);
return index < seq.Length;
}
- public object Current{ get { assert seq.elems != null; return seq.elems[index]; }}
- public void Reset() {index = -1; }
+ public object Current {
+ get {
+ Contract.Assert(seq.elems != null);
+ return seq.elems[index];
+ }
+ }
+ public void Reset() {
+ index = -1;
+ }
}
-
- public class Sequence:Coll, IEnumerable, IComparable
- {
- public Sequence(){elems = new object [4];}
-
+
+ public class Sequence : Coll, IEnumerable, IComparable {
+ public Sequence() {
+ elems = new object[4];
+ }
+
//invariant this.elems != null;
//constructors - - - - - - - - - - - - - - - - - - - - - - - - - - -
- public Sequence(params object []! ds){card = ds.Length; elems = ds; }
- public Sequence(Sequence! seq) {
- base(seq);
+ public Sequence(params object[] ds) {
+ Contract.Requires(ds != null);
+ card = ds.Length;
+ elems = ds;
+ }
+ public Sequence(Sequence seq)
+ : base(seq) {//BASEMOVEA
+ Contract.Requires(seq != null);
+ //base(seq);
+ }
+ public Sequence(Capacity c) {
+ elems = new object[c.capacity];
}
- public Sequence(Capacity c){elems = new object [c.capacity];}
// Iterators - - - - - - - - - - - - - - - - - - - - - - - - - - -
- [Pure] [GlobalAccess(false)] [Escapes(true,false)]
- public IEnumerator! GetEnumerator()
- ensures Owner.Same(result, this);
- ensures result.IsNew;
- {
+ [Pure]
+ [GlobalAccess(false)]
+ [Escapes(true, false)]
+ public IEnumerator/*!*/ GetEnumerator() {
+ Contract.Ensures(cce.Owner.Same(Contract.Result<IEnumerator>(), this));
+ Contract.Ensures(Contract.Result<IEnumerator>() != null);
+ Contract.Ensures(cce.IsNew(Contract.Result<IEnumerator>()));
return new SequenceEnumerator(this);
}
-
+
public object[] ToArray() {
- object [] n = new object[card];
+ object[] n = new object[card];
int ct = 0;
- assert this.elems != null;
- for(int i =0; i < elems.Length ; i++)
+ Contract.Assert(this.elems != null);
+ for (int i = 0; i < elems.Length; i++)
n[ct++] = elems[i];
return n;
}
-
+
//ASM Update - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
public Sequence Update(int i, object v) {
- Sequence n = new Sequence(new Capacity(card+1));
- assert this.elems != null;
- assert n.elems != null;
- for (int j = 0; j < elems.Length; j++ )
+ Sequence n = new Sequence(new Capacity(card + 1));
+ Contract.Assert(this.elems != null);
+ Contract.Assert(n.elems != null);
+ for (int j = 0; j < elems.Length; j++)
n.elems[j] = elems[j];
- if (i >= 0 && i < card){
+ if (i >= 0 && i < card) {
n.elems[i] = v;
n.card = card;
return n;
} else if (i == card) {
n.elems[i] = v;
- n.card = card+1;
+ n.card = card + 1;
return n;
} else
throw new Exception("Sequence Update out of range");
@@ -483,49 +597,61 @@ namespace PureCollections {
//In place Update (and Remove) and Length - - - - - - - - - - - - - - -
public int Length {
- get{return this.card;}
+ get {
+ return this.card;
+ }
}
- public object this[int index]{
- get{assert this.elems != null; return this.elems[index];}
- set{assert this.elems != null; this.elems[index] = value;}
+ public object this[int index] {
+ get {
+ Contract.Assert(this.elems != null);
+ return this.elems[index];
+ }
+ set {
+ Contract.Assert(this.elems != null);
+ this.elems[index] = value;
+ }
}
- public void Add(object o){
- assert this.elems != null;
+ public void Add(object o) {
+ Contract.Assert(this.elems != null);
int n = this.elems.Length;
int i = this.card++;
- if (i == n){
- int m = n*2; if (m < 4) m = 4;
- object [] newElems = new object [m];
- for (int j = 0; j < n; j++) newElems[j] = elems[j];
+ if (i == n) {
+ int m = n * 2;
+ if (m < 4)
+ m = 4;
+ object[] newElems = new object[m];
+ for (int j = 0; j < n; j++)
+ newElems[j] = elems[j];
elems = newElems;
}
elems[i] = o;
}
-
- public void AddRange(Sequence! seq){
+
+ public void AddRange(Sequence seq) {
+ Contract.Requires(seq != null);
foreach (object o in seq) {
Add(o);
}
}
-
- public void Remove(){
+
+ public void Remove() {
if (card == 0)
return;
card--;
- }
-
+ }
+
// remove the first occurrence of o from this sequence
public void Remove(Object x) {
if (x == null)
throw new MissingCase();
- assert this.elems != null;
+ Contract.Assert(this.elems != null);
for (int i = 0; i < card; i++) {
if (x.Equals(elems[i])) {
++i;
while (i < card) {
- elems[i-1] = elems[i];
+ elems[i - 1] = elems[i];
++i;
}
card--;
@@ -534,11 +660,10 @@ namespace PureCollections {
}
}
}
-
- public void Truncate(int newLen)
- requires 0 <= newLen && newLen <= Length;
- {
- assert elems != null;
+
+ public void Truncate(int newLen) {
+ Contract.Requires(0 <= newLen && newLen <= Length);
+ Contract.Assert(elems != null);
for (int i = newLen; i < card; i++) {
elems[i] = null;
}
@@ -547,65 +672,77 @@ namespace PureCollections {
//ToString - - - - - - - - - - - - - - - - - - - - - - - - - - - -
[Pure]
- public override string! ToString() {
- string s ="";
- assert this.elems != null;
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
+ string s = "";
+ if (this.elems == null)
+ return "(null)";
+ Contract.Assert(this.elems != null);
if (card > 0 && elems[0] is Char) {
- for(int i =0; i < card ; i++)
- {
+ for (int i = 0; i < card; i++) {
object elem = elems[i];
- if (elem != null) { s +=elem.ToString(); }
+ if (elem != null) {
+ s += elem.ToString();
+ }
}
return s;
} else {
s = "[";
- for(int i =0; i < card-1; i++) {
+ for (int i = 0; i < card - 1; i++) {
object elem = elems[i];
- if (elem != null) { s += elem.ToString()+", "; }
+ if (elem != null) {
+ s += elem.ToString() + ", ";
+ }
}
- if (card > 0)
- {
- object last = elems[card-1];
- if (last != null) { s += last.ToString(); }
+ if (card > 0) {
+ object last = elems[card - 1];
+ if (last != null) {
+ s += last.ToString();
+ }
}
s += "]";
return s;
}
}
//Equality- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- [Pure][Reads(ReadsAttribute.Reads.Nothing)]
- public override bool Equals (object that){
- return that != null && that is Sequence && ((Sequence) this == (Sequence) that);
- }
- [Pure][Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
- public static bool operator == (Sequence s, Sequence t){
- if ((object)s == (object)t) {
- return true;
- } else if ((object)s == null || (object)t == null) {
- return false;
- }
- if (s.card != t.card) return false;
- assert s.elems != null;
- assert t.elems != null;
- for(int i = 0; i < s.card; i++)
- if (! Equals(s.elems[i], t.elems[i]))
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)]
+ public override bool Equals(object that) {
+ return that != null && that is Sequence && ((Sequence)this == (Sequence)that);
+ }
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
+ public static bool operator ==(Sequence s, Sequence t) {
+ if ((object)s == (object)t) {
+ return true;
+ } else if ((object)s == null || (object)t == null) {
+ return false;
+ }
+ if (s.card != t.card)
+ return false;
+ Contract.Assert(s.elems != null);
+ Contract.Assert(t.elems != null);
+ for (int i = 0; i < s.card; i++)
+ if (!Equals(s.elems[i], t.elems[i]))
return false;
- return true;
+ return true;
}
- [Pure][Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
- public static bool operator != (Sequence s, Sequence t){
- return !(s == t);
+ [Pure]
+ [Reads(ReadsAttribute.Reads.Nothing)] // ugh, is this right? --KRML
+ public static bool operator !=(Sequence s, Sequence t) {
+ return !(s == t);
}
[Pure]
- public override int GetHashCode (){
+ public override int GetHashCode() {
int h = 0;
- for(int i = 0; i < card; i++)
- {
- assert this.elems != null;
+ for (int i = 0; i < card; i++) {
+ Contract.Assert(this.elems != null);
object elem = elems[i];
- if (elem != null) { h += elem.GetHashCode(); }
+ if (elem != null) {
+ h += elem.GetHashCode();
+ }
}
- return h;
+ return h;
}
//Subset- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// View Sequence of T as Set of (Integer,T)
@@ -613,44 +750,57 @@ namespace PureCollections {
if (o == null || !(o is Sequence))
throw new MissingCase();
// WS Improve performance!
- Sequence t = (Sequence) o;
- if (this < t) return -1;
- else if(this > t) return +1;
- else return 0;
- }
-
- public static bool operator < (Sequence s, Sequence t){
- if (s==null) throw new ArgumentNullException("s");
- if (t==null) throw new ArgumentNullException("t");
- if (s.card >= t.card) return false;
- assert s.elems != null;
- assert t.elems != null;
- for(int i = 0; i < s.card; i++)
- if ( ! Equals(s.elems[i], t.elems[i]))
+ Sequence t = (Sequence)o;
+ if (this < t)
+ return -1;
+ else if (this > t)
+ return +1;
+ else
+ return 0;
+ }
+
+ public static bool operator <(Sequence s, Sequence t) {
+ if (s == null)
+ throw new ArgumentNullException("s");
+ if (t == null)
+ throw new ArgumentNullException("t");
+ if (s.card >= t.card)
+ return false;
+ Contract.Assert(s.elems != null);
+ Contract.Assert(t.elems != null);
+ for (int i = 0; i < s.card; i++)
+ if (!Equals(s.elems[i], t.elems[i]))
return false;
- return true;
- }
- public static bool operator <= (Sequence s, Sequence t){
- if (s==null) throw new ArgumentNullException("s");
- if (t==null) throw new ArgumentNullException("t");
- if (s.card > t.card) return false;
- assert s.elems != null;
- assert t.elems != null;
- for(int i = 0; i < s.card; i++)
- if ( ! Equals(s.elems[i], t.elems[i]))
+ return true;
+ }
+ public static bool operator <=(Sequence s, Sequence t) {
+ if (s == null)
+ throw new ArgumentNullException("s");
+ if (t == null)
+ throw new ArgumentNullException("t");
+ if (s.card > t.card)
+ return false;
+ Contract.Assert(s.elems != null);
+ Contract.Assert(t.elems != null);
+ for (int i = 0; i < s.card; i++)
+ if (!Equals(s.elems[i], t.elems[i]))
return false;
- return true;
+ return true;
+ }
+ public static bool operator >(Sequence s, Sequence t) {
+ return t < s;
+ }
+ public static bool operator >=(Sequence s, Sequence t) {
+ return t <= s;
}
- public static bool operator > (Sequence s, Sequence t){ return t < s;}
- public static bool operator >= (Sequence s, Sequence t){ return t <= s;}
//pure---------------------------------------------------------------
[Pure]
public bool Has(object x) { // WS translate to tailrecursion
if (x == null)
throw new MissingCase();
- assert this.elems != null;
- for (int i = 0; i< card; i++)
+ Contract.Assert(this.elems != null);
+ for (int i = 0; i < card; i++)
if (x.Equals(elems[i]))
return true;
return false;
@@ -662,8 +812,8 @@ namespace PureCollections {
public int IndexOf(object x) {
if (x == null)
throw new MissingCase();
- assert this.elems != null;
- for (int i = 0; i< card; i++)
+ Contract.Assert(this.elems != null);
+ for (int i = 0; i < card; i++)
if (x.Equals(elems[i]))
return i;
return -1;
@@ -675,111 +825,135 @@ namespace PureCollections {
public int LastIndexOf(object x) {
if (x == null)
throw new MissingCase();
- assert this.elems != null;
+ Contract.Assert(this.elems != null);
for (int i = card - 1; i >= 0; i--)
if (x.Equals(elems[i]))
return i;
return -1;
}
- public object Head() {assert this.elems != null; return elems[0]; }
- public object Last() {assert this.elems != null; return elems[card-1]; }
+ public object Head() {
+ Contract.Assert(this.elems != null);
+ return elems[0];
+ }
+ public object Last() {
+ Contract.Assert(this.elems != null);
+ return elems[card - 1];
+ }
- public static Sequence Tail(Sequence! s) {
- Sequence n = new Sequence(new Capacity(s.card-1));
- assert n.elems != null;
- assert s.elems != null;
- for (int i = 1; i< s.card; i++) n.elems[n.card++] = s.elems[i];
+ public static Sequence Tail(Sequence s) {
+ Contract.Requires(s != null);
+ Sequence n = new Sequence(new Capacity(s.card - 1));
+ Contract.Assert(n.elems != null);
+ Contract.Assert(s.elems != null);
+ for (int i = 1; i < s.card; i++)
+ n.elems[n.card++] = s.elems[i];
return n;
}
- public static Sequence Front(Sequence! s) {
- Sequence n = new Sequence(new Capacity(s.card-1));
- assert n.elems != null;
- assert s.elems != null;
- for (int i = 0; i< s.card-1; i++) n.elems[n.card++] = s.elems[i];
+ public static Sequence Front(Sequence s) {
+ Contract.Requires(s != null);
+ Sequence n = new Sequence(new Capacity(s.card - 1));
+ Contract.Assert(n.elems != null);
+ Contract.Assert(s.elems != null);
+ for (int i = 0; i < s.card - 1; i++)
+ n.elems[n.card++] = s.elems[i];
return n;
}
- public static Sequence Concat(Sequence! s) {
+ public static Sequence Concat(Sequence s) {
+ Contract.Requires(s != null);
Sequence n = new Sequence(new Capacity(s.card));
- assert n.elems != null;
- assert s.elems != null;
- for (int i = 0; i< s.card; i++) {
- Sequence t = (Sequence!) s.elems[i];
- assert t.elems != null;
- for (int j = 0; j < t.card; j ++)
+ Contract.Assert(n.elems != null);
+ Contract.Assert(s.elems != null);
+ for (int i = 0; i < s.card; i++) {
+ Sequence t = (Sequence)cce.NonNull(s.elems[i]);
+ Contract.Assert(t.elems != null);
+ for (int j = 0; j < t.card; j++)
n.Add(t.elems[j]);
}
return n;
}
- public static Sequence Reverse(Sequence! s) {
+ public static Sequence Reverse(Sequence s) {
+ Contract.Requires(s != null);
Sequence n = new Sequence(new Capacity(s.card));
- assert n.elems != null;
- assert s.elems != null;
- for (int i = s.card-1; i>=0; i--) n.elems[n.card++] = s.elems[i];
+ Contract.Assert(n.elems != null);
+ Contract.Assert(s.elems != null);
+ for (int i = s.card - 1; i >= 0; i--)
+ n.elems[n.card++] = s.elems[i];
return n;
}
- public static Sequence operator + (Sequence s, Sequence t)
- {
- if (s==null) throw new ArgumentNullException("s");
- if (t == null) throw new ArgumentNullException("t");
- return Append(t,s);
- }
-
- public static Sequence! Append(Sequence! s, Sequence! t) {
- Sequence! n = new Sequence(new Capacity(s.card + t.card));
- assert n.elems != null;
- assert s.elems != null;
- assert t.elems != null;
- for (int i = 0; i< s.card; i++) n.elems[n.card++] = s.elems[i];
- for (int i = 0; i< t.card; i++) n.elems[n.card++] = t.elems[i];
+ public static Sequence operator +(Sequence s, Sequence t) {
+ if (s == null)
+ throw new ArgumentNullException("s");
+ if (t == null)
+ throw new ArgumentNullException("t");
+ return Append(t, s);
+ }
+
+ public static Sequence Append(Sequence s, Sequence t) {
+ Contract.Requires(t != null);
+ Contract.Requires(s != null);
+ Contract.Ensures(Contract.Result<Sequence>() != null);
+ Sequence n = new Sequence(new Capacity(s.card + t.card));
+ Contract.Assert(n != null);
+ Contract.Assert(n.elems != null);
+ Contract.Assert(s.elems != null);
+ Contract.Assert(t.elems != null);
+ for (int i = 0; i < s.card; i++)
+ n.elems[n.card++] = s.elems[i];
+ for (int i = 0; i < t.card; i++)
+ n.elems[n.card++] = t.elems[i];
return n;
}
- public static Sequence Zip(Sequence! s, Sequence! t) {
- int min = s.card<t.card ? s.card : t.card;
+ public static Sequence Zip(Sequence s, Sequence t) {
+ Contract.Requires(t != null);
+ Contract.Requires(s != null);
+ int min = s.card < t.card ? s.card : t.card;
Sequence n = new Sequence(new Capacity(min));
- assert n.elems != null;
- assert s.elems != null;
- assert t.elems != null;
- for (int i = 0; i< min; i++) n.elems[n.card++] = new Tuple(s.elems[i], t.elems[i]);
+ Contract.Assert(n.elems != null);
+ Contract.Assert(s.elems != null);
+ Contract.Assert(t.elems != null);
+ for (int i = 0; i < min; i++)
+ n.elems[n.card++] = new Tuple(s.elems[i], t.elems[i]);
return n;
}
- public static Tuple Unzip(Sequence! s) {
+ public static Tuple Unzip(Sequence s) {
+ Contract.Requires(s != null);
Sequence n0 = new Sequence(new Capacity(s.card));
Sequence n1 = new Sequence(new Capacity(s.card));
- assert s.elems != null;
- assert n0.elems != null;
- assert n1.elems != null;
- for (int i = 0; i< s.card; i++) {
- n0.elems[n0.card++] = ((!)((Tuple!)s.elems[i]).elems)[0];
- n1.elems[n1.card++] = ((!)((Tuple!)s.elems[i]).elems)[1];
+ Contract.Assert(s.elems != null);
+ Contract.Assert(n0.elems != null);
+ Contract.Assert(n1.elems != null);
+ for (int i = 0; i < s.card; i++) {
+ n0.elems[n0.card++] = (cce.NonNull((Tuple)s.elems[i]).elems)[0];
+ n1.elems[n1.card++] = (cce.NonNull((Tuple)s.elems[i]).elems)[1];
}
- return new Tuple(n0,n1);
+ return new Tuple(n0, n1);
}
public static Sequence FromTo(int from, int to) { //WS hash the result!
- if (from > to) return new Sequence();
- Sequence n = new Sequence(new Capacity(to-from+1));
- assert n.elems != null;
- for (int i = from; i<= to; i++)
+ if (from > to)
+ return new Sequence();
+ Sequence n = new Sequence(new Capacity(to - from + 1));
+ Contract.Assert(n.elems != null);
+ for (int i = from; i <= to; i++)
n.elems[n.card++] = i;
return n;
}
-
- public static Sequence FromStepTo(int from, int step, int to) {
+
+ public static Sequence FromStepTo(int from, int step, int to) {
Sequence n = new Sequence();
- int incr = step-from;
- if (incr >0)
- for (int i = from; i<= to; i+=incr)
- n.Add(i);
+ int incr = step - from;
+ if (incr > 0)
+ for (int i = from; i <= to; i += incr)
+ n.Add(i);
else if (incr < 0)
- for (int i = to; i>= from; i-=incr)
- n.Add(i);
+ for (int i = to; i >= from; i -= incr)
+ n.Add(i);
return n;
}
-
- }
-}
+ }
+} \ No newline at end of file
diff --git a/Source/Core/ResolutionContext.cs b/Source/Core/ResolutionContext.cs
index 10ff7d87..93018097 100644
--- a/Source/Core/ResolutionContext.cs
+++ b/Source/Core/ResolutionContext.cs
@@ -3,537 +3,574 @@
// Copyright (C) Microsoft Corporation. All Rights Reserved.
//
//-----------------------------------------------------------------------------
-namespace Microsoft.Boogie
-{
- using System.Collections;
- using System.Collections.Generic;
- using System;
- using Microsoft.SpecSharp.Collections;
- using Microsoft.Contracts;
-
- public interface IErrorSink
- {
- void Error(IToken! tok, string! msg);
- }
-
- public class CheckingContext
- {
- // ------------------------------ Error counting ------------------------------
-
- IErrorSink errorSink;
- int errors;
-
- public CheckingContext(IErrorSink errorSink)
- {
- this.errorSink = errorSink;
- }
-
- public int ErrorCount
- {
- get { return errors; }
- set { errors = value; }
- }
+namespace Microsoft.Boogie {
+ using System.Collections;
+ using System.Collections.Generic;
+ using System;
+ using Microsoft.SpecSharp.Collections;
+ using System.Diagnostics.Contracts;
+
+ [ContractClass(typeof(IErrorSinkContracts))]
+ public interface IErrorSink {
+ void Error(IToken/*!*/ tok, string/*!*/ msg);
+ }
+ [ContractClassFor(typeof(IErrorSink))]
+ public abstract class IErrorSinkContracts : IErrorSink {
+ #region IErrorSink Members
+ public void Error(IToken tok, string msg) {
+ Contract.Requires(tok != null);
+ Contract.Requires(msg != null);
+ throw new NotImplementedException();
+ }
+ #endregion
+ }
- public void Error(Absy! subject, string! msg, params object[]! args)
- {
- Error(subject.tok, msg, args);
- }
+ public class CheckingContext {
+ // ------------------------------ Error counting ------------------------------
- public virtual void Error(IToken! tok, string! msg)
- {
- errors++;
- if (errorSink == null) {
- ConsoleColor col = Console.ForegroundColor;
- Console.ForegroundColor = ConsoleColor.Red;
- Console.WriteLine("{0}({1},{2}): Error: {3}",
- tok.filename, tok.line, tok.col-1,
- msg);
- Console.ForegroundColor = col;
- } else {
- errorSink.Error(tok, msg);
- }
- }
+ IErrorSink errorSink;
+ int errors;
- private string! Format(string! msg, params object[] args) {
- if (System.Type.GetType("Mono.Runtime") != null) { // MONO
- // something in mono seems to be broken so that calling
- // NamedDeclarations.ToString (and similar ToString methods)
- // causes a stack overflow. We therefore convert those to
- // strings by hand
- object[] fixedArgs = new object [((!)args).Length];
- for (int i = 0; i < args.Length; ++i) {
- if (args[i] is NamedDeclaration) {
- fixedArgs[i] = ((NamedDeclaration!)args[i]).Name;
- } else if (args[i] is Type) {
- System.IO.StringWriter buffer = new System.IO.StringWriter();
- using (TokenTextWriter stream = new TokenTextWriter("<buffer>", buffer, false)) {
- ((Type!)args[i]).Emit(stream);
- }
- fixedArgs[i] = buffer.ToString();
- } else if (args[i] is Expr) {
- System.IO.StringWriter buffer = new System.IO.StringWriter();
- using (TokenTextWriter stream = new TokenTextWriter("<buffer>", buffer, false)) {
- ((Expr!)args[i]).Emit(stream, 0, false);
- }
- fixedArgs[i] = buffer.ToString();
- } else {
- fixedArgs[i] = args[i];
- }
+ public CheckingContext(IErrorSink errorSink) {
+ this.errorSink = errorSink;
+ }
+
+ public int ErrorCount {
+ get {
+ return errors;
+ }
+ set {
+ errors = value;
+ }
+ }
+
+ public void Error(Absy subject, string msg, params object[] args) {
+ Contract.Requires(args != null);
+ Contract.Requires(msg != null);
+ Contract.Requires(subject != null);
+ Error(subject.tok, msg, args);
+ }
+
+ public virtual void Error(IToken tok, string msg) {
+ Contract.Requires(msg != null);
+ Contract.Requires(tok != null);
+ errors++;
+ if (errorSink == null) {
+ ConsoleColor col = Console.ForegroundColor;
+ Console.ForegroundColor = ConsoleColor.Red;
+ Console.WriteLine("{0}({1},{2}): Error: {3}",
+ tok.filename, tok.line, tok.col - 1,
+ msg);
+ Console.ForegroundColor = col;
+ } else {
+ errorSink.Error(tok, msg);
+ }
+ }
+
+ private string Format(string msg, params object[] args) {
+ Contract.Requires(msg != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+ if (System.Type.GetType("Mono.Runtime") != null) { // MONO
+ // something in mono seems to be broken so that calling
+ // NamedDeclarations.ToString (and similar ToString methods)
+ // causes a stack overflow. We therefore convert those to
+ // strings by hand
+ object[] fixedArgs = new object[cce.NonNull(args).Length];
+ for (int i = 0; i < args.Length; ++i) {
+ if (args[i] is NamedDeclaration) {
+ fixedArgs[i] = cce.NonNull((NamedDeclaration)args[i]).Name;
+ } else if (args[i] is Type) {
+ System.IO.StringWriter buffer = new System.IO.StringWriter();
+ using (TokenTextWriter stream = new TokenTextWriter("<buffer>", buffer, false)) {
+ cce.NonNull((Type)args[i]).Emit(stream);
+ }
+ fixedArgs[i] = buffer.ToString();
+ } else if (args[i] is Expr) {
+ System.IO.StringWriter buffer = new System.IO.StringWriter();
+ using (TokenTextWriter stream = new TokenTextWriter("<buffer>", buffer, false)) {
+ cce.NonNull((Expr/*!*/)args[i]).Emit(stream, 0, false);
}
- args = fixedArgs;
+ fixedArgs[i] = buffer.ToString();
+ } else {
+ fixedArgs[i] = args[i];
}
- return string.Format(msg, args);
}
+ args = fixedArgs;
+ }
+ return string.Format(msg, args);
+ }
- public void Error(IToken! tok, string! msg, params object[] args)
- {
- Error(tok, Format(msg, args));
- }
+ public void Error(IToken tok, string msg, params object[] args) {
+ Contract.Requires(msg != null);
+ Contract.Requires(tok != null);
+ Error(tok, Format(msg, args));
+ }
- public void Warning(Absy! subject, string! msg, params object[]! args)
- {
- Warning(subject.tok, msg, args);
- }
+ public void Warning(Absy subject, string msg, params object[] args) {
+ Contract.Requires(args != null);
+ Contract.Requires(msg != null);
+ Contract.Requires(subject != null);
+ Warning(subject.tok, msg, args);
+ }
- public virtual void Warning(IToken! tok, string! msg)
- {
- // warnings are currently always written to the console
- ConsoleColor col = Console.ForegroundColor;
- Console.ForegroundColor = ConsoleColor.DarkYellow;
- Console.WriteLine("{0}({1},{2}): Warning: {3}",
- tok.filename, tok.line, tok.col-1,
- msg);
- Console.ForegroundColor = col;
- }
+ public virtual void Warning(IToken tok, string msg) {
+ Contract.Requires(msg != null);
+ Contract.Requires(tok != null);
+ // warnings are currently always written to the console
+ ConsoleColor col = Console.ForegroundColor;
+ Console.ForegroundColor = ConsoleColor.DarkYellow;
+ Console.WriteLine("{0}({1},{2}): Warning: {3}",
+ tok.filename, tok.line, tok.col - 1,
+ msg);
+ Console.ForegroundColor = col;
+ }
- public void Warning(IToken! tok, string! msg, params object[] args)
- {
- Warning(tok, Format(msg, args));
- }
+ public void Warning(IToken tok, string msg, params object[] args) {
+ Contract.Requires(msg != null);
+ Contract.Requires(tok != null);
+ Warning(tok, Format(msg, args));
}
+ }
- public class ResolutionContext : CheckingContext
- {
- public ResolutionContext(IErrorSink errorSink)
- {
- base(errorSink);
- }
-
- // ------------------------------ Boogie 2 Types -------------------------
-
- // user-defined types, which can be either TypeCtorDecl or TypeSynonymDecl
- Hashtable /*string->NamedDeclaration*/! types = new Hashtable /*string->NamedDeclaration*/ ();
-
- /// <summary>
- /// Checks if name coincides with the name of a bitvector type. If so, reports an error and
- /// returns true; otherwise, returns false.
- /// </summary>
- private bool CheckBvNameClashes(Absy! absy, string! name) {
- if (name.StartsWith("bv") && name.Length > 2) {
- for (int i = 2; i < name.Length; ++i)
- if (!char.IsDigit(name[i])) return false;
- Error(absy, "type name: {0} is registered for bitvectors", name);
- return true;
- }
+ public class ResolutionContext : CheckingContext {
+ public ResolutionContext(IErrorSink errorSink)
+ : base(errorSink) {//BASEMOVEA
+ //:base(errorSink);
+ }
+
+ // ------------------------------ Boogie 2 Types -------------------------
+
+ // user-defined types, which can be either TypeCtorDecl or TypeSynonymDecl
+ Hashtable /*string->NamedDeclaration*//*!*/ types = new Hashtable /*string->NamedDeclaration*/ ();
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(types != null);
+ Contract.Invariant(cce.NonNullElements(typeBinders));
+ Contract.Invariant(varContext != null);
+ Contract.Invariant(funcdures != null);
+ }
+
+
+ /// <summary>
+ /// Checks if name coincides with the name of a bitvector type. If so, reports an error and
+ /// returns true; otherwise, returns false.
+ /// </summary>
+ private bool CheckBvNameClashes(Absy absy, string name) {
+ Contract.Requires(name != null);
+ Contract.Requires(absy != null);
+ if (name.StartsWith("bv") && name.Length > 2) {
+ for (int i = 2; i < name.Length; ++i)
+ if (!char.IsDigit(name[i]))
return false;
- }
+ Error(absy, "type name: {0} is registered for bitvectors", name);
+ return true;
+ }
+ return false;
+ }
- public void AddType(NamedDeclaration! td)
- {
- assert (td is TypeCtorDecl) || (td is TypeSynonymDecl);
-
- string! name = (!)td.Name;
- if (CheckBvNameClashes(td, name))
- return; // error has already been reported
-
- if (types[name] != null)
- {
- Error(td, "more than one declaration of type name: {0}", name);
- }
- else
- {
- types.Add(name, td);
- }
- }
+ public void AddType(NamedDeclaration td) {
+ Contract.Requires(td != null);
+ Contract.Assert((td is TypeCtorDecl) || (td is TypeSynonymDecl));
- /// <summary>
- /// Returns the declaration of the named type, or null if
- /// no such type is declared. Also return null if the type
- /// declared with the given name is not a constructor but a
- /// type synonym
- /// </summary>
- /// <param name="name"></param>
- /// <returns></returns>
- public TypeCtorDecl LookUpType(string! name)
- {
- return types[name] as TypeCtorDecl;
- }
-
- public TypeSynonymDecl LookUpTypeSynonym(string! name)
- {
- return types[name] as TypeSynonymDecl;
- }
-
- // ------------------------------ Boogie 2 Type Binders ------------------------------
+ string name = cce.NonNull(td.Name);
+ if (CheckBvNameClashes(td, name))
+ return; // error has already been reported
- List<TypeVariable!>! typeBinders = new List<TypeVariable!>(5);
-
- public void AddTypeBinder(TypeVariable! td) {
- if (CheckBvNameClashes(td, td.Name)) {
- return;
- }
- if (types.ContainsKey(td.Name)) {
- Error(td, "name is already reserved for type constructor: {0}", td.Name);
- return;
- }
- for (int i = 0; i < typeBinders.Count; i++) {
- if (typeBinders[i].Name == td.Name) {
- Error(td, "more than one declaration of type variable: {0}", td.Name);
- return;
- }
- }
- typeBinders.Add(td);
- }
-
- public int TypeBinderState {
- get { return typeBinders.Count; }
- set { typeBinders.RemoveRange(value, typeBinders.Count - value); }
- }
-
- /// <summary>
- /// Returns the declaration of the named type binder, or null if
- /// no such binder is declared.
- /// </summary>
- public TypeVariable LookUpTypeBinder(string! name)
- {
- for (int i = typeBinders.Count; 0 <= --i; ) {
- TypeVariable! td = typeBinders[i];
- if (td.Name == name) {
- return td;
- }
- }
- return null; // not present
- }
-
- // ------------------------------ Types ------------------------------
+ if (types[name] != null) {
+ Error(td, "more than one declaration of type name: {0}", name);
+ } else {
+ types.Add(name, td);
+ }
+ }
- // user-defined types
- // Hashtable /*string->TypeDecl*/! types = new Hashtable /*string->TypeDecl*/ ();
-/*
- public void AddType(TypeDecl! td)
- {
- string! name = (!)td.Name;
-
- if (name.StartsWith("bv") && name.Length > 2) {
- bool isBv = true;
- for (int i = 2; i < name.Length; ++i)
- if (!char.IsDigit(name[i])) isBv = false;
- if (isBv)
- Error(td, "type name: {0} is registered for bitvectors", name);
- }
+ /// <summary>
+ /// Returns the declaration of the named type, or null if
+ /// no such type is declared. Also return null if the type
+ /// declared with the given name is not a constructor but a
+ /// type synonym
+ /// </summary>
+ /// <param name="name"></param>
+ /// <returns></returns>
+ public TypeCtorDecl LookUpType(string name) {
+ Contract.Requires(name != null);
+ return types[name] as TypeCtorDecl;
+ }
+
+ public TypeSynonymDecl LookUpTypeSynonym(string name) {
+ Contract.Requires(name != null);
+ return types[name] as TypeSynonymDecl;
+ }
+
+ // ------------------------------ Boogie 2 Type Binders ------------------------------
+
+ List<TypeVariable/*!*/>/*!*/ typeBinders = new List<TypeVariable/*!*/>(5);
+
+ public void AddTypeBinder(TypeVariable td) {
+ Contract.Requires(td != null);
+ if (CheckBvNameClashes(td, td.Name)) {
+ return;
+ }
+ if (types.ContainsKey(td.Name)) {
+ Error(td, "name is already reserved for type constructor: {0}", td.Name);
+ return;
+ }
+ for (int i = 0; i < typeBinders.Count; i++) {
+ if (typeBinders[i].Name == td.Name) {
+ Error(td, "more than one declaration of type variable: {0}", td.Name);
+ return;
+ }
+ }
+ typeBinders.Add(td);
+ }
+
+ public int TypeBinderState {
+ get {
+ return typeBinders.Count;
+ }
+ set {
+ typeBinders.RemoveRange(value, typeBinders.Count - value);
+ }
+ }
+
+ /// <summary>
+ /// Returns the declaration of the named type binder, or null if
+ /// no such binder is declared.
+ /// </summary>
+ public TypeVariable LookUpTypeBinder(string name) {
+ Contract.Requires(name != null);
+ for (int i = typeBinders.Count; 0 <= --i; ) {
+ TypeVariable/*!*/ td = typeBinders[i];
+ Contract.Assert(td != null);
+ if (td.Name == name) {
+ return td;
+ }
+ }
+ return null; // not present
+ }
+
+ // ------------------------------ Types ------------------------------
+
+ // user-defined types
+ // Hashtable /*string->TypeDecl*/! types = new Hashtable /*string->TypeDecl*/ ();
+ /*
+ public void AddType(TypeDecl td){
+ Contract.Requires(td != null);
+ string! name = (!)td.Name;
+
+ if (name.StartsWith("bv") && name.Length > 2) {
+ bool isBv = true;
+ for (int i = 2; i < name.Length; ++i)
+ if (!char.IsDigit(name[i])) isBv = false;
+ if (isBv)
+ Error(td, "type name: {0} is registered for bitvectors", name);
+ }
- if (types[name] != null)
- {
- Error(td, "more than one declaration of type name: {0}", name);
- }
- else
- {
- types.Add(name, td);
+ if (types[name] != null)
+ {
+ Error(td, "more than one declaration of type name: {0}", name);
+ }
+ else
+ {
+ types.Add(name, td);
+ }
}
- }
-*/
- /// <summary>
- /// Returns the declaration of the named type, or null if
- /// no such type is declared.
- /// </summary>
- /// <param name="name"></param>
- /// <returns></returns>
- /* public TypeDecl LookUpType(string! name)
- {
+ */
+ /// <summary>
+ /// Returns the declaration of the named type, or null if
+ /// no such type is declared.
+ /// </summary>
+ /// <param name="name"></param>
+ /// <returns></returns>
+ /* public TypeDecl LookUpType(string name){
+Contract.Requires(name != null);
return (TypeDecl)types[name];
}
- */
- // ------------------------------ Type Binders ------------------------------
-/*
- List<TypeBinderDecl!>! typeBinders = new List<TypeBinderDecl!>(5);
+ */
+ // ------------------------------ Type Binders ------------------------------
+ /*
+ List<TypeBinderDecl!>! typeBinders = new List<TypeBinderDecl!>(5);
- public void AddTypeBinder(TypeBinderDecl! td) {
- for (int i = 0; i < typeBinders.Count; i++) {
- if (typeBinders[i].Name == td.Name) {
- Error(td, "more than one declaration of type binder name: {0}", td.Name);
- return;
+ public void AddTypeBinder(TypeBinderDecl td){
+ Contract.Requires(td != null);
+ for (int i = 0; i < typeBinders.Count; i++) {
+ if (typeBinders[i].Name == td.Name) {
+ Error(td, "more than one declaration of type binder name: {0}", td.Name);
+ return;
+ }
+ }
+ typeBinders.Add(td);
}
- }
- typeBinders.Add(td);
- }
- public int TypeBinderState {
- get { return typeBinders.Count; }
- set { typeBinders.RemoveRange(value, typeBinders.Count - value); }
- }
+ public int TypeBinderState {
+ get { return typeBinders.Count; }
+ set { typeBinders.RemoveRange(value, typeBinders.Count - value); }
+ }
- /// <summary>
- /// Returns the declaration of the named type binder, or null if
- /// no such binder is declared.
- /// </summary>
- public TypeDecl LookUpTypeBinder(string! name)
- {
- for (int i = typeBinders.Count; 0 <= --i; ) {
- TypeBinderDecl td = typeBinders[i];
- if (td.Name == name) {
- return td;
+ /// <summary>
+ /// Returns the declaration of the named type binder, or null if
+ /// no such binder is declared.
+ /// </summary>
+ public TypeDecl LookUpTypeBinder(string name){
+ Contract.Requires(name != null);
+ for (int i = typeBinders.Count; 0 <= --i; ) {
+ TypeBinderDecl td = typeBinders[i];
+ if (td.Name == name) {
+ return td;
+ }
+ }
+ return null; // not present
}
- }
- return null; // not present
- }
- */
- // ------------------------------ Variables ------------------------------
+ */
+ // ------------------------------ Variables ------------------------------
+
+ class VarContextNode {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(VarSymbols != null);
+ }
+
+ public readonly Hashtable /*string->Variable*//*!*/ VarSymbols = new Hashtable /*string->Variable*/();
+ public /*maybe null*/ VarContextNode ParentContext;
+ public readonly bool Opaque;
+
+ public VarContextNode(/*maybe null*/ VarContextNode parentContext, bool opaque) {
+ ParentContext = parentContext;
+ Opaque = opaque;
+ }
+ }
- class VarContextNode
- {
- public readonly Hashtable /*string->Variable*/! VarSymbols = new Hashtable /*string->Variable*/();
- public /*maybe null*/ VarContextNode ParentContext;
- public readonly bool Opaque;
-
- public VarContextNode(/*maybe null*/ VarContextNode parentContext, bool opaque)
- {
- ParentContext = parentContext;
- Opaque = opaque;
- }
- }
+ // symbolic constants, global variables, local variables, formals, expression-bound variables
+ VarContextNode/*!*/ varContext = new VarContextNode(null, false);
- // symbolic constants, global variables, local variables, formals, expression-bound variables
- VarContextNode! varContext = new VarContextNode(null, false);
+ /// <summary>
+ /// Adds a variable context.
+ /// </summary>
+ public void PushVarContext() {
+ varContext = new VarContextNode(varContext, false);
+ }
- /// <summary>
- /// Adds a variable context.
- /// </summary>
- public void PushVarContext()
- {
- varContext = new VarContextNode(varContext, false);
- }
+ /// <summary>
+ /// Adds an opaque variable context, that is, one that blocks all previously pushed contexts.
+ /// </summary>
+ public void PushOpaqueVarContext() {
+ varContext = new VarContextNode(varContext, true);
+ }
- /// <summary>
- /// Adds an opaque variable context, that is, one that blocks all previously pushed contexts.
- /// </summary>
- public void PushOpaqueVarContext()
- {
- varContext = new VarContextNode(varContext, true);
- }
-
- /// <summary>
- /// Requires there to be more than one variable context.
- /// </summary>
- public void PopVarContext()
- {
- assert varContext.ParentContext != null;
- varContext = varContext.ParentContext;
+ /// <summary>
+ /// Requires there to be more than one variable context.
+ /// </summary>
+ public void PopVarContext() {
+ Contract.Assert(varContext.ParentContext != null);
+ varContext = varContext.ParentContext;
+ }
+
+ public void AddVariable(Variable var, bool global) {
+ Contract.Requires(var != null);
+ if (FindVariable(cce.NonNull(var.Name), !global) != null) {
+ Error(var, "more than one declaration of variable name: {0}", var.Name);
+ } else {
+ varContext.VarSymbols.Add(var.Name, var);
+ }
+ }
+
+ /// <summary>
+ /// Returns the declaration of the named variable, or null if
+ /// no such variable is declared.
+ /// </summary>
+ /// <param name="name"></param>
+ /// <returns></returns>
+ public Variable LookUpVariable(string name) {
+ Contract.Requires(name != null);
+ return FindVariable(name, false);
+ }
+
+ Variable FindVariable(string name, bool ignoreTopLevelVars) {
+ Contract.Requires(name != null);
+ VarContextNode c = varContext;
+ bool lookOnlyForConstants = false;
+ do {
+ if (ignoreTopLevelVars && c.ParentContext == null) {
+ // this is the top level and we're asked to ignore the top level; hence, we're done
+ break;
}
- public void AddVariable(Variable! var, bool global)
- {
- if (FindVariable((!)var.Name, !global) != null)
- {
- Error(var, "more than one declaration of variable name: {0}", var.Name);
- }
- else
- {
- varContext.VarSymbols.Add(var.Name, var);
- }
+ Variable var = (Variable)c.VarSymbols[name];
+ if (var != null && (!lookOnlyForConstants || var is Constant)) {
+ return var;
}
+ // not at this level
- /// <summary>
- /// Returns the declaration of the named variable, or null if
- /// no such variable is declared.
- /// </summary>
- /// <param name="name"></param>
- /// <returns></returns>
- public Variable LookUpVariable(string! name)
- {
- return FindVariable(name, false);
+ if (c.Opaque) {
+ // from here on, only constants can be looked up
+ lookOnlyForConstants = true;
}
+ c = c.ParentContext;
+ } while (c != null);
- Variable FindVariable(string! name, bool ignoreTopLevelVars)
- {
- VarContextNode c = varContext;
- bool lookOnlyForConstants = false;
- do {
- if (ignoreTopLevelVars && c.ParentContext == null) {
- // this is the top level and we're asked to ignore the top level; hence, we're done
- break;
- }
+ // not present in the relevant levels
+ return null;
+ }
- Variable var = (Variable)c.VarSymbols[name];
- if (var != null && (!lookOnlyForConstants || var is Constant)) {
- return var;
- }
- // not at this level
-
- if (c.Opaque) {
- // from here on, only constants can be looked up
- lookOnlyForConstants = true;
- }
- c = c.ParentContext;
- } while (c != null);
-
- // not present in the relevant levels
- return null;
- }
+ // ------------------------------ Functions/Procedures ------------------------------
- // ------------------------------ Functions/Procedures ------------------------------
+ // uninterpreted function symbols, procedures
+ Hashtable /*string->DeclWithFormals*//*!*/ funcdures = new Hashtable /*string->DeclWithFormals*/ ();
- // uninterpreted function symbols, procedures
- Hashtable /*string->DeclWithFormals*/! funcdures = new Hashtable /*string->DeclWithFormals*/ ();
+ public void AddProcedure(DeclWithFormals proc) {
+ Contract.Requires(proc != null);
+ if (funcdures[cce.NonNull(proc.Name)] != null) {
+ Error(proc, "more than one declaration of function/procedure name: {0}", proc.Name);
+ } else {
+ funcdures.Add(proc.Name, proc);
+ }
+ }
- public void AddProcedure(DeclWithFormals! proc)
- {
- if (funcdures[(!)proc.Name] != null)
- {
- Error(proc, "more than one declaration of function/procedure name: {0}", proc.Name);
- }
- else
- {
- funcdures.Add(proc.Name, proc);
- }
- }
+ /// <summary>
+ /// Returns the declaration of the named function/procedure, or null if
+ /// no such function or procedure is declared.
+ /// </summary>
+ /// <param name="name"></param>
+ /// <returns></returns>
+ public DeclWithFormals LookUpProcedure(string name) {
+ Contract.Requires(name != null);
+ return (DeclWithFormals)funcdures[name];
+ }
- /// <summary>
- /// Returns the declaration of the named function/procedure, or null if
- /// no such function or procedure is declared.
- /// </summary>
- /// <param name="name"></param>
- /// <returns></returns>
- public DeclWithFormals LookUpProcedure(string! name)
- {
- return (DeclWithFormals)funcdures[name];
- }
+ // ------------------------------ Blocks ------------------------------
- // ------------------------------ Blocks ------------------------------
+ class ProcedureContext {
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(Blocks != null);
+ }
- class ProcedureContext {
- public readonly Hashtable! /*string->Block!*/ Blocks;
- public readonly ProcedureContext Next;
- public ProcedureContext(ProcedureContext next) {
- Blocks = new Hashtable /*string->Block!*/ ();
- Next = next;
- }
- }
- /*maybe null*/ ProcedureContext procedureContext; // stack of procedure contexts
- public bool HasProcedureContext {
- get { return procedureContext != null; }
- }
+ public readonly Hashtable/*!*/ /*string->Block!*/ Blocks;
+ public readonly ProcedureContext Next;
+ public ProcedureContext(ProcedureContext next) {
+ Blocks = new Hashtable /*string->Block!*/ ();
+ Next = next;
+ }
+ }
+ /*maybe null*/
+ ProcedureContext procedureContext; // stack of procedure contexts
+ public bool HasProcedureContext {
+ get {
+ return procedureContext != null;
+ }
+ }
- /// <summary>
- /// Pushes a new procedure context.
- /// </summary>
- public void PushProcedureContext()
- ensures HasProcedureContext;
- {
- procedureContext = new ProcedureContext(procedureContext);
- }
+ /// <summary>
+ /// Pushes a new procedure context.
+ /// </summary>
+ public void PushProcedureContext() {
+ Contract.Ensures(HasProcedureContext);
+ procedureContext = new ProcedureContext(procedureContext);
+ }
- /// <summary>
- /// Requires there to be a procedure context. Pops it.
- /// </summary>
- public void PopProcedureContext()
- requires HasProcedureContext;
- {
- assert procedureContext != null; // follows from precondition
- procedureContext = procedureContext.Next;
- }
+ /// <summary>
+ /// Requires there to be a procedure context. Pops it.
+ /// </summary>
+ public void PopProcedureContext() {
+ Contract.Requires(HasProcedureContext);
+ Contract.Assert(procedureContext != null); // follows from precondition
+ procedureContext = procedureContext.Next;
+ }
- /// <summary>
- /// Requires there to be a procedure context.
- /// </summary>
- /// <param name="block"></param>
- public void AddBlock(Block! block)
- requires HasProcedureContext;
- {
- assert procedureContext != null; // follows from precondition
- Hashtable! /*string->Block!*/ blocks = procedureContext.Blocks;
- if (blocks[block.Label] != null)
- {
- Error(block, "more than one declaration of block name: {0}", block.Label);
- }
- else
- {
- blocks.Add(block.Label, block);
- }
- }
+ /// <summary>
+ /// Requires there to be a procedure context.
+ /// </summary>
+ /// <param name="block"></param>
+ public void AddBlock(Block block) {
+ Contract.Requires(block != null);
+ Contract.Requires(HasProcedureContext);
+ Contract.Assert(procedureContext != null); // follows from precondition
+ Hashtable/*!*/ /*string->Block!*/ blocks = procedureContext.Blocks;
+ Contract.Assert(blocks != null);
+ if (blocks[block.Label] != null) {
+ Error(block, "more than one declaration of block name: {0}", block.Label);
+ } else {
+ blocks.Add(block.Label, block);
+ }
+ }
- /// <summary>
- /// Requires there to be a procedure context.
- /// Returns the declaration of the named block, or null if
- /// no such block is declared.
- /// </summary>
- /// <param name="name"></param>
- /// <returns></returns>
- public Block LookUpBlock(string! name)
- requires HasProcedureContext;
- {
- assert procedureContext != null; // follows from precondition
- Hashtable! /*string->Block!*/ blocks = procedureContext.Blocks;
- return (Block)blocks[name];
- }
+ /// <summary>
+ /// Requires there to be a procedure context.
+ /// Returns the declaration of the named block, or null if
+ /// no such block is declared.
+ /// </summary>
+ /// <param name="name"></param>
+ /// <returns></returns>
+ public Block LookUpBlock(string name) {
+ Contract.Requires(name != null);
+ Contract.Requires(HasProcedureContext);
+ Contract.Assert(procedureContext != null); // follows from precondition
+ Hashtable/*!*/ /*string->Block!*/ blocks = procedureContext.Blocks;
+ Contract.Assert(blocks != null);
+ return (Block)blocks[name];
+ }
- // ------------------------------ Flags ------------------------------
+ // ------------------------------ Flags ------------------------------
- public enum State { StateLess, Single, Two }
- State stateMode = State.Single;
+ public enum State {
+ StateLess,
+ Single,
+ Two
+ }
+ State stateMode = State.Single;
+
+ /// <summary>
+ /// To increase our confidence in that the caller knows what it's doing, we only allow
+ /// the state mode to be changed in and out of the State.Single mode.
+ /// </summary>
+ public State StateMode {
+ get {
+ return stateMode;
+ }
+ set {
+ Contract.Assert(value != stateMode);
+ Contract.Assert(stateMode == State.Single || value == State.Single);
+ cce.BeginExpose(this);
+ {
+ stateMode = value;
+ }
+ cce.EndExpose();
+ }
+ }
- /// <summary>
- /// To increase our confidence in that the caller knows what it's doing, we only allow
- /// the state mode to be changed in and out of the State.Single mode.
- /// </summary>
- public State StateMode {
- get {
- return stateMode;
- }
- set {
- assert value != stateMode;
- assert stateMode == State.Single || value == State.Single;
- expose (this) {
- stateMode = value;
- }
- }
- }
-
- bool triggerMode = false;
-
- /// <summary>
- /// Setting TriggerMode is allowed only if the setting has the effect of toggling the
- /// boolean. That is, TriggerMode can be set to true only if it previously was false,
- /// and TriggerMode can be set to false only if it previously was true.
- /// </summary>
- public bool TriggerMode
- {
- get
- {
- return triggerMode;
- }
- set
- {
- assert triggerMode != value;
- expose (this) {
- triggerMode = value;
- }
- }
- }
+ bool triggerMode = false;
+
+ /// <summary>
+ /// Setting TriggerMode is allowed only if the setting has the effect of toggling the
+ /// boolean. That is, TriggerMode can be set to true only if it previously was false,
+ /// and TriggerMode can be set to false only if it previously was true.
+ /// </summary>
+ public bool TriggerMode {
+ get {
+ return triggerMode;
+ }
+ set {
+ Contract.Assert(triggerMode != value);
+ cce.BeginExpose(this);
+ {
+ triggerMode = value;
+ }
+ cce.EndExpose();
+ }
}
+ }
- public class TypecheckingContext : CheckingContext
- {
- public IdentifierExprSeq Frame; // used in checking the assignment targets of implementation bodies
+ public class TypecheckingContext : CheckingContext {
+ public IdentifierExprSeq Frame; // used in checking the assignment targets of implementation bodies
- public TypecheckingContext(IErrorSink errorSink)
- {
- base(errorSink);
- }
-
- public bool InFrame(Variable! v)
- requires Frame != null;
- {
- return exists{IdentifierExpr! ie in Frame; ie.Decl == v};
- }
+ public TypecheckingContext(IErrorSink errorSink)
+ : base(errorSink) {//BASEMOVEA
+ //:base(errorSink);
+ }
+
+ public bool InFrame(Variable v) {
+ Contract.Requires(v != null);
+ Contract.Requires(Frame != null);
+ return Contract.Exists(0, Frame.Length, ie => Frame[ie].Decl == v);
}
+ }
}
diff --git a/Source/Core/Scanner.cs b/Source/Core/Scanner.cs
index 870720d3..deb8b809 100644
--- a/Source/Core/Scanner.cs
+++ b/Source/Core/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.Boogie {
@@ -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 = 88;
- 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);
@@ -276,7 +293,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
@@ -284,7 +303,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);
@@ -292,13 +311,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();
}
@@ -318,7 +340,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
@@ -330,7 +353,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;
}
@@ -351,12 +375,13 @@ public class Scanner {
// eol handling uniform across Windows, Unix and Mac
if (ch == '\r' && buffer.Peek() != '\n') ch = EOL;
if (ch == EOL) {
- line++; col = 0;
+ line++; col = 0;
} else if (ch == '#' && col == 1) {
int prLine = line;
int prColumn = 0;
- string! hashLine = ReadToEOL();
+ string/*!*/ hashLine = ReadToEOL();
+ Contract.Assert(hashLine!=null);
col = 0;
line++;
@@ -502,7 +527,8 @@ public class Scanner {
}
}
- Token! NextToken() {
+ Token/*!*/ NextToken() {
+ Contract.Ensures(Contract.Result<Token>() != null);
while (ch == ' ' ||
ch >= 9 && ch <= 10 || ch == 13
) NextCh();
@@ -510,10 +536,10 @@ public class Scanner {
int recKind = noSym;
int recEnd = pos;
t = new Token();
- t.pos = pos; t.col = col; t.line = line;
+ 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/Core/StandardVisitor.cs b/Source/Core/StandardVisitor.cs
index 10984ff3..528e442f 100644
--- a/Source/Core/StandardVisitor.cs
+++ b/Source/Core/StandardVisitor.cs
@@ -8,150 +8,174 @@
//---------------------------------------------------------------------------------------------
using System.Collections.Generic;
+using System.Diagnostics.Contracts;
-namespace Microsoft.Boogie
-{
+namespace Microsoft.Boogie {
+ [ContractClass(typeof(VisitorContracts))]
/// <summary>
/// Base for all classes that process the Absy using the visitor pattern.
/// </summary>
- public abstract class Visitor
- {
+ public abstract class Visitor {
/// <summary>
/// Switches on node.NodeType to call a visitor method that has been specialized for node.
/// </summary>
/// <param name="a">The Absy node to be visited.</param>
/// <returns> Returns null if node is null. Otherwise returns an updated node (possibly a different object).</returns>
- public abstract Absy! Visit (Absy! node);
-
+ public abstract Absy/*!*/ Visit(Absy/*!*/ node);
+
/// <summary>
/// Transfers the state from one visitor to another. This enables separate visitor instances to cooperative process a single IR.
/// </summary>
- public virtual void TransferStateTo(Visitor targetVisitor)
- {
+ public virtual void TransferStateTo(Visitor targetVisitor) {
}
- public virtual ExprSeq! VisitExprSeq(ExprSeq! list)
- {
- for( int i = 0, n = list.Length; i < n; i++)
- list[i] = (Expr)this.Visit( (!) list[i]);
+ public virtual ExprSeq VisitExprSeq(ExprSeq list) {
+ Contract.Requires(list != null);
+ Contract.Ensures(Contract.Result<ExprSeq>() != null);
+ for (int i = 0, n = list.Length; i < n; i++)
+ list[i] = (Expr)this.Visit(cce.NonNull(list[i]));
return list;
}
}
+ [ContractClassFor(typeof(Visitor))]
+ abstract class VisitorContracts : Visitor {
+ public override Absy Visit(Absy node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
+
+ throw new System.NotImplementedException();
+ }
+ }
/// <summary>
/// Walks an IR, mutuating it into a new form
/// </summary>
- public abstract class StandardVisitor: Visitor
- {
+ public abstract class StandardVisitor : Visitor {
public Visitor callingVisitor;
-
- public StandardVisitor()
- {
+
+ public StandardVisitor() {
}
- public StandardVisitor(Visitor callingVisitor)
- {
+ public StandardVisitor(Visitor callingVisitor) {
this.callingVisitor = callingVisitor;
}
- public override Absy! Visit (Absy! node)
- {
+ public override Absy Visit(Absy node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Absy>() != null);
return node.StdDispatch(this);
}
- public virtual AIVariableExpr! VisitAIVariableExpr(AIVariableExpr! node)
- {
+ public virtual AIVariableExpr VisitAIVariableExpr(AIVariableExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<AIVariableExpr>() != null);
return node;
}
- public virtual Cmd! VisitAssertCmd(AssertCmd! node)
- {
+ public virtual Cmd VisitAssertCmd(AssertCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
node.Expr = this.VisitExpr(node.Expr);
return node;
}
- public virtual Cmd! VisitAssignCmd(AssignCmd! node)
- {
+ public virtual Cmd VisitAssignCmd(AssignCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
for (int i = 0; i < node.Lhss.Count; ++i) {
- node.Lhss[i] = (AssignLhs!)this.Visit(node.Lhss[i]);
- node.Rhss[i] = (Expr!)this.Visit(node.Rhss[i]);
+ node.Lhss[i] = cce.NonNull((AssignLhs)this.Visit(node.Lhss[i]));
+ node.Rhss[i] = cce.NonNull((Expr/*!*/)this.Visit(node.Rhss[i]));
}
return node;
}
- public virtual Cmd! VisitAssumeCmd(AssumeCmd! node)
- {
+ public virtual Cmd VisitAssumeCmd(AssumeCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
node.Expr = this.VisitExpr(node.Expr);
return node;
}
- public virtual AtomicRE! VisitAtomicRE(AtomicRE! node)
- {
+ public virtual AtomicRE VisitAtomicRE(AtomicRE node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<AtomicRE>() != null);
node.b = this.VisitBlock(node.b);
return node;
}
- public virtual Axiom! VisitAxiom(Axiom! node)
- {
+ public virtual Axiom VisitAxiom(Axiom node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Axiom>() != null);
node.Expr = this.VisitExpr(node.Expr);
return node;
}
- public virtual Type! VisitBasicType(BasicType! node)
- {
+ public virtual Type VisitBasicType(BasicType node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
return this.VisitType(node);
}
- public virtual BvConcatExpr! VisitBvConcatExpr(BvConcatExpr! node)
- {
+ public virtual BvConcatExpr VisitBvConcatExpr(BvConcatExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<BvConcatExpr>() != null);
node.E0 = this.VisitExpr(node.E0);
node.E1 = this.VisitExpr(node.E1);
return node;
}
- public virtual Type! VisitBvType(BvType! node)
- {
+ public virtual Type VisitBvType(BvType node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
return this.VisitType(node);
}
- public virtual Type! VisitBvTypeProxy(BvTypeProxy! node)
- {
+ public virtual Type VisitBvTypeProxy(BvTypeProxy node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
// if the type proxy is instantiated with some more
// specific type, we visit the instantiation
if (node.ProxyFor != null)
return (Type)this.Visit(node.ProxyFor);
return this.VisitType(node);
}
- public virtual Block! VisitBlock(Block! node)
- {
+ public virtual Block VisitBlock(Block node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Block>() != null);
node.Cmds = this.VisitCmdSeq(node.Cmds);
- node.TransferCmd = (TransferCmd)this.Visit((!)node.TransferCmd);
+ node.TransferCmd = (TransferCmd)this.Visit(cce.NonNull(node.TransferCmd));
return node;
}
- public virtual Expr! VisitCodeExpr(CodeExpr! node)
- {
+ public virtual Expr VisitCodeExpr(CodeExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
node.LocVars = this.VisitVariableSeq(node.LocVars);
node.Blocks = this.VisitBlockList(node.Blocks);
return node;
}
- public virtual BlockSeq! VisitBlockSeq(BlockSeq! blockSeq)
- {
+ public virtual BlockSeq VisitBlockSeq(BlockSeq blockSeq) {
+ Contract.Requires(blockSeq != null);
+ Contract.Ensures(Contract.Result<BlockSeq>() != null);
for (int i = 0, n = blockSeq.Length; i < n; i++)
- blockSeq[i] = this.VisitBlock( (!)blockSeq[i]);
+ blockSeq[i] = this.VisitBlock(cce.NonNull(blockSeq[i]));
return blockSeq;
}
- public virtual List<Block!>! VisitBlockList(List<Block!>! blocks)
- {
+ public virtual List<Block/*!*/>/*!*/ VisitBlockList(List<Block/*!*/>/*!*/ blocks) {
+ Contract.Requires(cce.NonNullElements(blocks));
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Block>>()));
for (int i = 0, n = blocks.Count; i < n; i++) {
blocks[i] = this.VisitBlock(blocks[i]);
}
return blocks;
}
- public virtual BoundVariable! VisitBoundVariable(BoundVariable! node)
- {
- node = (BoundVariable) this.VisitVariable(node);
+ public virtual BoundVariable VisitBoundVariable(BoundVariable node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<BoundVariable>() != null);
+ node = (BoundVariable)this.VisitVariable(node);
return node;
}
- public virtual Cmd! VisitCallCmd(CallCmd! node)
- {
+ public virtual Cmd VisitCallCmd(CallCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
for (int i = 0; i < node.Ins.Count; ++i)
if (node.Ins[i] != null)
- node.Ins[i] = this.VisitExpr((!)node.Ins[i]);
+ node.Ins[i] = this.VisitExpr(cce.NonNull(node.Ins[i]));
for (int i = 0; i < node.Outs.Count; ++i)
if (node.Outs[i] != null)
- node.Outs[i] = (IdentifierExpr)this.VisitIdentifierExpr((!)node.Outs[i]);
+ node.Outs[i] = (IdentifierExpr)this.VisitIdentifierExpr(cce.NonNull(node.Outs[i]));
return node;
}
- public virtual Cmd! VisitCallForallCmd(CallForallCmd! node)
- {
+ public virtual Cmd VisitCallForallCmd(CallForallCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
List<Expr> elist = new List<Expr>(node.Ins.Count);
foreach (Expr arg in node.Ins) {
if (arg == null) {
@@ -161,180 +185,211 @@ namespace Microsoft.Boogie
}
}
node.Ins = elist;
- node.Proc = this.VisitProcedure((!)node.Proc);
+ node.Proc = this.VisitProcedure(cce.NonNull(node.Proc));
return node;
}
- public virtual CmdSeq! VisitCmdSeq(CmdSeq! cmdSeq)
- {
+ public virtual CmdSeq VisitCmdSeq(CmdSeq cmdSeq) {
+ Contract.Requires(cmdSeq != null);
+ Contract.Ensures(Contract.Result<CmdSeq>() != null);
for (int i = 0, n = cmdSeq.Length; i < n; i++)
- cmdSeq[i] = (Cmd) this.Visit( (!)cmdSeq[i]); // call general Visit so subtypes of Cmd get visited by their particular visitor
+ cmdSeq[i] = (Cmd)this.Visit(cce.NonNull(cmdSeq[i])); // call general Visit so subtypes of Cmd get visited by their particular visitor
return cmdSeq;
}
- public virtual Choice! VisitChoice(Choice! node)
- {
+ public virtual Choice VisitChoice(Choice node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Choice>() != null);
node.rs = this.VisitRESeq(node.rs);
return node;
}
- public virtual Cmd! VisitCommentCmd(CommentCmd! node)
- {
+ public virtual Cmd VisitCommentCmd(CommentCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
return node;
}
- public virtual Constant! VisitConstant(Constant! node)
- {
+ public virtual Constant VisitConstant(Constant node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Constant>() != null);
return node;
}
- public virtual CtorType! VisitCtorType(CtorType! node)
- {
+ public virtual CtorType VisitCtorType(CtorType node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<CtorType>() != null);
for (int i = 0; i < node.Arguments.Length; ++i)
- node.Arguments[i] = (Type!)this.Visit(node.Arguments[i]);
+ node.Arguments[i] = cce.NonNull((Type/*!*/)this.Visit(node.Arguments[i]));
return node;
}
- public virtual Declaration! VisitDeclaration(Declaration! node)
- {
+ public virtual Declaration VisitDeclaration(Declaration node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Declaration>() != null);
return node;
}
- public virtual List<Declaration!>! VisitDeclarationList(List<Declaration!>! declarationList)
- {
+ public virtual List<Declaration/*!*/>/*!*/ VisitDeclarationList(List<Declaration/*!*/>/*!*/ declarationList) {
+ Contract.Requires(cce.NonNullElements(declarationList));
+ Contract.Ensures(cce.NonNullElements(Contract.Result<List<Declaration>>()));
for (int i = 0, n = declarationList.Count; i < n; i++)
- declarationList[i] = (Declaration!) this.Visit(declarationList[i]);
+ declarationList[i] = cce.NonNull((Declaration/*!*/)this.Visit(declarationList[i]));
return declarationList;
}
- public virtual DeclWithFormals! VisitDeclWithFormals(DeclWithFormals! node)
- {
+ public virtual DeclWithFormals VisitDeclWithFormals(DeclWithFormals node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<DeclWithFormals>() != null);
node.InParams = this.VisitVariableSeq(node.InParams);
node.OutParams = this.VisitVariableSeq(node.OutParams);
return node;
}
- public virtual ExistsExpr! VisitExistsExpr(ExistsExpr! node)
- {
- node = (ExistsExpr) this.VisitQuantifierExpr(node);
+ public virtual ExistsExpr VisitExistsExpr(ExistsExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<ExistsExpr>() != null);
+ node = (ExistsExpr)this.VisitQuantifierExpr(node);
return node;
}
- public virtual BvExtractExpr! VisitBvExtractExpr(BvExtractExpr! node)
- {
+ public virtual BvExtractExpr VisitBvExtractExpr(BvExtractExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<BvExtractExpr>() != null);
node.Bitvector = this.VisitExpr(node.Bitvector);
return node;
}
- public virtual Expr! VisitExpr(Expr! node)
- {
- Expr e = (Expr) this.Visit(node);
+ public virtual Expr VisitExpr(Expr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ Expr e = (Expr)this.Visit(node);
return e;
}
- public override ExprSeq! VisitExprSeq(ExprSeq! exprSeq)
- {
+ public override ExprSeq VisitExprSeq(ExprSeq exprSeq) {
+ //Contract.Requires(exprSeq != null);
+ Contract.Ensures(Contract.Result<ExprSeq>() != null);
for (int i = 0, n = exprSeq.Length; i < n; i++)
- exprSeq[i] = this.VisitExpr( (!)exprSeq[i]);
+ exprSeq[i] = this.VisitExpr(cce.NonNull(exprSeq[i]));
return exprSeq;
}
- public virtual Requires! VisitRequires(Requires! @requires)
- {
+ public virtual Requires VisitRequires(Requires @requires) {
+ Contract.Requires(@requires != null);
+ Contract.Ensures(Contract.Result<Requires>() != null);
@requires.Condition = this.VisitExpr(@requires.Condition);
return @requires;
}
- public virtual RequiresSeq! VisitRequiresSeq(RequiresSeq! requiresSeq)
- {
+ public virtual RequiresSeq VisitRequiresSeq(RequiresSeq requiresSeq) {
+ Contract.Requires(requiresSeq != null);
+ Contract.Ensures(Contract.Result<RequiresSeq>() != null);
for (int i = 0, n = requiresSeq.Length; i < n; i++)
requiresSeq[i] = this.VisitRequires(requiresSeq[i]);
return requiresSeq;
}
- public virtual Ensures! VisitEnsures(Ensures! @ensures)
- {
+ public virtual Ensures VisitEnsures(Ensures @ensures) {
+ Contract.Requires(@ensures != null);
+ Contract.Ensures(Contract.Result<Ensures>() != null);
@ensures.Condition = this.VisitExpr(@ensures.Condition);
return @ensures;
}
- public virtual EnsuresSeq! VisitEnsuresSeq(EnsuresSeq! ensuresSeq)
- {
+ public virtual EnsuresSeq VisitEnsuresSeq(EnsuresSeq ensuresSeq) {
+ Contract.Requires(ensuresSeq != null);
+ Contract.Ensures(Contract.Result<EnsuresSeq>() != null);
for (int i = 0, n = ensuresSeq.Length; i < n; i++)
ensuresSeq[i] = this.VisitEnsures(ensuresSeq[i]);
return ensuresSeq;
}
- public virtual ForallExpr! VisitForallExpr(ForallExpr! node)
- {
- node = (ForallExpr) this.VisitQuantifierExpr(node);
+ public virtual ForallExpr VisitForallExpr(ForallExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<ForallExpr>() != null);
+ node = (ForallExpr)this.VisitQuantifierExpr(node);
return node;
}
- public virtual LambdaExpr! VisitLambdaExpr(LambdaExpr! node)
- {
- node = (LambdaExpr) this.VisitBinderExpr(node);
+ public virtual LambdaExpr VisitLambdaExpr(LambdaExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<LambdaExpr>() != null);
+ node = (LambdaExpr)this.VisitBinderExpr(node);
return node;
}
- public virtual Formal! VisitFormal(Formal! node)
- {
+ public virtual Formal VisitFormal(Formal node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Formal>() != null);
return node;
}
- public virtual Function! VisitFunction(Function! node)
- {
- node = (Function) this.VisitDeclWithFormals(node);
+ public virtual Function VisitFunction(Function node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Function>() != null);
+ node = (Function)this.VisitDeclWithFormals(node);
if (node.Body != null)
node.Body = this.VisitExpr(node.Body);
return node;
}
- public virtual GlobalVariable! VisitGlobalVariable(GlobalVariable! node)
- {
- node = (GlobalVariable) this.VisitVariable(node);
+ public virtual GlobalVariable VisitGlobalVariable(GlobalVariable node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<GlobalVariable>() != null);
+ node = (GlobalVariable)this.VisitVariable(node);
return node;
}
- public virtual GotoCmd! VisitGotoCmd(GotoCmd! node)
- {
+ public virtual GotoCmd VisitGotoCmd(GotoCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<GotoCmd>() != null);
// do not visit the labelTargets, or control-flow loops will lead to a looping visitor
return node;
}
- public virtual Cmd! VisitHavocCmd(HavocCmd! node)
- {
+ public virtual Cmd VisitHavocCmd(HavocCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
node.Vars = this.VisitIdentifierExprSeq(node.Vars);
return node;
}
- public virtual Expr! VisitIdentifierExpr(IdentifierExpr! node)
- {
+ public virtual Expr VisitIdentifierExpr(IdentifierExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
if (node.Decl != null)
node.Decl = this.VisitVariable(node.Decl);
return node;
}
- public virtual IdentifierExprSeq! VisitIdentifierExprSeq(IdentifierExprSeq! identifierExprSeq)
- {
+ public virtual IdentifierExprSeq VisitIdentifierExprSeq(IdentifierExprSeq identifierExprSeq) {
+ Contract.Requires(identifierExprSeq != null);
+ Contract.Ensures(Contract.Result<IdentifierExprSeq>() != null);
for (int i = 0, n = identifierExprSeq.Length; i < n; i++)
- identifierExprSeq[i] = (IdentifierExpr) this.VisitIdentifierExpr( (!)identifierExprSeq[i]);
+ identifierExprSeq[i] = (IdentifierExpr)this.VisitIdentifierExpr(cce.NonNull(identifierExprSeq[i]));
return identifierExprSeq;
}
- public virtual Implementation! VisitImplementation(Implementation! node)
- {
+ public virtual Implementation VisitImplementation(Implementation node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Implementation>() != null);
node.LocVars = this.VisitVariableSeq(node.LocVars);
node.Blocks = this.VisitBlockList(node.Blocks);
- node.Proc = this.VisitProcedure((!)node.Proc);
- node = (Implementation) this.VisitDeclWithFormals(node); // do this first or last?
+ node.Proc = this.VisitProcedure(cce.NonNull(node.Proc));
+ node = (Implementation)this.VisitDeclWithFormals(node); // do this first or last?
return node;
}
- public virtual LiteralExpr! VisitLiteralExpr(LiteralExpr! node)
- {
+ public virtual LiteralExpr VisitLiteralExpr(LiteralExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<LiteralExpr>() != null);
return node;
}
- public virtual LocalVariable! VisitLocalVariable(LocalVariable! node)
- {
+ public virtual LocalVariable VisitLocalVariable(LocalVariable node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<LocalVariable>() != null);
return node;
}
- public virtual AssignLhs! VisitMapAssignLhs(MapAssignLhs! node)
- {
- node.Map = (AssignLhs!)this.Visit(node.Map);
+ public virtual AssignLhs VisitMapAssignLhs(MapAssignLhs node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<AssignLhs>() != null);
+ node.Map = cce.NonNull((AssignLhs)this.Visit(node.Map));
for (int i = 0; i < node.Indexes.Count; ++i)
- node.Indexes[i] = (Expr!)this.Visit(node.Indexes[i]);
+ node.Indexes[i] = cce.NonNull((Expr)this.Visit(node.Indexes[i]));
return node;
}
- public virtual MapType! VisitMapType(MapType! node)
- {
+ public virtual MapType VisitMapType(MapType node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<MapType>() != null);
// not doing anything about the bound variables ... maybe
// these should be visited as well ...
//
// NOTE: when overriding this method, you have to make sure that
// the bound variables of the map type are updated correctly
for (int i = 0; i < node.Arguments.Length; ++i)
- node.Arguments[i] = (Type!)this.Visit(node.Arguments[i]);
- node.Result = (Type!)this.Visit(node.Result);
+ node.Arguments[i] = cce.NonNull((Type/*!*/)this.Visit(node.Arguments[i]));
+ node.Result = cce.NonNull((Type/*!*/)this.Visit(node.Result));
return node;
}
- public virtual Type! VisitMapTypeProxy(MapTypeProxy! node)
- {
+ public virtual Type VisitMapTypeProxy(MapTypeProxy node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
// if the type proxy is instantiated with some more
// specific type, we visit the instantiation
if (node.ProxyFor != null)
@@ -342,18 +397,21 @@ namespace Microsoft.Boogie
return this.VisitType(node);
}
- public virtual Expr! VisitNAryExpr(NAryExpr! node)
- {
+ public virtual Expr VisitNAryExpr(NAryExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
node.Args = this.VisitExprSeq(node.Args);
return node;
}
- public virtual Expr! VisitOldExpr(OldExpr! node)
- {
+ public virtual Expr VisitOldExpr(OldExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
node.Expr = this.VisitExpr(node.Expr);
return node;
}
- public virtual Procedure! VisitProcedure(Procedure! node)
- {
+ public virtual Procedure VisitProcedure(Procedure node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Procedure>() != null);
node.Ensures = this.VisitEnsuresSeq(node.Ensures);
node.InParams = this.VisitVariableSeq(node.InParams);
node.Modifies = this.VisitIdentifierExprSeq(node.Modifies);
@@ -361,69 +419,81 @@ namespace Microsoft.Boogie
node.Requires = this.VisitRequiresSeq(node.Requires);
return node;
}
- public virtual Program! VisitProgram(Program! node)
- {
+ public virtual Program VisitProgram(Program node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Program>() != null);
node.TopLevelDeclarations = this.VisitDeclarationList(node.TopLevelDeclarations);
return node;
}
- public virtual BinderExpr! VisitBinderExpr(BinderExpr! node)
- {
+ public virtual BinderExpr VisitBinderExpr(BinderExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<BinderExpr>() != null);
node.Body = this.VisitExpr(node.Body);
node.Dummies = this.VisitVariableSeq(node.Dummies);
//node.Type = this.VisitType(node.Type);
return node;
}
- public virtual QuantifierExpr! VisitQuantifierExpr(QuantifierExpr! node)
- {
- node = (QuantifierExpr!) this.VisitBinderExpr(node);
+ public virtual QuantifierExpr VisitQuantifierExpr(QuantifierExpr node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<QuantifierExpr>() != null);
+ node = cce.NonNull((QuantifierExpr)this.VisitBinderExpr(node));
if (node.Triggers != null) {
node.Triggers = this.VisitTrigger(node.Triggers);
}
return node;
}
- public virtual Cmd! VisitRE(RE! node)
- {
- return (Cmd) this.Visit(node); // Call general visit so subtypes get visited by their particular visitor
+ public virtual Cmd VisitRE(RE node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
+ return (Cmd)this.Visit(node); // Call general visit so subtypes get visited by their particular visitor
}
- public virtual RESeq! VisitRESeq(RESeq! reSeq)
- {
+ public virtual RESeq VisitRESeq(RESeq reSeq) {
+ Contract.Requires(reSeq != null);
+ Contract.Ensures(Contract.Result<RESeq>() != null);
for (int i = 0, n = reSeq.Length; i < n; i++)
- reSeq[i] = (RE) this.VisitRE( (!)reSeq[i]);
+ reSeq[i] = (RE)this.VisitRE(cce.NonNull(reSeq[i]));
return reSeq;
}
- public virtual ReturnCmd! VisitReturnCmd(ReturnCmd! node)
- {
- return (ReturnCmd) this.VisitTransferCmd(node);
+ public virtual ReturnCmd VisitReturnCmd(ReturnCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<ReturnCmd>() != null);
+ return (ReturnCmd)this.VisitTransferCmd(node);
}
- public virtual ReturnExprCmd! VisitReturnExprCmd(ReturnExprCmd! node)
- {
+ public virtual ReturnExprCmd VisitReturnExprCmd(ReturnExprCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<ReturnExprCmd>() != null);
node.Expr = this.VisitExpr(node.Expr);
return node;
}
- public virtual Sequential! VisitSequential(Sequential! node)
- {
- node.first = (RE) this.VisitRE(node.first);
- node.second = (RE) this.VisitRE(node.second);
+ public virtual Sequential VisitSequential(Sequential node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Sequential>() != null);
+ node.first = (RE)this.VisitRE(node.first);
+ node.second = (RE)this.VisitRE(node.second);
return node;
}
- public virtual AssignLhs! VisitSimpleAssignLhs(SimpleAssignLhs! node)
- {
+ public virtual AssignLhs VisitSimpleAssignLhs(SimpleAssignLhs node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<AssignLhs>() != null);
node.AssignedVariable =
- (IdentifierExpr) this.VisitIdentifierExpr(node.AssignedVariable);
+ (IdentifierExpr)this.VisitIdentifierExpr(node.AssignedVariable);
return node;
}
- public virtual Cmd! VisitStateCmd(StateCmd! node)
- {
+ public virtual Cmd VisitStateCmd(StateCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
node.Locals = this.VisitVariableSeq(node.Locals);
node.Cmds = this.VisitCmdSeq(node.Cmds);
return node;
}
- public virtual TransferCmd! VisitTransferCmd(TransferCmd! node)
- {
+ public virtual TransferCmd VisitTransferCmd(TransferCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<TransferCmd>() != null);
return node;
}
- public virtual Trigger! VisitTrigger(Trigger! node)
- {
+ public virtual Trigger VisitTrigger(Trigger node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Trigger>() != null);
Trigger origNext = node.Next;
if (origNext != null) {
Trigger newNext = this.VisitTrigger(origNext);
@@ -436,65 +506,77 @@ namespace Microsoft.Boogie
return node;
}
// called by default for all nullary type constructors and type variables
- public virtual Type! VisitType(Type! node)
- {
+ public virtual Type VisitType(Type node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
return node;
}
- public virtual TypedIdent! VisitTypedIdent(TypedIdent! node)
- {
+ public virtual TypedIdent VisitTypedIdent(TypedIdent node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<TypedIdent>() != null);
node.Type = (Type)this.Visit(node.Type);
return node;
}
- public virtual Declaration! VisitTypeCtorDecl(TypeCtorDecl! node)
- {
+ public virtual Declaration VisitTypeCtorDecl(TypeCtorDecl node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Declaration>() != null);
return this.VisitDeclaration(node);
}
- public virtual Type! VisitTypeSynonymAnnotation(TypeSynonymAnnotation! node)
- {
- node.ExpandedType = (Type!)this.Visit(node.ExpandedType);
+ public virtual Type VisitTypeSynonymAnnotation(TypeSynonymAnnotation node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+ node.ExpandedType = cce.NonNull((Type/*!*/)this.Visit(node.ExpandedType));
for (int i = 0; i < node.Arguments.Length; ++i)
- node.Arguments[i] = (Type!)this.Visit(node.Arguments[i]);
+ node.Arguments[i] = cce.NonNull((Type/*!*/)this.Visit(node.Arguments[i]));
return node;
}
- public virtual Declaration! VisitTypeSynonymDecl(TypeSynonymDecl! node)
- {
+ public virtual Declaration VisitTypeSynonymDecl(TypeSynonymDecl node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Declaration>() != null);
return this.VisitDeclaration(node);
}
- public virtual Type! VisitTypeVariable(TypeVariable! node)
- {
+ public virtual Type VisitTypeVariable(TypeVariable node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
return this.VisitType(node);
}
- public virtual Type! VisitTypeProxy(TypeProxy! node)
- {
+ public virtual Type VisitTypeProxy(TypeProxy node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
// if the type proxy is instantiated with some more
// specific type, we visit the instantiation
if (node.ProxyFor != null)
- return (Type!)this.Visit(node.ProxyFor);
+ return cce.NonNull((Type/*!*/)this.Visit(node.ProxyFor));
return this.VisitType(node);
}
- public virtual Type! VisitUnresolvedTypeIdentifier(UnresolvedTypeIdentifier! node)
- {
+ public virtual Type VisitUnresolvedTypeIdentifier(UnresolvedTypeIdentifier node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
return this.VisitType(node);
}
- public virtual Variable! VisitVariable(Variable! node)
- {
+ public virtual Variable VisitVariable(Variable node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Variable>() != null);
node.TypedIdent = this.VisitTypedIdent(node.TypedIdent);
return node;
}
- public virtual VariableSeq! VisitVariableSeq(VariableSeq! variableSeq)
- {
+ public virtual VariableSeq VisitVariableSeq(VariableSeq variableSeq) {
+ Contract.Requires(variableSeq != null);
+ Contract.Ensures(Contract.Result<VariableSeq>() != null);
for (int i = 0, n = variableSeq.Length; i < n; i++)
- variableSeq[i] = this.VisitVariable( (!)variableSeq[i]);
+ variableSeq[i] = this.VisitVariable(cce.NonNull(variableSeq[i]));
return variableSeq;
- }
- public virtual Cmd! VisitAssertEnsuresCmd(AssertEnsuresCmd! node)
- {
+ }
+ public virtual Cmd VisitAssertEnsuresCmd(AssertEnsuresCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
node.Ensures = this.VisitEnsures(node.Ensures);
node.Expr = this.VisitExpr(node.Expr);
return node;
- }
- public virtual Cmd! VisitAssertRequiresCmd(AssertRequiresCmd! node)
- {
+ }
+ public virtual Cmd VisitAssertRequiresCmd(AssertRequiresCmd node) {
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Cmd>() != null);
node.Requires = this.VisitRequires(node.Requires);
node.Expr = this.VisitExpr(node.Expr);
return node;
diff --git a/Source/Core/TypeAmbiguitySeeker.cs b/Source/Core/TypeAmbiguitySeeker.cs
index fc7cf071..d878791b 100644
--- a/Source/Core/TypeAmbiguitySeeker.cs
+++ b/Source/Core/TypeAmbiguitySeeker.cs
@@ -4,27 +4,39 @@
//
//-----------------------------------------------------------------------------
using System;
+using System.Diagnostics.Contracts;
// Visitor to search for types proxies that could not completely be
// determined by type inference. If this happens, a warning is
// generated and the proxies are instantiated in a more or less arbitrary
// fashion.
-namespace Microsoft.Boogie
-{
+namespace Microsoft.Boogie {
public class TypeAmbiguitySeeker : StandardVisitor {
- private readonly InTypeSeeker! inTypeSeeker = new InTypeSeeker ();
- private readonly TypecheckingContext! TC;
+ private readonly InTypeSeeker/*!*/ inTypeSeeker = new InTypeSeeker();
+ private readonly TypecheckingContext/*!*/ TC;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(inTypeSeeker != null);
+ Contract.Invariant(TC != null);
+ }
+
- public TypeAmbiguitySeeker(TypecheckingContext! tc) {
+ public TypeAmbiguitySeeker(TypecheckingContext tc) {
+ Contract.Requires(tc != null);
TC = tc;
}
- private void CheckTypeParams(Absy! node, TypeParamInstantiation! insts) {
- foreach (TypeVariable! var in insts.FormalTypeParams) {
- Type! inst = insts[var];
+ private void CheckTypeParams(Absy node, TypeParamInstantiation insts) {
+ Contract.Requires(insts != null);
+ Contract.Requires(node != null);
+ foreach (TypeVariable/*!*/ var in insts.FormalTypeParams) {
+ Contract.Assert(var != null);
+ Type/*!*/ inst = insts[var];
+ Contract.Assert(inst != null);
+
inTypeSeeker.FoundAmbiguity = false;
inTypeSeeker.Visit(inst);
if (inTypeSeeker.FoundAmbiguity)
@@ -34,61 +46,76 @@ namespace Microsoft.Boogie
}
}
- public override Expr! VisitNAryExpr(NAryExpr! node)
- {
- CheckTypeParams(node, (!)node.TypeParameters);
+ public override Expr VisitNAryExpr(NAryExpr node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Expr>() != null);
+ CheckTypeParams(node, cce.NonNull(node.TypeParameters));
return base.VisitNAryExpr(node);
}
- public override AssignLhs! VisitMapAssignLhs(MapAssignLhs! node) {
- CheckTypeParams(node, (!)node.TypeParameters);
- return base.VisitMapAssignLhs(node);
+ public override AssignLhs VisitMapAssignLhs(MapAssignLhs node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<AssignLhs>() != null);
+ CheckTypeParams(node, cce.NonNull(node.TypeParameters));
+ return base.VisitMapAssignLhs(node);
}
}
internal class InTypeSeeker : StandardVisitor {
-
+
internal bool FoundAmbiguity = false;
// called when an uninstantiated proxy was found
- private Type! Instantiate(Type! node, Type! inst) {
- FoundAmbiguity = true;
- bool success = node.Unify(inst);
- assert success;
- return node;
+ private Type Instantiate(Type node, Type inst) {
+ Contract.Requires(inst != null);
+ Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
+ FoundAmbiguity = true;
+ bool success = node.Unify(inst);
+ Contract.Assert(success);
+ return node;
}
- public override Type! VisitTypeProxy(TypeProxy! node) {
+ public override Type VisitTypeProxy(TypeProxy node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
if (node.ProxyFor != null)
return base.VisitTypeProxy(node);
- return Instantiate(node, Type.Int);
+ return Instantiate(node, Type.Int);
}
- public override Type! VisitMapTypeProxy(MapTypeProxy! node) {
+ public override Type VisitMapTypeProxy(MapTypeProxy node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
if (node.ProxyFor != null)
return base.VisitMapTypeProxy(node);
- TypeVariableSeq! typeParams = new TypeVariableSeq ();
- TypeSeq! arguments = new TypeSeq ();
- for (int i = 0; i < node.Arity; ++i) {
- TypeVariable! param = new TypeVariable (Token.NoToken, "arg" + i);
- typeParams.Add(param);
- arguments.Add(param);
- }
- TypeVariable! result = new TypeVariable (Token.NoToken, "res");
- typeParams.Add(result);
+ TypeVariableSeq/*!*/ typeParams = new TypeVariableSeq();
+ TypeSeq/*!*/ arguments = new TypeSeq();
+ for (int i = 0; i < node.Arity; ++i) {
+ TypeVariable/*!*/ param = new TypeVariable(Token.NoToken, "arg" + i);
+ Contract.Assert(param != null);
+ typeParams.Add(param);
+ arguments.Add(param);
+ }
+ TypeVariable/*!*/ result = new TypeVariable(Token.NoToken, "res");
+ Contract.Assert(result != null);
+ typeParams.Add(result);
- Type! instantiation = new MapType (Token.NoToken, typeParams, arguments, result);
+ Type/*!*/ instantiation = new MapType(Token.NoToken, typeParams, arguments, result);
+ Contract.Assert(instantiation != null);
- return Instantiate(node, instantiation);
+ return Instantiate(node, instantiation);
}
- public override Type! VisitBvTypeProxy(BvTypeProxy! node) {
+ public override Type VisitBvTypeProxy(BvTypeProxy node) {
+ //Contract.Requires(node != null);
+ Contract.Ensures(Contract.Result<Type>() != null);
if (node.ProxyFor != null)
return base.VisitBvTypeProxy(node);
- return Instantiate(node, new BvType (node.MinBits));
+ return Instantiate(node, new BvType(node.MinBits));
}
}
diff --git a/Source/Core/Util.cs b/Source/Core/Util.cs
index 87323eb5..f6c94ee2 100644
--- a/Source/Core/Util.cs
+++ b/Source/Core/Util.cs
@@ -3,31 +3,35 @@
// Copyright (C) Microsoft Corporation. All Rights Reserved.
//
//-----------------------------------------------------------------------------
-namespace Microsoft.Boogie
-{
- using System;
- using System.IO;
- using System.Collections;
- using Microsoft.Contracts;
-
- public class TokenTextWriter : IDisposable
- {
- string! filename;
- TextWriter! writer;
- bool writerOpenedHere = false;
- bool setTokens = true;
- int line = 1;
- int col;
-
- private const int indent_size = 2;
- protected static string! Indent (int level)
- {
- return new string(' ', (indent_size * level));
- }
+namespace Microsoft.Boogie {
+ using System;
+ using System.IO;
+ using System.Collections;
+ using System.Diagnostics.Contracts;
+
+ public class TokenTextWriter : IDisposable {
+ string/*!*/ filename;
+ TextWriter/*!*/ writer;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(filename != null);
+ Contract.Invariant(writer != null);
+ }
+
+ bool writerOpenedHere = false;
+ bool setTokens = true;
+ int line = 1;
+ int col;
+ private const int indent_size = 2;
+ protected static string Indent(int level) {
+ Contract.Ensures(Contract.Result<string>() != null);
+ return new string(' ', (indent_size * level));
+ }
- // Keywords, this array *must* be sorted
- public static readonly string[]! BplKeywords =
+
+ // Keywords, this array *must* be sorted
+ public static readonly string[]/*!*/ BplKeywords =
{
"assert",
"assume",
@@ -64,418 +68,436 @@ namespace Microsoft.Boogie
"where",
"while",
};
-
- private IToken! CurrentToken
- {
- get
- {
- Token token = new Token();
- token.filename = filename;
- token.line = line;
- token.col = col;
- return token;
- }
- }
- public void SetToken(Absy! absy)
- {
- this.SetToken(ref absy.tok);
- }
+ private IToken/*!*/ CurrentToken {
+ get {
+ Contract.Ensures(Contract.Result<IToken>() != null);
- public void SetToken(ref IToken! tok)
- {
- if (this.setTokens) {
- tok = this.CurrentToken;
- }
- }
-
- public static string! SanitizeIdentifier (string! name)
- {
- int index = Array.BinarySearch(TokenTextWriter.BplKeywords, name);
- if (index >= 0) {
- return "\\" + name;
- } else if (name.Length > 2 && name[0] == 'b' && name[1] == 'v') {
- int dummy;
- return int.TryParse(name.Substring(2), out dummy) ? "\\" + name : name;
- } else {
- return name;
- }
- }
-
- public TokenTextWriter(string! filename)
- {
- this.filename = filename;
- this.writer = new StreamWriter(filename);
- this.writerOpenedHere = true;
- base();
- }
-
- public TokenTextWriter(string! filename, TextWriter! writer, bool setTokens)
- {
- this.filename = filename;
- this.writer = writer;
- this.setTokens = setTokens;
- base();
- }
-
- public TokenTextWriter(string! filename, TextWriter! writer)
- {
- this.filename = filename;
- this.writer = writer;
- base();
- }
-
- public TokenTextWriter(TextWriter! writer)
- {
- this.filename = "<no file>";
- this.writer = writer;
- base();
- }
-
- public void Write(string! text)
- {
- this.writer.Write(text);
- this.col += text.Length;
- }
-
- public void WriteIndent(int level)
- {
- this.Write(Indent(level));
- }
-
- public void Write(string! text, params object[] args)
- {
- this.Write(string.Format(text, args));
- }
-
- public void Write(int level, string! text)
- {
- this.WriteIndent(level);
- this.Write(text);
- }
-
- public void Write(int level, string! text, params object[] args)
- {
- this.WriteIndent(level);
- this.Write(text, args);
- }
-
- public void Write(Absy! node, string! text)
- {
- this.SetToken(node);
- this.Write(text);
- }
-
- public void Write(Absy! node, string! text, params string[] args)
- {
- this.SetToken(node);
- this.Write(text, args);
- }
-
- public void Write(Absy! node, int level, string! text)
- {
- this.WriteIndent(level);
- this.SetToken(node);
- this.Write(text);
- }
-
- public void Write(Absy! node, int level, string! text, params object[] args)
- {
- this.WriteIndent(level);
- this.SetToken(node);
- this.Write(text, args);
- }
-
- public void WriteLine()
- {
- this.writer.WriteLine();
- this.line++;
- this.col = 0;
- }
-
- public void WriteLine(string! text)
- {
- this.writer.WriteLine(text);
- this.line++;
- this.col = 0;
- }
-
- public void WriteText(string! text) {
- int processed = 0;
- while (true) {
- int n = text.IndexOf('\n', processed);
- if (n == -1) {
- this.writer.Write(text);
- this.col += text.Length - processed;
- return;
- }
- processed = n + 1;
- this.line++;
- this.col = 0;
- }
- }
-
- public void WriteLine(string! text, params object[] args)
- {
- this.WriteLine(string.Format(text, args));
- }
-
- public void WriteLine(int level, string! text)
- {
- this.WriteIndent(level);
- this.WriteLine(text);
- }
-
- public void WriteLine(int level, string! text, params object[] args)
- {
- this.WriteIndent(level);
- this.WriteLine(text, args);
- }
-
- public void WriteLine(Absy! node, string! text)
- {
- this.SetToken(node);
- this.WriteLine(text);
- }
-
- public void WriteLine(Absy! node, int level, string! text)
- {
- this.SetToken(node);
- this.WriteLine(level, text);
- }
-
- public void WriteLine(Absy! node, int level, string! text, params object[] args)
- {
- this.SetToken(node);
- this.WriteLine(level, text, args);
- }
-
- public void Close()
- {
- this.writer.Close();
- }
-
- public void Dispose()
- {
- this.Close();
- }
+ Token token = new Token();
+ token.filename = filename;
+ token.line = line;
+ token.col = col;
+ return token;
+ }
}
-
- public class Helpers {
- public static string! BeautifyBplString (string! s) {
- // strip "^" if it is the first character, change "$result" to "result"
- if (s.StartsWith("^") || s == "$result") {
- s = s.Substring(1);
- } else if (s.StartsWith("call")) {
- s = s.Substring(s.IndexOf('@') + 1);
- if (s.StartsWith("formal@")) {
- s = "(value of formal parameter: " + s.Substring(7) +")";
- }
- }
- // strip "$in" from the end of identifier names
- if (s.EndsWith("$in")) {
- return "(initial value of: " + s.Substring(0, s.Length-3) +")";
- } else {
- return s;
- }
+
+ public void SetToken(Absy absy) {
+ Contract.Requires(absy != null);
+ this.SetToken(ref absy.tok);
+ }
+
+ public void SetToken(ref IToken tok) {
+ Contract.Requires(tok != null);
+ if (this.setTokens) {
+ tok = this.CurrentToken;
+ }
+ }
+
+ public static string SanitizeIdentifier(string name) {
+ Contract.Requires(name != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+ int index = Array.BinarySearch(TokenTextWriter.BplKeywords, name);
+ if (index >= 0) {
+ return "\\" + name;
+ } else if (name.Length > 2 && name[0] == 'b' && name[1] == 'v') {
+ int dummy;
+ return int.TryParse(name.Substring(2), out dummy) ? "\\" + name : name;
+ } else {
+ return name;
+ }
+ }
+
+ public TokenTextWriter(string filename) :base(){//BASEMOVE DANGER
+ Contract.Requires(filename != null);
+ this.filename = filename;
+ this.writer = new StreamWriter(filename);
+ this.writerOpenedHere = true;
+ //base();
+ }
+
+ public TokenTextWriter(string filename, TextWriter writer, bool setTokens)
+ : base() {//BASEMOVE DANGER
+ Contract.Requires(writer != null);
+ Contract.Requires(filename != null);
+ this.filename = filename;
+ this.writer = writer;
+ this.setTokens = setTokens;
+ //base();
+ }
+
+ public TokenTextWriter(string filename, TextWriter writer)
+ : base() {//BASEMOVE DANGER
+ Contract.Requires(writer != null);
+ Contract.Requires(filename != null);
+ this.filename = filename;
+ this.writer = writer;
+ //base();
+ }
+
+ public TokenTextWriter(TextWriter writer)
+ : base() {//BASEMOVE DANGER
+ Contract.Requires(writer != null);
+ this.filename = "<no file>";
+ this.writer = writer;
+ //base();
+ }
+
+ public void Write(string text) {
+ Contract.Requires(text != null);
+ this.writer.Write(text);
+ this.col += text.Length;
+ }
+
+ public void WriteIndent(int level) {
+ this.Write(Indent(level));
+ }
+
+ public void Write(string text, params object[] args) {
+ Contract.Requires(text != null);
+ this.Write(string.Format(text, args));
+ }
+
+ public void Write(int level, string text) {
+ Contract.Requires(text != null);
+ this.WriteIndent(level);
+ this.Write(text);
+ }
+
+ public void Write(int level, string text, params object[] args) {
+ Contract.Requires(text != null);
+ this.WriteIndent(level);
+ this.Write(text, args);
+ }
+
+ public void Write(Absy node, string text) {
+ Contract.Requires(text != null);
+ Contract.Requires(node != null);
+ this.SetToken(node);
+ this.Write(text);
+ }
+
+ public void Write(Absy node, string text, params string[] args) {
+ Contract.Requires(text != null);
+ Contract.Requires(node != null);
+ this.SetToken(node);
+ this.Write(text, args);
+ }
+
+ public void Write(Absy node, int level, string text) {
+ Contract.Requires(text != null);
+ Contract.Requires(node != null);
+ this.WriteIndent(level);
+ this.SetToken(node);
+ this.Write(text);
+ }
+
+ public void Write(Absy node, int level, string text, params object[] args) {
+ Contract.Requires(text != null);
+ Contract.Requires(node != null);
+ this.WriteIndent(level);
+ this.SetToken(node);
+ this.Write(text, args);
+ }
+
+ public void WriteLine() {
+ this.writer.WriteLine();
+ this.line++;
+ this.col = 0;
+ }
+
+ public void WriteLine(string text) {
+ Contract.Requires(text != null);
+ this.writer.WriteLine(text);
+ this.line++;
+ this.col = 0;
+ }
+
+ public void WriteText(string text) {
+ Contract.Requires(text != null);
+ int processed = 0;
+ while (true) {
+ int n = text.IndexOf('\n', processed);
+ if (n == -1) {
+ this.writer.Write(text);
+ this.col += text.Length - processed;
+ return;
+ }
+ processed = n + 1;
+ this.line++;
+ this.col = 0;
}
- public static string! PrettyPrintBplExpr (Expr! e) {
- // anything that is unknown will just be printed via ToString
- // OldExpr and QuantifierExpr, BvExtractExpr, BvConcatExpr are ignored for now
- // LiteralExpr is printed as itself by ToString
- if (e is IdentifierExpr) {
- string s = e.ToString();
- return Helpers.BeautifyBplString(s);
+ }
+
+ public void WriteLine(string text, params object[] args) {
+ Contract.Requires(text != null);
+ this.WriteLine(string.Format(text, args));
+ }
+
+ public void WriteLine(int level, string text) {
+ Contract.Requires(text != null);
+ this.WriteIndent(level);
+ this.WriteLine(text);
+ }
+
+ public void WriteLine(int level, string text, params object[] args) {
+ Contract.Requires(text != null);
+ this.WriteIndent(level);
+ this.WriteLine(text, args);
+ }
+
+ public void WriteLine(Absy node, string text) {
+ Contract.Requires(text != null);
+ Contract.Requires(node != null);
+ this.SetToken(node);
+ this.WriteLine(text);
+ }
+
+ public void WriteLine(Absy node, int level, string text) {
+ Contract.Requires(text != null);
+ Contract.Requires(node != null);
+ this.SetToken(node);
+ this.WriteLine(level, text);
+ }
+
+ public void WriteLine(Absy node, int level, string text, params object[] args) {
+ Contract.Requires(text != null);
+ Contract.Requires(node != null);
+ this.SetToken(node);
+ this.WriteLine(level, text, args);
+ }
+
+ public void Close() {
+ this.writer.Close();
+ }
+
+ public void Dispose() {
+ this.Close();
+ }
+ }
+
+ public class Helpers {
+ public static string BeautifyBplString(string s) {
+ Contract.Requires(s != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+ // strip "^" if it is the first character, change "$result" to "result"
+ if (s.StartsWith("^") || s == "$result") {
+ s = s.Substring(1);
+ } else if (s.StartsWith("call")) {
+ s = s.Substring(s.IndexOf('@') + 1);
+ if (s.StartsWith("formal@")) {
+ s = "(value of formal parameter: " + s.Substring(7) + ")";
}
- else if (e is NAryExpr) {
- NAryExpr ne = (NAryExpr) e;
- IAppliable fun = ne.Fun;
- ExprSeq eSeq = ne.Args;
- if (fun != null) {
- if ((fun.FunctionName == "$Length" || fun.FunctionName == "$StringLength" ) && eSeq.Length == 1) {
- Expr e0 = eSeq[0];
- if (e0 != null) {
- string s0 = PrettyPrintBplExpr(e0);
- return s0 + ".Length";
- }
- //unexpected, just fall outside to the default
- } else if (fun.FunctionName == "$typeof" && eSeq.Length == 1) {
- Expr e0 = eSeq[0];
- if (e0 != null) {
- string s0 = PrettyPrintBplExpr(e0);
- return "(the dynamic type of: " + s0 + ")";
- }
- //unexpected, just fall outside to the default
- } else if (fun.FunctionName == "IntArrayGet" && eSeq.Length == 2) {
- Expr e0 = eSeq[0];
- Expr e1 = eSeq[1];
- if (e0 != null && e1 != null) {
- string s0 = PrettyPrintBplExpr(e0);
- string s1 = PrettyPrintBplExpr(e1);
- return s0 + "[" + s1 + "]";
- }
- //unexpected, just fall outside to the default
- } else if (fun.FunctionName == "$Is" && eSeq.Length == 2) {
- Expr e0 = eSeq[0];
- Expr e1 = eSeq[1];
- if (e0 != null && e1 != null) {
- string s0 = PrettyPrintBplExpr(e0);
- string s1 = PrettyPrintBplExpr(e1);
- return "(" + s0 + " == null || (" + s0 + " is " + s1 + "))";
+ }
+ // strip "$in" from the end of identifier names
+ if (s.EndsWith("$in")) {
+ return "(initial value of: " + s.Substring(0, s.Length - 3) + ")";
+ } else {
+ return s;
+ }
+ }
+ public static string PrettyPrintBplExpr(Expr e) {
+ Contract.Requires(e != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+ // anything that is unknown will just be printed via ToString
+ // OldExpr and QuantifierExpr, BvExtractExpr, BvConcatExpr are ignored for now
+ // LiteralExpr is printed as itself by ToString
+ if (e is IdentifierExpr) {
+ string s = e.ToString();
+ return Helpers.BeautifyBplString(s);
+ } else if (e is NAryExpr) {
+ NAryExpr ne = (NAryExpr)e;
+ IAppliable fun = ne.Fun;
+ ExprSeq eSeq = ne.Args;
+ if (fun != null) {
+ if ((fun.FunctionName == "$Length" || fun.FunctionName == "$StringLength") && eSeq.Length == 1) {
+ Expr e0 = eSeq[0];
+ if (e0 != null) {
+ string s0 = PrettyPrintBplExpr(e0);
+ return s0 + ".Length";
+ }
+ //unexpected, just fall outside to the default
+ } else if (fun.FunctionName == "$typeof" && eSeq.Length == 1) {
+ Expr e0 = eSeq[0];
+ if (e0 != null) {
+ string s0 = PrettyPrintBplExpr(e0);
+ return "(the dynamic type of: " + s0 + ")";
+ }
+ //unexpected, just fall outside to the default
+ } else if (fun.FunctionName == "IntArrayGet" && eSeq.Length == 2) {
+ Expr e0 = eSeq[0];
+ Expr e1 = eSeq[1];
+ if (e0 != null && e1 != null) {
+ string s0 = PrettyPrintBplExpr(e0);
+ string s1 = PrettyPrintBplExpr(e1);
+ return s0 + "[" + s1 + "]";
+ }
+ //unexpected, just fall outside to the default
+ } else if (fun.FunctionName == "$Is" && eSeq.Length == 2) {
+ Expr e0 = eSeq[0];
+ Expr e1 = eSeq[1];
+ if (e0 != null && e1 != null) {
+ string s0 = PrettyPrintBplExpr(e0);
+ string s1 = PrettyPrintBplExpr(e1);
+ return "(" + s0 + " == null || (" + s0 + " is " + s1 + "))";
+ }
+ //unexpected, just fall outside to the default
+ } else if (fun.FunctionName == "$IsNotNull" && eSeq.Length == 2) {
+ Expr e0 = eSeq[0];
+ Expr e1 = eSeq[1];
+ if (e0 != null && e1 != null) {
+ string s0 = PrettyPrintBplExpr(e0);
+ string s1 = PrettyPrintBplExpr(e1);
+ return "(" + s0 + " is " + s1 + ")";
+ }
+ //unexpected, just fall outside to the default
+ } else if (fun is MapSelect && eSeq.Length <= 3) {
+ // only maps with up to two arguments are supported right now (here)
+ if (cce.NonNull(eSeq[0]).ToString() == "$Heap") {
+ //print Index0.Index1, unless Index1 is "$elements", then just print Index0
+ string s0 = PrettyPrintBplExpr(cce.NonNull(eSeq[1]));
+ if (eSeq.Length > 2) {
+ string s1 = PrettyPrintBplExpr(cce.NonNull(eSeq[2]));
+ if (s1 == "$elements") {
+ return s0;
+ } else {
+ if (eSeq[2] is IdentifierExpr) {
+ // strip the class name out of a fieldname
+ s1 = s1.Substring(s1.LastIndexOf('.') + 1);
+ }
+ return s0 + "." + s1;
+ }
}
- //unexpected, just fall outside to the default
- } else if (fun.FunctionName == "$IsNotNull" && eSeq.Length == 2) {
- Expr e0 = eSeq[0];
- Expr e1 = eSeq[1];
- if (e0 != null && e1 != null) {
- string s0 = PrettyPrintBplExpr(e0);
- string s1 = PrettyPrintBplExpr(e1);
- return "(" + s0 + " is " + s1 +")";
+ }
+ //unexpected, just fall outside to the default
+ } else if (fun is Microsoft.Boogie.BinaryOperator && eSeq.Length == 2) {
+ Microsoft.Boogie.BinaryOperator f = (Microsoft.Boogie.BinaryOperator)fun;
+ Expr e0 = eSeq[0];
+ Expr e1 = eSeq[1];
+ if (e0 != null && e1 != null) {
+ string s0 = PrettyPrintBplExpr(e0);
+ string s1 = PrettyPrintBplExpr(e1);
+ string op = "";
+ switch (f.Op) {
+ case Microsoft.Boogie.BinaryOperator.Opcode.Add:
+ op = " + ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.And:
+ op = " && ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Div:
+ op = " / ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Eq:
+ op = " == ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Ge:
+ op = " >= ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Gt:
+ op = " > ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Iff:
+ op = " <==> ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Imp:
+ op = " ==> ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Le:
+ op = " <= ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Lt:
+ op = " < ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Mod:
+ op = " % ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Mul:
+ op = " * ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Neq:
+ op = " != ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Or:
+ op = " || ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Sub:
+ op = " - ";
+ break;
+ case Microsoft.Boogie.BinaryOperator.Opcode.Subtype:
+ op = " <: ";
+ break;
+ default:
+ op = " ";
+ break;
}
- //unexpected, just fall outside to the default
- } else if (fun is MapSelect && eSeq.Length <= 3) {
- // only maps with up to two arguments are supported right now (here)
- if (((!)eSeq[0]).ToString() == "$Heap") {
- //print Index0.Index1, unless Index1 is "$elements", then just print Index0
- string s0 = PrettyPrintBplExpr((!)eSeq[1]);
- if (eSeq.Length > 2) {
- string s1 = PrettyPrintBplExpr((!)eSeq[2]);
- if (s1 == "$elements") {
- return s0;
- } else {
- if (eSeq[2] is IdentifierExpr) {
- // strip the class name out of a fieldname
- s1 = s1.Substring(s1.LastIndexOf('.') + 1);
- }
- return s0 + "." + s1;
- }
- }
- }
- //unexpected, just fall outside to the default
- } else if (fun is Microsoft.Boogie.BinaryOperator && eSeq.Length == 2) {
- Microsoft.Boogie.BinaryOperator f = (Microsoft.Boogie.BinaryOperator) fun;
- Expr e0 = eSeq[0];
- Expr e1 = eSeq[1];
- if (e0 != null && e1 != null) {
- string s0 = PrettyPrintBplExpr(e0);
- string s1 = PrettyPrintBplExpr(e1);
- string op = "";
- switch (f.Op) {
- case Microsoft.Boogie.BinaryOperator.Opcode.Add:
- op = " + ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.And:
- op = " && ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Div:
- op = " / ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Eq:
- op = " == ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Ge:
- op = " >= ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Gt:
- op = " > ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Iff:
- op = " <==> ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Imp:
- op = " ==> ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Le:
- op = " <= ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Lt:
- op = " < ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Mod:
- op = " % ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Mul:
- op = " * ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Neq:
- op = " != ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Or:
- op = " || ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Sub:
- op = " - ";
- break;
- case Microsoft.Boogie.BinaryOperator.Opcode.Subtype:
- op = " <: ";
- break;
- default: op = " ";
- break;
- }
- return "(" + s0 + op + s1 + ")";
+ return "(" + s0 + op + s1 + ")";
+ }
+ //unexpected, just fall outside to the default
+ } else {
+ string s = fun.FunctionName + "(";
+ for (int i = 0; i < eSeq.Length; i++) {
+ Expr ex = eSeq[i];
+ Contract.Assume(ex != null);
+ if (i > 0) {
+ s += ", ";
}
- //unexpected, just fall outside to the default
- } else {
- string s = fun.FunctionName + "(";
- for (int i = 0; i < eSeq.Length; i++) {
- Expr ex = eSeq[i];
- assume ex != null;
- if (i>0) {
- s += ", ";
- }
- string t = PrettyPrintBplExpr(ex);
- if (t.StartsWith("(") && t.EndsWith(")")) {
- t = t.Substring(1, t.Length -2);
- }
- s += t;
+ string t = PrettyPrintBplExpr(ex);
+ if (t.StartsWith("(") && t.EndsWith(")")) {
+ t = t.Substring(1, t.Length - 2);
}
- s += ")";
- return s;
- //unexpected, just fall outside to the default
- }
+ s += t;
+ }
+ s += ")";
+ return s;
+ //unexpected, just fall outside to the default
}
- }
-
- return e.ToString();
- }
-
- private static readonly DateTime StartUp = DateTime.Now;
-
- public static void ExtraTraceInformation(string! point) {
- if (CommandLineOptions.Clo.TraceTimes) {
- DateTime now = DateTime.Now;
- TimeSpan timeSinceStartUp = now - StartUp;
- Console.WriteLine(">>> {0} [{1} s]", point, timeSinceStartUp.TotalSeconds);
}
}
- // Substitute @PROC@ in a filename with the given descName
- public static string! SubstituteAtPROC(string! descName, string! fileName) {
- System.Text.StringBuilder! sb =
- new System.Text.StringBuilder(descName.Length);
- // quote the name, characters like ^ cause trouble in CMD
- // while $ could cause trouble in SH
- foreach (char c in descName) {
- if (Char.IsLetterOrDigit(c) || c == '.') {
- sb.Append(c);
- } else {
- sb.Append('_');
- }
- }
- string pn = sb.ToString();
- // We attempt to avoid filenames that are too long, but we only
- // do it by truncating the @PROC@ replacement, which leaves unchanged
- // any filename extension specified by the user. We base our
- // calculations on that there is at most one occurrence of @PROC@.
- if (180 <= fileName.Length - 6 + pn.Length) {
- pn = pn.Substring(0, max{180 - (fileName.Length - 6), 0}) + "-n" + sequenceNumber;
- sequenceNumber++;
- }
+ return e.ToString();
+ }
+
+ private static readonly DateTime StartUp = DateTime.Now;
- return fileName.Replace("@PROC@", pn);
+ public static void ExtraTraceInformation(string point) {
+ Contract.Requires(point != null);
+ if (CommandLineOptions.Clo.TraceTimes) {
+ DateTime now = DateTime.Now;
+ TimeSpan timeSinceStartUp = now - StartUp;
+ Console.WriteLine(">>> {0} [{1} s]", point, timeSinceStartUp.TotalSeconds);
}
+ }
- private static int sequenceNumber = 0;
+ // Substitute @PROC@ in a filename with the given descName
+ public static string SubstituteAtPROC(string descName, string fileName) {
+ Contract.Requires(fileName != null);
+ Contract.Requires(descName != null);
+ Contract.Ensures(Contract.Result<string>() != null);
+ System.Text.StringBuilder/*!*/ sb =
+ new System.Text.StringBuilder(descName.Length);
+ // quote the name, characters like ^ cause trouble in CMD
+ // while $ could cause trouble in SH
+ foreach (char c in descName) {
+ if (Char.IsLetterOrDigit(c) || c == '.') {
+ sb.Append(c);
+ } else {
+ sb.Append('_');
+ }
+ }
+ string pn = sb.ToString();
+ // We attempt to avoid filenames that are too long, but we only
+ // do it by truncating the @PROC@ replacement, which leaves unchanged
+ // any filename extension specified by the user. We base our
+ // calculations on that there is at most one occurrence of @PROC@.
+ if (180 <= fileName.Length - 6 + pn.Length) {
+ pn = pn.Substring(0, Math.Max(180 - (fileName.Length - 6), 0)) + "-n" + sequenceNumber;
+ sequenceNumber++;
+ }
+ return fileName.Replace("@PROC@", pn);
}
+
+ private static int sequenceNumber = 0;
+
+ }
}
diff --git a/Source/Core/VCExp.cs b/Source/Core/VCExp.cs
index 650b3145..756f20b6 100644
--- a/Source/Core/VCExp.cs
+++ b/Source/Core/VCExp.cs
@@ -9,16 +9,17 @@ using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
using Microsoft.Basetypes;
-
-
namespace Microsoft.Boogie {
- public class ProverOptions
- {
+ public class ProverOptions {
public class OptionException : Exception {
- public OptionException(string! msg) { base(msg); }
+ public OptionException(string msg)
+ : base(msg) {//BASEMOVEA
+ Contract.Requires(msg != null);
+ //:base(msg);
+ }
}
public string/*?*/ LogFilename = null;
@@ -31,30 +32,37 @@ namespace Microsoft.Boogie {
public CommandLineOptions.BvHandling BitVectors = CommandLineOptions.BvHandling.None;
public int Verbosity = 0;
- private string! stringRepr = "";
+ private string/*!*/ stringRepr = "";
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(stringRepr != null);
+ }
+
[Pure]
- public override string! ToString()
- {
+ public override string ToString() {
+ Contract.Ensures(Contract.Result<string>() != null);
return stringRepr;
}
// The usual thing to override.
- protected virtual bool Parse(string! opt)
- {
+ protected virtual bool Parse(string opt) {
+ Contract.Requires(opt != null);
return ParseString(opt, "LOG_FILE", ref LogFilename) ||
ParseBool(opt, "APPEND_LOG_FILE", ref AppendLogFile) ||
ParseBool(opt, "FORCE_LOG_STATUS", ref ForceLogStatus) ||
ParseInt(opt, "MEMORY_LIMIT", ref MemoryLimit) ||
ParseInt(opt, "VERBOSITY", ref Verbosity) ||
ParseInt(opt, "TIME_LIMIT", ref TimeLimit);
- // || base.Parse(opt)
+ // || base.Parse(opt)
}
- public virtual void Parse(List<string!>! opts)
- {
- StringBuilder! sb = new StringBuilder(stringRepr);
- foreach (string! opt in opts) {
+ public virtual void Parse(List<string/*!*/>/*!*/ opts) {
+ Contract.Requires(cce.NonNullElements(opts));
+ StringBuilder sb = new StringBuilder(stringRepr);
+ Contract.Assert(sb != null);
+ foreach (string/*!*/ opt in opts) {
+ Contract.Assert(opt != null);
if (!Parse(opt)) {
ReportError("Unrecognised prover option: " + opt);
}
@@ -64,20 +72,20 @@ namespace Microsoft.Boogie {
PostParse();
}
- protected virtual void PostParse()
- {
+ protected virtual void PostParse() {
if (LogFilename != null && LogFilename.Contains("@PROC@")) {
SeparateLogFiles = true;
}
}
- protected void ReportError(string! msg)
- {
+ protected void ReportError(string msg) {
+ Contract.Requires(msg != null);
throw new OptionException(msg);
}
- protected virtual bool ParseString(string! opt, string! name, ref string field)
- {
+ protected virtual bool ParseString(string opt, string name, ref string field) {
+ Contract.Requires(name != null);
+ Contract.Requires(opt != null);
if (opt.Length >= name.Length && opt.StartsWith(name)) {
if (opt.Length == name.Length) {
field = "";
@@ -90,33 +98,35 @@ namespace Microsoft.Boogie {
return false;
}
- protected virtual bool ParseBool(string! opt, string! name, ref bool field)
- {
+ protected virtual bool ParseBool(string opt, string name, ref bool field) {
+ Contract.Requires(name != null);
+ Contract.Requires(opt != null);
string tmp = null;
if (ParseString(opt, name, ref tmp))
- switch (((!)tmp).ToLower()) {
- case "1":
- case "true":
- case "":
- field = true;
- return true;
- case "0":
- case "false":
- field = false;
- return true;
- default:
- ReportError("Invalid Boolean option \"" + opt + "\"");
- return false;
+ switch (cce.NonNull(tmp).ToLower()) {
+ case "1":
+ case "true":
+ case "":
+ field = true;
+ return true;
+ case "0":
+ case "false":
+ field = false;
+ return true;
+ default:
+ ReportError("Invalid Boolean option \"" + opt + "\"");
+ return false;
}
return false;
}
- protected virtual bool ParseInt(string! opt, string! name, ref int field)
- {
+ protected virtual bool ParseInt(string opt, string name, ref int field) {
+ Contract.Requires(name != null);
+ Contract.Requires(opt != null);
string tmp = null;
int t2;
if (ParseString(opt, name, ref tmp)) {
- if (int.TryParse((!)tmp, out t2)) {
+ if (int.TryParse(cce.NonNull(tmp), out t2)) {
field = t2;
return true;
} else {
@@ -127,10 +137,10 @@ namespace Microsoft.Boogie {
}
static int sequenceNumber = 0;
- public virtual TextWriter? OpenLog(string/*?*/ descName)
- {
+ public virtual TextWriter OpenLog(string/*?*/ descName) {
if (LogFilename != null) {
- string! filename = LogFilename;
+ string filename = LogFilename;
+ Contract.Assert(filename != null);
if (descName != null)
filename = Helpers.SubstituteAtPROC(descName, filename);
return new StreamWriter(filename, AppendLogFile);
@@ -140,52 +150,62 @@ namespace Microsoft.Boogie {
}
}
- public abstract class ProverFactory
- {
+ [ContractClass(typeof(ProverFactoryContracts))]
+ public abstract class ProverFactory {
// Really returns ProverInterface.
//public abstract object! SpawnProver(ProverOptions! options, object! ctxt);
public abstract object SpawnProver(ProverOptions options, object ctxt);
// Really returns ProverContext
- public abstract object! NewProverContext(ProverOptions! options);
+ public abstract object/*!*/ NewProverContext(ProverOptions/*!*/ options);
- public virtual ProverOptions! BlankProverOptions()
- {
+ public virtual ProverOptions BlankProverOptions() {
+ Contract.Ensures(Contract.Result<ProverOptions>() != null);
return new ProverOptions();
}
// return true if the prover supports DAG AST as opposed to LET AST
- public virtual bool SupportsDags
- {
- get { return false; }
+ public virtual bool SupportsDags {
+ get {
+ return false;
+ }
}
- public virtual CommandLineOptions.VCVariety DefaultVCVariety
- {
- get
- ensures result != CommandLineOptions.VCVariety.Unspecified;
- { return CommandLineOptions.VCVariety.Dag; }
+ public virtual CommandLineOptions.VCVariety DefaultVCVariety {
+ get {
+ Contract.Ensures(Contract.Result<CommandLineOptions.VCVariety>() != CommandLineOptions.VCVariety.Unspecified);
+ return CommandLineOptions.VCVariety.Dag;
+ }
}
- public virtual void Close()
- {
+ public virtual void Close() {
}
- public static ProverFactory! Load(string! proverName)
- ensures result.IsNew && Microsoft.Contracts.Owner.New(result);
- {
- string! path;
+ public static ProverFactory Load(string proverName) {
+ Contract.Requires(proverName != null);
+ Contract.Ensures(Contract.Result<ProverFactory>() != null);
+ Contract.Ensures(cce.IsNew(Contract.Result<ProverFactory>()) && cce.Owner.New(Contract.Result<ProverFactory>()));
+ string/*!*/ path;
if (proverName.IndexOf("/") > 0 || proverName.IndexOf("\\") > 0) {
path = proverName;
} else {
- string! codebase = (!) System.IO.Path.GetDirectoryName(
- (!)System.Reflection.Assembly.GetExecutingAssembly().Location);
+ string codebase = cce.NonNull(System.IO.Path.GetDirectoryName(
+ cce.NonNull(System.Reflection.Assembly.GetExecutingAssembly().Location)));
path = System.IO.Path.Combine(codebase, "Provers." + proverName + ".dll");
}
- Assembly asm = (!)Assembly.LoadFrom(path);
- string name = (!)asm.GetName().Name;
- System.Type factoryType = (!)asm.GetType("Microsoft.Boogie." + name.Replace("Provers.", "") + ".Factory");
- return (ProverFactory!)Activator.CreateInstance(factoryType);
+ Assembly asm = cce.NonNull(Assembly.LoadFrom(path));
+ string name = cce.NonNull(asm.GetName().Name);
+ System.Type factoryType = cce.NonNull(asm.GetType("Microsoft.Boogie." + name.Replace("Provers.", "") + ".Factory"));
+ return cce.NonNull((ProverFactory/*!*/)Activator.CreateInstance(factoryType));
+ }
+ }
+ [ContractClassFor(typeof(ProverFactory))]
+ public abstract class ProverFactoryContracts : ProverFactory {
+ public override object NewProverContext(ProverOptions options) {
+ Contract.Requires(options != null);
+ Contract.Ensures(Contract.Result<object>() != null);
+
+ throw new NotImplementedException();
}
}
}
diff --git a/Source/Core/Xml.cs b/Source/Core/Xml.cs
index e0583793..8fca82f8 100644
--- a/Source/Core/Xml.cs
+++ b/Source/Core/Xml.cs
@@ -7,35 +7,42 @@ using System;
using System.IO;
using System.Xml;
using System.Collections.Generic;
-using Microsoft.Contracts;
+using System.Diagnostics.Contracts;
using Cci = System.Compiler;
-
-namespace Microsoft.Boogie
-{
+namespace Microsoft.Boogie {
public class XmlSink {
- string! filename;
- [Rep] XmlWriter wr;
+ string/*!*/ filename;
+ [ContractInvariantMethod]
+ void ObjectInvariant() {
+ Contract.Invariant(filename != null);
+ }
+
+ [Rep]
+ XmlWriter wr;
public bool IsOpen {
- get { return wr != null; }
+ get {
+ return wr != null;
+ }
}
-
- public XmlSink(string! filename) {
+
+ public XmlSink(string filename) {
+ Contract.Requires(filename != null);
this.filename = filename;
}
-
+
/// <summary>
/// Returns null on success, in which case the caller should eventually invoke Close.
/// Returns an error string on failure.
/// </summary>
- public string Open()
- modifies this.*;
- ensures IsOpen;
- {
+ public string Open() {
+ //modifies this.*;
+ Contract.Ensures(IsOpen);
if (wr != null) {
Close();
}
- expose (this) {
+ cce.BeginExpose(this);
+ {
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
wr = XmlWriter.Create(filename, settings);
@@ -44,133 +51,138 @@ namespace Microsoft.Boogie
wr.WriteAttributeString("version", CommandLineOptions.VersionNumber);
wr.WriteAttributeString("commandLine", Environment.CommandLine);
}
+ cce.EndExpose();
return null; // success
}
-
- public void Close()
- modifies this.*;
- {
+
+ public void Close() {
+ //modifies this.*;
if (wr != null) {
- expose (this) {
+ cce.BeginExpose(this);
+ {
wr.WriteEndDocument();
wr.Close();
wr = null;
}
+ cce.EndExpose();
}
}
-
+
const string DateTimeFormatString = "u";
-
- public void WriteStartMethod(string! methodName, DateTime startTime)
- requires IsOpen;
- modifies this.*;
- ensures IsOpen;
- {
- assert wr != null;
- expose (this) {
+
+ public void WriteStartMethod(string methodName, DateTime startTime) {
+ Contract.Requires(methodName != null);
+ Contract.Requires(IsOpen);
+ //modifies this.*;
+ Contract.Ensures(IsOpen);
+ Contract.Assert(wr != null);
+ cce.BeginExpose(this);
+ {
wr.WriteStartElement("method");
wr.WriteAttributeString("name", methodName);
wr.WriteAttributeString("startTime", startTime.ToString(DateTimeFormatString));
}
+ cce.EndExpose();
}
-
- public void WriteEndMethod(string! outcome, DateTime endTime, TimeSpan elapsed)
- requires IsOpen;
- modifies this.*;
- ensures IsOpen;
- {
- assert wr != null;
- expose (this) {
+
+ public void WriteEndMethod(string outcome, DateTime endTime, TimeSpan elapsed) {
+ Contract.Requires(outcome != null);
+ Contract.Requires(IsOpen);
+ //modifies this.*;
+ Contract.Ensures(IsOpen);
+ Contract.Assert(wr != null);
+ cce.BeginExpose(this);
+ {
wr.WriteStartElement("conclusion");
wr.WriteAttributeString("endTime", endTime.ToString(DateTimeFormatString));
wr.WriteAttributeString("duration", elapsed.TotalSeconds.ToString());
wr.WriteAttributeString("outcome", outcome);
-
+
wr.WriteEndElement(); // outcome
wr.WriteEndElement(); // method
}
+ cce.EndExpose();
}
-
- public void WriteError(string! message, IToken! errorToken, IToken relatedToken, BlockSeq trace)
- requires IsOpen && (trace == null || Owner.Different(this, trace));
- modifies this.*, errorToken.*, relatedToken.*, trace.*;
- ensures IsOpen;
- {
- assert wr != null;
- expose(this){
+
+ public void WriteError(string message, IToken errorToken, IToken relatedToken, BlockSeq trace) {
+ Contract.Requires(errorToken != null);
+ Contract.Requires(message != null);
+ Contract.Requires(IsOpen && (trace == null || cce.Owner.Different(this, trace)));
+ //modifies this.*, errorToken.*, relatedToken.*, trace.*;
+ Contract.Ensures(IsOpen);
+ Contract.Assert(wr != null);
+ cce.BeginExpose(this);
+ {
wr.WriteStartElement("error");
wr.WriteAttributeString("message", message);
WriteTokenAttributes(errorToken);
- if (relatedToken != null)
- {
+ if (relatedToken != null) {
wr.WriteStartElement("related");
WriteTokenAttributes(relatedToken);
wr.WriteEndElement();
}
- if (trace != null)
- {
+ if (trace != null) {
wr.WriteStartElement("trace");
{
- foreach (object bo in trace)
- invariant wr != null;
- {
- assume bo is Block;
+ foreach (object bo in trace) {
+ cce.LoopInvariant(wr != null);
+ Contract.Assume(bo is Block);
Block b = (Block)bo;
wr.WriteStartElement("traceNode");
{
WriteTokenAttributes(b.tok);
wr.WriteAttributeString("label", b.Label);
}
- wr.WriteEndElement();
+ wr.WriteEndElement();
}
wr.WriteEndElement();
}
}
- wr.WriteEndElement();
- }
- }
+ wr.WriteEndElement();
+ }
+ cce.EndExpose();
+ }
- public void WriteError(string! message, Cci.Node! offendingNode, BlockSeq trace)
- requires IsOpen && Owner.Different(this, offendingNode);
- requires trace == null || Owner.Different(this, trace);
- modifies this.*, offendingNode.*, trace.*;
- ensures IsOpen;
- {
- assert wr != null;
- expose(this){
+ public void WriteError(string message, Cci.Node offendingNode, BlockSeq trace) {
+ Contract.Requires(offendingNode != null);
+ Contract.Requires(message != null);
+ Contract.Requires(IsOpen && cce.Owner.Different(this, offendingNode));
+ Contract.Requires(trace == null || cce.Owner.Different(this, trace));
+ //modifies this.*, offendingNode.*, trace.*;
+ Contract.Ensures(IsOpen);
+ Contract.Assert(wr != null);
+ cce.BeginExpose(this);
+ {
wr.WriteStartElement("error");
wr.WriteAttributeString("message", message);
WriteTokenAttributes(offendingNode);
- if (trace != null)
- {
+ if (trace != null) {
wr.WriteStartElement("trace");
{
- foreach (object bo in trace)
- invariant wr != null;
- {
- assume bo is Block;
+ foreach (object bo in trace) {
+ cce.LoopInvariant(wr != null);
+ Contract.Assume(bo is Block);
Block b = (Block)bo;
wr.WriteStartElement("traceNode");
{
this.WriteTokenAttributes(b.tok);
wr.WriteAttributeString("label", b.Label);
}
- wr.WriteEndElement();
+ wr.WriteEndElement();
}
wr.WriteEndElement();
}
}
- wr.WriteEndElement();
- }
+ wr.WriteEndElement();
+ }
+ cce.EndExpose();
}
[Inside]
- private void WriteTokenAttributes(IToken tok)
- requires wr != null && wr.IsPeerConsistent;
- modifies this.0, wr.*;
- {
- if (tok != null && tok.filename != null)
- {
+ private void WriteTokenAttributes(IToken tok) {
+ Contract.Requires(wr != null && cce.IsPeerConsistent(wr));
+ //modifies this.0, wr.*;
+ if (tok != null && tok.filename != null) {
wr.WriteAttributeString("file", tok.filename);
wr.WriteAttributeString("line", tok.line.ToString());
wr.WriteAttributeString("column", tok.col.ToString());
@@ -178,114 +190,124 @@ namespace Microsoft.Boogie
}
[Inside]
- private void WriteTokenAttributes(Cci.Node! node)
- requires wr != null && wr.IsPeerConsistent;
- modifies this.0, wr.*;
- {
- assert wr != null;
- if (node.SourceContext.Document != null)
- {
+ private void WriteTokenAttributes(Cci.Node node) {
+ Contract.Requires(node != null);
+ Contract.Requires(wr != null && cce.IsPeerConsistent(wr));
+ //modifies this.0, wr.*;
+ Contract.Assert(wr != null);
+ if (node.SourceContext.Document != null) {
wr.WriteAttributeString("file", node.SourceContext.Document.Name);
wr.WriteAttributeString("line", node.SourceContext.StartLine.ToString());
wr.WriteAttributeString("column", node.SourceContext.StartColumn.ToString());
}
}
-
- public void WriteStartInference(string! inferenceName)
- requires IsOpen;
- modifies this.*;
- ensures IsOpen;
- {
- assert wr != null;
- expose (this) {
+
+ public void WriteStartInference(string inferenceName) {
+ Contract.Requires(inferenceName != null);
+ Contract.Requires(IsOpen);
+ //modifies this.*;
+ Contract.Ensures(IsOpen);
+ Contract.Assert(wr != null);
+ cce.BeginExpose(this);
+ {
wr.WriteStartElement("inference");
wr.WriteAttributeString("name", inferenceName);
}
+ cce.EndExpose();
}
-
- public void WriteEndInference()
- requires IsOpen;
- modifies this.*;
- ensures IsOpen;
- {
- assert wr != null;
- expose (this) {
+
+ public void WriteEndInference() {
+ Contract.Requires(IsOpen);
+ //modifies this.*;
+ Contract.Ensures(IsOpen);
+ Contract.Assert(wr != null);
+ cce.BeginExpose(this);
+ {
wr.WriteEndElement(); // inference
}
+ cce.EndExpose();
}
-
- public void WriteContractParaAssignment(string! varName, string val)
- requires IsOpen;
- modifies this.*;
- ensures IsOpen;
- {
- assert wr != null;
- expose (this) {
+
+ public void WriteContractParaAssignment(string varName, string val) {
+ Contract.Requires(varName != null);
+ Contract.Requires(IsOpen);
+ //modifies this.*;
+ Contract.Ensures(IsOpen);
+ Contract.Assert(wr != null);
+ cce.BeginExpose(this);
+ {
wr.WriteStartElement("assignment");
wr.WriteAttributeString("name", varName);
wr.WriteAttributeString("value", val);
wr.WriteEndElement();
}
+ cce.EndExpose();
}
-
- public void WriteStartFile(string! filename)
- requires IsOpen;
- modifies this.*;
- ensures IsOpen;
- {
- assert wr != null;
- expose (this) {
+
+ public void WriteStartFile(string filename) {
+ Contract.Requires(filename != null);
+ Contract.Requires(IsOpen);
+ //modifies this.*;
+ Contract.Ensures(IsOpen);
+ Contract.Assert(wr != null);
+ cce.BeginExpose(this);
+ {
wr.WriteStartElement("file");
wr.WriteAttributeString("name", filename);
}
+ cce.EndExpose();
}
- public void WriteEndFile()
- requires IsOpen;
- modifies this.*;
- ensures IsOpen;
- {
- assert wr != null;
- expose (this) {
+ public void WriteEndFile() {
+ Contract.Requires(IsOpen);
+ //modifies this.*;
+ Contract.Ensures(IsOpen);
+ Contract.Assert(wr != null);
+ cce.BeginExpose(this);
+ {
wr.WriteEndElement();
}
+ cce.EndExpose();
}
-
- public void WriteFileFragment(string! fragment)
- requires IsOpen;
- modifies this.*;
- ensures IsOpen;
- {
- assert wr != null;
- expose (this) {
+
+ public void WriteFileFragment(string fragment) {
+ Contract.Requires(fragment != null);
+ Contract.Requires(IsOpen);
+ //modifies this.*;
+ Contract.Ensures(IsOpen);
+ Contract.Assert(wr != null);
+ cce.BeginExpose(this);
+ {
wr.WriteStartElement("fileFragment");
wr.WriteAttributeString("name", fragment);
wr.WriteEndElement();
}
+ cce.EndExpose();
}
}
-
+
public class XmlFileScope : IDisposable {
- [Peer] [SpecPublic] XmlSink sink;
-
+ [Peer]
+ [SpecPublic]
+ XmlSink sink;
+
[Captured]
- public XmlFileScope(XmlSink? sink, string! filename)
- requires sink != null ==> sink.IsOpen;
- modifies sink.*;
- {
+ public XmlFileScope(XmlSink sink, string filename) {
+ Contract.Requires(filename != null);
+ Contract.Requires(sink == null || sink.IsOpen);
+ //modifies sink.*;
if (sink != null) {
sink.WriteStartFile(filename); // invoke this method while "sink" is still peer consistent
- Owner.AssignSame(this, sink);
+ cce.Owner.AssignSame(this, sink);
this.sink = sink;
}
}
-
- public void Dispose()
- {
+
+ public void Dispose() {
if (sink != null) {
- assume sink.IsOpen;
+ Contract.Assume(sink.IsOpen);
sink.WriteEndFile();
}
}
}
-}
+} \ No newline at end of file