예제 #1
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);
            }
        }
예제 #2
0
        public void TestMultipleStatements()
        {
            var programSource = new TokenList()
            {
                { TokenType.KwAssert },
                { TokenType.Identifier, "true" },
                { TokenType.LineTerm },
                { TokenType.Identifier, "writeln" },
                { TokenType.LParen },
                { TokenType.RParen },
                { TokenType.LineTerm }
            };
            Parser      parser  = new Parser(CreateMockScanner(programSource), new ErrorHandler());
            ProgramNode program = parser.Parse();

            var assert = new AssertStmt(0, 0);

            assert.AssertExpr = new VariableExpr(0, 0, "true");
            var call = new CallStmt(0, 0);

            call.ProcedureId = "writeln";
            expected.Block.Statements.Add(assert);
            expected.Block.Statements.Add(call);
            program.ShouldBeEquivalentTo(expected);
        }
예제 #3
0
        public void GetConditions(Method method, int offset, out AssertStmt preCond, out AssertStmt postCond)
        {
            List <Statement> body = method.Body.Body;
            List <Statement> lst  = body.Where(m => m is AssertStmt).ToList();
            int max = int.MinValue;
            int min = int.MaxValue;

            preCond  = null;
            postCond = null;
            foreach (var statement in lst)
            {
                if (statement.Tok.pos < offset)
                {
                    if (statement.Tok.pos - offset > max)
                    {
                        max     = statement.Tok.pos - offset;
                        preCond = statement as AssertStmt;
                    }
                }
                else
                if (offset - statement.Tok.pos < min)
                {
                    min      = offset - statement.Tok.pos;
                    postCond = statement as AssertStmt;
                }
            }
        }
        public string GenerateString(AssertStmt statement, int tabs)
        {
            StringBuilder bob = new StringBuilder();

            ApplyIndentation(bob, tabs);
            bob.Append(statement.Tok.val + " " + GenerateString(statement.Expr) + statement.EndTok.val);
            return(bob.ToString());
        }
        public void TestAssertWithoutBoolean()
        {
            var program = new ProgramNode(0, 0);

            program.Block = new BlockStmt(0, 0);
            var assert = new AssertStmt(0, 0);

            assert.AssertExpr = new IntLiteralExpr(0, 0, 1);
            program.Block.Statements.Add(assert);
            AssertErrorContains(program, "Assertion expression has to be of type Bool");
        }
예제 #6
0
        private void FindRemovableTypesInAssertStmt(AssertStmt assert, Statement parent, Method method)
        {
            if (!(parent is BlockStmt))
            {
                return;
            }
            var block      = (BlockStmt)parent;
            var assertWrap = new Wrap <Statement>(assert, block.Body);

            _allRemovableTypes.AddAssert(assertWrap, method);
        }
        public void TestBooleanAssert()
        {
            var program = new ProgramNode(0, 0);

            program.Block = new BlockStmt(0, 0);
            var assert = new AssertStmt(0, 0);

            assert.AssertExpr = new VariableExpr(0, 0, "true");
            program.Block.Statements.Add(assert);
            AssertNoErrors(program);
        }
예제 #8
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private void MenuItemCallback(object sender, EventArgs e)
        {
            string      message     = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);
            string      title       = "Command1";
            var         textManager = this.ServiceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager;
            IVsTextView textview;

            textManager.GetActiveView(1, null, out textview);
            var componentModel = this.ServiceProvider.GetService(typeof(SComponentModel)) as IComponentModel;
            var text           = componentModel.GetService <IVsEditorAdaptersFactoryService>().GetWpfTextView(textview);
            int selection      = text.Caret.Position.BufferPosition.Position;
            int end            = text.Selection.End.Position;
            int start          = text.Selection.Start.Position;

            //            addWhileStatement(text);
            // Show a message box to prove we were here

            /*          VsShellUtilities.ShowMessageBox(
             *            this.ServiceProvider,
             *            message,
             *            title,
             *            OLEMSGICON.OLEMSGICON_INFO,
             *            OLEMSGBUTTON.OLEMSGBUTTON_OK,
             *            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
             */
            string filename = "C:\\Users\\AboNezar\\Desktop\\Documents" +
                              "\\Visual Studio 2015\\Projects\\ConsoleApplication5\\ConsoleApplication5\\test.dfy";
            Method           m = FindMethod(filename, selection);
            List <Statement> other;
            var stmts = GetSelectedStatements(m, start, end, out other);
            List <DVariable> ins, outs, decs;

            GetVariables(stmts, other, out ins, out outs, out decs);

            AssertStmt preCond, postCond;

            GetConditions(m, selection, out preCond, out postCond);
            HashSet <DVariable> d;
            var v = GetVars(m.Body.Body, out d);

            selection = m.BodyEndTok.pos + 1;
            string s = buildMethod(preCond.ToString(), postCond.ToString());

            s = "\n" + num(m.Body.Body, new List <AssertStmt>(), new List <AssertStmt>()) + "\n";
            var textService = this.ServiceProvider.GetService(typeof(EnvDTE._DTE)) as EnvDTE._DTE;
            //           var t = textService.ActiveDocument.Object() as EnvDTE.TextDocument;
            //           t.Selection.EndOfDocument();
            //           selection = text.Caret.Position.BufferPosition.Position;
            //WriteToTextViewer(s,text, selection);
            AssertStmt astmt = m.Body.Body[0] as AssertStmt;
            var        exp   = ExtractGuard(astmt.Expr);
        }
