Beispiel #1
0
        public override IEnumerable <ProofState> EvalInit(Statement statement, ProofState state0)
        {
            Contract.Assume(statement is WhileStmt);
            var whileStmt = statement as WhileStmt;

            if (whileStmt != null)
            {
                var tryEval = EvalExpr.EvalTacticExpression(state0, whileStmt.Guard);
                if (tryEval == null)
                {
                    yield break;
                }

                if (!(tryEval is LiteralExpr && (tryEval as LiteralExpr).Value is bool))
                {
                    var state = state0.Copy();
                    var st    = SimpExpr.SimpTacticExpr(state, statement);
                    state.NeedVerify = true;
                    state.AddStatement(st);
                    yield return(state);

                    yield break;
                }
                else
                {
                    var state     = state0.Copy();
                    var whileCtrl = this.Copy();

                    whileCtrl._guard = whileStmt.Guard;
                    whileCtrl._body  = whileStmt.Body.Body;

                    if ((bool)(tryEval as LiteralExpr).Value)
                    {
                        // insert the control frame
                        var dummyBody = new List <Statement> {
                            whileStmt
                        };
                        whileCtrl.InitBasicFrameCtrl(dummyBody, true, null, VerifyN);
                        state.AddNewFrame(whileCtrl);

                        //insert the body frame
                        var bodyFrame = new DefaultTacticFrameCtrl();
                        bodyFrame.InitBasicFrameCtrl(whileCtrl._body, whileCtrl.IsPartial, null, VerifyN);
                        state.AddNewFrame(bodyFrame);
                    }

                    yield return(state);
                }
            }
        }
Beispiel #2
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);
        }
Beispiel #3
0
        public override IEnumerable <ProofState> EvalStep(ProofState state0)
        {
            var tryEval = EvalExpr.EvalTacticExpression(state0, _guard);

            if (tryEval == null)
            {
                yield break;
            }

            var state       = state0.Copy();
            var literalExpr = tryEval as LiteralExpr;

            if (literalExpr != null && (bool)literalExpr.Value)
            {
                //insert the body frame
                var bodyFrame = new DefaultTacticFrameCtrl();
                bodyFrame.InitBasicFrameCtrl(_body, state.IsCurFramePartial(), null, VerifyN);
                state.AddNewFrame(bodyFrame);
            }
            else
            {
                state.NeedVerify = true;
            }
            yield return(state);
        }
