Exemple #1
0
 /// <summary>
 /// Insert the statement as is into the state
 /// </summary>
 /// <param name="stmt"></param>
 /// <param name="state"></param>
 /// <returns></returns>
 private static IEnumerable <ProofState> DefaultAction(Statement stmt, ProofState state)
 {
     Contract.Requires <ArgumentNullException>(stmt != null, "stmt");
     Contract.Requires <ArgumentNullException>(state != null, "state");
     state.AddStatement(stmt);
     yield return(state.Copy());
 }
Exemple #2
0
 internal static VerifyResult VerifyState(ProofState state, ErrorReporterDelegate er) {
   if (_proofList == null)
     _proofList = new List<ProofState>();
   if (_proofList.Count + 1 < SolutionCounter) {
     _proofList.Add(state);
     return VerifyResult.Cached;
   } else {
     _proofList.Add(state);
     var bodyList = new Dictionary<ProofState, BlockStmt>();
     foreach (var proofState in _proofList) {
       bodyList.Add(proofState, Util.InsertCode(proofState,
         new Dictionary<UpdateStmt, List<Statement>>() {
           {proofState.TacticApplication, proofState.GetGeneratedCode()}
         }));
     }
     var memberList = Util.GenerateMembers(state, bodyList);
     var prog = Util.GenerateDafnyProgram(state, memberList.Values.ToList());
     var result = Util.ResolveAndVerify(prog, errorInfo => { er?.Invoke(new CompoundErrorInformation(errorInfo.Tok, errorInfo.Msg, errorInfo, state)); });
     if (result.Count == 0)
       return VerifyResult.Verified;
     else {
       //TODO: find which proof state verified (if any)
       //TODO: update verification results
       
       //  er();
       return VerifyResult.Failed;
     }
   }
 }
Exemple #3
0
        private static IEnumerable <ProofState> UpdateLocalValue(UpdateStmt us, ProofState state)
        {
            Contract.Requires <ArgumentNullException>(us != null, "stmt");
            Contract.Requires <ArgumentNullException>(state != null, "state");
            Contract.Requires <ArgumentException>(state.IsLocalAssignment(us), "stmt");

            foreach (var item in us.Rhss)
            {
                int index = us.Rhss.IndexOf(item);
                Contract.Assert(us.Lhss.ElementAtOrDefault(index) != null, "register var err");
                var exprRhs = item as ExprRhs;
                if (exprRhs?.Expr is ApplySuffix)
                {
                    var aps = (ApplySuffix)exprRhs.Expr;
                    foreach (var result in EvaluateTacnyExpression(state, aps))
                    {
                        state.UpdateLocal(((NameSegment)us.Lhss[index]).Name, result);
                    }
                }
                else if (exprRhs?.Expr is Dafny.LiteralExpr)
                {
                    state.UpdateLocal(((NameSegment)us.Lhss[index]).Name, (Dafny.LiteralExpr)exprRhs?.Expr);
                }
                else
                {
                    state.UpdateLocal(((NameSegment)us.Lhss[index]).Name, exprRhs?.Expr);
                }
            }
            yield return(state.Copy());
        }
Exemple #4
0
        public IEnumerable <ProofState> Search(ProofState state, ErrorReporterDelegate er)
        {
            Contract.Requires <ArgumentNullException>(state != null, "rootState");

            IEnumerable <ProofState> enumerable;

            switch (ActiveStrategy)
            {
            case Strategy.Bfs:
                enumerable = BreadthFirstSeach.Search(state, er);
                break;

            case Strategy.Dfs:
                enumerable = DepthFirstSeach.Search(state, er);
                break;

            case Strategy.Undefined:
                throw new tcce.UnreachableException();

            default:
                enumerable = DepthFirstSeach.Search(state, er);
                break;
            }
            return(enumerable);
        }
Exemple #5
0
        /*
         * private static IEnumerable<ProofState> ResolveFlowControlStmt(Statement stmt, ProofState state) {
         *   Language.FlowControlStmt fcs = null;
         *   if(stmt is IfStmt) {
         *     //fcs = new Language.IfStmt();
         *     //TODO: if statemenet
         *   } else if(stmt is WhileStmt) {
         *     //TODO: while statemenet
         *   } else {
         *     Contract.Assert(false);
         *     return null;
         *   }
         *   return fcs.Generate(stmt, state);
         * }
         */

        public static IEnumerable <ProofState> EvalTacApp(UpdateStmt stmt, ProofState state)
        {
            var state0 = state.Copy();

            state0.InitTacFrame(stmt, true);
            yield return(state0);
        }
Exemple #6
0
    public static VerifyResult VerifyState(ProofState state, ErrorReporterDelegate er) {
      // at the momemnt,we don't propagate errors from buanches to user, no need to use er, in the future this will
      // come to play when repair kicks in

      var prog =  Util.GenerateResolvedProg(state);
      if (prog == null)
        return VerifyResult.Unresolved;

   //   ErrorReporterDelegate tmp_er =
     //   errorInfo => { er?.Invoke(new CompoundErrorInformation(errorInfo.Tok, errorInfo.Msg, errorInfo, state)); };
      var result = Util.VerifyResolvedProg(prog, null);
/*
      ErrorReporterDelegate tmp_er =
        errorInfo => { er?.Invoke(new CompoundErrorInformation(errorInfo.Tok, errorInfo.Msg, errorInfo, state)); };
      var boogieProg = Util.Translate(prog, prog.Name, tmp_er);
      PipelineStatistics stats;
      List<ErrorInformation> errorList;

      //Console.WriteLine("call verifier in Tacny !!!");
      PipelineOutcome tmp = Util.BoogiePipeline(boogieProg,
        new List<string> { prog.Name }, prog.Name, tmp_er,
        out stats, out errorList, prog);
*/

      if(result)
        return VerifyResult.Verified;
      else {
        return VerifyResult.Failed;
      }
    }
Exemple #7
0
        public static Dictionary <ProofState, MemberDecl> GenerateMembers(ProofState state, Dictionary <ProofState, BlockStmt> bodies)
        {
            Contract.Requires <ArgumentNullException>(state != null, "state");
            Contract.Requires <ArgumentNullException>(bodies != null, "bodies");
            var result = new Dictionary <ProofState, MemberDecl>();
            var cl     = new Cloner();

            foreach (var body in bodies)
            {
                var md = cl.CloneMember(state.TargetMethod) as Method;
                md.Body.Body.Clear();
                md.Body.Body.AddRange(body.Value.Body);
                if (result.Values.All(x => x.Name != md.Name))
                {
                    result.Add(body.Key, md);
                }
                else
                {
                    md = new Method(md.tok, FreshMemberName(md, result.Values.ToList()), md.HasStaticKeyword, md.IsGhost, md.TypeArgs, md.Ins,
                                    md.Outs, md.Req, md.Mod, md.Ens, md.Decreases, md.Body, md.Attributes, md.SignatureEllipsis);
                    result.Add(body.Key, md);
                }
            }
            return(result);
        }
Exemple #8
0
        public static Program GenerateDafnyProgram(ProofState state, List <MemberDecl> newMembers)
        {
            var prog = state.GetDafnyProgram();
            var tld  = prog.DefaultModuleDef.TopLevelDecls.FirstOrDefault(x => x.Name == state.TargetMethod.EnclosingClass.Name) as ClassDecl;

            Contract.Assert(tld != null);
            var member = tld.Members.FirstOrDefault(x => x.Name == state.TargetMethod.Name);

            Contract.Assert(member != null);
            // we can safely remove the tactics
            tld.Members.RemoveAll(x => x is Tactic); //remove before else index will be wrong
            int index = tld.Members.IndexOf(member);

            tld.Members.RemoveAt(index);
            tld.Members.InsertRange(index, newMembers);
            var filePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());
            var tw       = new StreamWriter(filePath);
            var printer  = new Printer(tw);

            printer.PrintTopLevelDecls(prog.DefaultModuleDef.TopLevelDecls, 0, filePath);
            tw.Close();
            Parser.ParseOnly(new List <string>()
            {
                filePath
            }, prog.Name, out prog);
            return(prog);
        }
Exemple #9
0
 private Interpreter(Program program, Program unresolvedProgram = null) {
   Contract.Requires(tcce.NonNull(program));
   // initialize state
   _errorReporter = new ConsoleErrorReporter();
   _state = new ProofState(program, _errorReporter, unresolvedProgram);
   _frame = new Stack<Dictionary<IVariable, Type>>();
   _resultList = new Dictionary<UpdateStmt, List<Statement>>();
 }
Exemple #10
0
 public static IEnumerable <object> EvaluateLeaf(ExpressionTree expt, ProofState state)
 {
     Contract.Requires(expt != null && expt.IsLeaf());
     foreach (var item in Interpreter.EvalTacnyExpression(state, expt.Data))
     {
         yield return(item);
     }
 }