예제 #9
0
        public void TestAssert()
        {
            var programSource = new TokenList()
            {
                { TokenType.KwAssert },
                { TokenType.LParen },
                { TokenType.Identifier, "true" },
                { TokenType.RParen }
            };
            Parser      parser  = new Parser(CreateMockScanner(programSource), new ErrorHandler());
            ProgramNode program = parser.Parse();

            var assert = new AssertStmt(0, 0);

            assert.AssertExpr = new VariableExpr(0, 0, "true");
            expected.Block.Statements.Add(assert);
            program.ShouldBeEquivalentTo(expected);
        }
예제 #10
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);
            }
        }
예제 #11
0
        private void BuildBlock(IWpfTextView text, Method method)
        {
            string     newMethodName = GetNewName(text);
            UpdateStmt firstStmt;
            int        i = 0;


            AssertStmt pre = null, post = null;
            Expression invariant = null;
            Expression guard     = ExtractGuard(method.Ens.Last().E);

            if (method.Ens.Last().E is BinaryExpr)
            {
                var bexp = method.Ens.Last().E as BinaryExpr;
                if (bexp.Op == BinaryExpr.Opcode.And)
                {
                    guard     = InvertExp(bexp.E1);
                    post      = new AssertStmt(null, null, bexp, null, null);
                    pre       = new AssertStmt(null, null, bexp.E0, null, null);
                    invariant = bexp.E0;
                }
            }

            //new UnaryOpExpr(null, UnaryOpExpr.Opcode.Not,ExtractGuard(method.Ens.Last().E));
            List <Expression> decress = new List <Expression>();
            var decExp = new BinaryExpr(null, BinaryExpr.Opcode.Sub, ((BinaryExpr)guard).E0, ((BinaryExpr)guard).E1);

            decress.Add(decExp);

            List <MaybeFreeExpression> invs = new List <MaybeFreeExpression>();

            invs.Add(new MaybeFreeExpression(invariant));
            var newStmts       = new List <Statement>();
            var whileBodystmts = new List <Statement>();

            if (BuildFirstStatement(method.Ins, method.Outs, out firstStmt))
            {
                newStmts.Add(firstStmt);
            }

            List <Expression> args = new List <Expression>();

            foreach (var v in GetAllVars(method.Ins, method.Outs))
            {
                args.Add(new NameSegment(null, v.Name, null));
            }
            AssignmentRhs arhs = new ExprRhs(new ApplySuffix(null, new NameSegment(null, newMethodName, null)
                                                             , args));
            var lstRhs = new List <AssignmentRhs>();

            lstRhs.Add(arhs);
            whileBodystmts.Add(new UpdateStmt(null, null, firstStmt.Lhss, lstRhs));

            BlockStmt whileBody = new BlockStmt(null, null, whileBodystmts);
            WhileStmt wstmt     = new WhileStmt(null, null, guard, invs, new Specification <Expression>(decress, null), new Specification <FrameExpression>(null, null), whileBody);


            newStmts.Add(pre);
            newStmts.Add(wstmt);
            newStmts.Add(post);
            BlockStmt funcBody = new BlockStmt(null, null, newStmts);

            List <MaybeFreeExpression> newMethodreq = new List <MaybeFreeExpression>();
            List <MaybeFreeExpression> newMethodens = new List <MaybeFreeExpression>();

            newMethodreq.Add(new MaybeFreeExpression(new BinaryExpr(null, BinaryExpr.Opcode.And,
                                                                    ReplaceOutsWithIns(invariant, method.Ins, method.Outs),
                                                                    ReplaceOutsWithIns(guard, method.Ins, method.Outs))));

            newMethodens.Add(new MaybeFreeExpression(new BinaryExpr(null, BinaryExpr.Opcode.And, invariant,
                                                                    new BinaryExpr(null, BinaryExpr.Opcode.Le, decExp, ReplaceOutsWithIns(decExp, method.Ins, method.Outs)))));

            Method m = new Method(null, newMethodName, false, false, new List <TypeParameter>(),
                                  method.Ins, method.Outs, newMethodreq,
                                  new Specification <FrameExpression>(null, null), newMethodens, new Specification <Expression>(null, null), null, null, null);

            int selection = text.Selection.End.Position;

            selection = GetPositionOFLastToken(method, text);
            string s = Printer.StatementToString(funcBody) + "\n\n";
            string f = "\n\n" + Printer.MethodSignatureToString(m) + "\n";

            WriteToTextViewer(f, text, selection);
            WriteToTextViewer(s, text, selection);
        }
