static int InjectAssertionInBpl(string bplFileName, string fileName, int lineNumber, int columnNumber) { Bpl.CommandLineOptions.Install(new Bpl.CommandLineOptions()); Bpl.CommandLineOptions.Clo.DoModSetAnalysis = true; var returnValue = errorValue; Bpl.Program program; Bpl.Parser.Parse(bplFileName, new List<string>(), out program); int errorCount = program.Resolve(); if (errorCount != 0) { Console.WriteLine("{0} name resolution errors detected in {1}", errorCount, bplFileName); return returnValue; } errorCount = program.Typecheck(); if (errorCount != 0) { Console.WriteLine("{0} type checking errors detected in {1}", errorCount, bplFileName); return returnValue; } GetMeHereBplInjector bplInjector = new GetMeHereBplInjector(fileName, lineNumber, columnNumber); bplInjector.Visit(program); using (Bpl.TokenTextWriter writer = new Bpl.TokenTextWriter(bplFileName)) { Bpl.CommandLineOptions.Clo.PrintInstrumented = true; program.Emit(writer); } return returnValue; }
public Expr Rename(Expr e) { Expr ne; if (!cache.TryGetValue(e, out ne)) { boundVarCount = 0; freeVarCount = 0; freeVarMap = new Dictionary <Variable, FreeVariable>(); ne = VisitExpr(e); cache[e] = ne; #if DEBUG_ALPHA_RENAMING var wr = new TokenTextWriter("<console>", Console.Out, true); Console.Write("nm( "); e.Emit(wr); Console.WriteLine(" )"); Console.Write(" = "); ne.Emit(wr); Console.WriteLine(""); Console.WriteLine("h = " + ne.GetHashCode()); #endif } return(ne); }
public override void Emit(TokenTextWriter stream, int contextBindingStrength, bool fragileContext) { //Contract.Requires(stream != null); stream.push(); stream.Write(this, "(var "); string sep = ""; stream.push(); foreach (var v in Dummies) { stream.Write("{0}", sep); v.EmitVitals(stream, 0, true, false); sep = ", "; stream.sep(); } stream.pop(); stream.Write(" := "); this.Rhss.Emit(stream); stream.Write("; "); stream.sep(); for (QKeyValue kv = this.Attributes; kv != null; kv = kv.Next) { kv.Emit(stream); stream.Write(" "); } stream.sep(); this.Body.Emit(stream); stream.Write(")"); stream.pop(); }
public static Program Desugar(Program program, out List<Expr /*!*/> /*!*/ axioms, out List<Function /*!*/> /*!*/ functions) { Contract.Requires(program != null); Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out functions))); Contract.Ensures(cce.NonNullElements(Contract.ValueAtReturn(out axioms))); Contract.Ensures(Contract.Result<Program>() != null); LambdaVisitor v = new LambdaVisitor(); program = v.VisitProgram(program); axioms = v.lambdaAxioms; functions = v.lambdaFunctions; if (CommandLineOptions.Clo.TraceVerify) { Console.WriteLine("Desugaring of lambda expressions produced {0} functions and {1} axioms:", functions.Count, axioms.Count); TokenTextWriter wr = new TokenTextWriter("<console>", Console.Out, /*pretty=*/ false); foreach (Function f in functions) { f.Emit(wr, 0); } foreach (Expr ax in axioms) { ax.Emit(wr); Console.WriteLine(); } } return program; }
static int InjectAssertionInBpl(string bplFileName, string fileName, int lineNumber, int columnNumber) { Bpl.CommandLineOptions.Install(new Bpl.CommandLineOptions()); Bpl.CommandLineOptions.Clo.DoModSetAnalysis = true; var returnValue = errorValue; Bpl.Program program; Bpl.Parser.Parse(bplFileName, new List <string>(), out program); int errorCount = program.Resolve(); if (errorCount != 0) { Console.WriteLine("{0} name resolution errors detected in {1}", errorCount, bplFileName); return(returnValue); } errorCount = program.Typecheck(); if (errorCount != 0) { Console.WriteLine("{0} type checking errors detected in {1}", errorCount, bplFileName); return(returnValue); } GetMeHereBplInjector bplInjector = new GetMeHereBplInjector(fileName, lineNumber, columnNumber); bplInjector.Visit(program); using (Bpl.TokenTextWriter writer = new Bpl.TokenTextWriter(bplFileName)) { Bpl.CommandLineOptions.Clo.PrintInstrumented = true; program.Emit(writer); } return(returnValue); }
public void Test() { ErrorReporter reporter = new ConsoleErrorReporter(); var options = new DafnyOptions(reporter); options.DafnyPrelude = "../../../../../Binaries/DafnyPrelude.bpl"; DafnyOptions.Install(options); var programString = @"trait Trait<A, B> { }"; ModuleDecl module = new LiteralModuleDecl(new DefaultModuleDecl(), null); Microsoft.Dafny.Type.ResetScopes(); BuiltIns builtIns = new BuiltIns(); Parser.Parse(programString, "virtual", "virtual", module, builtIns, reporter); var dafnyProgram = new Program("programName", module, builtIns, reporter); Main.Resolve(dafnyProgram, reporter); foreach (var prog in Translator.Translate(dafnyProgram, dafnyProgram.reporter)) { var writer = new StringWriter(); var tokenWriter = new Bpl.TokenTextWriter("virtual", writer, true); prog.Item2.Emit(tokenWriter); var parseErrorCount = Bpl.Parser.Parse(writer.ToString(), "virtualBoogie", out var boogieProgram); Assert.Equal(0, parseErrorCount); } }
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 = ", "; if (p is string) { stream.Write("\""); stream.Write((string)p); stream.Write("\""); } else { ((Expr)p).Emit(stream); } } stream.Write("}"); }
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(" "); } }
private static void init() { if (noDebuggingOutput) { return; } if (debugOut == null) { debugOut = new TokenTextWriter("corraldebug.out"); } }
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, /*setTokens=*/ false, /*pretty=*/ 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, /*setTokens=*/ false, /*pretty=*/ false)) { cce.NonNull((Expr /*!*/)args[i]).Emit(stream, 0, false); } fixedArgs[i] = buffer.ToString(); } else { fixedArgs[i] = args[i]; } } args = fixedArgs; } return(string.Format(msg, args)); }
public void Emit(TokenTextWriter stream) { Contract.Requires(stream != null); stream.SetToken(this); Contract.Assert(this.Tr.Count >= 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 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); stream.Write(this, " "); this.Dummies.Emit(stream, true); stream.Write(" :: "); for (QKeyValue kv = this.Attributes; kv != null; kv = kv.Next) { kv.Emit(stream); stream.Write(" "); } this.EmitTriggers(stream); this.Body.Emit(stream); stream.Write(")"); }
public static int TranslateAssemblyAndWriteOutput(List <string> assemblyNames, HeapFactory heapFactory, Options options, List <Regex> exemptionList, bool whiteList) { Contract.Requires(assemblyNames != null); Contract.Requires(heapFactory != null); try { var pgm = TranslateAssembly(assemblyNames, heapFactory, options, exemptionList, whiteList); var fileName = assemblyNames[0]; fileName = Path.GetFileNameWithoutExtension(fileName); string outputFileName = fileName + ".bpl"; using (var writer = new Microsoft.Boogie.TokenTextWriter(outputFileName)) { Prelude.Emit(writer); pgm.Emit(writer); writer.Close(); } return(0); // success } catch (Exception e) { // swallow everything and just return an error code Console.WriteLine("The byte-code translator failed: {0}", e.Message); Console.WriteLine("Stack trace: {0}", e.StackTrace); return(-1); } }
/// <summary> /// Performs lambda lifting (see <see cref="LambdaHelper.ExpandLambdas"/>) by replacing the lambda's /// free variables with bound ones. /// </summary> /// <param name="lambda">A lambda expression /// <code>(lambda x1: T1 ... x_n: T_n :: t)</code> /// where <c>t</c> contains the free variables <c>y1</c>, ..., <c>y_m</c>. /// </param> /// <returns> /// <list type="bullet"> /// <item> /// A function application <c>f(y1, ..., y_m)</c> where <c>f</c>'s body is defined to be the result of /// replacing the free variables <c>y1</c>, ..., <c>y_m</c> in <c>t</c> with bound variables /// <c>b1</c>, ..., <c>b_m</c>. /// </item> /// <item> /// Adds a definition and axiom for <c>f</c> to <see cref="lambdaFunctions"/> and <see cref="lambdaAxioms"/>. /// Memoizes <c>f</c> as the lifted lambda for <para>lambda</para>. /// </item> /// </list> /// </returns> private Expr LiftLambdaFreeVars(LambdaExpr lambda) { // We start by getting rid of any use of "old" inside the lambda. This is done as follows. // For each variable "g" occurring inside lambda as "old(... g ...)", create a new name "og". // Replace each old occurrence of "g" with "og", removing the enclosing "old" wrappers. var oldFinder = new OldFinder(); oldFinder.Visit(lambda); var oldSubst = new Dictionary<Variable, Expr>(); // g -> g0 var callOldMapping = new Dictionary<Variable, Expr>(); // g0 -> old(g) foreach (var v in oldFinder.FreeOldVars) { var g = v as GlobalVariable; if (g != null) { var g0 = new GlobalVariable(g.tok, new TypedIdent(g.tok, g.TypedIdent.Name + "@old", g.TypedIdent.Type)); oldSubst.Add(g, new IdentifierExpr(g0.tok, g0)); callOldMapping.Add(g0, new OldExpr(g0.tok, new IdentifierExpr(g.tok, g))); } } var lambdaBody = Substituter.ApplyReplacingOldExprs( Substituter.SubstitutionFromDictionary(new Dictionary<Variable, Expr>()), Substituter.SubstitutionFromDictionary(oldSubst), lambda.Body); var lambdaAttrs = Substituter.ApplyReplacingOldExprs( Substituter.SubstitutionFromDictionary(new Dictionary<Variable, Expr>()), Substituter.SubstitutionFromDictionary(oldSubst), lambda.Attributes); if (0 < CommandLineOptions.Clo.VerifySnapshots && QKeyValue.FindStringAttribute(lambdaAttrs, "checksum") == null) { // Attach a dummy checksum to avoid issues in the dependency analysis. var checksumAttr = new QKeyValue(lambda.tok, "checksum", new List<object> {"lambda expression"}, null); if (lambdaAttrs == null) { lambdaAttrs = checksumAttr; } else { lambdaAttrs.AddLast(checksumAttr); } } // this is ugly, the output will depend on hashing order var subst = new Dictionary<Variable, Expr>(); var substFnAttrs = new Dictionary<Variable, Expr>(); var formals = new List<Variable>(); var callArgs = new List<Expr>(); var axCallArgs = new List<Expr>(); var dummies = new List<Variable>(lambda.Dummies); var freeTypeVars = new List<TypeVariable>(); var fnTypeVarActuals = new List<Type /*!*/>(); var freshTypeVars = new List<TypeVariable>(); // these are only used in the lambda@n function's definition // compute the free variables of the lambda expression, but with lambdaBody instead of lambda.Body Set freeVars = new Set(); BinderExpr.ComputeBinderFreeVariables(lambda.TypeParameters, lambda.Dummies, lambdaBody, null, lambdaAttrs, freeVars); foreach (object o in freeVars) { // 'o' is either a Variable or a TypeVariable. if (o is Variable) { var v = o as Variable; var ti = new TypedIdent(v.TypedIdent.tok, v.TypedIdent.Name, v.TypedIdent.Type); var f = new Formal(v.tok, ti, true); formals.Add(f); substFnAttrs.Add(v, new IdentifierExpr(f.tok, f)); var b = new BoundVariable(v.tok, ti); dummies.Add(b); if (callOldMapping.ContainsKey(v)) { callArgs.Add(callOldMapping[v]); } else { callArgs.Add(new IdentifierExpr(v.tok, v)); } Expr id = new IdentifierExpr(b.tok, b); subst.Add(v, id); axCallArgs.Add(id); } else { var tv = (TypeVariable) o; freeTypeVars.Add(tv); fnTypeVarActuals.Add(tv); freshTypeVars.Add(new TypeVariable(tv.tok, tv.Name)); } } var sw = new System.IO.StringWriter(); var wr = new TokenTextWriter(sw, true); lambda.Emit(wr); string lam_str = sw.ToString(); FunctionCall fcall; IToken tok = lambda.tok; Formal res = new Formal(tok, new TypedIdent(tok, TypedIdent.NoName, cce.NonNull(lambda.Type)), false); if (liftedLambdas.TryGetValue(lambda, out fcall)) { if (CommandLineOptions.Clo.TraceVerify) { Console.WriteLine("Old lambda: {0}", lam_str); } } else { if (CommandLineOptions.Clo.TraceVerify) { Console.WriteLine("New lambda: {0}", lam_str); } Function fn = new Function(tok, FreshLambdaFunctionName(), freshTypeVars, formals, res, "auto-generated lambda function", Substituter.Apply(Substituter.SubstitutionFromDictionary(substFnAttrs), lambdaAttrs)); fn.OriginalLambdaExprAsString = lam_str; fcall = new FunctionCall(new IdentifierExpr(tok, fn.Name)); fcall.Func = fn; // resolve here liftedLambdas[lambda] = fcall; 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); axcall.Type = res.TypedIdent.Type; axcall.TypeParameters = SimpleTypeParamInstantiation.From(freeTypeVars, fnTypeVarActuals); NAryExpr select = Expr.Select(axcall, selectArgs); select.Type = lambdaBody.Type; List<Type /*!*/> selectTypeParamActuals = new List<Type /*!*/>(); List<TypeVariable> forallTypeVariables = new List<TypeVariable>(); foreach (TypeVariable /*!*/ tp in lambda.TypeParameters) { Contract.Assert(tp != null); selectTypeParamActuals.Add(tp); forallTypeVariables.Add(tp); } forallTypeVariables.AddRange(freeTypeVars); select.TypeParameters = SimpleTypeParamInstantiation.From(lambda.TypeParameters, selectTypeParamActuals); Expr bb = Substituter.Apply(Substituter.SubstitutionFromDictionary(subst), lambdaBody); NAryExpr body = Expr.Eq(select, bb); body.Type = Type.Bool; body.TypeParameters = SimpleTypeParamInstantiation.EMPTY; Trigger trig = new Trigger(select.tok, true, new List<Expr> {select}); lambdaFunctions.Add(fn); lambdaAxioms.Add(new ForallExpr(tok, forallTypeVariables, dummies, Substituter.Apply(Substituter.SubstitutionFromDictionary(subst), lambdaAttrs), trig, body)); } NAryExpr call = new NAryExpr(tok, fcall, callArgs); call.Type = res.TypedIdent.Type; call.TypeParameters = SimpleTypeParamInstantiation.From(freeTypeVars, fnTypeVarActuals); return call; }
public static int Inline(string bplFileName) { Bpl.CommandLineOptions options = new Bpl.CommandLineOptions(); Bpl.CommandLineOptions.Install(options); Bpl.CommandLineOptions.Clo.DoModSetAnalysis = true; Bpl.Program program; string _bplFileName = "_" + bplFileName; Bpl.Parser.Parse(_bplFileName, new List<string>(), out program); int errorCount = program.Resolve(); if (errorCount != 0) { Console.WriteLine("{0} name resolution errors detected in {1}", errorCount, _bplFileName); return -1; } errorCount = program.Typecheck(); if (errorCount != 0) { Console.WriteLine("{0} type checking errors detected in {1}", errorCount, _bplFileName); return -1; } bool inline = false; foreach (var d in program.TopLevelDeclarations) { if (d.FindExprAttribute("inline") != null) { inline = true; } } if (inline) { foreach (var d in program.TopLevelDeclarations) { var impl = d as Bpl.Implementation; if (impl != null) { impl.OriginalBlocks = impl.Blocks; impl.OriginalLocVars = impl.LocVars; } } foreach (var d in program.TopLevelDeclarations) { var impl = d as Bpl.Implementation; if (impl != null && !impl.SkipVerification) { Bpl.Inliner.ProcessImplementation(program, impl); } } foreach (var d in program.TopLevelDeclarations) { var impl = d as Bpl.Implementation; if (impl != null) { impl.OriginalBlocks = null; impl.OriginalLocVars = null; } } } Microsoft.Boogie.TokenTextWriter writer = new Microsoft.Boogie.TokenTextWriter(bplFileName); options.PrintInstrumented = true; program.Emit(writer); writer.Close(); return 0; }
public static int TranslateAssemblyAndWriteOutput(List<string> assemblyNames, HeapFactory heapFactory, Options options, List<Regex> exemptionList, bool whiteList) { Contract.Requires(assemblyNames != null); Contract.Requires(heapFactory != null); try { var pgm = TranslateAssembly(assemblyNames, heapFactory, options, exemptionList, whiteList); var fileName = assemblyNames[0]; fileName = Path.GetFileNameWithoutExtension(fileName); string outputFileName = fileName + ".bpl"; using (var writer = new Microsoft.Boogie.TokenTextWriter(outputFileName)) { Prelude.Emit(writer); pgm.Emit(writer); writer.Close(); } return 0; // success } catch (Exception e) { // swallow everything and just return an error code Console.WriteLine("The byte-code translator failed: {0}", e.Message); // Console.WriteLine("Stack trace: {0}", e.StackTrace); return -1; } }
protected virtual void EmitTriggers(TokenTextWriter stream) { Contract.Requires(stream != null); }
public override Cmd VisitCallCmd(CallCmd node) { var result = base.VisitCallCmd(node); var oldProc = programInCachedSnapshot.FindProcedure(node.Proc.Name); if (oldProc != null && oldProc.DependencyChecksum != node.Proc.DependencyChecksum && node.AssignedAssumptionVariable == null) { var before = new List <Cmd>(); var beforePreconditionCheck = new List <Cmd>(); var after = new List <Cmd>(); var axioms = new List <Axiom>(); Expr assumedExpr = new LiteralExpr(Token.NoToken, false); // TODO(wuestholz): Try out two alternatives: only do this for low priority implementations or not at all. var canUseSpecs = DependencyCollector.CanExpressOldSpecs(oldProc, Program); if (canUseSpecs && oldProc.SignatureEquals(node.Proc)) { var desugaring = node.Desugaring; Contract.Assert(desugaring != null); var precond = node.CheckedPrecondition(oldProc, Program, e => FunctionExtractor.Extract(e, Program, axioms)); if (precond != null) { var assume = new AssumeCmd(node.tok, precond, new QKeyValue(Token.NoToken, "precondition_previous_snapshot", new List <object>(), null)); assume.IrrelevantForChecksumComputation = true; beforePreconditionCheck.Add(assume); } var unmods = node.UnmodifiedBefore(oldProc); var eqs = new List <Expr>(); foreach (var unmod in unmods) { var oldUnmod = new LocalVariable(Token.NoToken, new TypedIdent(Token.NoToken, string.Format("{0}##old##{1}", unmod.Name, FreshTemporaryVariableName), unmod.Type)); var lhs = new SimpleAssignLhs(Token.NoToken, new IdentifierExpr(Token.NoToken, oldUnmod)); var rhs = new IdentifierExpr(Token.NoToken, unmod.Decl); var cmd = new AssignCmd(Token.NoToken, new List <AssignLhs> { lhs }, new List <Expr> { rhs }); cmd.IrrelevantForChecksumComputation = true; before.Add(cmd); var eq = LiteralExpr.Eq(new IdentifierExpr(Token.NoToken, oldUnmod), new IdentifierExpr(Token.NoToken, unmod.Decl)); eq.Type = Type.Bool; eq.TypeParameters = SimpleTypeParamInstantiation.EMPTY; eqs.Add(eq); } var mods = node.ModifiedBefore(oldProc); var oldSubst = new Dictionary <Variable, Expr>(); foreach (var mod in mods) { var oldMod = new LocalVariable(Token.NoToken, new TypedIdent(Token.NoToken, string.Format("{0}##old##{1}", mod.Name, FreshTemporaryVariableName), mod.Type)); oldSubst[mod.Decl] = new IdentifierExpr(Token.NoToken, oldMod); var lhs = new SimpleAssignLhs(Token.NoToken, new IdentifierExpr(Token.NoToken, oldMod)); var rhs = new IdentifierExpr(Token.NoToken, mod.Decl); var cmd = new AssignCmd(Token.NoToken, new List <AssignLhs> { lhs }, new List <Expr> { rhs }); cmd.IrrelevantForChecksumComputation = true; before.Add(cmd); } assumedExpr = node.Postcondition(oldProc, eqs, oldSubst, Program, e => FunctionExtractor.Extract(e, Program, axioms)); if (assumedExpr == null) { assumedExpr = new LiteralExpr(Token.NoToken, true); } } if (assumedExpr != null) { var lv = new LocalVariable(Token.NoToken, new TypedIdent(Token.NoToken, string.Format("a##cached##{0}", FreshAssumptionVariableName), Type.Bool), new QKeyValue(Token.NoToken, "assumption", new List <object>(), null)); node.AssignedAssumptionVariable = lv; currentImplementation.InjectAssumptionVariable(lv, !canUseSpecs); var lhs = new SimpleAssignLhs(Token.NoToken, new IdentifierExpr(Token.NoToken, lv)); var rhs = LiteralExpr.And(new IdentifierExpr(Token.NoToken, lv), assumedExpr); var assumed = new AssignCmd(node.tok, new List <AssignLhs> { lhs }, new List <Expr> { rhs }); assumed.IrrelevantForChecksumComputation = true; after.Add(assumed); } node.ExtendDesugaring(before, beforePreconditionCheck, after); if (CommandLineOptions.Clo.TraceCachingForTesting || CommandLineOptions.Clo.TraceCachingForBenchmarking) { using (var tokTxtWr = new TokenTextWriter("<console>", Console.Out, false, false)) { var loc = node.tok != null && node.tok != Token.NoToken ? string.Format("{0}({1},{2})", node.tok.filename, node.tok.line, node.tok.col) : "<unknown location>"; Console.Out.WriteLine("Processing call to procedure {0} in implementation {1} (at {2}):", node.Proc.Name, currentImplementation.Name, loc); foreach (var a in axioms) { Console.Out.Write(" >>> added axiom: "); a.Expr.Emit(tokTxtWr); Console.Out.WriteLine(); } foreach (var b in before) { Console.Out.Write(" >>> added before: "); b.Emit(tokTxtWr, 0); } foreach (var b in beforePreconditionCheck) { Console.Out.Write(" >>> added before precondition check: "); b.Emit(tokTxtWr, 0); } foreach (var a in after) { Console.Out.Write(" >>> added after: "); a.Emit(tokTxtWr, 0); } } } } return(result); }
public Implementation Inject(Implementation implementation, Program programInCachedSnapshot) { Contract.Requires(implementation != null && programInCachedSnapshot != null); this.programInCachedSnapshot = programInCachedSnapshot; assumptionVariableCount = 0; temporaryVariableCount = 0; currentImplementation = implementation; #region Introduce explict assumption about the precondition. var oldProc = programInCachedSnapshot.FindProcedure(currentImplementation.Proc.Name); if (oldProc != null && oldProc.DependencyChecksum != currentImplementation.Proc.DependencyChecksum && currentImplementation.ExplicitAssumptionAboutCachedPrecondition == null) { var axioms = new List <Axiom>(); var after = new List <Cmd>(); Expr assumedExpr = new LiteralExpr(Token.NoToken, false); var canUseSpecs = DependencyCollector.CanExpressOldSpecs(oldProc, Program, true); if (canUseSpecs && oldProc.SignatureEquals(currentImplementation.Proc)) { var always = Substituter.SubstitutionFromHashtable(currentImplementation.GetImplFormalMap(), true, currentImplementation.Proc); var forOld = Substituter.SubstitutionFromHashtable(new Dictionary <Variable, Expr>()); var clauses = oldProc.Requires.Select(r => Substituter.FunctionCallReresolvingApply(always, forOld, r.Condition, Program)); var conj = Expr.And(clauses, true); assumedExpr = conj != null ? FunctionExtractor.Extract(conj, Program, axioms) : new LiteralExpr(Token.NoToken, true); } if (assumedExpr != null) { var lv = new LocalVariable(Token.NoToken, new TypedIdent(Token.NoToken, string.Format("a##cached##{0}", FreshAssumptionVariableName), Type.Bool), new QKeyValue(Token.NoToken, "assumption", new List <object>(), null)); currentImplementation.InjectAssumptionVariable(lv, !canUseSpecs); var lhs = new SimpleAssignLhs(Token.NoToken, new IdentifierExpr(Token.NoToken, lv)); var rhs = LiteralExpr.And(new IdentifierExpr(Token.NoToken, lv), assumedExpr); var assumed = new AssignCmd(currentImplementation.tok, new List <AssignLhs> { lhs }, new List <Expr> { rhs }); assumed.IrrelevantForChecksumComputation = true; currentImplementation.ExplicitAssumptionAboutCachedPrecondition = assumed; after.Add(assumed); } if (CommandLineOptions.Clo.TraceCachingForTesting || CommandLineOptions.Clo.TraceCachingForBenchmarking) { using (var tokTxtWr = new TokenTextWriter("<console>", Console.Out, false, false)) { var loc = currentImplementation.tok != null && currentImplementation.tok != Token.NoToken ? string.Format("{0}({1},{2})", currentImplementation.tok.filename, currentImplementation.tok.line, currentImplementation.tok.col) : "<unknown location>"; Console.Out.WriteLine("Processing implementation {0} (at {1}):", currentImplementation.Name, loc); foreach (var a in axioms) { Console.Out.Write(" >>> added axiom: "); a.Expr.Emit(tokTxtWr); Console.Out.WriteLine(); } foreach (var b in after) { Console.Out.Write(" >>> added after assuming the current precondition: "); b.Emit(tokTxtWr, 0); } } } } #endregion var result = VisitImplementation(currentImplementation); currentImplementation = null; this.programInCachedSnapshot = null; return(result); }
static int Main(string[] args) { int errorReturnValue = -1; #region Parse options and check for errors var options = new Options(); options.Parse(args); if (options.HelpRequested) { options.PrintOptions(""); return errorReturnValue; } if (options.HasErrors) { options.PrintErrorsAndExit(Console.Out); } if (!String.IsNullOrWhiteSpace(options.exemptionFile)) { string fileName = options.exemptionFile; var c = fileName[fileName.Length - 1]; if (c == '+' || c == '-') fileName = options.exemptionFile.Remove(fileName.Length - 1); if (!File.Exists(fileName)) { Console.WriteLine("Specified exemption file '{0}' not found.", fileName); } } if (options.stub != null) { Console.WriteLine("/s is no longer used to specify stub assemblies"); return errorReturnValue; } if (options.modelExceptions == 1 && !options.wholeProgram) { Console.WriteLine("can specify a precise modeling of exceptions only when doing whole program analysis"); return errorReturnValue; } if (options.breakIntoDebugger) { System.Diagnostics.Debugger.Launch(); } #endregion var assemblyNames = options.assemblies; if (assemblyNames == null || assemblyNames.Count == 0) { assemblyNames = new List<string>(); foreach (var g in options.GeneralArguments) { assemblyNames.Add(g); } } #region If an exclusion file has been specified, read in each line as a regular expression List<Regex> exemptionList = null; bool whiteList = false; if (!String.IsNullOrWhiteSpace(options.exemptionFile)) { int i = 0; exemptionList = new List<Regex>(); string fileName = options.exemptionFile; var c = fileName[fileName.Length - 1]; whiteList = true; if (c == '+' || c == '-') { fileName = options.exemptionFile.Remove(fileName.Length - 1); if (c == '-') whiteList = false; } try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader(fileName)) { String line; // Read and display lines from the file until the end of // the file is reached. while ((line = sr.ReadLine()) != null) { exemptionList.Add(new Regex(line)); i++; } //Console.WriteLine("Read {0} lines from the exclusion file '{1}'.", // i, options.exemptionFile); } } catch (Exception e) { Console.WriteLine("Something went wrong reading the exclusion file '{0}'; read in {1} lines, continuing processing.", fileName, i); Console.WriteLine(e.Message); } } #endregion try { HeapFactory heap; switch (options.heapRepresentation) { case Options.HeapRepresentation.splitFields: heap = new SplitFieldsHeap(); break; case Options.HeapRepresentation.general: heap = new GeneralHeap(); break; default: Console.WriteLine("Unknown setting for /heap"); return 1; } if ((options.phoneFeedbackCode || options.phoneNavigationCode) && (options.phoneControls == null || options.phoneControls == "")) { Console.WriteLine("Options /phoneNavigationCode and /phoneFeedbackCode need /phoneControls option set."); return 1; } var pgm = TranslateAssembly(assemblyNames, heap, options, exemptionList, whiteList); var fileName = assemblyNames[0]; fileName = Path.GetFileNameWithoutExtension(fileName); string outputFileName = fileName + ".bpl"; // Microsoft.Boogie.TokenTextWriter writer = new Microsoft.Boogie.TokenTextWriter("_" + outputFileName); Microsoft.Boogie.TokenTextWriter writer = new Microsoft.Boogie.TokenTextWriter(outputFileName); Prelude.Emit(writer); pgm.Emit(writer); writer.Close(); return 0; // return Inline(outputFileName); } catch (Exception e) { // swallow everything and just return an error code Console.WriteLine("The byte-code translator failed: {0}", e.Message); // Console.WriteLine("Stack trace: {0}", e.StackTrace); return -1; } }
static void Main(string[] args) { con = new Context(); string inFileName = null, unrolledFileName = null, tidRewrittenFileName = null, expandedFileName = null, annotatedFileName = null, splitFileName = null, yieldedFileName = null, instantiatedFileName = null, finalFileName = null, mhpFileName = null, hmifFileName = null; dbg = false; inFileName = parseCommandLine(args); string[] parts = inFileName.Split('.'); if (parts.Count() == 1) { unrolledFileName = inFileName + "_unrolled"; hmifFileName = inFileName + "_hmif"; expandedFileName = inFileName + "_expanded"; tidRewrittenFileName = inFileName + "_tidRewritten"; annotatedFileName = inFileName + "_annotated"; splitFileName = inFileName + "_split"; yieldedFileName = inFileName + "_yielded"; finalFileName = inFileName + "_final"; mhpFileName = inFileName + "_mhp"; instantiatedFileName = inFileName + "_inst"; } else { string name = parts[0]; unrolledFileName = name + "_unrolled"; hmifFileName = name + "_hmif"; expandedFileName = name + "_expanded"; annotatedFileName = name + "_annotated"; splitFileName = name + "_split"; yieldedFileName = name + "_yielded"; finalFileName = name + "_final"; mhpFileName = name + "_mhp"; instantiatedFileName = name + "_inst"; tidRewrittenFileName = name + "_tidRewritten"; for (int i = 1; i < parts.Count(); ++i) { unrolledFileName += "." + parts[i]; hmifFileName += "." + parts[i]; expandedFileName += "." + parts[i]; annotatedFileName += "." + parts[i]; splitFileName += "." + parts[i]; yieldedFileName += "." + parts[i]; finalFileName += "." + parts[i]; tidRewrittenFileName += "." + parts[i]; mhpFileName += "." + parts[i]; instantiatedFileName += "." + parts[i]; } } var tmpFileName = "og__tmp.bpl"; ExecutionEngine.printer = new ConsolePrinter(); //CommanLineOptions will control how boogie parses the program and gives us the IR CommandLineOptions.Install(new CommandLineOptions()); CommandLineOptions.Clo.Parse(new string[] { }); CommandLineOptions.Clo.PrintInstrumented = true; CommandLineOptions.Clo.StratifiedInliningVerbose = 2; CommandLineOptions.Clo.UseArrayTheory = true; CommandLineOptions.Clo.TypeEncodingMethod = CommandLineOptions.TypeEncoding.Monomorphic; Program program; program = BoogieUtil.ReadAndOnlyResolve(inFileName); // TODO: assert that no procedure can be called in both sync and async mode! // Find entrypoint and initialize con var entry = program.TopLevelDeclarations.OfType <Procedure>() .Where(proc => QKeyValue.FindBoolAttribute(proc.Attributes, "entrypoint")) .FirstOrDefault(); if (entry == null) { Console.WriteLine("Warning: No entrypoint given"); con.entryFunc = null; } else { con.entryFunc = entry.Name; } // Remove unreachable procedures BoogieUtil.pruneProcs(program, con.entryFunc); // Extract loops if (extractLoops) { program.ExtractLoops(); } BoogieUtil.DoModSetAnalysis(program); if (pruneAsserts) { program = og.GuardAsserts(program); } if (injectYields) { program = og.InsertYields(program); } if (instantiateTemplates) { var inst = new TemplateInstantiator(program); inst.Instantiate(program); program = BoogieUtil.ReResolve(program, dbg ? instantiatedFileName : tmpFileName); } var sp = new SplitThreads(con, dbg); var hmif = new HowManyInstanceFinder(con, dbg); var split = new Converter <Program, Program>(sp.split); var findHowManyInstances = new Converter <Program, Program>(hmif.Compute); if (entry != null && splitThreads) { if (dbg) { Console.WriteLine("Splitting procedures on thread entry: {0}", splitFileName); } program = split(program); program = BoogieUtil.ReResolve(program, dbg ? hmifFileName : tmpFileName); program = findHowManyInstances(program); program = BoogieUtil.ReResolve(program, dbg ? splitFileName : tmpFileName); } // Get rid of corral_yield program = og.RemoveCorralYield(program, con.yieldProc); var yieldedProgram = new ProgTransformation.PersistentProgram(program); if (dbg) { Console.WriteLine("Instrumenting: {0}", annotatedFileName); } if (!noTid) { program = og.InstrumentTid(program); } program = og.InstrumentAtomicBlocks(program); if (instrumentPermissions) { program = og.InstrumentPermissions(program); } program = BoogieUtil.ReResolve(program, dbg ? annotatedFileName : tmpFileName); CommandLineOptions.Clo.ContractInfer = true; CommandLineOptions.Clo.AbstractHoudini = absDomain; CommandLineOptions.Clo.UseProverEvaluate = true; CommandLineOptions.Clo.ModelViewFile = "z3model"; Microsoft.Boogie.Houdini.AbstractDomainFactory.Initialize(program); // First, do sequential var answer = DoInference(program, InferenceMode.SEQUENTIAL, annotatedFileName, expandedFileName); program = BoogieUtil.ReadAndOnlyResolve(dbg ? annotatedFileName : tmpFileName); // prune "true" functions var progFuncs = new Dictionary <string, Function>(); program.TopLevelDeclarations.OfType <Function>() .Iter(f => progFuncs.Add(f.Name, f)); var truefuncs = new List <Function>(); foreach (var f in answer) { if (f.Body is LiteralExpr && (f.Body as LiteralExpr).IsTrue) { truefuncs.Add(f); var actualf = progFuncs[f.Name]; actualf.Attributes = BoogieUtil.removeAttr("existential", actualf.Attributes); actualf.Body = Expr.True; } } Console.WriteLine("Sequential check pruned away {0} functions, {1} remain", truefuncs.Count, answer.Count() - truefuncs.Count); // now do concurrent answer = DoInference(program, InferenceMode.CONCURRENT, annotatedFileName, expandedFileName); answer = answer.Concat(truefuncs); var provedAsserts = new Dictionary <string, bool>(); answer.Where(func => QKeyValue.FindBoolAttribute(func.Attributes, "assertGuard")) .Iter(func => { var le = func.Body as LiteralExpr; System.Diagnostics.Debug.Assert(le != null); provedAsserts.Add(func.Name, le.IsFalse); }); // remove injected existential functions answer = answer.Where(func => !QKeyValue.FindBoolAttribute(func.Attributes, "chignore") && !QKeyValue.FindBoolAttribute(func.Attributes, "assertGuard")); if (printAssignment) { using (var tt = new TokenTextWriter(Console.Out)) answer.ToList().Iter(func => func.Emit(tt, 0)); } if (dbg) { Console.WriteLine("Injecting invariants back into the original program: {0}", finalFileName); } program = yieldedProgram.getProgram(); // remove existential functions program.RemoveTopLevelDeclarations(decl => (decl is Function) && QKeyValue.FindBoolAttribute((decl as Function).Attributes, "existential")); program.AddTopLevelDeclarations(answer); program = og.PruneProvedAsserts(program, f => provedAsserts[f]); // Remove ensures and requires program = og.RemoveRequiresAndEnsures(program); // Remove tid func program = og.RemoveThreadIdFunc(program); using (Microsoft.Boogie.TokenTextWriter writer = new Microsoft.Boogie.TokenTextWriter(finalFileName)) program.Emit(writer); }
public static int Inline(string bplFileName) { Bpl.CommandLineOptions options = new Bpl.CommandLineOptions(); Bpl.CommandLineOptions.Install(options); Bpl.CommandLineOptions.Clo.DoModSetAnalysis = true; Bpl.Program program; string _bplFileName = "_" + bplFileName; Bpl.Parser.Parse(_bplFileName, new List <string>(), out program); int errorCount = program.Resolve(); if (errorCount != 0) { Console.WriteLine("{0} name resolution errors detected in {1}", errorCount, _bplFileName); return(-1); } errorCount = program.Typecheck(); if (errorCount != 0) { Console.WriteLine("{0} type checking errors detected in {1}", errorCount, _bplFileName); return(-1); } bool inline = false; foreach (var d in program.TopLevelDeclarations) { if (d.FindExprAttribute("inline") != null) { inline = true; } } if (inline) { foreach (var d in program.TopLevelDeclarations) { var impl = d as Bpl.Implementation; if (impl != null) { impl.OriginalBlocks = impl.Blocks; impl.OriginalLocVars = impl.LocVars; } } foreach (var d in program.TopLevelDeclarations) { var impl = d as Bpl.Implementation; if (impl != null && !impl.SkipVerification) { Bpl.Inliner.ProcessImplementation(program, impl); } } foreach (var d in program.TopLevelDeclarations) { var impl = d as Bpl.Implementation; if (impl != null) { impl.OriginalBlocks = null; impl.OriginalLocVars = null; } } } Microsoft.Boogie.TokenTextWriter writer = new Microsoft.Boogie.TokenTextWriter(bplFileName); options.PrintInstrumented = true; program.Emit(writer); writer.Close(); return(0); }
static int Main(string[] args) { int errorReturnValue = -1; #region Parse options and check for errors var options = new Options(); options.Parse(args); if (options.HelpRequested) { options.PrintOptions(""); return(errorReturnValue); } if (options.HasErrors) { options.PrintErrorsAndExit(Console.Out); } if (!String.IsNullOrWhiteSpace(options.exemptionFile)) { string fileName = options.exemptionFile; var c = fileName[fileName.Length - 1]; if (c == '+' || c == '-') { fileName = options.exemptionFile.Remove(fileName.Length - 1); } if (!File.Exists(fileName)) { Console.WriteLine("Specified exemption file '{0}' not found.", fileName); } } if (options.stub != null) { Console.WriteLine("/s is no longer used to specify stub assemblies"); return(errorReturnValue); } if (options.modelExceptions == 1 && !options.wholeProgram) { Console.WriteLine("can specify a precise modeling of exceptions only when doing whole program analysis"); return(errorReturnValue); } if (options.breakIntoDebugger) { System.Diagnostics.Debugger.Launch(); } #endregion var assemblyNames = options.assemblies; if (assemblyNames == null || assemblyNames.Count == 0) { assemblyNames = new List <string>(); foreach (var g in options.GeneralArguments) { assemblyNames.Add(g); } } #region If an exclusion file has been specified, read in each line as a regular expression List <Regex> exemptionList = null; bool whiteList = false; if (!String.IsNullOrWhiteSpace(options.exemptionFile)) { int i = 0; exemptionList = new List <Regex>(); string fileName = options.exemptionFile; var c = fileName[fileName.Length - 1]; whiteList = true; if (c == '+' || c == '-') { fileName = options.exemptionFile.Remove(fileName.Length - 1); if (c == '-') { whiteList = false; } } try { // Create an instance of StreamReader to read from a file. // The using statement also closes the StreamReader. using (StreamReader sr = new StreamReader(fileName)) { String line; // Read and display lines from the file until the end of // the file is reached. while ((line = sr.ReadLine()) != null) { exemptionList.Add(new Regex(line)); i++; } //Console.WriteLine("Read {0} lines from the exclusion file '{1}'.", // i, options.exemptionFile); } } catch (Exception e) { Console.WriteLine("Something went wrong reading the exclusion file '{0}'; read in {1} lines, continuing processing.", fileName, i); Console.WriteLine(e.Message); } } #endregion try { HeapFactory heap; switch (options.heapRepresentation) { case Options.HeapRepresentation.splitFields: heap = new SplitFieldsHeap(); break; case Options.HeapRepresentation.general: heap = new GeneralHeap(); break; default: Console.WriteLine("Unknown setting for /heap"); return(1); } var pgm = TranslateAssembly(assemblyNames, heap, options, exemptionList, whiteList); var fileName = assemblyNames[0]; fileName = Path.GetFileNameWithoutExtension(fileName); string outputFileName = fileName + ".bpl"; // Microsoft.Boogie.TokenTextWriter writer = new Microsoft.Boogie.TokenTextWriter("_" + outputFileName); Microsoft.Boogie.TokenTextWriter writer = new Microsoft.Boogie.TokenTextWriter(outputFileName); Prelude.Emit(writer); pgm.Emit(writer); writer.Close(); return(0); // return Inline(outputFileName); } catch (Exception e) { // swallow everything and just return an error code Console.WriteLine("The byte-code translator failed: {0}", e.Message); Console.WriteLine("Stack trace: {0}", e.StackTrace); return(-1); } }