public IEnumerable<Solution> AddInvar(TacticInvariantStmt st, Solution solution) { MaybeFreeExpression invariant = null; foreach (var item in ResolveExpression(st.Expr)) { if (item is UpdateStmt) { var us = item as UpdateStmt; var aps = ((ExprRhs)us.Rhss[0]).Expr as ApplySuffix; if (aps != null) invariant = new MaybeFreeExpression(aps); } else { invariant = item as MaybeFreeExpression ?? new MaybeFreeExpression(item as Expression); } WhileStmt nws = null; var ws = DynamicContext.whileStmt; Contract.Assert(ws != null, Error.MkErr(st, 11)); // if we already added new invariants to the statement, use the updated statement instead nws = GetUpdated(ws) as WhileStmt; var invarArr = nws?.Invariants.ToArray() ?? ws.Invariants.ToArray(); var invar = new List<MaybeFreeExpression>(invarArr) {invariant}; //invar.Insert(0, invariant); nws = new WhileStmt(ws.Tok, ws.EndTok, ws.Guard, invar, ws.Decreases, ws.Mod, ws.Body); yield return AddNewStatement(ws, nws); } }
private IEnumerable<Solution> InsertLoop(WhileStmt whileStmt) { Contract.Requires(whileStmt != null); ResolveExpression(ref Guard); var guard = Guard.TreeToExpression(); foreach (var item in ResolveBody(whileStmt.Body)) { var result = GenerateWhileStmt(whileStmt, guard, item); yield return AddNewStatement(result, result); } }
private IEnumerable<Solution> ExecuteLoop(WhileStmt whileStmt) { bool guardRes = EvaluateGuard(); // if the guard has been resolved to true resolve then body if (!guardRes) yield break; // reset the PartialyResolved DynamicContext.isPartialyResolved = false; foreach (var item in ResolveBody(whileStmt.Body)) { item.State.DynamicContext.isPartialyResolved = true; yield return item; } }
public void WhileLoopConditionIgnoredTest() { var target = new EvaluateVisitor(); var conditionExecuted = false; var condition = new Mock <Expression>(); condition.Setup(c => c.Accept(It.IsAny <IExpressionVisitor <Value, Scope> >(), It.IsAny <Scope>())) .Returns <IExpressionVisitor <Value, Scope>, Scope>( (v, s) => { var retVal = new Value(!conditionExecuted); conditionExecuted = true; return(retVal); }); var statement = new Mock <Statement>(); statement.Setup(c => c.Accept(It.IsAny <IExpressionVisitor <Value, Scope> >(), It.IsAny <Scope>())) .Returns <IExpressionVisitor <Value, Scope>, Scope>( (v, s) => { if (!conditionExecuted) { throw new Exception("Statement executed before condition evaluated."); } return(new Value(false)); }); var expr = new WhileStmt(condition.Object, new ScopeBlockStmt(new[] { statement.Object })); target.Visit(expr, _scope); condition.Verify(c => c.Accept(target, _scope), Times.Exactly(2)); statement.Verify(s => s.Accept(target, It.IsAny <Scope>()), Times.Once); }
/// <summary> /// Visit cycle condition expression and cycle body. /// </summary> /// <param name="x"></param> virtual public void VisitWhileStmt(WhileStmt x) { VisitElement(x.CondExpr); VisitElement(x.Body); }
public ForStmt(DefStmt counter_definition, WhileStmt body) { this.counter_definition = counter_definition; this.body = body; }
void PrintWhileStatement(int indent, WhileStmt s, bool omitGuard, bool omitBody) { Contract.Requires(0 <= indent); if (omitGuard) { wr.WriteLine("while ..."); } else { wr.Write("while "); PrintGuard(false, s.Guard); wr.WriteLine(); } PrintSpec("invariant", s.Invariants, indent + IndentAmount, s.Body != null || omitBody || (s.Decreases.Expressions != null && s.Decreases.Expressions.Count != 0) || (s.Mod.Expressions != null && s.Mod.Expressions.Count != 0)); PrintDecreasesSpec(s.Decreases, indent + IndentAmount, s.Body != null || omitBody || (s.Mod.Expressions != null && s.Mod.Expressions.Count != 0)); if (s.Mod.Expressions != null) { PrintFrameSpecLine("modifies", s.Mod.Expressions, indent + IndentAmount, s.Mod.HasAttributes() ? s.Mod.Attributes : null, s.Body != null || omitBody); } Indent(indent); if (omitBody) { wr.WriteLine("...;"); } else if (s.Body != null) { PrintStatement(s.Body, indent); } }
public override Null Visit(WhileStmt node) { base.Visit(node); if (!node.test.computedType.IsBool()) { log.ErrorTypeMismatch(node.test.location, new PrimType { kind = PrimKind.Bool }, node.test.computedType); } return null; }
public void FinalizeStatement() { Statement = new WhileStmt(Exp.GetExp(), Stmt.Statement); }
public override void Visit(WhileStmt s) { }
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); }
WhileStmt MergeWhileStmt(WhileStmt cNew, WhileStmt cOld, Expression guard) { Contract.Requires(cNew != null); Contract.Requires(cOld != null); // Note, the parser produces errors if there are any decreases or modifies clauses (and it creates // the Specification structures with a null list). Contract.Assume(cNew.Mod.Expressions == null); Specification<Expression> decr; if (cNew.Decreases.Expressions.Count == 0) { // inherited whatever the previous loop used decr = refinementCloner.CloneSpecExpr(cOld.Decreases); } else { if (!Contract.Exists(cOld.Decreases.Expressions, e => e is WildcardExpr)) { // If the previous loop was not specified with "decreases *", then the new loop is not allowed to provide any "decreases" clause. reporter.Error(MessageSource.RefinementTransformer, cNew.Decreases.Expressions[0].tok, "a refining loop can provide a decreases clause only if the loop being refined was declared with 'decreases *'"); } decr = cNew.Decreases; } var invs = cOld.Invariants.ConvertAll(refinementCloner.CloneMayBeFreeExpr); invs.AddRange(cNew.Invariants); var r = new RefinedWhileStmt(cNew.Tok, cNew.EndTok, guard, invs, decr, refinementCloner.CloneSpecFrameExpr(cOld.Mod), MergeBlockStmt(cNew.Body, cOld.Body)); return r; }
public ValueType Visit(WhileStmt stmt, Scope scope) { return(ValueType.Unit); }
private Solution ResolveTactic(List<IVariable> variables, List<IVariable> resolved, UpdateStmt us, MemberDecl md, WhileStmt ws = null) { try { var prog = Util.ObjectExtensions.Copy(_tacnyProgram); var result = Atomic.ResolveTactic(us, md, prog, variables, resolved, ws); prog.PrintDebugData(prog.CurrentDebug); return result; } catch (Exception e) { Printer.Error(e.Message); return null; } }
public virtual void Visit(WhileStmt stmt) { }
private static WhileStmt GenerateWhileStmt(WhileStmt original, Expression guard, Solution body) { var bodyList = body.State.GetAllUpdated(); var thenBody = new BlockStmt(original.Body.Tok, original.Body.EndTok, bodyList); return new WhileStmt(original.Tok, original.EndTok, Util.Copy.CopyExpression(guard), original.Invariants, original.Decreases, original.Mod, Util.Copy.CopyBlockStmt(thenBody)); }
// Desugaring method that parses _for_ into _while_ private Stmt ForStatement() { // Start by eating left parenthesis... Consume(TokenType.LeftParen, "Expect '(' after 'for'."); // ...consume initializer, if one is present... Stmt initializer; if (Match(TokenType.Semicolon)) { initializer = null; } else if (Match(TokenType.Var)) { initializer = VarDeclaration(); } else { initializer = ExpressionStatement(); } // ...consume loop condition, if one is present, and ensure that the semicolon is there... Expr condition = null; if (!Check(TokenType.Semicolon)) { condition = Expression(); } Consume(TokenType.Semicolon, "Expect ';' after loop condition."); // ...ditto for increment... Expr increment = null; if (!Check(TokenType.RightParen)) { increment = Expression(); } Consume(TokenType.RightParen, "Expect ')' after for clauses."); // ...and finally construct a body. var body = Statement(); // Now the fun begins! // If increment was present, we put it a little block with the body, // in order to run increment once after every, well, loop if (increment != null) { body = new BlockStmt(new List <Stmt> { body, new ExpressionStmt(increment) }); } // If condition was null, make a literal true, so we can get an infinite while if (condition is null) { condition = new LiteralExpr(true); } // Now we wrap the body into a while statment, with condition body = new WhileStmt(condition, body); // And finally another small block, this time with initializer before body // because initializer should only run once, of course if (initializer != null) { body = new BlockStmt(new List <Stmt> { initializer, body }); } // And we can return the 'body' which is really full-fledged // while by now. return(body); }
private Solution ResolveTactic(List <IVariable> variables, List <IVariable> resolved, UpdateStmt us, MemberDecl md, WhileStmt ws = null) { try { var prog = Util.ObjectExtensions.Copy(_tacnyProgram); var result = Atomic.ResolveTactic(us, md, prog, variables, resolved, ws); prog.PrintDebugData(prog.CurrentDebug); return(result); } catch (Exception e) { Printer.Error(e.Message); return(null); } }
private Solution LazyScanMemberBody(MemberDecl md) { Contract.Requires(md != null); Console.WriteLine($"Starting thread: {System.Threading.Thread.CurrentThread.Name}"); Debug.WriteLine($"Scanning member {md.Name} body"); var function = md as Function; if (function != null) { var fun = function; if (fun.Body == null) { return(null); } var expt = ExpressionTree.ExpressionToTree(fun.Body); expt.FindAndResolveTacticApplication(_tacnyProgram, fun); /* No reason ot generate new solution * if nothing has been changed */ if (!expt.Modified) { return(null); } var res = expt.TreeToExpression(); var newFun = new Function(fun.tok, fun.Name, fun.HasStaticKeyword, fun.IsProtected, fun.IsGhost, fun.TypeArgs, fun.Formals, fun.ResultType, fun.Req, fun.Reads, fun.Ens, fun.Decreases, res, fun.Attributes, fun.SignatureEllipsis); var ac = new Atomic { IsFunction = true, DynamicContext = { newTarget = newFun } }; return(new Solution(ac)); } var m = md as Method; if (m?.Body == null) { return(null); } List <IVariable> variables = new List <IVariable>(); List <IVariable> resolved; lock (_tacnyProgram) { resolved = _tacnyProgram.GetResolvedVariables(md); } variables.AddRange(m.Ins); variables.AddRange(m.Outs); resolved.AddRange(m.Ins); // add input arguments as resolved variables resolved.AddRange(m.Outs); // does not work for multiple tactic applications foreach (var st in m.Body.Body) { UpdateStmt us = null; WhileStmt ws = null; // register local variables if (st is VarDeclStmt) { VarDeclStmt vds = st as VarDeclStmt; variables.AddRange(vds.Locals); } else if (st is UpdateStmt) { us = st as UpdateStmt; } else if (st is WhileStmt) { ws = st as WhileStmt; us = ws.TacAps as UpdateStmt; foreach (var wst in ws.Body.Body) { if (!(wst is VarDeclStmt)) { continue; } var vds = wst as VarDeclStmt; variables.AddRange(vds.Locals); } } if (us == null || !_tacnyProgram.IsTacticCall(us)) { continue; } Debug.WriteLine("Tactic call found"); return(ResolveTactic(variables, resolved, us, md, ws)); } return(null); }
private void AddVariant(Statement st, ref List<Solution> solution_list) { List<Expression> call_arguments = null; List<Expression> dec_list = null; Expression input = null; InitArgs(st, out call_arguments); Contract.Assert(tcce.OfSize(call_arguments, 1), Util.Error.MkErr(st, 0, 1, call_arguments.Count)); StringLiteralExpr wildCard = call_arguments[0] as StringLiteralExpr; if (wildCard != null) { if (wildCard.Value.Equals("*")) input = new WildcardExpr(wildCard.tok); } else { // hack /* * TODO: * Implement propper variable replacement */ object tmp; ProcessArg(call_arguments[0], out tmp); Contract.Assert(tmp != null); IVariable form = tmp as IVariable; if (form != null) input = new NameSegment(form.Tok, form.Name, null); else if (tmp is BinaryExpr) { input = tmp as BinaryExpr; } else if (tmp is NameSegment) { input = tmp as NameSegment; } } WhileStmt ws = FindWhileStmt(globalContext.tac_call, globalContext.md); if (ws != null) { WhileStmt nws = null; dec_list = new List<Expression>(ws.Decreases.Expressions.ToArray()); dec_list.Add(input); Specification<Expression> decreases = new Specification<Expression>(dec_list, ws.Attributes); nws = new WhileStmt(ws.Tok, ws.EndTok, ws.Guard, ws.Invariants, decreases, ws.Mod, ws.Body); AddUpdated(ws, nws); } else { Method target = Program.FindMember(globalContext.program.ParseProgram(), localContext.md.Name) as Method; if (GetNewTarget() != null && GetNewTarget().Name == target.Name) target = GetNewTarget(); Contract.Assert(target != null, Util.Error.MkErr(st, 3)); dec_list = target.Decreases.Expressions; // insert new variants at the end of the existing variants list Contract.Assert(input != null); dec_list.Add(input); Specification<Expression> decreases = new Specification<Expression>(dec_list, target.Decreases.Attributes); Method result = null; dynamic lemma = null; if ((lemma = target as Lemma) != null) { result = new Lemma(lemma.tok, lemma.Name, lemma.HasStaticKeyword, lemma.TypeArgs, lemma.Ins, lemma.Outs, lemma.Req, lemma.Mod, lemma.Ens, decreases, lemma.Body, lemma.Attributes, lemma.SignatureEllipsis); } else if ((lemma = target as CoLemma) != null) { result = new CoLemma(lemma.tok, lemma.Name, lemma.HasStaticKeyword, lemma.TypeArgs, lemma.Ins, lemma.Outs, lemma.Req, lemma.Mod, lemma.Ens, decreases, lemma.Body, lemma.Attributes, lemma.SignatureEllipsis); } else result = new Method(target.tok, target.Name, target.HasStaticKeyword, target.IsGhost, target.TypeArgs, target.Ins, target.Outs, target.Req, target.Mod, target.Ens, decreases, target.Body, target.Attributes, target.SignatureEllipsis); // register new method this.localContext.new_target = result; globalContext.program.IncTotalBranchCount(globalContext.program.currentDebug); } solution_list.Add(new Solution(this.Copy())); }
/// <summary> /// Deep Copy WhileStmt /// @TODO copy mod /// </summary> /// <param name="stmt"></param> /// <returns></returns> public static WhileStmt CopyWhileStmt(WhileStmt stmt) { return(new WhileStmt(stmt.Tok, stmt.EndTok, CopyExpression(stmt.Guard), CopyMaybeFreeExpressionList(stmt.Invariants), CopySpecificationExpression(stmt.Decreases), stmt.Mod, CopyBlockStmt(stmt.Body))); }
protected abstract void MatchWhileStmt(WhileStmt whileStmt);
//laddon public static List <Statement> GetSelectedStatementsRecursive(IEnumerable <Statement> statements, int start, int end) { List <Statement> selected = new List <Statement>(); // Run over all the method's statements and retrieve the selected statements only. // Block statements (such as while, if, etc...) recieve special care. foreach (var s in statements) { if (s is WhileStmt) { WhileStmt w = s as WhileStmt; // If the while loop guard is grabbed by the selection, we consider the entire loop in. if (IsExpressionInRange(w.Guard, start, end)) { selected.Add(s); } else { if (s.Tok.pos < start && end < s.EndTok.pos) { SelectionScope = s; } selected.AddRange ( GetSelectedStatementsRecursive(w.SubStatements.First().SubStatements, start, end) ); } } else if (s is IfStmt) { // For now we can only grab an entire "if/else" clause, along with all "if else" clauses, // but not individual statements WITHIN any of the clauses. // TODO: Support individual statements within an "if", "if else" or "else" clause. IfStmt i = s as IfStmt; if (IsExpressionInRange(i.Guard, start, end)) { selected.Add(s); } else { if (s.Tok.pos < start && end < s.EndTok.pos) { SelectionScope = s; } selected.AddRange ( GetSelectedStatementsRecursive(i.Thn.SubStatements, start, end) ); if (i.Els is IfStmt) // i.Els represents "else if" { selected.AddRange ( GetSelectedStatementsRecursive(new List <Statement> { i.Els }, start, end) ); } else if (i.Els is BlockStmt) // i.Els represents "else" { selected.AddRange ( GetSelectedStatementsRecursive(i.Els.SubStatements, start, end) ); } } } else if (s is AlternativeStmt) { if (IsExpressionInRange(s.SubExpressions.First(), start, end)) { selected.Add(s); } else { SelectionScope = s; foreach (Statement block in s.SubStatements) { selected.AddRange ( GetSelectedStatementsRecursive(block.SubStatements, start, end) ); } } } else if (s is BlockStmt) { if (IsStatementInRange(s, start, end)) { if (s.Tok.pos < start && end < s.EndTok.pos) { SelectionScope = s; selected.AddRange ( GetSelectedStatementsRecursive(s.SubStatements, start, end) ); } else { selected.Add(s); } } } else { if (IsStatementInRange(s, start, end)) { selected.Add(s); } } } return(selected); }
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; }
private StmtResult ForStatement() { /* * forStmt → "for" "(" ( varDecl | exprStmt | ";" ) * expression? ";" * expression? ")" statement ; */ StmtResult ForInitializer() { if (Match(TokenType.Semicolon)) { return(StmtResult.Ok(null)); } if (Match(TokenType.Var)) { return(VarDeclaration()); } return(ExpressionStatement()); } ExprResult ForCondition() { if (Check(TokenType.Semicolon)) { return(ExprResult.Ok(null)); } return(Expression()); } ExprResult ForIncrementer() { if (Check(TokenType.RightParen)) { return(ExprResult.Ok(null)); } return(Expression()); } Stmt BuildForAst(Stmt initializer, Expr condition, Expr incrementer, Stmt statement) { // express `for(var i = 0; i < 10; i++) { statement }` as a while loop; // var i = 0; // while(i<10) { // { statement; } // i++; // } var body = incrementer is null ? statement : new BlockStmt(new List <Stmt>() { statement, new ExpressionStmt(incrementer) }); var cond = condition ?? new LiteralExpr(true); var loop = new WhileStmt(cond, body); var block = initializer is null ? loop : new BlockStmt(new List <Stmt>() { initializer, loop }) as Stmt; return(block); } return (from lParen in Consume(TokenType.LeftParen, "Expected '(' after 'for'.") from initializer in ForInitializer() //first semi is parsed as part of initializer from condition in ForCondition() from semi2 in Consume(TokenType.Semicolon, "Expected ';' after condition.") from incrementer in ForIncrementer() from rParen in Consume(TokenType.RightParen, "Expected ')' after increment expression.") from statement in Statement() select BuildForAst(initializer, condition, incrementer, statement)); }
public string Visit(WhileStmt stmt, Scope scope) { return(string.Format("while({0})\r\n{{\r\n\t{1}\r\n}}", stmt.Condition.Accept(this, scope), stmt.Block.Accept(this, scope))); }
public override void Leave(WhileStmt e) { JumpUpInScope(); }
private void AddVariant(Statement st, ref List <Solution> solution_list) { List <Expression> call_arguments = null; List <Expression> dec_list = null; Expression input = null; InitArgs(st, out call_arguments); Contract.Assert(tcce.OfSize(call_arguments, 1), Util.Error.MkErr(st, 0, 1, call_arguments.Count)); StringLiteralExpr wildCard = call_arguments[0] as StringLiteralExpr; if (wildCard != null) { if (wildCard.Value.Equals("*")) { input = new WildcardExpr(wildCard.tok); } } else { // hack /* * TODO: * Implement propper variable replacement */ object tmp; ProcessArg(call_arguments[0], out tmp); Contract.Assert(tmp != null); IVariable form = tmp as IVariable; if (form != null) { input = new NameSegment(form.Tok, form.Name, null); } else if (tmp is BinaryExpr) { input = tmp as BinaryExpr; } else if (tmp is NameSegment) { input = tmp as NameSegment; } } WhileStmt ws = FindWhileStmt(globalContext.tac_call, globalContext.md); if (ws != null) { WhileStmt nws = null; dec_list = new List <Expression>(ws.Decreases.Expressions.ToArray()); dec_list.Add(input); Specification <Expression> decreases = new Specification <Expression>(dec_list, ws.Attributes); nws = new WhileStmt(ws.Tok, ws.EndTok, ws.Guard, ws.Invariants, decreases, ws.Mod, ws.Body); AddUpdated(ws, nws); } else { Method target = Program.FindMember(globalContext.program.ParseProgram(), localContext.md.Name) as Method; if (GetNewTarget() != null && GetNewTarget().Name == target.Name) { target = GetNewTarget(); } Contract.Assert(target != null, Util.Error.MkErr(st, 3)); dec_list = target.Decreases.Expressions; // insert new variants at the end of the existing variants list Contract.Assert(input != null); dec_list.Add(input); Specification <Expression> decreases = new Specification <Expression>(dec_list, target.Decreases.Attributes); Method result = null; dynamic lemma = null; if ((lemma = target as Lemma) != null) { result = new Lemma(lemma.tok, lemma.Name, lemma.HasStaticKeyword, lemma.TypeArgs, lemma.Ins, lemma.Outs, lemma.Req, lemma.Mod, lemma.Ens, decreases, lemma.Body, lemma.Attributes, lemma.SignatureEllipsis); } else if ((lemma = target as CoLemma) != null) { result = new CoLemma(lemma.tok, lemma.Name, lemma.HasStaticKeyword, lemma.TypeArgs, lemma.Ins, lemma.Outs, lemma.Req, lemma.Mod, lemma.Ens, decreases, lemma.Body, lemma.Attributes, lemma.SignatureEllipsis); } else { result = new Method(target.tok, target.Name, target.HasStaticKeyword, target.IsGhost, target.TypeArgs, target.Ins, target.Outs, target.Req, target.Mod, target.Ens, decreases, target.Body, target.Attributes, target.SignatureEllipsis); } // register new method this.localContext.new_target = result; globalContext.program.IncTotalBranchCount(globalContext.program.currentDebug); } solution_list.Add(new Solution(this.Copy())); }
public override Null Visit(WhileStmt node) { // Create an flow node for the back edge FlowNode end = next.Get(); FlowNode loop = new FlowNode(); // Calculate flow for the body block next.Set(loop); node.block.Accept(this); FlowNode body = next.Get(); // Calculate flow for the test expression next.Set(body, end); node.test.Accept(this); // Link the back edge to before the test expression loop.next.Add(next.Get()); return null; }
public override void Leave(WhileStmt e) { }
protected override void MatchWhileStmt(WhileStmt stmt) { Resolve(stmt.Condition); Resolve(stmt.Body); }
void WhileStmt(out Statement stmt) { Contract.Ensures(Contract.ValueAtReturn(out stmt) != null); IToken x; Expression guard = null; IToken guardEllipsis = null; List<MaybeFreeExpression> invariants = new List<MaybeFreeExpression>(); List<Expression> decreases = new List<Expression>(); Attributes decAttrs = null; Attributes modAttrs = null; List<FrameExpression> mod = null; BlockStmt body = null; IToken bodyEllipsis = null; IToken bodyStart = null, bodyEnd = null, endTok = Token.NoToken; List<GuardedAlternative> alternatives; stmt = dummyStmt; // to please the compiler bool isDirtyLoop = true; Expect(99); x = t; if (IsLoopSpec() || IsAlternative()) { while (StartOf(22)) { LoopSpec(invariants, decreases, ref mod, ref decAttrs, ref modAttrs); } AlternativeBlock(false, out alternatives, out endTok); stmt = new AlternativeLoopStmt(x, endTok, invariants, new Specification<Expression>(decreases, decAttrs), new Specification<FrameExpression>(mod, modAttrs), alternatives); } else if (StartOf(20)) { if (StartOf(21)) { Guard(out guard); Contract.Assume(guard == null || cce.Owner.None(guard)); } else { Get(); guardEllipsis = t; } while (StartOf(22)) { LoopSpec(invariants, decreases, ref mod, ref decAttrs, ref modAttrs); } if (la.kind == _lbrace) { BlockStmt(out body, out bodyStart, out bodyEnd); endTok = body.EndTok; isDirtyLoop = false; } else if (la.kind == _ellipsis) { Expect(59); bodyEllipsis = t; endTok = t; isDirtyLoop = false; } else if (StartOf(23)) { } else SynErr(187); if (guardEllipsis != null || bodyEllipsis != null) { if (mod != null) { SemErr(mod[0].E.tok, "'modifies' clauses are not allowed on refining loops"); } if (body == null && !isDirtyLoop) { body = new BlockStmt(x, endTok, new List<Statement>()); } stmt = new WhileStmt(x, endTok, guard, invariants, new Specification<Expression>(decreases, decAttrs), new Specification<FrameExpression>(null, null), body); stmt = new SkeletonStatement(stmt, guardEllipsis, bodyEllipsis); } else { // The following statement protects against crashes in case of parsing errors if (body == null && !isDirtyLoop) { body = new BlockStmt(x, endTok, new List<Statement>()); } stmt = new WhileStmt(x, endTok, guard, invariants, new Specification<Expression>(decreases, decAttrs), new Specification<FrameExpression>(mod, modAttrs), body); } } else SynErr(188); }
public void WhileLoopTest() { var target = new EvaluateVisitor(); const int totalLoopIteration = 3; int loopIterations = 0; var condition = new Mock<Expression>(); condition.Setup(c => c.Accept(It.IsAny<IExpressionVisitor<Value, Scope>>(), It.IsAny<Scope>())) .Returns<IExpressionVisitor<Value, Scope>, Scope>( (v, s) => { loopIterations++; return new Value(loopIterations <= totalLoopIteration); }); var statement = new Mock<Statement>(); var expr = new WhileStmt(condition.Object, new ScopeBlockStmt(new[] { statement.Object })); target.Visit(expr, _scope); condition.Verify(c => c.Accept(target, _scope), Times.Exactly(totalLoopIteration + 1)); statement.Verify( s => s.Accept(target, It.IsAny<Scope>()), Times.Exactly(totalLoopIteration) ); }
/// <summary> /// Deep Copy WhileStmt /// @TODO copy mod /// </summary> /// <param name="stmt"></param> /// <returns></returns> public static WhileStmt CopyWhileStmt(WhileStmt stmt) { return new WhileStmt(stmt.Tok, stmt.EndTok, CopyExpression(stmt.Guard), CopyMaybeFreeExpressionList(stmt.Invariants), CopySpecificationExpression(stmt.Decreases), stmt.Mod, CopyBlockStmt(stmt.Body)); }
public void WhileFalseLoopTest() { var target = new EvaluateVisitor(); var condition = new Mock<Expression>(); condition.Setup(c => c.Accept(It.IsAny<IExpressionVisitor<Value, Scope>>(), It.IsAny<Scope>())) .Returns<IExpressionVisitor<Value, Scope>, Scope>( (v, s) => { return new Value(false); }); var statement = new Mock<Statement>(); var expr = new WhileStmt(condition.Object, new ScopeBlockStmt(new[] { statement.Object })); target.Visit(expr, _scope); condition.Verify(c => c.Accept(target, _scope), Times.Exactly(1)); statement.Verify(s => s.Accept(target, _scope), Times.Never()); }
public bool VisitWhileStmt(WhileStmt stmt) { throw new NotImplementedException(); }
public void WhileLoopConditionIgnoredTest() { var target = new EvaluateVisitor(); var conditionExecuted = false; var condition = new Mock<Expression>(); condition.Setup(c => c.Accept(It.IsAny<IExpressionVisitor<Value, Scope>>(), It.IsAny<Scope>())) .Returns<IExpressionVisitor<Value, Scope>, Scope>( (v, s) => { var retVal = new Value(!conditionExecuted); conditionExecuted = true; return retVal; }); var statement = new Mock<Statement>(); statement.Setup(c => c.Accept(It.IsAny<IExpressionVisitor<Value, Scope>>(), It.IsAny<Scope>())) .Returns<IExpressionVisitor<Value, Scope>, Scope>( (v, s) => { if (!conditionExecuted) throw new Exception("Statement executed before condition evaluated."); return new Value(false); }); var expr = new WhileStmt(condition.Object, new ScopeBlockStmt(new[] { statement.Object })); target.Visit(expr, _scope); condition.Verify(c => c.Accept(target, _scope), Times.Exactly(2)); statement.Verify(s => s.Accept(target, It.IsAny<Scope>()), Times.Once); }