예제 #12
0
파일: Interpreter.cs 프로젝트: ggrov/tacny
 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;
   }
 }
 public virtual void Visit(AssertStmt assertStatement)
 {
     VisitNullableAttributes(assertStatement.Attributes);
     Visit(assertStatement.Expr);
     VisitNullableStatement(assertStatement.Proof);
 }
예제 #14
0
파일: Interpreter.cs 프로젝트: ggrov/tacny
    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;
      }
    }
예제 #15
0
 private Statement ParseStatement()
 {
     if (Accept(Token.Types.KwVar))
     {
         DeclarationStmt declaration = new DeclarationStmt(AcceptedToken.Line, AcceptedToken.Column);
         Token id = Match(Token.Types.Identifier);
         declaration.Identifier = new IdentifierExpr(id.Line, id.Column, id.Content);
         Match(Token.Types.Colon);
         TypeNode typeNode = ParseType();
         declaration.Type = typeNode;
         if (Accept(Token.Types.OpAssignment))
         {
             declaration.AssignmentExpr = ParseExpression();
         }
         return declaration;
     }
     else if (Accept(Token.Types.Identifier))
     {
         AssignmentStmt statement = new AssignmentStmt(AcceptedToken.Line, AcceptedToken.Column);
         statement.Identifier = new IdentifierExpr(AcceptedToken.Line, AcceptedToken.Column, AcceptedToken.Content);
         Match(Token.Types.OpAssignment);
         statement.AssignmentExpr = ParseExpression();
         return statement;
     }
     else if (Accept(Token.Types.KwFor))
     {
         ForStmt statement = new ForStmt(AcceptedToken.Line, AcceptedToken.Column);
         Token idToken = Match(Token.Types.Identifier);
         statement.LoopVar = new IdentifierExpr(idToken.Line, idToken.Column, idToken.Content);
         Match(Token.Types.KwIn);
         statement.StartExpr = ParseExpression();
         Match(Token.Types.OpRange);
         statement.EndExpr = ParseExpression();
         Match(Token.Types.KwDo);
         statement.Body = ParseStatements(new StmtList(CurrentToken.Line, CurrentToken.Column));
         Match(Token.Types.KwEnd);
         Match(Token.Types.KwFor);
         return statement;
     }
     else if (Accept(Token.Types.KwRead))
     {
         ReadStmt statement = new ReadStmt(AcceptedToken.Line, AcceptedToken.Column);
         Token idToken = Match(Token.Types.Identifier);
         statement.Variable = new IdentifierExpr(idToken.Line, idToken.Column, idToken.Content);
         return statement;
     }
     else if (Accept(Token.Types.KwPrint))
     {
         PrintStmt statement = new PrintStmt(AcceptedToken.Line, AcceptedToken.Column);
         statement.PrintExpr = ParseExpression();
         return statement;
     }
     else if (Accept(Token.Types.KwAssert))
     {
         AssertStmt statement = new AssertStmt(AcceptedToken.Line, AcceptedToken.Column);
         Match(Token.Types.LParen);
         statement.AssertExpr = ParseExpression();
         Match(Token.Types.RParen);
         return statement;
     }
     throw new ParserException(String.Format("Expected statement, got {0} instead at line {1} column {2}.",
         CurrentToken.Type, CurrentToken.Line, CurrentToken.Column));
 }