Beispiel #4
0
        public override IEnumerable <ProofState> EvalStep(ProofState state0)
        {
            var state = state0.Copy();

            var stmt      = GetStmt() as TacticCasesBlockStmt;
            var framectrl = new DefaultTacticFrameCtrl();

            if (stmt != null)
            {
                framectrl.InitBasicFrameCtrl(stmt.Body.Body, state0.IsCurFramePartial(), null, VerifyN);
            }
            state.AddNewFrame(framectrl);

            var idx = GetNthCaseIdx(RawCodeList);

            if (_matchStmt != null)
            {
                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.NeedVerify = true;
            yield return(state);
        }
Beispiel #5
0
        public override IEnumerable <ProofState> Generate(Statement statement, ProofState state)
        {
            var tvds = statement as TacticVarDeclStmt;
            AssignSuchThatStmt suchThat = null;

            if (tvds != null)
            {
                suchThat = tvds.Update as AssignSuchThatStmt;
            }
            else if (statement is AssignSuchThatStmt)
            {
                suchThat = (AssignSuchThatStmt)statement;
            }
            else
            {
                Contract.Assert(false, "Unexpected statement type");
            }
            Contract.Assert(suchThat != null, "Unexpected statement type");

            BinaryExpr bexp   = suchThat.Expr as BinaryExpr;
            var        locals = new List <string>();

            if (tvds == null)
            {
                foreach (var item in suchThat.Lhss)
                {
                    if (item is IdentifierExpr)
                    {
                        var id = (IdentifierExpr)item;
                        if (state.ContainTacnyVal(id.Name))
                        {
                            locals.Add(id.Name);
                        }
                        else
                        {
                            //TODO: error
                        }
                    }
                }
            }
            else
            {
                locals = new List <string>(tvds.Locals.Select(x => x.Name).ToList());
            }
            // this will cause issues when multiple variables are used
            // as the variables are updated one at a time
            foreach (var local in locals)
            {
                foreach (var item in ResolveExpression(state, bexp, local))
                {
                    var copy = state.Copy();
                    copy.UpdateTacnyVar(local, item);
                    yield return(copy);
                }
            }
        }
Beispiel #6
0
        public override IEnumerable <ProofState> EvalInit(Statement statement, ProofState state0)
        {
            var state     = state0.Copy();
            var blockStmt = statement as Dafny.BlockStmt;

            if (blockStmt != null)
            {
                var frameCtrl = new DefaultTacticFrameCtrl();
                frameCtrl.InitBasicFrameCtrl(blockStmt.Body, true, null, VerifyN);
                state.AddNewFrame(frameCtrl);
                yield return(state);
            }
        }
Beispiel #7
0
        private IEnumerable <object> ResolveExpression(ProofState state, Expression expr, string declaration)
        {
            Contract.Requires(expr != null);

            if (expr is BinaryExpr)
            {
                BinaryExpr bexp = (BinaryExpr)expr;
                switch (bexp.Op)
                {
                case BinaryExpr.Opcode.In:
                    // Contract.Assert(var != null, Error.MkErr(bexp, 6, declaration.Name));
                    //  Contract.Assert(var.Name == declaration.Name, Error.MkErr(bexp, 6, var.Name));
                    foreach (var result in Interpreter.EvalTacnyExpression(state, bexp.E1))
                    {
                        if (result is IEnumerable)
                        {
                            foreach (var item in (IEnumerable)result)
                            {
                                yield return(item);
                            }
                        }
                    }
                    yield break;

                case BinaryExpr.Opcode.And:
                    // for each item in the resolved lhs of the expression
                    foreach (var item in ResolveExpression(state, bexp.E0, declaration))
                    {
                        var copy = state.Copy();
                        copy.AddTacnyVar(declaration, item);
                        // resolve the rhs expression
                        foreach (var res in Interpreter.EvalTacnyExpression(copy, bexp.E1))
                        {
                            LiteralExpr lit = res as LiteralExpr;
                            // sanity check
                            Contract.Assert(lit != null);
                            if (lit.Value is bool)
                            {
                                // if resolved to true
                                if ((bool)lit.Value)
                                {
                                    yield return(item);
                                }
                            }
                        }
                    }
                    yield break;
                }
            }
        }
Beispiel #8
0
        public override IEnumerable <ProofState> EvalInit(Statement statement, ProofState state0)
        {
            var tryBlockStmt = statement as TacticTryBlockStmt;

            if (tryBlockStmt != null)
            {
                _stmt     = tryBlockStmt;
                _oriState = state0;
                this.InitBasicFrameCtrl(tryBlockStmt.Body.Body, true, null, VerifyN);

                var state = state0.Copy();
                state.AddNewFrame(this);
                yield return(state);
            }
        }
Beispiel #9
0
        public override IEnumerable <ProofState> EvalInit(Statement statement, ProofState state0)
        {
            Contract.Assume(statement != null);
            Contract.Assume(MatchStmt(statement, state0));
            //Contract.Requires(statement is TacticCasesBlockStmt);

            bool partial = true;

            List <BlockStmt> choices = new List <BlockStmt>();

            var stmt = statement as IfStmt;

            if (stmt != null)
            {
                var ifstmt = stmt;
                if (ifstmt.Thn != null)
                {
                    choices.Add(ifstmt.Thn as BlockStmt);
                }
                if (ifstmt.Els != null)
                {
                    choices.Add(ifstmt.Els as BlockStmt);
                }
            }
            var alternativeStmt = statement as AlternativeStmt;

            if (alternativeStmt != null)
            {
                var ifstmt = alternativeStmt;
                foreach (GuardedAlternative a in ifstmt.Alternatives)
                {
                    if (a.Body != null && a.Body.Count != 0)
                    {
                        choices.Add(new BlockStmt(a.Body.First().Tok, a.Body.Last().EndTok, a.Body));
                    }
                }
            }
            foreach (BlockStmt choice in choices)
            {
                var state    = state0.Copy();
                var orChoice = this.Copy();
                orChoice.InitBasicFrameCtrl(choice.Body, partial, null, VerifyN);
                state.AddNewFrame(orChoice);
                yield return(state);
            }
        }
Beispiel #10
0
    private IEnumerable<object> ResolveExpression(ProofState state, Expression expr, string declaration) {
      Contract.Requires(expr != null);

      if (expr is BinaryExpr) {

        BinaryExpr bexp = (BinaryExpr) expr;
        switch (bexp.Op) {
          case BinaryExpr.Opcode.In:
           // Contract.Assert(var != null, Error.MkErr(bexp, 6, declaration.Name));
          //  Contract.Assert(var.Name == declaration.Name, Error.MkErr(bexp, 6, var.Name));
            foreach (var result in Interpreter.EvaluateTacnyExpression(state, bexp.E1)) {
              if (result is IEnumerable) {
                foreach (var item in (IEnumerable)result) {
                  yield return item;
                }
              }
            }
            yield break;
          case BinaryExpr.Opcode.And:
            // for each item in the resolved lhs of the expression
            foreach (var item in ResolveExpression(state, bexp.E0, declaration)) {
              var copy = state.Copy();
              copy.AddLocal(declaration, item);
              // resolve the rhs expression
              foreach (var res in Interpreter.EvaluateTacnyExpression(copy, bexp.E1)) {
                LiteralExpr lit = res as LiteralExpr;
                // sanity check
                Contract.Assert(lit != null);
                if (lit.Value is bool) {
                  // if resolved to true
                  if ((bool)lit.Value) {
                    yield return item;
                  }
                }
              }
            }
            yield break;
        }
      }
    }
Beispiel #11
0
    public override IEnumerable<ProofState> Generate(Statement statement, ProofState state) {
      var tvds = statement as TacticVarDeclStmt;
      AssignSuchThatStmt suchThat = null;
      if (tvds != null)
        suchThat = tvds.Update as AssignSuchThatStmt;
      else if (statement is AssignSuchThatStmt) {
        suchThat = (AssignSuchThatStmt)statement;
      } else {
        Contract.Assert(false, "Unexpected statement type");
      }
      Contract.Assert(suchThat != null, "Unexpected statement type");

      BinaryExpr bexp = suchThat.Expr as BinaryExpr;
      var locals = new List<string>();
      if (tvds == null) {
        foreach (var item in suchThat.Lhss) {
          if (item is IdentifierExpr) {
            var id = (IdentifierExpr)item;
            if (state.HasLocalValue(id.Name))
              locals.Add(id.Name);
            else {
              //TODO: error
            }
          }
        }
      }
      else {
        locals = new List<string>(tvds.Locals.Select(x => x.Name).ToList());
      }
      // this will cause issues when multiple variables are used
      // as the variables are updated one at a time
      foreach (var local in locals) {
        foreach (var item in ResolveExpression(state, bexp, local)) {
          var copy = state.Copy();
          copy.UpdateLocal(local, item);
          yield return copy;
        }
      }
    }
Beispiel #12
0
        public override IEnumerable <ProofState> Generate(Statement statement, ProofState state)
        {
            List <List <IVariable> > args  = new List <List <IVariable> >();
            List <IVariable>         mdIns = new List <IVariable>();
            List <Expression>        callArguments;
            bool branchGenerated = false;

            state.NeedVerify = true;

            InitArgs(state, statement, out callArguments);

            /**********************
            * init lemmas
            **********************/
            //check the number of arguments
            if (callArguments == null || callArguments.Count != 2)
            {
                state.ReportTacticError(statement.Tok, " The number of arguments for explore is not correct, expect 2.");
                yield break;
            }
            // get the first arg: a sequence of lemmas
            var members0 = EvalExpr.EvalTacticExpression(state, callArguments[0]) as SeqDisplayExpr;

            if (members0 == null)
            {
                state.ReportTacticError(statement.Tok, Printer.ExprToString(callArguments[0]) + " is not a sequence.");
                yield break;
            }
            List <MemberDecl> members = new List <MemberDecl>();

            foreach (var mem in members0.Elements)
            {
                if (!(mem is TacticLiteralExpr))
                {
                    state.ReportTacticError(statement.Tok,
                                            "In " + Printer.ExprToString(callArguments[0]) +
                                            Printer.ExprToString(mem) + " is not a lemma.");
                    yield break;
                }
                var key = (string)(mem as TacticLiteralExpr).Value;
                if (state.Members.ContainsKey(key))
                {
                    members.Add(state.Members[key]);
                }
                else
                {
                    state.ReportTacticError(statement.Tok,
                                            "In " + Printer.ExprToString(callArguments[0]) + ", " +
                                            key + " is not a lemma.");
                    yield break;
                }
            }
            if (members.Count == 0)
            {
                branchGenerated = true;
                yield return(state);

                yield break;
            }

            foreach (var member in members)
            {
                mdIns.Clear();
                args.Clear();

                var md = (MemberDecl)member;

                // take the membed decl parameters
                var method = md as Method;
                if (method != null)
                {
                    mdIns.AddRange(method.Ins);
                }
                else if (md is Function)
                {
                    mdIns.AddRange(((Function)md).Formals);
                }
                else
                {
                    state.ReportTacticError(statement.Tok,
                                            Printer.ExprToString(callArguments[0]) + " is neither a Method or a Function");
                    yield break;
                }

                /**********************
                * init args for lemmas
                **********************/
                var ovars = EvalExpr.EvalTacticExpression(state, callArguments[1]) as SeqDisplayExpr;
                if (ovars == null)
                {
                    state.ReportTacticError(statement.Tok, Printer.ExprToString(callArguments[1]) + " is not a sequence.");
                    yield break;
                }

                List <IVariable> vars = new List <IVariable>();

                foreach (var var in ovars.Elements)
                {
                    string key;
                    if (var is TacticLiteralExpr)
                    {
                        key = (string)(var as TacticLiteralExpr).Value;
                    }
                    else if (var is NameSegment)
                    {
                        key = (var as NameSegment).Name;
                    }
                    else
                    {
                        state.ReportTacticError(statement.Tok,
                                                "In " + Printer.ExprToString(callArguments[1]) + ", " +
                                                Printer.ExprToString(var) + " is not a dafny variable.");
                        yield break;
                    }

                    if (state.GetAllDafnyVars().ContainsKey(key))
                    {
                        vars.Add(state.GetAllDafnyVars()[key].Variable);
                    }
                    else
                    {
                        state.ReportTacticError(statement.Tok,
                                                "In " + Printer.ExprToString(callArguments[1]) + ", " +
                                                key + " is not in scope.");
                        yield break;
                    }
                }

                //for the case of no args, just add an empty list
                if (mdIns.Count == 0)
                {
                    args.Add(new List <IVariable>());
                }
                //if any of the arguements is not valid, set it to false.
                bool flag = true;
                for (int i = 0; i < mdIns.Count; i++)
                {
                    var item = mdIns[i];
                    args.Add(new List <IVariable>());
                    foreach (var arg in vars)
                    {
                        // get variable type
                        Type type = state.GetDafnyVarType(arg.Name);
                        if (type != null)
                        {
                            if (type is UserDefinedType && item.Type is UserDefinedType)
                            {
                                var udt1 = type as UserDefinedType;
                                var udt2 = (UserDefinedType)item.Type;
                                if (udt1.Name == udt2.Name)
                                {
                                    args[i].Add(arg);
                                }
                            }
                            else
                            {
                                // if variable type and current argument types match, or the type is yet to be inferred
                                if (item.Type.ToString() == type.ToString() || type is InferredTypeProxy)
                                {
                                    args[i].Add(arg);
                                }
                            }
                        }
                        else
                        {
                            args[i].Add(arg);
                        }
                    }

                    /**
                     * if no type correct variables have been added we can return
                     * because we won't be able to generate valid calls
                     */
                    if (args[i].Count == 0)
                    {
                        flag = false;
                    }
                }
                // permute lemma call for the current lemma
                if (flag)
                {
                    foreach (var result in PermuteArguments(args, 0, new List <NameSegment>()))
                    {
                        // create new fresh list of items to remove multiple references to the same object
                        List <Expression> newList = result.Cast <Expression>().ToList().Copy();
                        ApplySuffix       aps     = new ApplySuffix(callArguments[0].tok,
                                                                    new NameSegment(callArguments[0].tok, md.Name, null),
                                                                    newList);

                        var        newState = state.Copy();
                        UpdateStmt us       = new UpdateStmt(aps.tok, aps.tok, new List <Expression>(),
                                                             new List <AssignmentRhs> {
                            new ExprRhs(aps)
                        });
                        newState.AddStatement(us);
                        branchGenerated = true;
                        yield return(newState);
                    }
                }
            }
            // for the case when no lemma call is generated.
            if (!branchGenerated)
            {
                yield return(state);
            }
        }
Beispiel #13
0
        public override IEnumerable <ProofState> EvalInit(Statement statement, ProofState state0)
        {
            bool partial = true;
            List <Tuple <Expression, List <Statement> > > guardBodyList = new List <Tuple <Expression, List <Statement> > >();

            int counter = 0;

            guardBodyList = GetGuadBodyList(statement, guardBodyList);
            Contract.Assert(guardBodyList.Count > 0);

            var tryEval = EvalExpr.EvalTacticExpression(state0, guardBodyList[0].Item1);

            if (tryEval == null)
            {
                yield break;
            }
            //check whether the top level of the first guard is tactic level or object level
            if (!(tryEval is LiteralExpr && (tryEval as LiteralExpr).Value is bool))
            {
                var state = state0.Copy();
                var st    = SimpExpr.SimpTacticExpr(state, statement);
                state.NeedVerify = true;
                state.AddStatement(st);
                yield return(state);

                yield break;
            }
            else
            {
                // tactic if
                foreach (var item in guardBodyList)
                {
                    if (item.Item1 == null && counter == 0) //else branch and no other branch is satisfied.
                    {
                        counter++;
                        var state    = state0.Copy();
                        var ifChoice = this.Copy();
                        ifChoice.InitBasicFrameCtrl(item.Item2, partial, null, VerifyN);
                        state.AddNewFrame(ifChoice);

                        yield return(state);
                    }
                    else
                    {
                        var res = EvalExpr.EvalTacticExpression(state0, item.Item1);
                        if (res == null)
                        {
                            yield break;
                        }
                        if (res is LiteralExpr &&
                            (res as LiteralExpr).Value is bool &&
                            (bool)(res as LiteralExpr).Value)
                        {
                            counter++;
                            var state    = state0.Copy();
                            var ifChoice = this.Copy();
                            ifChoice.InitBasicFrameCtrl(item.Item2, partial, null, VerifyN);
                            state.AddNewFrame(ifChoice);
                            yield return(state);
                        }
                    }
                }
                //no condition can be found, then do nothing
                if (counter == 0)
                {
                    yield return(state0.Copy());
                }
            }
        }
Beispiel #14
0
    public override IEnumerable<ProofState> Generate(Statement statement, ProofState state) {
      List<List<IVariable>> args = new List<List<IVariable>>();
      List<IVariable> mdIns = new List<IVariable>();
      List<Expression> callArguments;
      IVariable lv;
      InitArgs(state, statement, out lv, out callArguments);

      state.IfVerify = true;


      //TODO: implement this properly
      //var members = state.GetLocalValue(callArguments[0] as NameSegment) as IEnumerable<MemberDecl>;
      //evaluate the argument (methods/lemma)
      var members0 = Interpreter.EvalTacnyExpression(state, callArguments[0]).GetEnumerator();
      members0.MoveNext();
      var members = members0.Current as List<MemberDecl>;

      if (members == null){
        yield break;
      }

      foreach(var member in members) {
        MemberDecl md;
        mdIns.Clear();
        args.Clear();

        if(member is NameSegment) {
          //TODO:
          Console.WriteLine("double check this");
          md = null;
          // md = state.GetDafnyProgram().  Members.FirstOrDefault(i => i.Key == (member as NameSegment)?.Name).Value;
        } else {
          md = member as MemberDecl;
        }

        // take the membed decl parameters
        var method = md as Method;
        if(method != null)
          mdIns.AddRange(method.Ins);
        else if(md is Microsoft.Dafny.Function)
          mdIns.AddRange(((Microsoft.Dafny.Function)md).Formals);
        else
          Contract.Assert(false, "In Explore Atomic call," + callArguments[0] + "is neither a Method or a Function");

        //evaluate the arguemnts for the lemma to be called
        var instArgs = Interpreter.EvalTacnyExpression(state, callArguments[1]);
        foreach(var ovars in instArgs) {
          Contract.Assert(ovars != null, "In Explore Atomic call," + callArguments[1] + "is not variable");

          List<IVariable> vars = ovars as List<IVariable> ?? new List<IVariable>();
          //Contract.Assert(vars != null, Util.Error.MkErr(call_arguments[0], 1, typeof(List<IVariable>)));

          //for the case when no args, just add an empty list
          if (mdIns.Count == 0){
            args.Add(new List<IVariable>());
          }
          for(int i = 0; i < mdIns.Count; i++) {
            var item = mdIns[i];
            args.Add(new List<IVariable>());
            foreach(var arg in vars) {
              // get variable type
              Type type = state.GetDafnyVarType(arg.Name);
              if(type != null) {
                if(type is UserDefinedType && item.Type is UserDefinedType) {
                  var udt1 = type as UserDefinedType;
                  var udt2 = item.Type as UserDefinedType;
                  if(udt1.Name == udt2.Name)
                    args[i].Add(arg);
                } else {
                  // if variable type and current argument types match, or the type is yet to be inferred
                  if(item.Type.ToString() == type.ToString() || type is InferredTypeProxy)
                    args[i].Add(arg);
                }
              } else
                args[i].Add(arg);
            }
            /**
             * if no type correct variables have been added we can safely return
             * because we won't be able to generate valid calls
             */
            if(args[i].Count == 0) {
              Debug.WriteLine("No type matching variables were found");
              yield break;
            }
          }

          foreach(var result in PermuteArguments(args, 0, new List<NameSegment>())) {
            // create new fresh list of items to remove multiple references to the same object
            List<Expression> newList = result.Cast<Expression>().ToList().Copy();
            //TODO: need to double check wirh Vito, why can't use copy ?
            //Util.Copy.CopyExpressionList(result.Cast<Expression>().ToList());
            ApplySuffix aps = new ApplySuffix(callArguments[0].tok, new NameSegment(callArguments[0].tok, md.Name, null),
              newList);
            if(lv != null) {
              var newState = state.Copy();
              newState.AddTacnyVar(lv, aps);
              yield return newState;
            } else {
              var newState = state.Copy();
              UpdateStmt us = new UpdateStmt(aps.tok, aps.tok, new List<Expression>(),
                new List<AssignmentRhs> { new ExprRhs(aps) });
              //Printer p = new Printer(Console.Out);
              //p.PrintStatement(us,0);
              newState.AddStatement(us);
              yield return newState;
            }
          }
        }
      }
    }
Beispiel #15
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);
        }