Exemple #11
0
        public new static IEnumerable <ProofState> Search(ProofState state)
        {
            return(null);

            /*
             * Stack<IEnumerator<Solution>> solutionStack = new Stack<IEnumerator<Solution>>();
             *
             * if (atomic != null)
             * solutionStack.Push(Atomic.ResolveStatement(new Solution(atomic)).GetEnumerator());
             *
             * while (true) {
             * if (solutionStack.Count == 0) {
             *
             * yield break;
             * }
             *
             * var solutionEnum = solutionStack.Pop();
             *
             * // if the solution is fully resolved skip resolution
             * if (!solutionEnum.MoveNext())
             * continue;
             *
             * var solution = solutionEnum.Current;
             * solutionStack.Push(solutionEnum);
             * if (solution.IsEvaluated()) {
             * if (verify) {
             *  if (VerifyState(solution)) {
             *    yield return solution;
             *    yield break;
             *  }
             * }
             * else {
             *  yield return solution;
             * }
             * }
             * else if (solution.State.DynamicContext.isPartialyResolved) {
             * if (verify) {
             *  if (VerifyState(solution)) {
             *    yield return solution;
             *    yield break;
             *  }
             *  solutionStack.Push(Atomic.ResolveStatement(solution).GetEnumerator());
             * }
             * else {
             *  solutionStack.Push(Atomic.ResolveStatement(solution).GetEnumerator());
             *  yield return solution;
             * }
             * }
             * else {
             * solutionStack.Push(Atomic.ResolveStatement(solution).GetEnumerator());
             * }
             *
             *
             *
             * }
             */
        }
Exemple #12
0
        public static IEnumerable <IList <Expression> > ResolveDisplayExpression(ProofState state, DisplayExpression list)
        {
            Contract.Requires <ArgumentNullException>(state != null, "state");
            Contract.Requires <ArgumentNullException>(list != null, "list");
            Contract.Ensures(Contract.Result <IEnumerable <IList <Expression> > >() != null);
            var dict = list.Elements.ToDictionary(element => element, element => EvaluateTacnyExpression(state, element));

            return(GenerateList(dict, null));
        }
Exemple #13
0
 private Interpreter(Program program, Program unresolvedProgram = null)
 {
     Contract.Requires(tcce.NonNull(program));
     // initialize state
     _errorReporter = new ConsoleErrorReporter();
     _state         = new ProofState(program, _errorReporter, unresolvedProgram);
     _frame         = new Stack <Dictionary <IVariable, Type> >();
     _resultList    = new Dictionary <UpdateStmt, List <Statement> >();
 }
Exemple #14
0
        public static bool IsPartial(ProofState state, UpdateStmt tacticApplication)
        {
            //still need to check the localtion of the application, is it the last call ? is it a neswted call ?
            if (state.FrameCtrlInfo.IsPartial)
            {
                return(true);
            }

            return(tacticApplication.Rhss[0].Attributes != null && ParsePartialAttribute(tacticApplication.Rhss[0].Attributes));
        }
Exemple #15
0
        public static void PrepareFrame(BlockStmt body, ProofState state)
        {
            Contract.Requires <ArgumentNullException>(body != null, "body");
            Contract.Requires <ArgumentNullException>(state != null, "state");
            state.AddNewFrame(body);
            // call the search engine
            var search = new BaseSearchStrategy(state.TacticInfo.SearchStrategy, true);

            search.Search(state, _errorReporterDelegate);
            state.RemoveFrame();
        }
Exemple #16
0
        public static ProofState ApplyTactic(ProofState state, Dictionary <IVariable, Type> variables,
                                             UpdateStmt tacticApplication)
        {
            Contract.Requires <ArgumentNullException>(tcce.NonNull(variables));
            Contract.Requires <ArgumentNullException>(tcce.NonNull(tacticApplication));
            Contract.Requires <ArgumentNullException>(state != null, "state");
            state.InitState(tacticApplication, variables);
            var search = new BaseSearchStrategy(state.TacticInfo.SearchStrategy, true);

            return(search.Search(state, _errorReporterDelegate).FirstOrDefault());
        }
Exemple #17
0
 public static IEnumerable<ProofState> EvalNextControlFlow(Statement stmt, ProofState state) {
   IEnumerable<ProofState> ret;
   switch(state.GetCurFrameTyp()) {
     case "tmatch":
       ret = new Match().EvalNext(stmt as TacnyCasesBlockStmt, state);
       break;
     default:
       ret = null;
       break;
   }
   return ret;
 }
Exemple #18
0
 public IEnumerable<ProofState> Search(ProofState state, ErrorReporterDelegate er) {
   Contract.Requires<ArgumentNullException>(state != null, "rootState");
   
   switch (ActiveStrategy) {
     case Strategy.Bfs:
       return BreadthFirstSeach.Search(state, er);
     case Strategy.Dfs:
       return DepthFirstSeach.Search(state);
     case Strategy.Undefined:
       throw new tcce.UnreachableException();
     default:
       return BreadthFirstSeach.Search(state, er);
   }
 }
Exemple #19
0
        public static IEnumerable <ProofState> EvalStep(ProofState state)
        {
            Contract.Requires <ArgumentNullException>(state != null, "state");
            // one step
            // call the
            IEnumerable <ProofState> enumerable = null;
            var stmt = state.GetStmt();

            if (stmt is TacticVarDeclStmt)
            {
                enumerable = RegisterVariable(stmt as TacticVarDeclStmt, state);
            }
            else if (stmt is UpdateStmt)
            {
                var us = stmt as UpdateStmt;
                if (state.IsLocalAssignment(us))
                {
                    enumerable = UpdateLocalValue(us, state);
                }
                else if (state.IsArgumentApplication(us))
                {
                    //TODO: argument application
                }
                else if (state.IsTacticCall(us))
                {
                    enumerable = ApplyNestedTactic(state.Copy(), state.DafnyVars(), us);
                }
            }
            else if (stmt is AssignSuchThatStmt)
            {
                enumerable = EvaluateSuchThatStmt((AssignSuchThatStmt)stmt, state);
            }
            else if (stmt is PredicateStmt)
            {
                enumerable = ResolvePredicateStmt((PredicateStmt)stmt, state);
            }
            else if (stmt is TStatement || stmt is IfStmt || stmt is WhileStmt)
            {
                //TODO:
            }
            else
            {
                enumerable = DefaultAction(stmt, state);
            }

            foreach (var item in enumerable)
            {
                yield return(item.Copy());
            }
        }
Exemple #20
0
        public static IEnumerable <ProofState> ApplyNestedTactic(ProofState state, Dictionary <IVariable, Type> variables,
                                                                 UpdateStmt tacticApplication)
        {
            Contract.Requires <ArgumentNullException>(tcce.NonNull(variables));
            Contract.Requires <ArgumentNullException>(tcce.NonNull(tacticApplication));
            Contract.Requires <ArgumentNullException>(state != null, "state");
            state.InitState(tacticApplication, variables);
            var search = new BaseSearchStrategy(state.TacticInfo.SearchStrategy, false);

            foreach (var result in search.Search(state, _errorReporterDelegate))
            {
                var c = state.Copy();
                c.AddStatementRange(result.GetGeneratedCode());
                yield return(c);
            }
        }
Exemple #21
0
        protected Expression EvaluateExpression(ExpressionTree expt, ProofState state)
        {
            Contract.Requires(expt != null);
            if (expt.IsLeaf())
            {
                return(EvaluateLeaf(expt, state) as LiteralExpr);
            }
            var bexp = (BinaryExpr)expt.Data;

            if (BinaryExpr.IsEqualityOp(bexp.Op))
            {
                bool boolVal = EvaluateEqualityExpression(expt, state);
                return(new LiteralExpr(new Token(), boolVal));
            }
            var lhs = EvaluateExpression(expt.LChild, state) as LiteralExpr;
            var rhs = EvaluateExpression(expt.RChild, state) as LiteralExpr;
            // for now asume lhs and rhs are integers
            var l = (BigInteger)lhs?.Value;
            var r = (BigInteger)rhs?.Value;

            BigInteger res = 0;


            switch (bexp.Op)
            {
            case BinaryExpr.Opcode.Sub:
                res = BigInteger.Subtract(l, r);
                break;

            case BinaryExpr.Opcode.Add:
                res = BigInteger.Add(l, r);
                break;

            case BinaryExpr.Opcode.Mul:
                res = BigInteger.Multiply(l, r);
                break;

            case BinaryExpr.Opcode.Div:
                res = BigInteger.Divide(l, r);
                break;
            }

            return(new LiteralExpr(lhs.tok, res));
        }
Exemple #22
0
        /// <summary>
        /// Insert generated code into a method
        /// </summary>
        /// <param name="state"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public static BlockStmt InsertCode(ProofState state, Dictionary <UpdateStmt, List <Statement> > code)
        {
            Contract.Requires <ArgumentNullException>(state != null, "state");
            Contract.Requires <ArgumentNullException>(code != null, "code");
            var prog = state.GetDafnyProgram();
            var tld  = prog.DefaultModuleDef.TopLevelDecls.FirstOrDefault(x => x.Name == state.ActiveClass.Name) as ClassDecl;

            Contract.Assert(tld != null);
            var member = tld.Members.FirstOrDefault(x => x.Name == state.TargetMethod.Name) as Method;
            var body   = member?.Body;

            foreach (var kvp in code)
            {
                body = InsertCodeInternal(body, kvp.Value, kvp.Key);
            }
            var r = new Resolver(prog);

            r.ResolveProgram(prog);
            return(body);
        }