예제 #16
0
        void AssertStmt(out Statement/*!*/ s)
        {
            Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x;
            Expression e = dummyExpr; Attributes attrs = null;
            IToken dotdotdot = null;
            BlockStmt proof = null;
            IToken proofStart, proofEnd;

            Expect(105);
            x = t;
            while (IsAttribute()) {
            Attribute(ref attrs);
            }
            if (StartOf(10)) {
            Expression(out e, false, true);
            if (la.kind == 106) {
                Get();
                BlockStmt(out proof, out proofStart, out proofEnd);
            } else if (la.kind == 30) {
                Get();
            } else SynErr(198);
            } else if (la.kind == 63) {
            Get();
            dotdotdot = t;
            Expect(30);
            } else SynErr(199);
            if (dotdotdot != null) {
             s = new SkeletonStatement(new AssertStmt(x, t, new LiteralExpr(x, true), null, attrs), dotdotdot, null);
            } else {
             s = new AssertStmt(x, t, e, proof, attrs);
            }
        }
예제 #17
0
파일: Cloner.cs 프로젝트: ggrov/tacny
    public virtual Statement CloneStmt(Statement stmt) {
      if (stmt == null) {
        return null;
      }

      Statement r;
      if (stmt is AssertStmt) {
        var s = (AssertStmt)stmt;
        r = new AssertStmt(Tok(s.Tok), Tok(s.EndTok), CloneExpr(s.Expr), null);

      } else if (stmt is AssumeStmt) {
        var s = (AssumeStmt)stmt;
        r = new AssumeStmt(Tok(s.Tok), Tok(s.EndTok), CloneExpr(s.Expr), null);
      } else if (stmt is TacticInvariantStmt) {
        var s = (TacticInvariantStmt)stmt;
        r = new TacticInvariantStmt(Tok(s.Tok), Tok(s.EndTok), CloneExpr(s.Expr), null, s.IsObjectLevel);
      } else if (stmt is TacticAssertStmt) {
        var s = (TacticAssertStmt)stmt;
        r = new TacticAssertStmt(Tok(s.Tok), Tok(s.EndTok), CloneExpr(s.Expr), null, s.IsObjectLevel);
      } else if (stmt is PrintStmt) {
        var s = (PrintStmt)stmt;
        r = new PrintStmt(Tok(s.Tok), Tok(s.EndTok), s.Args.ConvertAll(CloneExpr));
      } else if (stmt is BreakStmt) {
        var s = (BreakStmt)stmt;
        if (s.TargetLabel != null) {
          r = new BreakStmt(Tok(s.Tok), Tok(s.EndTok), s.TargetLabel);
        } else {
          r = new BreakStmt(Tok(s.Tok), Tok(s.EndTok), s.BreakCount);
        }

      } else if (stmt is ReturnStmt) {
        var s = (ReturnStmt)stmt;
        r = new ReturnStmt(Tok(s.Tok), Tok(s.EndTok), s.rhss == null ? null : s.rhss.ConvertAll(CloneRHS));

      } else if (stmt is YieldStmt) {
        var s = (YieldStmt)stmt;
        r = new YieldStmt(Tok(s.Tok), Tok(s.EndTok), s.rhss == null ? null : s.rhss.ConvertAll(CloneRHS));

      } else if (stmt is AssignStmt) {
        var s = (AssignStmt)stmt;
        r = new AssignStmt(Tok(s.Tok), Tok(s.EndTok), CloneExpr(s.Lhs), CloneRHS(s.Rhs));

      } else if (stmt is BlockStmt) {
        r = CloneBlockStmt((BlockStmt)stmt);

      } else if (stmt is IfStmt) {
        var s = (IfStmt)stmt;
        r = new IfStmt(Tok(s.Tok), Tok(s.EndTok), s.IsExistentialGuard, CloneExpr(s.Guard), CloneBlockStmt(s.Thn), CloneStmt(s.Els));

      } else if (stmt is AlternativeStmt) {
        var s = (AlternativeStmt)stmt;
        r = new AlternativeStmt(Tok(s.Tok), Tok(s.EndTok), s.Alternatives.ConvertAll(CloneGuardedAlternative));

      } else if (stmt is WhileStmt) {
        var s = (WhileStmt)stmt;
        r = new WhileStmt(Tok(s.Tok), Tok(s.EndTok), CloneExpr(s.Guard), s.Invariants.ConvertAll(CloneMayBeFreeExpr), CloneSpecExpr(s.Decreases), CloneSpecFrameExpr(s.Mod), CloneBlockStmt(s.Body));
        ((WhileStmt)r).TacAps = s.TacAps;
      } else if (stmt is AlternativeLoopStmt) {
        var s = (AlternativeLoopStmt)stmt;
        r = new AlternativeLoopStmt(Tok(s.Tok), Tok(s.EndTok), s.Invariants.ConvertAll(CloneMayBeFreeExpr), CloneSpecExpr(s.Decreases), CloneSpecFrameExpr(s.Mod), s.Alternatives.ConvertAll(CloneGuardedAlternative));

      } else if (stmt is ForallStmt) {
        var s = (ForallStmt)stmt;
        r = new ForallStmt(Tok(s.Tok), Tok(s.EndTok), s.BoundVars.ConvertAll(CloneBoundVar), null, CloneExpr(s.Range), s.Ens.ConvertAll(CloneMayBeFreeExpr), CloneStmt(s.Body));
        if (s.ForallExpressions != null) {
          ((ForallStmt)r).ForallExpressions = s.ForallExpressions.ConvertAll(CloneExpr);
        }
      } else if (stmt is CalcStmt) {
        var s = (CalcStmt)stmt;
        // calc statements have the unusual property that the last line is duplicated.  If that is the case (which
        // we expect it to be here), we share the clone of that line as well.
        var lineCount = s.Lines.Count;
        var lines = new List<Expression>(lineCount);
        for (int i = 0; i < lineCount; i++) {
          lines.Add(i == lineCount - 1 && 2 <= lineCount && s.Lines[i] == s.Lines[i - 1] ? lines[i - 1] : CloneExpr(s.Lines[i]));
        }
        Contract.Assert(lines.Count == lineCount);
        r = new CalcStmt(Tok(s.Tok), Tok(s.EndTok), CloneCalcOp(s.Op), lines, s.Hints.ConvertAll(CloneBlockStmt), s.StepOps.ConvertAll(CloneCalcOp), CloneCalcOp(s.ResultOp), CloneAttributes(s.Attributes));

      } else if (stmt is MatchStmt) {
        var s = (MatchStmt)stmt;
        r = new MatchStmt(Tok(s.Tok), Tok(s.EndTok), CloneExpr(s.Source),
        s.Cases.ConvertAll(CloneMatchCaseStmt), s.UsesOptionalBraces);

      } else if (stmt is AssignSuchThatStmt) {
        var s = (AssignSuchThatStmt)stmt;
        r = new AssignSuchThatStmt(Tok(s.Tok), Tok(s.EndTok), s.Lhss.ConvertAll(CloneExpr), CloneExpr(s.Expr), s.AssumeToken == null ? null : Tok(s.AssumeToken), null);

      } else if (stmt is UpdateStmt) {
        var s = (UpdateStmt)stmt;
        r = new UpdateStmt(Tok(s.Tok), Tok(s.EndTok), s.Lhss.ConvertAll(CloneExpr), s.Rhss.ConvertAll(CloneRHS), s.CanMutateKnownState);

      } else if (stmt is VarDeclStmt) {
        var s = (VarDeclStmt)stmt;
        var lhss = s.Locals.ConvertAll(c => new LocalVariable(Tok(c.Tok), Tok(c.EndTok), c.Name, CloneType(c.OptionalType), c.IsGhost));
        r = new VarDeclStmt(Tok(s.Tok), Tok(s.EndTok), lhss, (ConcreteUpdateStatement)CloneStmt(s.Update));
      } else if (stmt is LetStmt) {
        var s = (LetStmt)stmt;
        r = new LetStmt(Tok(s.Tok), Tok(s.EndTok), s.LHSs.ConvertAll(CloneCasePattern), s.RHSs.ConvertAll(CloneExpr));
      } else if (stmt is ModifyStmt) {
        var s = (ModifyStmt)stmt;
        var mod = CloneSpecFrameExpr(s.Mod);
        var body = s.Body == null ? null : CloneBlockStmt(s.Body);
        r = new ModifyStmt(Tok(s.Tok), Tok(s.EndTok), mod.Expressions, mod.Attributes, body);
      } else if (stmt is TacnyCasesBlockStmt) {
        var s = (TacnyCasesBlockStmt)stmt;
        var guard = CloneExpr(s.Guard);
        var body = s.Body == null ? null : CloneBlockStmt(s.Body);
        r = new TacnyCasesBlockStmt(Tok(s.Tok), Tok(s.EndTok), guard, body);
      } else if (stmt is TacnyChangedBlockStmt) {
        var s = (TacnyChangedBlockStmt)stmt;
        var body = s.Body == null ? null : CloneBlockStmt(s.Body);
        r = new TacnyChangedBlockStmt(Tok(s.Tok), Tok(s.EndTok), body);
      } else if (stmt is TacnySolvedBlockStmt) {
        var s = (TacnySolvedBlockStmt)stmt;
        var body = s.Body == null ? null : CloneBlockStmt(s.Body);
        r = new TacnySolvedBlockStmt(Tok(s.Tok), Tok(s.EndTok), body);
      } else if (stmt is TacnyTryCatchBlockStmt) {
        var s = (TacnyTryCatchBlockStmt)stmt;
        var body = s.Body == null ? null : CloneBlockStmt(s.Body);
        var c = s.Ctch == null ? null : CloneBlockStmt(s.Ctch);
        r = new TacnyTryCatchBlockStmt(Tok(s.Tok), Tok(s.EndTok), body, c);
      } else if (stmt is TacticVarDeclStmt) {
        var s = (TacticVarDeclStmt)stmt;
        var lhss = s.Locals.ConvertAll(c => new LocalVariable(Tok(c.Tok), Tok(c.EndTok), c.Name, CloneType(c.OptionalType), c.IsGhost));
        r = new TacticVarDeclStmt(Tok(s.Tok), Tok(s.EndTok), lhss, (ConcreteUpdateStatement)CloneStmt(s.Update));
      } else {
        Contract.Assert(false); throw new cce.UnreachableException();  // unexpected statement
      }

      // add labels to the cloned statement
      AddStmtLabels(r, stmt.Labels);
      r.Attributes = CloneAttributes(stmt.Attributes);

      return r;
    }