Beispiel #16
0
        public override IEnumerable <ProofState> Generate(Statement statement, ProofState state)
        {
            AssignSuchThatStmt suchThat = null;

            if (statement is AssignSuchThatStmt)
            {
                suchThat = (AssignSuchThatStmt)statement;
            }
            else
            {
                state.ReportTacticError(statement.Tok, "Unexpected statement for suchthat(:|)");
                yield break;
            }

            var nameExpr = suchThat.Lhss[0];

            if (nameExpr is IdentifierExpr)
            {
                var id = nameExpr as IdentifierExpr;
                name = id.Name;
            }
            else if (nameExpr is NameSegment)
            {
                var id = nameExpr as NameSegment;
                if (!state.ContainTVal(id.Name))
                {
                    state.ReportTacticError(statement.Tok, "Fail to register variable " + id.Name);
                    yield break;
                }
                else
                {
                    name = id.Name;
                }
            }
            else
            {
                state.ReportTacticError(statement.Tok, "Fail to register variable.");
                yield break;
            }

            string errInfo;
            //  var expr = Expr.SimpExpr.SimpTacticExpr(state, suchThat.Expr);
            var expr = suchThat.Expr;

            /*
             * if (!CheckExpr(expr, out errInfo)) {
             * state.ReportTacticError(statement.Tok, "Unexpceted expression in suchthat statement: " + errInfo);
             * yield break;
             * }*/
            Expression pos, neg, pred;

            if (!RewriteExpr(expr as BinaryExpr, out pos, out neg, out pred))
            {
                state.ReportTacticError(expr.tok, "Syntax error in Suchthat expression.");
                yield break;
            }
            if (pos != null)
            {
                pos = EvalExpr.EvalTacticExpression(state, pos);
                if (pos == null)
                {
                    yield break;
                }
            }

            if (neg != null)
            {
                neg = EvalExpr.EvalTacticExpression(state, neg);
                if (neg == null)
                {
                    yield break;
                }
            }

            if (pos == null)
            {
                state.ReportTacticError(statement.Tok, "Suchthat expression is evaluated as an empty sequence.");
                yield break;
            }
            if (pos is SeqDisplayExpr)
            {
                if (neg != null && !(neg is SeqDisplayExpr))
                {
                    state.ReportTacticError(statement.Tok, "Unexpceted expression in suchthat statement.");
                    yield break;
                }
                var eles = EvalExpr.RemoveDup((pos as SeqDisplayExpr).Elements);
                if (eles.Count == 0)
                {
                    state.ReportTacticError(statement.Tok, "The expression is evaluated as an empty set.");
                    yield break;
                }

                foreach (var item in eles)
                {
                    var copy = state.Copy();
                    copy.UpdateTacticVar(name, item);

                    if (neg != null)
                    {
                        var inNeg = EvalExpr.EvalTacticExpression(state,
                                                                  new BinaryExpr(new Token(TacnyDriver.TacticCodeTokLine, 0),
                                                                                 BinaryExpr.Opcode.In, item, neg));
                        if (inNeg is LiteralExpr && (inNeg as LiteralExpr).Value is bool)
                        {
                            if ((bool)(inNeg as LiteralExpr).Value)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            throw new Exception("A unhandled error orrurs when evaluating a suchtaht statement");
                        }
                    }
                    if (pred != null)
                    {
                        var value = new BinaryExpr(new Token(TacnyDriver.TacticCodeTokLine, 0),
                                                   BinaryExpr.Opcode.Eq, suchThat.Lhss[0].Copy(), item);
                        var candidate = new BinaryExpr(new Token(TacnyDriver.TacticCodeTokLine, 0), BinaryExpr.Opcode.Add, value, pred);
                        var res       = EvalExpr.EvalTacticExpression(copy, pred);
                        Console.WriteLine(Printer.ExprToString(res));
                        if (res is LiteralExpr && (res as LiteralExpr).Value is bool)
                        {
                            if (!(bool)(res as LiteralExpr).Value)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            throw new Exception("A unhandled error orrurs when evaluating a suchtaht statement");
                        }
                    }

                    yield return(copy);
                }
            }
            else
            {
                state.ReportTacticError(statement.Tok, "Unexpceted expression in suchthat statement.");
                yield break;
            }
        }