Exemple #23
0
        internal static VerifyResult VerifyState(ProofState state, ErrorReporterDelegate er)
        {
            if (_proofList == null)
            {
                _proofList = new List <ProofState>();
            }
            if (_proofList.Count + 1 < SolutionCounter)
            {
                _proofList.Add(state);
                return(VerifyResult.Cached);
            }
            else
            {
                _proofList.Add(state);
                var bodyList = new Dictionary <ProofState, BlockStmt>();
                foreach (var proofState in _proofList)
                {
                    bodyList.Add(proofState, Util.InsertCode(proofState,
                                                             new Dictionary <UpdateStmt, List <Statement> >()
                    {
                        { proofState.TacticApplication, proofState.GetGeneratedCode() }
                    }));
                }
                var memberList = Util.GenerateMembers(state, bodyList);
                var prog       = Util.GenerateDafnyProgram(state, memberList.Values.ToList());
                var result     = Util.ResolveAndVerify(prog, errorInfo => { er?.Invoke(new CompoundErrorInformation(errorInfo.Tok, errorInfo.Msg, errorInfo, state)); });
                if (result.Count == 0)
                {
                    return(VerifyResult.Verified);
                }
                else
                {
                    //TODO: find which proof state verified (if any)
                    //TODO: update verification results

                    //  er();
                    return(VerifyResult.Failed);
                }
            }
        }