예제 #18
0
 private void FindRemovableTypesInAssertStmt(AssertStmt assert, Statement parent, Method method)
 {
     if (!(parent is BlockStmt)) return;
     var block = (BlockStmt) parent;
     var assertWrap = new Wrap<Statement>(assert, block.Body);
     _allRemovableTypes.AddAssert(assertWrap, method);
 }
예제 #19
0
파일: Parser.cs 프로젝트: dbremner/dafny
        void AssertStmt(out Statement/*!*/ s)
        {
            Contract.Ensures(Contract.ValueAtReturn(out s) != null); IToken/*!*/ x;
            Expression e = dummyExpr; Attributes attrs = null;
            IToken dotdotdot = null;

            Expect(101);
            x = t;
            while (IsAttribute()) {
            Attribute(ref attrs);
            }
            if (StartOf(7)) {
            Expression(out e, false, true);
            } else if (la.kind == 59) {
            Get();
            dotdotdot = t;
            } else SynErr(180);
            Expect(28);
            if (dotdotdot != null) {
             s = new SkeletonStatement(new AssertStmt(x, t, new LiteralExpr(x, true), attrs), dotdotdot, null);
            } else {
             s = new AssertStmt(x, t, e, attrs);
            }
        }
 public override void Visit(AssertStmt assertStmt)
 {
     Expression assert = assertStmt.AssertExpr;
     assert.Accept(this);
     if (assert.Type != ExprType.BoolType)
     {
         Errors.AddError(String.Format("Assertion expression type {0} illegal at line {1} column {2}.",
             assert.Type, assertStmt.Line, assertStmt.Column), ErrorTypes.SemanticError);
     }
 }
 public string GenerateConditionString(AssertStmt assert, IDictionary <string, string> rename)
 {
     return(GenerateConditionString(assert.Expr, rename));
 }