Beispiel #17
0
        public override IEnumerable <ProofState> Generate(Statement statement, ProofState state)
        {
            List <List <IVariable> > args  = new List <List <IVariable> >();
            List <IVariable>         mdIns = new List <IVariable>();
            List <Expression>        callArguments;
            IVariable lv;

            InitArgs(state, statement, out lv, out callArguments);

            state.IfVerify = true;


            //TODO: implement this properly
            //var members = state.GetLocalValue(callArguments[0] as NameSegment) as IEnumerable<MemberDecl>;
            //evaluate the argument (methods/lemma)
            var members0 = Interpreter.EvalTacnyExpression(state, callArguments[0]).GetEnumerator();

            members0.MoveNext();
            var members = members0.Current as List <MemberDecl>;

            if (members == null)
            {
                yield break;
            }

            foreach (var member in members)
            {
                MemberDecl md;
                mdIns.Clear();
                args.Clear();

                if (member is NameSegment)
                {
                    //TODO:
                    Console.WriteLine("double check this");
                    md = null;
                    // md = state.GetDafnyProgram().  Members.FirstOrDefault(i => i.Key == (member as NameSegment)?.Name).Value;
                }
                else
                {
                    md = member as MemberDecl;
                }

                // take the membed decl parameters
                var method = md as Method;
                if (method != null)
                {
                    mdIns.AddRange(method.Ins);
                }
                else if (md is Microsoft.Dafny.Function)
                {
                    mdIns.AddRange(((Microsoft.Dafny.Function)md).Formals);
                }
                else
                {
                    Contract.Assert(false, "In Explore Atomic call," + callArguments[0] + "is neither a Method or a Function");
                }

                //evaluate the arguemnts for the lemma to be called
                var instArgs = Interpreter.EvalTacnyExpression(state, callArguments[1]);
                foreach (var ovars in instArgs)
                {
                    Contract.Assert(ovars != null, "In Explore Atomic call," + callArguments[1] + "is not variable");

                    List <IVariable> vars = ovars as List <IVariable> ?? new List <IVariable>();
                    //Contract.Assert(vars != null, Util.Error.MkErr(call_arguments[0], 1, typeof(List<IVariable>)));

                    //for the case when no args, just add an empty list
                    if (mdIns.Count == 0)
                    {
                        args.Add(new List <IVariable>());
                    }
                    for (int i = 0; i < mdIns.Count; i++)
                    {
                        var item = mdIns[i];
                        args.Add(new List <IVariable>());
                        foreach (var arg in vars)
                        {
                            // get variable type
                            Type type = state.GetDafnyVarType(arg.Name);
                            if (type != null)
                            {
                                if (type is UserDefinedType && item.Type is UserDefinedType)
                                {
                                    var udt1 = type as UserDefinedType;
                                    var udt2 = item.Type as UserDefinedType;
                                    if (udt1.Name == udt2.Name)
                                    {
                                        args[i].Add(arg);
                                    }
                                }
                                else
                                {
                                    // if variable type and current argument types match, or the type is yet to be inferred
                                    if (item.Type.ToString() == type.ToString() || type is InferredTypeProxy)
                                    {
                                        args[i].Add(arg);
                                    }
                                }
                            }
                            else
                            {
                                args[i].Add(arg);
                            }
                        }

                        /**
                         * if no type correct variables have been added we can safely return
                         * because we won't be able to generate valid calls
                         */
                        if (args[i].Count == 0)
                        {
                            Debug.WriteLine("No type matching variables were found");
                            yield break;
                        }
                    }

                    foreach (var result in PermuteArguments(args, 0, new List <NameSegment>()))
                    {
                        // create new fresh list of items to remove multiple references to the same object
                        List <Expression> newList = result.Cast <Expression>().ToList().Copy();
                        //TODO: need to double check wirh Vito, why can't use copy ?
                        //Util.Copy.CopyExpressionList(result.Cast<Expression>().ToList());
                        ApplySuffix aps = new ApplySuffix(callArguments[0].tok, new NameSegment(callArguments[0].tok, md.Name, null),
                                                          newList);
                        if (lv != null)
                        {
                            var newState = state.Copy();
                            newState.AddTacnyVar(lv, aps);
                            yield return(newState);
                        }
                        else
                        {
                            var        newState = state.Copy();
                            UpdateStmt us       = new UpdateStmt(aps.tok, aps.tok, new List <Expression>(),
                                                                 new List <AssignmentRhs> {
                                new ExprRhs(aps)
                            });
                            //Printer p = new Printer(Console.Out);
                            //p.PrintStatement(us,0);
                            newState.AddStatement(us);
                            yield return(newState);
                        }
                    }
                }
            }
        }