Exemple #24
0
        public static bool IsResolvable(ExpressionTree expt, ProofState state)
        {
            Contract.Requires(expt.IsRoot());
            var leafs = expt.GetLeafData();

            if (leafs == null)
            {
                throw new ArgumentNullException(nameof(leafs));
            }

            foreach (var leaf in leafs)
            {
                if (leaf is NameSegment)
                {
                    var ns = leaf as NameSegment;
                    if (state.ContainTacnyVal(ns))
                    {
                        var local = state.GetTacnyVarValue(ns);
                        if (local is ApplySuffix || local is IVariable || local is NameSegment || local is Statement)
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else if (!(leaf is LiteralExpr))
                {
                    if (leaf is ApplySuffix)
                    {
                        return(false);
                    }
                }
            }
            return(true);
        }
Exemple #25
0
        public static VerifyResult VerifyState(ProofState state, ErrorReporterDelegate er)
        {
            // at the momemnt,we don't propagate errors from buanches to user, no need to use er, in the future this will
            // come to play when repair kicks in

            var prog = Util.GenerateResolvedProg(state);

            if (prog == null)
            {
                return(VerifyResult.Unresolved);
            }

            //   ErrorReporterDelegate tmp_er =
            //   errorInfo => { er?.Invoke(new CompoundErrorInformation(errorInfo.Tok, errorInfo.Msg, errorInfo, state)); };
            var result = Util.VerifyResolvedProg(prog, null);

/*
 *    ErrorReporterDelegate tmp_er =
 *      errorInfo => { er?.Invoke(new CompoundErrorInformation(errorInfo.Tok, errorInfo.Msg, errorInfo, state)); };
 *    var boogieProg = Util.Translate(prog, prog.Name, tmp_er);
 *    PipelineStatistics stats;
 *    List<ErrorInformation> errorList;
 *
 *    //Console.WriteLine("call verifier in Tacny !!!");
 *    PipelineOutcome tmp = Util.BoogiePipeline(boogieProg,
 *      new List<string> { prog.Name }, prog.Name, tmp_er,
 *      out stats, out errorList, prog);
 */

            if (result)
            {
                return(VerifyResult.Verified);
            }
            else
            {
                return(VerifyResult.Failed);
            }
        }
Exemple #26
0
 public static IEnumerable<ProofState> RegisterVariable(TacticVarDeclStmt declaration, ProofState state) {
   if(declaration.Update == null)
     yield break;
   var rhs = declaration.Update as UpdateStmt;
   if(rhs == null) {
     // check if rhs is SuchThatStmt
     if(declaration.Update is AssignSuchThatStmt) {
       foreach(var item in declaration.Locals)
         state.AddTacnyVar(item, null);
       foreach(var item in EvalSuchThatStmt(declaration.Update as AssignSuchThatStmt, state)) {
         yield return item.Copy();
       }
     } else {
       foreach(var item in declaration.Locals)
         state.AddTacnyVar(item, null);
     }
   } else {
     foreach(var item in rhs.Rhss) {
       int index = rhs.Rhss.IndexOf(item);
       Contract.Assert(declaration.Locals.ElementAtOrDefault(index) != null, "register var err");
       var exprRhs = item as ExprRhs;
       if(exprRhs?.Expr is ApplySuffix) {
         var aps = (ApplySuffix)exprRhs.Expr;
         foreach(var result in EvalTacnyExpression(state, aps)) {
           state.AddTacnyVar(declaration.Locals[index], result);
         }
       } else if(exprRhs?.Expr is Dafny.LiteralExpr) {
         state.AddTacnyVar(declaration.Locals[index], (Dafny.LiteralExpr)exprRhs?.Expr);
       } else if(exprRhs?.Expr is Dafny.NameSegment) {
         var name = ((Dafny.NameSegment)exprRhs.Expr).Name;
         if(state.ContainTacnyVal(name))
           // in the case that referring to an exisiting tvar, dereference it
           state.AddTacnyVar(declaration.Locals[index], state.GetTacnyVarValue(name));
       } else {
         state.AddTacnyVar(declaration.Locals[index], exprRhs?.Expr);
       }
     }
   }
   yield return state.Copy();
 }
Exemple #27
0
        public static bool EvaluateEqualityExpression(ExpressionTree expt, ProofState state)
        {
            Contract.Requires(expt != null);
            // if the node is leaf, cast it to bool and return
            if (expt.IsLeaf())
            {
                var lit = EvaluateLeaf(expt, state) as LiteralExpr;
                return(lit?.Value is bool && (bool)lit.Value);
            }
            // left branch only
            if (expt.LChild != null && expt.RChild == null)
            {
                return(EvaluateEqualityExpression(expt.LChild, state));
            }
            // if there is no more nesting resolve the expression
            if (expt.LChild.IsLeaf() && expt.RChild.IsLeaf())
            {
                LiteralExpr lhs = null;
                LiteralExpr rhs = null;
                lhs = EvaluateLeaf(expt.LChild, state).FirstOrDefault() as LiteralExpr;
                rhs = EvaluateLeaf(expt.RChild, state).FirstOrDefault() as LiteralExpr;
                Contract.Assert(lhs != null && rhs != null);
                var bexp = expt.Data as BinaryExpr;
                int res  = -1;
                if (lhs?.Value is BigInteger)
                {
                    var l = (BigInteger)lhs.Value;
                    var r = (BigInteger)rhs?.Value;
                    res = l.CompareTo(r);
                }
                else if (lhs?.Value is string)
                {
                    var l = (string)lhs.Value;
                    var r = rhs?.Value as string;
                    res = string.Compare(l, r, StringComparison.Ordinal);
                }
                else if (lhs?.Value is bool)
                {
                    res = ((bool)lhs.Value).CompareTo(rhs?.Value != null && (bool)rhs?.Value);
                }

                switch (bexp.Op)
                {
                case BinaryExpr.Opcode.Eq:
                    return(res == 0);

                case BinaryExpr.Opcode.Neq:
                    return(res != 0);

                case BinaryExpr.Opcode.Ge:
                    return(res >= 0);

                case BinaryExpr.Opcode.Gt:
                    return(res > 0);

                case BinaryExpr.Opcode.Le:
                    return(res <= 0);

                case BinaryExpr.Opcode.Lt:
                    return(res < 0);
                }
            }
            else
            {
                // evaluate a nested expression

                var bexp = expt.Data as BinaryExpr;
                switch (bexp.Op)
                {
                case BinaryExpr.Opcode.And:
                    return(EvaluateEqualityExpression(expt.LChild, state) &&
                           EvaluateEqualityExpression(expt.RChild, state));

                case BinaryExpr.Opcode.Or:
                    return(EvaluateEqualityExpression(expt.LChild, state) ||
                           EvaluateEqualityExpression(expt.RChild, state));
                }
            }
            return(false);
        }
Exemple #28
0
    public IEnumerable<ProofState> EvalInit(Statement statement, ProofState state0){
      Contract.Requires(statement != null);
      Contract.Requires(statement is TacnyCasesBlockStmt);
      var state = state0.Copy();

      var stmt = statement as TacnyCasesBlockStmt;
      var p = new Printer(Console.Out);
      NameSegment caseVar;

      //get guards
      Debug.Assert(stmt != null, "stmt != null");
      var guard = stmt.Guard as ParensExpression;

      if(guard == null)
        caseVar = stmt.Guard as NameSegment;
      else
        caseVar = guard.E as NameSegment;

      //TODO: need to check the datatype pf caseGuard, 
      // also need to consider the case that caseVar is a tac var
      var srcVar = state.GetTacnyVarValue(caseVar) as NameSegment;
      var srcVarData = state.GetDafnyVar(srcVar.Name);
      var datatype = state.GetDafnyVarType(srcVar.Name).AsDatatype;


      //generate a test program to check which cases need to apply tacny
      bool[] ctorFlags;
      int ctor; // current active match case
      InitCtorFlags(datatype, out ctorFlags);

      List<Func<int, List<Statement>>> fList = new List<Func<int, List<Statement>>>();

      int i;
      for(i = 0; i < datatype.Ctors.Count; i++) {
        fList.Add(GenerateAssumeFalseStmtAsStmtList);
      }

      //var matchStmt = GenerateMatchStmt(state.TacticApplication.Tok.line, srcVar.Copy(), datatype, fList);
      var matchStmt = GenerateMatchStmt(Interpreter.TACNY_CODE_TOK_LINE, srcVar.Copy(), datatype, fList);

      //use a dummystmt to creat a frame for match, note that this stmts is never be evaluated
      var dummystmt = new List<Statement>();
      for(i = 0; i < datatype.Ctors.Count; i++) {
        dummystmt.Add(stmt);
      }

      state.AddNewFrame(dummystmt, IsPartial, Signature);
      //add raw[0]
      state.AddStatement(matchStmt);

      //push a frame for the first case
      //TODO: add case variable to frame, so that variable () can refer to it
      state.AddNewFrame(stmt.Body.Body, IsPartial);

      foreach(var tmp in matchStmt.Cases[0].CasePatterns) {
        state.AddDafnyVar(tmp.Var.Name, new ProofState.VariableData { Variable = tmp.Var, Type = tmp.Var.Type });
      }
      //with this flag set to true, dafny will check the case brnach before evaluates any tacny code
      state.IfVerify = true;
      yield return state;
    }
Exemple #29
0
    internal new static IEnumerable<ProofState> Search(ProofState rootState, ErrorReporterDelegate er) {

      var queue = new Queue<IEnumerator<ProofState>>();
      queue.Enqueue(Interpreter.EvalStep(rootState).GetEnumerator());
      while (queue.Count > 0) {
        // remove first enumerator on the queue
        var enumerator = queue.Dequeue();
        // if all the statements have been resolve skip
        if (!enumerator.MoveNext())
          continue;

        var proofState = enumerator.Current;
        queue.Enqueue(enumerator);

        if (Verify) {
          if (proofState.IsEvaluated() || proofState.IsPartiallyEvaluated()) {
            switch (VerifyState(proofState, er)) {
              case VerifyResult.Cached:
                if (proofState.IsPartiallyEvaluated()) {
                  yield return proofState;
                  queue.Enqueue(Interpreter.EvalStep(proofState).GetEnumerator());
                }
                continue;
              case VerifyResult.Verified:
                yield return proofState;
                yield break;
              case VerifyResult.Failed:
                /*
                * verification failed, but the evaluation is partial return
                * but continue evaluating the proofState
                */
                if (proofState.IsPartiallyEvaluated()) {
                  yield return proofState;
                  queue.Enqueue(Interpreter.EvalStep(proofState).GetEnumerator());
                }
                continue;
              default:
                throw new ArgumentOutOfRangeException();
            }
          }
          queue.Enqueue(Interpreter.EvalStep(proofState).GetEnumerator());
        } else {
          if (!(proofState.IsEvaluated() || proofState.IsPartiallyEvaluated()))
            queue.Enqueue(Interpreter.EvalStep(proofState).GetEnumerator());
          else {
            yield return proofState;
            if (proofState.IsPartiallyEvaluated()) {
              queue.Enqueue(Interpreter.EvalStep(proofState).GetEnumerator());
            }
          }
        }
      }
    }
Exemple #30
0
        public static IEnumerable <object> EvaluateTacnyExpression(ProofState state, Expression expr)
        {
            Contract.Requires <ArgumentNullException>(state != null, "state");
            Contract.Requires <ArgumentNullException>(expr != null, "expr");
            if (expr is NameSegment)
            {
                var ns = (NameSegment)expr;
                if (state.HasLocalValue(ns.Name))
                {
                    yield return(state.GetLocalValue(ns.Name));
                }
                else
                {
                    yield return(ns);
                }
            }
            else if (expr is ApplySuffix)
            {
                var aps = (ApplySuffix)expr;
                if (state.IsTacticCall(aps))
                {
                    var us = new UpdateStmt(aps.tok, aps.tok, new List <Expression>()
                    {
                        aps.Lhs
                    },
                                            new List <AssignmentRhs>()
                    {
                        new ExprRhs(aps)
                    });
                    foreach (var item in ApplyNestedTactic(state, state.DafnyVars(), us).Select(x => x.GetGeneratedCode()))
                    {
                        yield return(item);
                    }
                }
                // rewrite the expression
                if (aps.Lhs is ExprDotName)
                {
                    foreach (var item in EvaluateTacnyExpression(state, aps.Lhs))
                    {
                        if (item is Expression)
                        {
                            yield return(new ApplySuffix(aps.tok, (Expression)item, aps.Args));
                        }
                        else
                        {
                            Contract.Assert(false, "Unexpected ExprNotName case");
                        }
                    }
                }
                else
                {
                    // try to evaluate as tacny expression
                    string sig = Util.GetSignature(aps);
                    // using reflection find all classes that extend EAtomic
                    var types =
                        Assembly.GetAssembly(typeof(EAtomic.EAtomic)).GetTypes().Where(t => t.IsSubclassOf(typeof(EAtomic.EAtomic)));
                    foreach (var type in types)
                    {
                        var resolverInstance = Activator.CreateInstance(type) as EAtomic.EAtomic;
                        if (sig == resolverInstance?.Signature)
                        {
                            //TODO: validate input countx
                            foreach (var item in resolverInstance?.Generate(aps, state))
                            {
                                yield return(item);
                            }
                        }
                        // if we reached this point, rewrite  the apply suffix
                        foreach (var item in EvaluateTacnyExpression(state, aps.Lhs))
                        {
                            if (!(item is NameSegment))
                            {
                                //TODO: warning
                            }
                            else
                            {
                                var argList = new List <Expression>();
                                foreach (var arg in aps.Args)
                                {
                                    foreach (var result in EvaluateTacnyExpression(state, arg))
                                    {
                                        if (result is Expression)
                                        {
                                            argList.Add(result as Expression);
                                        }
                                        else
                                        {
                                            argList.Add(Util.VariableToExpression(result as IVariable));
                                        }
                                        break;
                                    }
                                }
                                yield return(new ApplySuffix(aps.tok, aps.Lhs, argList));
                            }
                        }
                    }
                }
            }
            else if (expr is ExprDotName)
            {
                var edn = (ExprDotName)expr;
                var ns  = edn.Lhs as NameSegment;
                if (ns != null && state.ContainsVariable(ns))
                {
                    var newLhs = state.GetLocalValue(ns);
                    var lhs    = newLhs as Expression;
                    if (lhs != null)
                    {
                        yield return(new ExprDotName(edn.tok, lhs, edn.SuffixName, edn.OptTypeArguments));
                    }
                }
                yield return(edn);
            }
            else if (expr is UnaryOpExpr)
            {
                var op = (UnaryOpExpr)expr;
                foreach (var result in EvaluateTacnyExpression(state, op.E))
                {
                    switch (op.Op)
                    {
                    case UnaryOpExpr.Opcode.Cardinality:
                        if (!(result is IEnumerable))
                        {
                            var resultExp = result is IVariable
                  ? Util.VariableToExpression(result as IVariable)
                  : result as Expression;

                            yield return(new UnaryOpExpr(op.tok, op.Op, resultExp));
                        }
                        else
                        {
                            var enumerator = result as IList;
                            if (enumerator != null)
                            {
                                yield return(new Dafny.LiteralExpr(op.tok, enumerator.Count));
                            }
                        }
                        yield break;

                    case UnaryOpExpr.Opcode.Not:
                        if (result is Dafny.LiteralExpr)
                        {
                            var lit = (Dafny.LiteralExpr)result;
                            if (lit.Value is bool)
                            {
                                // inverse the bool value
                                yield return(new Dafny.LiteralExpr(op.tok, !(bool)lit.Value));
                            }
                            else
                            {
                                Contract.Assert(false);
                                //TODO: error message
                            }
                        }
                        else
                        {
                            var resultExp = result is IVariable?Util.VariableToExpression(result as IVariable) : result as Expression;

                            yield return(new UnaryOpExpr(op.tok, op.Op, resultExp));
                        }
                        yield break;

                    default:
                        Contract.Assert(false, "Unsupported Unary Operator");
                        yield break;
                    }
                }
            }
            else if (expr is DisplayExpression)
            {
                var dexpr = (DisplayExpression)expr;
                if (dexpr.Elements.Count == 0)
                {
                    yield return(dexpr.Copy());
                }
                else
                {
                    foreach (var item in ResolveDisplayExpression(state, dexpr))
                    {
                        yield return(item);
                    }
                }
            }
            else
            {
                yield return(expr);
            }
        }
Exemple #31
0
        internal new static IEnumerable <ProofState> Search(ProofState rootState, ErrorReporterDelegate er)
        {
            var stack = new Stack <IEnumerator <ProofState> >();

            stack.Push(Interpreter.EvalStep(rootState).GetEnumerator());
            IEnumerator <ProofState> enumerator = Enumerable.Empty <ProofState>().GetEnumerator();

            while (stack.Count > 0)
            {
                if (!enumerator.MoveNext())
                {
                    enumerator = stack.Pop();
                    if (!enumerator.MoveNext())
                    {
                        continue;
                    }
                }
                var proofState = enumerator.Current;
                //check if any new added coded reuqires to call verifier, or reach the last line of code
                if (proofState.IfVerify || proofState.IsEvaluated())
                {
                    proofState.IfVerify = false;
                    switch (VerifyState(proofState, er))
                    {
                    case VerifyResult.Verified:
                        proofState.MarkCurFrameAsTerminated(true);
                        if (proofState.IsTerminated())
                        {
                            yield return(proofState);

                            yield break;
                        }
                        //stack.Push(enumerator);
                        //enumerator = (Interpreter.EvalStep(proofState).GetEnumerator());
                        break;

                    case VerifyResult.Failed:
                        if (proofState.IsEvaluated())
                        {
                            proofState.MarkCurFrameAsTerminated(false);
                            if (proofState.IsTerminated())
                            {
                                yield return(proofState);

                                yield break;
                            }
                        }
                        break;

                    case VerifyResult.Unresolved:
                        //discharge current branch if fails to resolve
                        continue;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }

                /*
                 * when failed, check if this mmethod is evaluated , i.e. all tstmt are evalauted,
                 * if so, dischard this branch and continue with the next one
                 * otherwise, continue to evaluate the next stmt
                 */
                if (!proofState.IsEvaluated())
                {
                    //push the current one to the stack
                    stack.Push(enumerator);
                    //move to the next stmt
                    enumerator = (Interpreter.EvalStep(proofState).GetEnumerator());
                }
            }
        }
Exemple #32
0
        private static IEnumerable <ProofState> RegisterVariable(TacticVarDeclStmt declaration, ProofState state)
        {
            if (declaration.Update == null)
            {
                yield break;
            }
            var rhs = declaration.Update as UpdateStmt;

            if (rhs == null)
            {
                // check if rhs is SuchThatStmt
                if (declaration.Update is AssignSuchThatStmt)
                {
                    foreach (var item in declaration.Locals)
                    {
                        state.AddLocal(item, null);
                    }
                    foreach (var item in EvaluateSuchThatStmt(declaration.Update as AssignSuchThatStmt, state))
                    {
                        yield return(item.Copy());
                    }
                }
                else
                {
                    foreach (var item in declaration.Locals)
                    {
                        state.AddLocal(item, null);
                    }
                }
            }
            else
            {
                foreach (var item in rhs.Rhss)
                {
                    int index = rhs.Rhss.IndexOf(item);
                    Contract.Assert(declaration.Locals.ElementAtOrDefault(index) != null, "register var err");
                    var exprRhs = item as ExprRhs;
                    if (exprRhs?.Expr is ApplySuffix)
                    {
                        var aps = (ApplySuffix)exprRhs.Expr;
                        foreach (var result in EvaluateTacnyExpression(state, aps))
                        {
                            state.AddLocal(declaration.Locals[index], result);
                        }
                    }
                    else if (exprRhs?.Expr is Dafny.LiteralExpr)
                    {
                        state.AddLocal(declaration.Locals[index], (Dafny.LiteralExpr)exprRhs?.Expr);
                    }
                    else
                    {
                        state.AddLocal(declaration.Locals[index], exprRhs?.Expr);
                    }
                }
            }
            yield return(state.Copy());
        }
Exemple #33
0
        public static Program GenerateResolvedProg(ProofState state)
        {
            var prog = state.GetDafnyProgram();
            var r    = new Resolver(prog);

            r.ResolveProgram(prog);
            //get the generated code
            var results = new Dictionary <UpdateStmt, List <Statement> >();

            results.Add(state.TacticApplication, state.GetGeneratedCode().Copy());
            var body = Util.InsertCode(state, results);
            // find the membcl in the resoved prog
            Method dest_md = null;

            foreach (var m in prog.DefaultModuleDef.TopLevelDecls)
            {
                if (m.WhatKind == "class")
                {
                    foreach (var method in (m as DefaultClassDecl).Members)
                    {
                        if (method.FullName == state.TargetMethod.FullName)
                        {
                            dest_md = (method as Method);
                            dest_md.Body.Body.Clear();
                            dest_md.Body.Body.AddRange(body.Body);
                        }// if some other method has tactic call, then empty the body
                        else if (method.CallsTactic)
                        {
                            method.CallsTactic = false;
                            (method as Method).Body.Body.Clear();
                            SetVerifyFalseAttr(method);
                        }
                        else
                        {
                            //set other memberdecl as verify false
                            SetVerifyFalseAttr(method);
                        }
                    }
                }
            }

#if _TACTIC_DEBUG
            Console.WriteLine("*********************Verifying Tacny Generated Prog*****************");
            var printer = new Printer(Console.Out);
            //printer.PrintProgram(prog, false);
            foreach (var stmt in state.GetGeneratedCode())
            {
                printer.PrintStatement(stmt, 0);
            }
            Console.WriteLine("\n*********************Prog END*****************");
#endif

            dest_md.CallsTactic = false;
            r.SetCurClass(dest_md.EnclosingClass as ClassDecl);
            r.ResolveMethodBody(dest_md);

            if (prog.reporter.Count(ErrorLevel.Error) != 0)
            {
#if _TACTIC_DEBUG
                Console.Write("Fail to resolve prog, skip verifier ! \n");
#endif
                return(null);
            }
            else
            {
                return(prog);
            }
        }
Exemple #34
0
 public static IEnumerable<ProofState> ApplyNestedTactic(ProofState state, Dictionary<IVariable, Type> variables,
   UpdateStmt tacticApplication) {
   Contract.Requires<ArgumentNullException>(tcce.NonNull(variables));
   Contract.Requires<ArgumentNullException>(tcce.NonNull(tacticApplication));
   Contract.Requires<ArgumentNullException>(state != null, "state");
   state.InitState(tacticApplication, variables);
   var search = new BaseSearchStrategy(state.TacticInfo.SearchStrategy, false);
   foreach (var result in search.Search(state, _errorReporterDelegate)) {
     var c = state.Copy();
     c.AddStatementRange(result.GetGeneratedCode());
     yield return c;
   }
 }
Exemple #35
0
 public static ProofState ApplyTactic(ProofState state, Dictionary<IVariable, Type> variables,
   UpdateStmt tacticApplication) {
   Contract.Requires<ArgumentNullException>(tcce.NonNull(variables));
   Contract.Requires<ArgumentNullException>(tcce.NonNull(tacticApplication));
   Contract.Requires<ArgumentNullException>(state != null, "state");
   state.InitState(tacticApplication, variables);
   var search = new BaseSearchStrategy(state.TacticInfo.SearchStrategy, true);
   return search.Search(state, _errorReporterDelegate).FirstOrDefault();
 }
Exemple #36
0
        /// <summary>
        /// Resolve all variables in expression to either literal values
        /// or to orignal declared nameSegments
        /// </summary>
        /// <param name="guard"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public static IEnumerable <ExpressionTree> ResolveExpression(ExpressionTree guard, ProofState state)
        {
            Contract.Requires <ArgumentNullException>(guard != null, "guard");
            Contract.Requires <ArgumentNullException>(state != null, "state");

            if (guard.IsLeaf())
            {
                if (!(guard.Data is NameSegment))
                {
                    yield return(guard.Copy());
                }
                var newGuard = guard.Copy();
                var result   = EvaluateLeaf(newGuard, state);
                foreach (var item in result)
                {
                    Contract.Assert(result != null);
                    Expression newNs = null; // potential encapsulation problems
                    if (item is MemberDecl)
                    {
                        var md = item as MemberDecl;
                        newNs = new StringLiteralExpr(new Token(), md.Name, true);
                    }
                    else if (item is Formal)
                    {
                        var tmp = item as Formal;
                        newNs = new NameSegment(tmp.tok, tmp.Name, null);
                    }
                    else if (item is NameSegment)
                    {
                        newNs = item as NameSegment;
                    }
                    else
                    {
                        newNs = item as Expression; // Dafny.LiteralExpr;
                    }
                    newGuard.Data = newNs;
                    yield return(newGuard);
                }
            }
            else
            {
                foreach (var lChild in ResolveExpression(guard.LChild, state))
                {
                    if (guard.RChild != null)
                    {
                        foreach (var rChild in ResolveExpression(guard.RChild, state))
                        {
                            yield return(new ExpressionTree(guard.Data, null, lChild, rChild));
                        }
                    }
                    else
                    {
                        yield return(new ExpressionTree(guard.Data, null, lChild, null));
                    }
                }
            }
        }
Exemple #37
0
    /*
       private static IEnumerable<ProofState> ResolveFlowControlStmt(Statement stmt, ProofState state) {
         Language.FlowControlStmt fcs = null;
         if(stmt is IfStmt) {
           //fcs = new Language.IfStmt();
           //TODO: if statemenet
         } else if(stmt is WhileStmt) {
           //TODO: while statemenet
         } else {
           Contract.Assert(false);
           return null;
         }
         return fcs.Generate(stmt, state);
       }
   */

    public static IEnumerable<ProofState> EvalTacApp(UpdateStmt stmt, ProofState state){
      var state0 = state.Copy();
      state0.InitTacFrame(stmt, true);
      yield return state0;
    }
Exemple #38
0
 /// <summary>
 /// Insert the statement as is into the state
 /// </summary>
 /// <param name="stmt"></param>
 /// <param name="state"></param>
 /// <returns></returns>
 private static IEnumerable<ProofState> DefaultAction(Statement stmt, ProofState state) {
   Contract.Requires<ArgumentNullException>(stmt != null, "stmt");
   Contract.Requires<ArgumentNullException>(state != null, "state");
   state.AddStatement(stmt);
   yield return state.Copy();
 }
Exemple #39
0
        internal new static IEnumerable <ProofState> Search(ProofState rootState, ErrorReporterDelegate er)
        {
            var queue = new Queue <IEnumerator <ProofState> >();

            queue.Enqueue(Interpreter.EvalStep(rootState).GetEnumerator());


            IEnumerator <ProofState> enumerator = Enumerable.Empty <ProofState>().GetEnumerator();

            while (queue.Count > 0)
            {
                // check if there is any more item in the enumerartor, if so, MoveNext will move to the next item
                if (!enumerator.MoveNext())
                {
                    // if no item in the current enumerator, pop a new enumerator from the queie,
                    enumerator = queue.Dequeue();
                    // set the start point for enumulator, if there is no valid start point, i.e. empty, skip this one
                    if (!enumerator.MoveNext())
                    {
                        continue;
                    }
                }
                var proofState = enumerator.Current;
                //check if any new added code reuqires to call the dafny to verity, or reach the last line of code
                if (proofState.IfVerify || proofState.IsEvaluated())
                {
                    proofState.IfVerify = false;
                    switch (VerifyState(proofState, er))
                    {
                    case VerifyResult.Verified:
                        proofState.MarkCurFrameAsTerminated(true);
                        if (proofState.IsTerminated())
                        {
                            yield return(proofState);

                            yield break;
                        }
                        //queue.Enqueue(Interpreter.EvalStep(proofState).GetEnumerator());
                        break;

                    case VerifyResult.Failed:
                        if (proofState.IsEvaluated())
                        {
                            proofState.MarkCurFrameAsTerminated(false);
                            if (proofState.IsTerminated())
                            {
                                yield return(proofState);

                                yield break;
                            }
                        }
                        break;

                    case VerifyResult.Unresolved:
                        //discharge current branch if fails to resolve
                        continue;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                }

                /*
                 * when failed, check if this mmethod is evaluated , i.e. all tstmt are evalauted,
                 * if so, dischard this branch and continue with the next one
                 * otherwise, continue to evaluate the next stmt
                 */
                if (!proofState.IsEvaluated())
                {
                    queue.Enqueue(Interpreter.EvalStep(proofState).GetEnumerator());
                }
            }
        }
Exemple #40
0
        public static IEnumerable <ProofState> EvaluateSuchThatStmt(AssignSuchThatStmt stmt, ProofState state)
        {
            var evaluator = new Atomic.SuchThatAtomic();

            return(evaluator.Generate(stmt, state));
        }
Exemple #41
0
 public IEnumerable <ProofState> Search(ProofState state, ErrorReporterDelegate er)
 {
     Contract.Requires(state != null);
     return(default(IEnumerable <ProofState>));
 }
Exemple #42
0
    protected Expression EvaluateExpression(ExpressionTree expt, ProofState state) {
      Contract.Requires(expt != null);
      if (expt.IsLeaf()) {
        return EvaluateLeaf(expt, state) as LiteralExpr;
      }
      var bexp = (BinaryExpr) expt.Data;
      if (BinaryExpr.IsEqualityOp(bexp.Op)) {
        bool boolVal = EvaluateEqualityExpression(expt, state);
        return new LiteralExpr(new Token(), boolVal);
      }
      var lhs = EvaluateExpression(expt.LChild,state) as LiteralExpr;
      var rhs = EvaluateExpression(expt.RChild, state) as LiteralExpr;
      // for now asume lhs and rhs are integers
      var l = (BigInteger)lhs?.Value;
      var r = (BigInteger)rhs?.Value;

      BigInteger res = 0;


      switch (bexp.Op) {
        case BinaryExpr.Opcode.Sub:
          res = BigInteger.Subtract(l, r);
          break;
        case BinaryExpr.Opcode.Add:
          res = BigInteger.Add(l, r);
          break;
        case BinaryExpr.Opcode.Mul:
          res = BigInteger.Multiply(l, r);
          break;
        case BinaryExpr.Opcode.Div:
          res = BigInteger.Divide(l, r);
          break;
      }

      return new LiteralExpr(lhs.tok, res);
    }
Exemple #43
0
 public static IEnumerable<object> EvaluateLeaf(ExpressionTree expt, ProofState state) {
   Contract.Requires(expt != null && expt.IsLeaf());
   foreach (var item in Interpreter.EvaluateTacnyExpression(state, expt.Data))
     yield return item;
 }
Exemple #44
0
    internal new static IEnumerable<ProofState> Search(ProofState rootState, ErrorReporterDelegate er){
      var stack = new Stack<IEnumerator<ProofState>>();
      stack.Push(Interpreter.EvalStep(rootState).GetEnumerator());
      IEnumerator<ProofState> enumerator = Enumerable.Empty<ProofState>().GetEnumerator();

      while(stack.Count > 0) {
        if(!enumerator.MoveNext()) {
          enumerator = stack.Pop();
          if(!enumerator.MoveNext())
            continue;
        }
        var proofState = enumerator.Current;
        //check if any new added coded reuqires to call verifier, or reach the last line of code
        if(proofState.IfVerify || proofState.IsEvaluated()) {
          proofState.IfVerify = false;
          switch(VerifyState(proofState, er)) {
            case VerifyResult.Verified:
              proofState.MarkCurFrameAsTerminated(true);
              if(proofState.IsTerminated()) {
                yield return proofState;
                yield break;
             }
              //stack.Push(enumerator);
              //enumerator = (Interpreter.EvalStep(proofState).GetEnumerator());
              break;
            case VerifyResult.Failed:
              if(proofState.IsEvaluated()) {
                proofState.MarkCurFrameAsTerminated(false);
                if(proofState.IsTerminated()) {
                  yield return proofState;
                  yield break;
                }
              }
              break;
            case VerifyResult.Unresolved:
              //discharge current branch if fails to resolve
              continue;
            default:
              throw new ArgumentOutOfRangeException();
          }
        }
        /*
       * when failed, check if this mmethod is evaluated , i.e. all tstmt are evalauted,
       * if so, dischard this branch and continue with the next one
       * otherwise, continue to evaluate the next stmt
       */
        if(!proofState.IsEvaluated()) {
          //push the current one to the stack
          stack.Push(enumerator);
          //move to the next stmt
          enumerator = (Interpreter.EvalStep(proofState).GetEnumerator());
        }
      }
    }
Exemple #45
0
    public new static IEnumerable<ProofState> Search(ProofState state) {
      return null;
      /*
    Stack<IEnumerator<Solution>> solutionStack = new Stack<IEnumerator<Solution>>();

    if (atomic != null)
      solutionStack.Push(Atomic.ResolveStatement(new Solution(atomic)).GetEnumerator());

    while (true) {
      if (solutionStack.Count == 0) {

        yield break;
      }

      var solutionEnum = solutionStack.Pop();

      // if the solution is fully resolved skip resolution
      if (!solutionEnum.MoveNext())
        continue;

      var solution = solutionEnum.Current;
      solutionStack.Push(solutionEnum);
      if (solution.IsEvaluated()) {
        if (verify) {
          if (VerifyState(solution)) {
            yield return solution;
            yield break;
          }
        }
        else {
          yield return solution;
        }
      }
      else if (solution.State.DynamicContext.isPartialyResolved) {
        if (verify) {
          if (VerifyState(solution)) {
            yield return solution;
            yield break;
          }
          solutionStack.Push(Atomic.ResolveStatement(solution).GetEnumerator());
        }
        else {
          solutionStack.Push(Atomic.ResolveStatement(solution).GetEnumerator());
          yield return solution;
        }
      }
      else {
        solutionStack.Push(Atomic.ResolveStatement(solution).GetEnumerator());
      }



    }
    */
    }
Exemple #46
0
    private IEnumerable<ProofState> StmtHandler(List<Statement> stmts, ProofState state){
      IEnumerable<ProofState> enumerable = null;
      ProofState ret = state;

      foreach (var stmt in stmts){
        if (stmt is TacticVarDeclStmt){
          enumerable = Interpreter.RegisterVariable(stmt as TacticVarDeclStmt, ret);
          var e = enumerable.GetEnumerator();
          e.MoveNext();
          ret = e.Current;
        }
        else if (stmt is PredicateStmt){
          enumerable = Interpreter.EvalPredicateStmt((PredicateStmt) stmt, ret);
          var e = enumerable.GetEnumerator();
          e.MoveNext();
          ret = e.Current;
        }
      }

      foreach(var item in enumerable)
        yield return item.Copy();
    }
Exemple #47
0
 private static IEnumerable<ProofState> ResolvePredicateStmt(PredicateStmt predicate, ProofState state) {
   Contract.Requires<ArgumentNullException>(predicate != null, "predicate");
   foreach (var result in EvaluateTacnyExpression(state, predicate.Expr)) {
     var resultExpression = result is IVariable ? Util.VariableToExpression(result as IVariable) : result as Expression;
     PredicateStmt newPredicate;
     if (predicate is AssertStmt) {
       newPredicate = new AssertStmt(predicate.Tok, predicate.EndTok, resultExpression, predicate.Attributes);
     } else {
       newPredicate = new AssumeStmt(predicate.Tok, predicate.EndTok, resultExpression, predicate.Attributes);
     }
     var copy = state.Copy();
     copy.AddStatement(newPredicate);
     yield return copy;
   }
 }
Exemple #48
0
    public IEnumerable<ProofState> EvalNext(Statement statement, ProofState state0){
      Contract.Requires(statement != null);
      Contract.Requires(statement is TacnyCasesBlockStmt);
      var state = state0.Copy();

      var stmt = statement as TacnyCasesBlockStmt;
      var raw = state.GetGeneratedaRawCode();


      state.AddNewFrame(stmt.Body.Body, IsPartial);

      var matchStmt = raw[0][0] as MatchStmt;

      var idx = GetNthCaseIdx(raw);
      foreach(var tmp in matchStmt.Cases[idx].CasePatterns) {
        state.AddDafnyVar(tmp.Var.Name, new ProofState.VariableData { Variable = tmp.Var, Type = tmp.Var.Type });
      }
      //with this flag set to true, dafny will check the case branch before evaluates any tacny code
      state.IfVerify = true;
      yield return state;
     
    }
Exemple #49
0
    public static bool EvaluateEqualityExpression(ExpressionTree expt, ProofState state) {
      Contract.Requires(expt != null);
      // if the node is leaf, cast it to bool and return
      if (expt.IsLeaf()) {
        var lit = EvaluateLeaf(expt, state) as LiteralExpr;
        return lit?.Value is bool && (bool)lit.Value;
      }
      // left branch only
      if (expt.LChild != null && expt.RChild == null)
        return EvaluateEqualityExpression(expt.LChild, state);
      // if there is no more nesting resolve the expression
      if (expt.LChild.IsLeaf() && expt.RChild.IsLeaf()) {
        LiteralExpr lhs = null;
        LiteralExpr rhs = null;
        lhs = (LiteralExpr) EvaluateLeaf(expt.LChild, state).FirstOrDefault();
        rhs = EvaluateLeaf(expt.RChild, state).FirstOrDefault() as LiteralExpr;
        if (lhs?.GetType() == rhs?.GetType())
          return false;
        var bexp = expt.Data as BinaryExpr;
        int res = -1;
        if (lhs?.Value is BigInteger) {
          var l = (BigInteger)lhs.Value;
          var r = (BigInteger)rhs?.Value;
          res = l.CompareTo(r);
        } else if (lhs?.Value is string) {
          var l = (string)lhs.Value;
          var r = rhs?.Value as string;
          res = string.Compare(l, r, StringComparison.Ordinal);
        } else if (lhs?.Value is bool) {
          res = ((bool)lhs.Value).CompareTo(rhs?.Value != null && (bool)rhs?.Value);
        }

        switch (bexp.Op) {
          case BinaryExpr.Opcode.Eq:
            return res == 0;
          case BinaryExpr.Opcode.Neq:
            return res != 0;
          case BinaryExpr.Opcode.Ge:
            return res >= 0;
          case BinaryExpr.Opcode.Gt:
            return res > 0;
          case BinaryExpr.Opcode.Le:
            return res <= 0;
          case BinaryExpr.Opcode.Lt:
            return res < 0;
        }
      } else { // evaluate a nested expression

        var bexp = expt.Data as BinaryExpr;
        switch (bexp.Op) {
          case BinaryExpr.Opcode.And:
            return EvaluateEqualityExpression(expt.LChild, state) && EvaluateEqualityExpression(expt.RChild, state);
          case BinaryExpr.Opcode.Or:
            return EvaluateEqualityExpression(expt.LChild, state) || EvaluateEqualityExpression(expt.RChild, state);
        }
      }
      return false;
    }
Exemple #50
0
    public static IEnumerable<object> EvaluateTacnyExpression(ProofState state, Expression expr) {
      Contract.Requires<ArgumentNullException>(state != null, "state");
      Contract.Requires<ArgumentNullException>(expr != null, "expr");
      if (expr is NameSegment) {
        var ns = (NameSegment)expr;
        if (state.HasLocalValue(ns.Name)) {
          yield return state.GetLocalValue(ns.Name);
        } else {
          yield return ns;
        }
      } else if (expr is ApplySuffix) {
        var aps = (ApplySuffix)expr;
        if (state.IsTacticCall(aps)) {
          var us = new UpdateStmt(aps.tok, aps.tok, new List<Expression>() { aps.Lhs },
            new List<AssignmentRhs>() { new ExprRhs(aps) });
          foreach (var item in ApplyNestedTactic(state, state.DafnyVars(), us).Select(x => x.GetGeneratedCode())) {
            yield return item;
          }
        }
        // rewrite the expression
        if (aps.Lhs is ExprDotName) {
          foreach (var item in EvaluateTacnyExpression(state, aps.Lhs)) {
            if (item is Expression) {
              yield return new ApplySuffix(aps.tok, (Expression)item, aps.Args);
            } else {
              Contract.Assert(false, "Unexpected ExprNotName case");
            }
          }
        } else {
          // try to evaluate as tacny expression
          string sig = Util.GetSignature(aps);
          // using reflection find all classes that extend EAtomic
          var types =
            Assembly.GetAssembly(typeof(EAtomic.EAtomic)).GetTypes().Where(t => t.IsSubclassOf(typeof(EAtomic.EAtomic)));
          foreach (var type in types) {
            var resolverInstance = Activator.CreateInstance(type) as EAtomic.EAtomic;
            if (sig == resolverInstance?.Signature) {
              //TODO: validate input countx
              foreach (var item in resolverInstance?.Generate(aps, state))
                yield return item;
            }
            // if we reached this point, rewrite  the apply suffix
            foreach (var item in EvaluateTacnyExpression(state, aps.Lhs)) {
              if (!(item is NameSegment)) {
                //TODO: warning
              } else {
                var argList = new List<Expression>();
                foreach (var arg in aps.Args) {
                  foreach (var result in EvaluateTacnyExpression(state, arg)) {
                    if (result is Expression)
                      argList.Add(result as Expression);
                    else
                      argList.Add(Util.VariableToExpression(result as IVariable));
                    break;
                  }
                }
                yield return new ApplySuffix(aps.tok, aps.Lhs, argList);
              }
            }

          }
        }
      } else if (expr is ExprDotName) {
        var edn = (ExprDotName)expr;
        var ns = edn.Lhs as NameSegment;
        if (ns != null && state.ContainsVariable(ns)) {
          var newLhs = state.GetLocalValue(ns);
          var lhs = newLhs as Expression;
          if (lhs != null)
            yield return new ExprDotName(edn.tok, lhs, edn.SuffixName, edn.OptTypeArguments);
        }
        yield return edn;
      } else if (expr is UnaryOpExpr) {
        var op = (UnaryOpExpr)expr;
        foreach (var result in EvaluateTacnyExpression(state, op.E)) {
          switch (op.Op) {
            case UnaryOpExpr.Opcode.Cardinality:
              if (!(result is IEnumerable)) {
                var resultExp = result is IVariable
                  ? Util.VariableToExpression(result as IVariable)
                  : result as Expression;
                yield return new UnaryOpExpr(op.tok, op.Op, resultExp);
              } else {
                var enumerator = result as IList;
                if (enumerator != null)
                  yield return new Dafny.LiteralExpr(op.tok, enumerator.Count);
              }
              yield break;
            case UnaryOpExpr.Opcode.Not:
              if (result is Dafny.LiteralExpr) {
                var lit = (Dafny.LiteralExpr)result;
                if (lit.Value is bool) {
                  // inverse the bool value
                  yield return new Dafny.LiteralExpr(op.tok, !(bool)lit.Value);
                } else {
                  Contract.Assert(false);
                  //TODO: error message
                }
              } else {
                var resultExp = result is IVariable ? Util.VariableToExpression(result as IVariable) : result as Expression;
                yield return new UnaryOpExpr(op.tok, op.Op, resultExp);
              }
              yield break;
            default:
              Contract.Assert(false, "Unsupported Unary Operator");
              yield break;
          }
        }
      } else if (expr is DisplayExpression) {
        var dexpr = (DisplayExpression)expr;
        if (dexpr.Elements.Count == 0) {
          yield return dexpr.Copy();
        } else {
          foreach (var item in ResolveDisplayExpression(state, dexpr)) {
            yield return item;
          }

        }
      } else { yield return expr; }
    }
Exemple #51
0
    internal new static IEnumerable<ProofState> Search(ProofState rootState, ErrorReporterDelegate er){

      var queue = new Queue<IEnumerator<ProofState>>();
      queue.Enqueue(Interpreter.EvalStep(rootState).GetEnumerator());


      IEnumerator<ProofState> enumerator = Enumerable.Empty<ProofState>().GetEnumerator();

      while (queue.Count > 0){
        // check if there is any more item in the enumerartor, if so, MoveNext will move to the next item
        if (!enumerator.MoveNext()){
          // if no item in the current enumerator, pop a new enumerator from the queie, 
          enumerator = queue.Dequeue();
          // set the start point for enumulator, if there is no valid start point, i.e. empty, skip this one
          if (!enumerator.MoveNext())
            continue;
        }
        var proofState = enumerator.Current;
        //check if any new added code reuqires to call the dafny to verity, or reach the last line of code
        if (proofState.IfVerify || proofState.IsEvaluated()) {
          proofState.IfVerify = false;
          switch (VerifyState(proofState, er)){
            case VerifyResult.Verified:
              proofState.MarkCurFrameAsTerminated(true);
              if (proofState.IsTerminated()){
                 yield return proofState;
                 yield break;
              }
              //queue.Enqueue(Interpreter.EvalStep(proofState).GetEnumerator());
              break;
            case VerifyResult.Failed:
              if (proofState.IsEvaluated()){
                proofState.MarkCurFrameAsTerminated(false);
                if(proofState.IsTerminated()) {
                  yield return proofState;
                  yield break;
                }
              }
              break;
            case VerifyResult.Unresolved:
              //discharge current branch if fails to resolve
              continue;
            default:
              throw new ArgumentOutOfRangeException();
          }
        }
        /*
       * when failed, check if this mmethod is evaluated , i.e. all tstmt are evalauted,
       * if so, dischard this branch and continue with the next one
       * otherwise, continue to evaluate the next stmt
       */
        if(!proofState.IsEvaluated()) {
          queue.Enqueue(Interpreter.EvalStep(proofState).GetEnumerator());
        }
      }
    }
Exemple #52
0
 public static IEnumerable<IList<Expression>> ResolveDisplayExpression(ProofState state, DisplayExpression list) {
   Contract.Requires<ArgumentNullException>(state != null, "state");
   Contract.Requires<ArgumentNullException>(list != null, "list");
   Contract.Ensures(Contract.Result<IEnumerable<IList<Expression>>>() != null);
   var dict = list.Elements.ToDictionary(element => element, element => EvaluateTacnyExpression(state, element));
   return GenerateList(dict, null);
 }
Exemple #53
0
 public IEnumerable<ProofState> Search(ProofState state, ErrorReporterDelegate er) {
   Contract.Requires(state != null);
   return default(IEnumerable<ProofState>);
 }
Exemple #54
0
 public static IEnumerable<ProofState> EvaluateSuchThatStmt(AssignSuchThatStmt stmt, ProofState state) {
   var evaluator = new Atomic.SuchThatAtomic();
   return evaluator.Generate(stmt, state);
 }
Exemple #55
0
 private static IEnumerable<ProofState> RegisterVariable(TacticVarDeclStmt declaration, ProofState state) {
   if (declaration.Update == null) yield break;
   var rhs = declaration.Update as UpdateStmt;
   if (rhs == null) {
     // check if rhs is SuchThatStmt
     if (declaration.Update is AssignSuchThatStmt) {
       foreach (var item in declaration.Locals)
         state.AddLocal(item, null);
       foreach (var item in EvaluateSuchThatStmt(declaration.Update as AssignSuchThatStmt, state)) {
         yield return item.Copy();
       }
     } else {
       foreach (var item in declaration.Locals)
         state.AddLocal(item, null);
     }
   } else {
     foreach (var item in rhs.Rhss) {
       int index = rhs.Rhss.IndexOf(item);
       Contract.Assert(declaration.Locals.ElementAtOrDefault(index) != null, "register var err");
       var exprRhs = item as ExprRhs;
       if (exprRhs?.Expr is ApplySuffix) {
         var aps = (ApplySuffix)exprRhs.Expr;
         foreach (var result in EvaluateTacnyExpression(state, aps)) {
           state.AddLocal(declaration.Locals[index], result);
         }
       } else if (exprRhs?.Expr is Dafny.LiteralExpr) {
         state.AddLocal(declaration.Locals[index], (Dafny.LiteralExpr)exprRhs?.Expr);
       } else {
         state.AddLocal(declaration.Locals[index], exprRhs?.Expr);
       }
     }
   }
   yield return state.Copy();
 }
Exemple #56
0
    private static IEnumerable<ProofState> UpdateLocalValue(UpdateStmt us, ProofState state) {
      Contract.Requires<ArgumentNullException>(us != null, "stmt");
      Contract.Requires<ArgumentNullException>(state != null, "state");
      Contract.Requires<ArgumentException>(state.IsLocalAssignment(us), "stmt");

      foreach (var item in us.Rhss) {
        int index = us.Rhss.IndexOf(item);
        Contract.Assert(us.Lhss.ElementAtOrDefault(index) != null, "register var err");
        var exprRhs = item as ExprRhs;
        if (exprRhs?.Expr is ApplySuffix) {
          var aps = (ApplySuffix)exprRhs.Expr;
          foreach (var result in EvaluateTacnyExpression(state, aps)) {
            state.UpdateLocal(((NameSegment)us.Lhss[index]).Name, result);
          }
        } else if (exprRhs?.Expr is Dafny.LiteralExpr) {
          state.UpdateLocal(((NameSegment)us.Lhss[index]).Name, (Dafny.LiteralExpr)exprRhs?.Expr);
        } else {
          state.UpdateLocal(((NameSegment)us.Lhss[index]).Name, exprRhs?.Expr);
        }
      }
      yield return state.Copy();
    }
Exemple #57
0
 public static void PrepareFrame(BlockStmt body, ProofState state) {
   Contract.Requires<ArgumentNullException>(body != null, "body");
   Contract.Requires<ArgumentNullException>(state != null, "state");
   state.AddNewFrame(body);
   // call the search engine
   var search = new BaseSearchStrategy(state.TacticInfo.SearchStrategy, true);
   search.Search(state, _errorReporterDelegate);
   state.RemoveFrame();
 }
Exemple #58
0
    public static IEnumerable<ProofState> EvalPredicateStmt(PredicateStmt predicate, ProofState state) {
      Contract.Requires<ArgumentNullException>(predicate != null, "predicate");
      foreach(var result in EvalTacnyExpression(state, predicate.Expr)) {
        var resultExpression = result is IVariable ? Util.VariableToExpression(result as IVariable) : result as Expression;
        PredicateStmt newPredicate;

        var tok = predicate.Tok.Copy();
        tok.line = TACNY_CODE_TOK_LINE;

        var endTok = predicate.EndTok.Copy();
        endTok.line = TACNY_CODE_TOK_LINE;

        if(predicate is AssertStmt) {
          newPredicate = new AssertStmt(tok, endTok, resultExpression, predicate.Attributes);
        } else {
          newPredicate = new AssumeStmt(tok, endTok, resultExpression, predicate.Attributes);
        }
        var copy = state.Copy();
        copy.AddStatement(newPredicate);
        copy.IfVerify = true;
        yield return copy;
      }
    }
Exemple #59
0
 public CompoundErrorInformation(IToken tok, string msg, ErrorInformation e, ProofState s) : base(tok, msg)
 {
     E = e;
     S = s;
 }
Exemple #60
0
    public static IEnumerable<ProofState> EvalStep(ProofState state) {
      Contract.Requires<ArgumentNullException>(state != null, "state");
      // one step
      // call the 
      IEnumerable<ProofState> enumerable = null;
      var stmt = state.GetStmt();
      if (stmt is TacticVarDeclStmt) {
        enumerable = RegisterVariable(stmt as TacticVarDeclStmt, state);
      } else if (stmt is UpdateStmt) {
        var us = stmt as UpdateStmt;
        if (state.IsLocalAssignment(us)) {
          enumerable = UpdateLocalValue(us, state);
        } else if (state.IsArgumentApplication(us)) {
          //TODO: argument application
        } else if (state.IsTacticCall(us)) {
          enumerable = ApplyNestedTactic(state.Copy(), state.DafnyVars(), us);
        }
      } else if (stmt is AssignSuchThatStmt) {
        enumerable = EvaluateSuchThatStmt((AssignSuchThatStmt)stmt, state);
      } else if (stmt is PredicateStmt) {
        enumerable = ResolvePredicateStmt((PredicateStmt)stmt, state);
      } else if (stmt is TStatement || stmt is IfStmt || stmt is WhileStmt) {
                //TODO: 
      } else {
        enumerable = DefaultAction(stmt, state);
      }

      foreach (var item in enumerable)
        yield return item.Copy();
    }