예제 #22
0
파일: TacnyDriver.cs 프로젝트: ggrov/dafny
 private void InterpretAssertStmt(AssertStmt stmt, Stack <Dictionary <IVariable, Type> > frame)
 {
     InterpertBlockStmt(stmt.Proof, frame);
 }
예제 #23
0
 public override void Visit(AssertStmt assertStmt)
 {
     assertStmt.AssertExpr.Accept(this);
     if ((bool) assertStmt.AssertExpr.ExprValue != true)
     {
         throw new RuntimeException(String.Format("Assertion failed at line {0} column {1}.",
             assertStmt.Line, assertStmt.Column));
     }
 }
예제 #24
0
    public virtual void AddResolvedGhostStatement(Statement stmt)
    {
        BlockStmt          block      = stmt as BlockStmt;
        IfStmt             ifStmt     = stmt as IfStmt;
        AssertStmt         assertStmt = stmt as AssertStmt;
        AssignStmt         assignStmt = stmt as AssignStmt;
        CallStmt           callStmt   = stmt as CallStmt;
        VarDecl            varDecl    = stmt as VarDecl;
        CalcStmt           calcStmt   = stmt as CalcStmt;
        ForallStmt         forallStmt = stmt as ForallStmt;
        AssignSuchThatStmt existsStmt = stmt as AssignSuchThatStmt;

        if (block != null)
        {
            var oldRenamer = PushRename();
            block.Body.ForEach(AddGhostStatement);
            PopRename(oldRenamer);
        }
        else if (varDecl != null)
        {
            AddGhostVarDecl(varDecl.Name, varDecl.Type, varDecl.IsGhost);
        }
        else if (minVerify)
        {
            return;
        }
        else if (assignStmt != null)
        {
            ExprRhs expRhs = assignStmt.Rhs as ExprRhs;
            if (expRhs != null)
            {
                FieldSelectExpr fieldSelect = assignStmt.Lhs as FieldSelectExpr;
                RtlVar          destVar;
                if (fieldSelect != null)
                {
                    destVar = new RtlVar(GhostVar(fieldSelect.FieldName), true, fieldSelect.Type);
                }
                else
                {
                    destVar = AsVar(assignStmt.Lhs);
                    Util.Assert(destVar != null);
                }
                stmts.Add(new RtlGhostMove(new RtlVar[] { destVar },
                                           new RtlExp[] { GhostExpression(expRhs.Expr) }));
            }
            else
            {
                throw new Exception("not implemented: " + assignStmt.Rhs);
            }
        }
        else if (callStmt != null)
        {
            AddGhostCall(callStmt.Lhs.ConvertAll(AsVar), callStmt.Args,
                         dafnySpec.Compile_Method(callStmt.Method,
                                                  callStmt.TypeArgumentSubstitutions.ToDictionary(p => p.Key, p => AppType(p.Value))),
                         DafnySpec.IsHeapMethod(callStmt.Method));
            SymdiffLinearityPoint();
        }
        else if (ifStmt != null)
        {
            stmts.Add(new RtlGhostStmtComputed(s => "if (" + s.args[0] + ") {",
                                               new RtlExp[] { GhostExpression(ifStmt.Guard) }));
            Indent();
            AddGhostStatement(ifStmt.Thn);
            Unindent();
            stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
            if (ifStmt.Els != null)
            {
                stmts.Add(new RtlGhostStmtComputed(s => "if (" + s.args[0] + ") {",
                                                   new RtlExp[] {
                    GhostExpression(new UnaryExpr(Bpl.Token.NoToken, UnaryExpr.Opcode.Not, ifStmt.Guard))
                }));
                Indent();
                AddGhostStatement(ifStmt.Els);
                Unindent();
                stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
            }
        }
        else if (assertStmt != null)
        {
            stmts.Add(new RtlAssert(GhostExpression(assertStmt.Expr)));
        }
        else if (forallStmt != null)
        {
            var    oldRenamer = PushRename(forallStmt.BoundVars.Select(v => v.Name));
            RtlExp ens        = new RtlLiteral("true");
            foreach (var e in forallStmt.Ens)
            {
                ens = new RtlBinary("&&", ens, GhostExpression(e.E));
            }
            RtlExp range = (forallStmt.Range == null) ? new RtlLiteral("true")
                : GhostExpression(forallStmt.Range);
            List <RtlExp> wellFormed = GetTypeWellFormed(forallStmt.BoundVars.
                                                         Select(x => Tuple.Create(GhostVar(x.Name), x.IsGhost, x.Type)).ToList());
            wellFormed.ForEach(e => range = new RtlBinary("&&", e, range));
            ens = new RtlBinary("==>", range, ens);
            string vars = String.Join(", ", forallStmt.BoundVars.Select(x => GhostVar(x.Name) + ":" +
                                                                        TypeString(AppType(x.Type))));
            stmts.Add(new RtlGhostStmtComputed(s => "forall " + vars + "::(" + s.args[0] + ")",
                                               new List <RtlExp> {
                ens
            }));
            stmts.Add(new RtlGhostStmtComputed(s => "{", new RtlExp[0]));
            Indent();
            stmts.Add(PushForall());
            stmts.Add(new RtlGhostStmtComputed(s => "if (" + s.args[0] + ")",
                                               new List <RtlExp> {
                range
            }));
            stmts.Add(new RtlGhostStmtComputed(s => "{", new RtlExp[0]));
            Indent();
            AddGhostStatement(forallStmt.Body);
            foreach (var e in forallStmt.Ens)
            {
                stmts.Add(new RtlAssert(GhostExpression(e.E)));
            }
            PopForall();
            Unindent();
            stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
            Unindent();
            stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
            PopRename(oldRenamer);
        }
        else if (existsStmt != null)
        {
            List <RtlStmt> assigns = new List <RtlStmt>();
            List <RtlVar>  tmps    = new List <RtlVar>();
            List <Tuple <string, bool, Type> > varTuples = new List <Tuple <string, bool, Type> >();
            var oldRenamer = PushRename();
            foreach (var lhs in existsStmt.Lhss)
            {
                IdentifierExpr idExp   = lhs.Resolved as IdentifierExpr;
                RtlVar         origVar = AsVar(lhs);
                AddRename(idExp.Name);
                RtlVar renameVar = AsVar(lhs);
                tmps.Add(renameVar);
                varTuples.Add(Tuple.Create(renameVar.ToString(), true, idExp.Type));
                assigns.Add(new RtlGhostMove(new RtlVar[] { origVar },
                                             new RtlExp[] { renameVar }));
            }
            string vars = String.Join(", ", tmps.Select(x => x.getName() + ":" + TypeString(AppType(x.type))));
            stmts.Add(new RtlGhostStmtComputed(s => "exists " + vars + "::(" + s.args[0] + ");",
                                               new List <RtlExp> {
                GetTypeWellFormedExp(varTuples.ToList(), "&&", GhostExpression(existsStmt.Expr))
            }));
            stmts.AddRange(assigns);
            PopRename(oldRenamer);
        }
        else if (calcStmt != null)
        {
            Util.Assert(calcStmt.Steps.Count == calcStmt.Hints.Count);
            CalcStmt.BinaryCalcOp binOp = calcStmt.Op as CalcStmt.BinaryCalcOp;
            bool isImply = binOp != null && binOp.Op == BinaryExpr.Opcode.Imp && calcStmt.Steps.Count > 0;
            if (isImply)
            {
                stmts.Add(new RtlGhostStmtComputed(s => "if (" + s.args[0] + ")",
                                                   new RtlExp[] { GhostExpression(CalcStmt.Lhs(calcStmt.Steps[0])) }));
                stmts.Add(new RtlGhostStmtComputed(s => "{", new RtlExp[0]));
                Indent();
            }
            var stepCount = calcStmt.Hints.Last().Body.Count == 0 ? calcStmt.Steps.Count - 1 : calcStmt.Steps.Count;
            for (int i = 0; i < stepCount; i++)
            {
                if (calcStmt.Hints[i] == null)
                {
                    stmts.Add(new RtlAssert(GhostExpression(calcStmt.Steps[i])));
                }
                else
                {
                    stmts.Add(new RtlGhostStmtComputed(s => "forall::(" + s.args[0] + ")",
                                                       new List <RtlExp> {
                        GhostExpression(calcStmt.Steps[i])
                    }));
                    stmts.Add(new RtlGhostStmtComputed(s => "{", new RtlExp[0]));
                    Indent();
                    var dict = new Dictionary <string, RtlVar>();
                    stmts.Add(new RtlGhostStmtComputed(s => String.Concat(dict.Values.Select(
                                                                              x => "var " + x.x + ":" + TypeString(x.type) + ";")),
                                                       new RtlExp[0]));
                    forallVars.Add(dict);
                    AddGhostStatement(calcStmt.Hints[i]);
                    forallVars.RemoveAt(forallVars.Count - 1);
                    Unindent();
                    stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
                }
            }
            if (isImply)
            {
                Unindent();
                stmts.Add(new RtlGhostStmtComputed(s => "}", new RtlExp[0]));
            }
        }
        else
        {
            throw new Exception("not implemented in ghost methods: " + stmt);
        }
    }