public void TestIfWithThen() { var programSource = new TokenList() { { TokenType.KwIf }, { TokenType.Identifier, "true" }, { TokenType.KwThen }, { TokenType.KwReturn }, { TokenType.KwElse }, { TokenType.Identifier, "writeln" }, { TokenType.LParen }, { TokenType.RParen } }; Parser parser = new Parser(CreateMockScanner(programSource), new ErrorHandler()); ProgramNode program = parser.Parse(); var ifStmt = new IfStmt(0, 0); ifStmt.TestExpr = new VariableExpr(0, 0, "true"); ifStmt.TrueStatement = new ReturnStmt(0, 0); var call = new CallStmt(0, 0); call.ProcedureId = "writeln"; ifStmt.FalseStatement = call; expected.Block.Statements.Add(ifStmt); program.ShouldBeEquivalentTo(expected); }
/// <summary> /// Visit all conditional statements. /// See VisitConditionalStmt(ConditionalStmt x). /// </summary> virtual public void VisitIfStmt(IfStmt x) { for (int i = 0; i < x.Conditions.Count; i++) { VisitConditionalStmt(x.Conditions[i]); } }
public void Visit(IfStmt ifStmt, object[] args) { ifStmt.BlockList = new List <IfBlock>(); do { IfBlock block = new IfBlock(); block.Content = new List <Statement>(); block.Parent = ifStmt; block.Location = new Location(file, reader.LineNumber, reader.LinePosition); if (dic[reader.Name] == "else") { block.Condition = null; } else { reader.MoveToAttribute("cond"); string condExpr = reader.Value; Expr.Expression expr = exprParser.ParseExpr(condExpr, new Location(file, reader.LineNumber, reader.LinePosition).Offset(6)); //TODO:Location block.Condition = expr; } visitMainContent(block, block.Content); ifStmt.BlockList.Add(block); } while (dic[reader.Name] == "elseif" || dic[reader.Name] == "else"); }
public object Visit(IfStmt stmt) { LLVMValueRef condition = stmt.Condition.Accept(this); LLVMValueRef func = LLVM.GetBasicBlockParent(LLVM.GetInsertBlock(_builder)); // Blocks LLVMBasicBlockRef thenBB = LLVM.AppendBasicBlock(func, "then"); LLVMBasicBlockRef elseBB = LLVM.AppendBasicBlock(func, "else"); LLVMBasicBlockRef mergeBB = LLVM.AppendBasicBlock(func, "ifcont"); // Build condition LLVM.BuildCondBr(_builder, condition, thenBB, elseBB); // Then branch LLVM.PositionBuilderAtEnd(_builder, thenBB); // Position builder at block stmt.ThenBranch.Accept(this); // Generate branch code LLVM.BuildBr(_builder, mergeBB); // Redirect to merge // Else branch LLVM.PositionBuilderAtEnd(_builder, elseBB); // Position builder at block if (stmt.ElseBranch != null) { stmt.ElseBranch.Accept(this); // Generate branch code if else statement is present } LLVM.BuildBr(_builder, mergeBB); // Redirect to merge LLVM.PositionBuilderAtEnd(_builder, mergeBB); return(null); }
private IEnumerable <Solution> GenerateIfStmt(IfStmt original, Expression guard, IEnumerable <Solution> ifStmtEnum, IEnumerable <Solution> elseStmtEnum) { foreach (var @if in ifStmtEnum) { var bodyList = @if.State.GetAllUpdated(); var ifBody = new BlockStmt(original.Thn.Tok, original.Thn.EndTok, bodyList); if (elseStmtEnum != null) { foreach (var @else in elseStmtEnum) { var elseList = @else.State.GetAllUpdated(); Statement elseBody = null; // if original body was a plain else block if (original.Els is BlockStmt) { elseBody = new BlockStmt(original.Els.Tok, original.Thn.EndTok, elseList); } else // otherwise it was a 'else if' and the solution list should only contain one if stmt { elseBody = elseList[0]; } yield return(AddNewStatement(original, new IfStmt(original.Tok, original.EndTok, original.IsExistentialGuard, CopyExpression(guard), CopyBlockStmt(ifBody), elseBody))); } } else { yield return(AddNewStatement(original, new IfStmt(original.Tok, original.EndTok, original.IsExistentialGuard, CopyExpression(guard), CopyBlockStmt(ifBody), null))); } } }
/// <summary> /// Visits IfStmt and constructs if branch basic block. /// /// Does not decompose the condition expression using logical operations (&&, ||, and xor). /// Note that this is no longer supported - analyzer now expects that the expression is decomposed /// on the level of CFG and it does not deal with logical operations explicitly. /// See <see cref="VisitIfStmt"/>. /// </summary> /// <param name="x">IfStmt</param> public void VisitIfStmtOld(IfStmt x) { //Merge destination for if and else branch BasicBlock bottomBox = new BasicBlock(); currentBasicBlock.CreateWorklistSegment(bottomBox); foreach (var condition in x.Conditions) { if (condition.Condition != null) { //IF or ELSEIF branch currentBasicBlock = constructIfBranch(bottomBox, condition); } else { //ELSE branch condition.Statement.VisitMe(this); } } //Connect else branch to bottomBox //Must be here becouse in the construc phase we dont know whether the else block would split in the future BasicBlockEdge.ConnectDirectEdge(currentBasicBlock, bottomBox); currentBasicBlock = bottomBox; }
public void Visit(IfStmt ifStmt, object[] args) { foreach (IfBlock block in ifStmt.BlockList) { if (block.Condition != null) { RightValue cond = exprProcessor.Eval(block.Condition); if (cond.ToBoolean()) { kernel.RuntimeData.ScopeStack.Open(new LocalScope()); kernel.RuntimeData.InstructionStack.Push(InstructionStack.CLOSE_LOCAL_SCOPE_FLAG); kernel.RuntimeData.InstructionStack.Push(block.Content); break; } } else { kernel.RuntimeData.ScopeStack.Open(new LocalScope()); kernel.RuntimeData.InstructionStack.Push(InstructionStack.CLOSE_LOCAL_SCOPE_FLAG); kernel.RuntimeData.InstructionStack.Push(block.Content); break; } } kernel.Next(); }
private List <Tuple <Expression, List <Statement> > > GetGuadBodyList(IfStmt stmt, List <Tuple <Expression, List <Statement> > > resList) { // the else stmt will have expression true as the guard resList.Add(new Tuple <Expression, List <Statement> >(stmt.Guard, stmt.Thn.Body)); if (stmt.Els == null) { return(resList); } else { var blockStmt = stmt.Els as BlockStmt; if (blockStmt != null) { // else var body = blockStmt; resList.Add(new Tuple <Expression, List <Statement> >(null, body.Body)); return(resList); } else { // else if return(GetGuadBodyList(stmt.Els, resList)); } } }
public static void Main(string[] args) { IExeStack <IStatement> stack = new ExeStack <IStatement>(); Utils.IDictionary <string, int> dict = new MyDictionary <string, int>(); IMyList <int> output = new MyList <int>(); FileTable <int, FileData> fileTable = new FileTable <int, FileData>(); IStatement s1 = new OpenRFile("var_f", "C:\\Users\\Emy\\RiderProjects\\lab7\\text1.txt"); IStatement s2 = new ReadFile(new VarExp("var_f"), "var_c"); IStatement thenS1 = new ReadFile(new VarExp("var_f"), "var_c"); IStatement thenS2 = new PrintStmt(new VarExp("var_c")); IStatement thenS = new CompStmt(thenS1, thenS2); IStatement elseS = new PrintStmt(new ConstExp(0)); IStatement s3 = new IfStmt(new VarExp("var_c"), thenS, elseS); IStatement s4 = new CloseRFile(new VarExp("var_f")); IStatement s5 = new CompStmt(s1, s2); IStatement s6 = new CompStmt(s3, s4); IStatement s7 = new CompStmt(s5, s6); stack.push(s7); PrgState state = new PrgState(dict, stack, output, fileTable); Controller.Controller ctrl = new Controller.Controller(state); TextMenu menu = new TextMenu(); menu.addCommand(new ExitCommand("0", "exit")); menu.addCommand(new RunExample("1", "example_1", ctrl)); menu.show(); }
public virtual void Visit(IfStmt ifStatement) { // A guard may be null when using an asterisk for non-deterministic choices. VisitNullableExpression(ifStatement.Guard); VisitNullableAttributes(ifStatement.Attributes); VisitNullableBlock(ifStatement.Thn); VisitNullableStatement(ifStatement.Els); }
override public void VisitIfStmt(IfStmt x) { _serializer.StartSerialize(typeof(IfStmt).Name, SerializeSpan(x.Span)); _serializer.StartSerialize("CondList"); base.VisitIfStmt(x); _serializer.EndSerialize(); _serializer.EndSerialize(); }
public virtual bool VisitIfStmt(IfStmt stmt) { if (!VisitStmt(stmt)) { return(false); } return(true); }
protected override void MatchIfStmt(IfStmt stmt) { Resolve(stmt.Condition); Resolve(stmt.Then); if (stmt.Else != null) { Resolve(stmt.Else); } }
private void Resolve(IfStmt @if) { Resolve(@if.Condition); Resolve(@if.Consequent); if (@if.Alternative != null) { Resolve(@if.Alternative); } }
public override IAstNode VisitIfStmt(MicroCParser.IfStmtContext context) { var label = ++_label; IBExpr condition = Visit(context.b_expr()) as IBExpr; UnscopedBlock body = Visit(context.unscopedBlock()) as UnscopedBlock; var ifStmt = new IfStmt(condition, body); ifStmt.Label = label; return(ifStmt); }
public override void Visit(IfStmt n) { n.logi_expr.accept(this); plusScope(); foreach (AST ast in n.stmt_list) { ast.accept(this); } minusScope(); n.elseIF_Eles?.accept(this); }
private void Execute(IfStmt @if) { if (IsTruthy(Evaluate(@if.Condition))) { Execute(@if.Consequent); } else if (@if.Alternative != null) { Execute(@if.Alternative); } }
public void TestBooleanIfTest() { var program = new ProgramNode(0, 0); program.Block = new BlockStmt(0, 0); var ifStmt = new IfStmt(0, 0); ifStmt.TestExpr = new VariableExpr(0, 0, "true"); ifStmt.TrueStatement = new BlockStmt(0, 0); program.Block.Statements.Add(ifStmt); AssertNoErrors(program); }
public void Visit(IfStmt stmt) { stmt.Function.Accept(this); stmt.Body.Accept(this); if (stmt.ElseBody != null) { // else label remains unlinked EmitLabel("else"); stmt.ElseBody.Accept(this); } }
public void TestIfTestWithoutBoolean() { var program = new ProgramNode(0, 0); program.Block = new BlockStmt(0, 0); var ifStmt = new IfStmt(0, 0); ifStmt.TrueStatement = new BlockStmt(0, 0); ifStmt.TestExpr = new IntLiteralExpr(0, 0, 1); program.Block.Statements.Add(ifStmt); AssertErrorContains(program, "If test expression has to be of type Bool"); }
private static List <Expression> ExtractGuard(IfStmt statement) { Contract.Requires(statement != null); List <Expression> guardList = new List <Expression>(); guardList.Add(statement.Guard); if (statement.Els != null && statement.Els is IfStmt) { guardList.AddRange(ExtractGuard(statement.Els as IfStmt)); } return(guardList); }
public string Visit(IfStmt stmt, Scope scope) { var ifstatement = string.Format("if({0})\r\n{{\r\n\t{1}\r\n}}", stmt.Condition.Accept(this, scope), stmt.ThenExpression.Accept(this, scope)); if (!(stmt.ElseExpression is NoOpStatement)) { ifstatement += string.Format("else\r\n{{\r\n\t{0}\r\n}}", stmt.ThenExpression.Accept(this, scope)); } return(ifstatement); }
public void Visit(IfStmt stmt) { stmt.Function.Accept(this); stmt.Body.Accept(this); var thenStart = BlockStart; if (stmt.ElseBody != null) { // else label remains unlinked EmitLabel("else"); stmt.ElseBody.Accept(this); var elseStart = BlockStart; thenStart.LinkedElement = elseStart; } }
public void visit_if(IfStmt if_stmt) { // Resolve the if condition resolve(if_stmt.if_body.Item1); // Resolve the if body resolve(if_stmt.if_body.Item2); foreach (Tuple <Expression, Statement> elif in if_stmt.elif_body) { resolve(elif.Item1); resolve(elif.Item2); } if (if_stmt.else_body != null) { resolve(if_stmt.else_body); } }
public Value Visit(IfStmt stmt, Scope scope) { var condition = stmt.Condition.Accept(this, scope); if (condition.Type != ValueType.Boolean) { throw new InvalidCastException(); } if (condition.ToBoolean()) { return(stmt.ThenExpression.Accept(this, scope)); } return(stmt.ElseExpression.Accept(this, scope)); }
private static IfStmt InsertCodeIfStmt(IfStmt stmt, List <Statement> code, UpdateStmt tacticCall) { Contract.Requires <ArgumentNullException>(stmt != null, "stmt"); Contract.Requires <ArgumentNullException>(code != null, "code"); Contract.Requires <ArgumentNullException>(tacticCall != null, "tacticCall"); stmt.Thn = InsertCodeInternal(stmt.Thn, code, tacticCall); if (stmt.Els is BlockStmt) { stmt.Els = InsertCodeInternal((BlockStmt)stmt.Els, code, tacticCall); } else if (stmt.Els is IfStmt) { stmt.Els = InsertCodeIfStmt((IfStmt)stmt.Els, code, tacticCall); } return(stmt); }
public PrgState <T> Execute <T>(PrgState <T> state) { // MyIDictionary symTable = state.getSymTable(); // int var = switchStmt.getExp2().eval(symTable); // if(var - switchStmt.getExp1().eval(symTable) == 0) // if(var - switchStmt.getExp1().eval(symTable) == 0) // state.addExeStack(switchStmt.getStatement3()); // else state.addExeStack(switchStmt.getStatement1()); // else state.addExeStack(switchStmt.getStatement2()); IStmt stmt = new IfStmt(new ArithExp("-", mVarExp, mExp2), new IfStmt(new ArithExp("-", mVarExp, mExp1), mStatement3, mStatement1), mStatement2); state.AddExeStack((T)stmt); return(null); }
public object Visit(IfStmt stmt) { DataType conditionType = stmt.Condition.Accept(this); if (conditionType.BaseType != BaseType.Boolean || conditionType.ArrayDepth > 0) { Reporter.Error(new Pos(0, 0), "Expected type 'bool' as conditional."); } stmt.ThenBranch.Accept(this); if (stmt.ElseBranch != null) { stmt.ElseBranch.Accept(this); } return(null); }
protected override ILattice <FVDomain> TransferFunctions(int label) { var block = GetBlock(label); var domain = _analysisCircle[label].GetDomain(); var newDomain = block switch { AssignStmt assignStmt => AssignTransfer(assignStmt, domain), RecAssignStmt recAssignStmt => RecAssignTransfer(recAssignStmt, domain), IfStmt ifStmt => ConditionTransfer(ifStmt.Condition, domain), IfElseStmt ifElseStmt => ConditionTransfer(ifElseStmt.Condition, domain), WhileStmt whileStmt => ConditionTransfer(whileStmt.Condition, domain), WriteStmt writeStmt => WriteTransfer(writeStmt, domain), ReadStmt readStmt => ReadTransfer(readStmt, domain), _ => new FVDomain(), }; return(new FVLattice(newDomain)); }
public void IfStatementWithNoElseTest(bool conditionValue) { 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) => new Value(conditionValue)); var trueStmt = new Mock <Statement>(); var expr = new IfStmt(condition.Object, trueStmt.Object, null); target.Visit(expr, _scope); condition.Verify(c => c.Accept(target, _scope), Times.Once); trueStmt.Verify(s => s.Accept(target, _scope), Times.Exactly(conditionValue ? 1 : 0)); }
BlockStmt MergeBlockStmt(BlockStmt skeleton, BlockStmt oldStmt) { Contract.Requires(skeleton != null); Contract.Requires(oldStmt != null); var body = new List<Statement>(); int i = 0, j = 0; while (i < skeleton.Body.Count) { var cur = skeleton.Body[i]; if (j == oldStmt.Body.Count) { if (!(cur is SkeletonStatement)) { MergeAddStatement(cur, body); } else if (((SkeletonStatement)cur).S == null) { // the "..." matches the empty statement sequence } else { reporter.Error(MessageSource.RefinementTransformer, cur.Tok, "skeleton statement does not match old statement"); } i++; } else { var oldS = oldStmt.Body[j]; /* See how the two statements match up. * oldS cur result * ------ ------ ------ * assume E; assert ...; assert E; * assert E; assert ...; assert E; * assert E; assert E; * * assume E; assume ...; assume E; * * var x; var x := E; var x := E; * var x := *; var x := E; var x := E; * var x :| P; var x := E1; var x := E1; assert P; * var VarProduction; var VarProduction; * * x := *; x := E; x := E; * x :| P; x := E; x := E; assert P; * * modify E; modify ...; modify E; * modify E; modify ... { S } modify E { S } * modify E { S } modify ... { S' } modify E { Merge(S, S') } * * if (G) Then' else Else' if ... Then else Else if (G) Merge(Then,Then') else Merge(Else,Else') * if (*) Then' else Else' if (G) Then else Else if (G) Merge(Then,Then') else Merge(Else,Else') * * while (G) LoopSpec' Body while ... LoopSpec ... while (G) Merge(LoopSpec,LoopSpec') Body * while (G) LoopSpec' Body' while ... LoopSpec Body while (G) Merge(LoopSpec,LoopSpec') Merge(Body,Body') * while (*) LoopSpec' Body while (G) LoopSpec ... while (G) Merge(LoopSpec,LoopSpec') Body * while (*) LoopSpec' Body' while (G) LoopSpec Body while (G) Merge(LoopSpec,LoopSpec') Merge(Body,Body') * * StmtThatDoesNotMatchS; S' ... where x = e; S StatementThatDoesNotMatchS[e/x]; Merge( ... where x = e; S , S') * StmtThatMatchesS; S' ... where x = e; S StmtThatMatchesS; S' * * Note, LoopSpec must contain only invariant declarations (as the parser ensures for the first three cases). * Note, there is an implicit "...;" at the end of every block in a skeleton. */ if (cur is SkeletonStatement) { var c = (SkeletonStatement)cur; var S = c.S; if (S == null) { var nxt = i + 1 == skeleton.Body.Count ? null : skeleton.Body[i + 1]; if (nxt != null && nxt is SkeletonStatement && ((SkeletonStatement)nxt).S == null) { // "...; ...;" is the same as just "...;", so skip this one } else { SubstitutionCloner subber = null; if (c.NameReplacements != null) { var subExprs = new Dictionary<string, Expression>(); Contract.Assert(c.NameReplacements.Count == c.ExprReplacements.Count); for (int k = 0; k < c.NameReplacements.Count; k++) { if (subExprs.ContainsKey(c.NameReplacements[k].val)) { reporter.Error(MessageSource.RefinementTransformer, c.NameReplacements[k], "replacement definition must contain at most one definition for a given label"); } else subExprs.Add(c.NameReplacements[k].val, c.ExprReplacements[k]); } subber = new SubstitutionCloner(subExprs, rawCloner); } // skip up until the next thing that matches "nxt" var hoverTextA = ""; var sepA = ""; while (nxt == null || !PotentialMatch(nxt, oldS)) { // loop invariant: oldS == oldStmt.Body[j] var s = refinementCloner.CloneStmt(oldS); if (subber != null) s = subber.CloneStmt(s); body.Add(s); hoverTextA += sepA + Printer.StatementToString(s); sepA = "\n"; j++; if (j == oldStmt.Body.Count) { break; } oldS = oldStmt.Body[j]; } if (hoverTextA.Length != 0) { reporter.Info(MessageSource.RefinementTransformer, c.Tok, hoverTextA); } if (subber != null && subber.SubstitutionsMade.Count < subber.Exprs.Count) { foreach (var s in subber.SubstitutionsMade) subber.Exprs.Remove(s); reporter.Error(MessageSource.RefinementTransformer, c.Tok, "could not find labeled expression(s): " + Util.Comma(", ", subber.Exprs.Keys, x => x)); } } i++; } else if (S is AssertStmt) { var skel = (AssertStmt)S; Contract.Assert(c.ConditionOmitted); var oldAssume = oldS as PredicateStmt; if (oldAssume == null) { reporter.Error(MessageSource.RefinementTransformer, cur.Tok, "assert template does not match inherited statement"); i++; } else { // Clone the expression, but among the new assert's attributes, indicate // that this assertion is supposed to be translated into a check. That is, // it is not allowed to be just assumed in the translation, despite the fact // that the condition is inherited. var e = refinementCloner.CloneExpr(oldAssume.Expr); var attrs = refinementCloner.MergeAttributes(oldAssume.Attributes, skel.Attributes); body.Add(new AssertStmt(new Translator.ForceCheckToken(skel.Tok), new Translator.ForceCheckToken(skel.EndTok), e, skel.Proof, new Attributes("prependAssertToken", new List<Expression>(), attrs))); reporter.Info(MessageSource.RefinementTransformer, c.ConditionEllipsis, "assume->assert: " + Printer.ExprToString(e)); i++; j++; } } else if (S is AssumeStmt) { var skel = (AssumeStmt)S; Contract.Assert(c.ConditionOmitted); var oldAssume = oldS as AssumeStmt; if (oldAssume == null) { reporter.Error(MessageSource.RefinementTransformer, cur.Tok, "assume template does not match inherited statement"); i++; } else { var e = refinementCloner.CloneExpr(oldAssume.Expr); var attrs = refinementCloner.MergeAttributes(oldAssume.Attributes, skel.Attributes); body.Add(new AssumeStmt(skel.Tok, skel.EndTok, e, attrs)); reporter.Info(MessageSource.RefinementTransformer, c.ConditionEllipsis, Printer.ExprToString(e)); i++; j++; } } else if (S is IfStmt) { var skel = (IfStmt)S; Contract.Assert(c.ConditionOmitted); var oldIf = oldS as IfStmt; if (oldIf == null) { reporter.Error(MessageSource.RefinementTransformer, cur.Tok, "if-statement template does not match inherited statement"); i++; } else { var resultingThen = MergeBlockStmt(skel.Thn, oldIf.Thn); var resultingElse = MergeElse(skel.Els, oldIf.Els); var e = refinementCloner.CloneExpr(oldIf.Guard); var r = new IfStmt(skel.Tok, skel.EndTok, oldIf.IsExistentialGuard, e, resultingThen, resultingElse); body.Add(r); reporter.Info(MessageSource.RefinementTransformer, c.ConditionEllipsis, Printer.GuardToString(oldIf.IsExistentialGuard, e)); i++; j++; } } else if (S is WhileStmt) { var skel = (WhileStmt)S; var oldWhile = oldS as WhileStmt; if (oldWhile == null) { reporter.Error(MessageSource.RefinementTransformer, cur.Tok, "while-statement template does not match inherited statement"); i++; } else { Expression guard; if (c.ConditionOmitted) { guard = refinementCloner.CloneExpr(oldWhile.Guard); reporter.Info(MessageSource.RefinementTransformer, c.ConditionEllipsis, Printer.GuardToString(false, oldWhile.Guard)); } else { if (oldWhile.Guard != null) { reporter.Error(MessageSource.RefinementTransformer, skel.Guard.tok, "a skeleton while statement with a guard can only replace a while statement with a non-deterministic guard"); } guard = skel.Guard; } // Note, if the loop body is omitted in the skeleton, the parser will have set the loop body to an empty block, // which has the same merging behavior. var r = MergeWhileStmt(skel, oldWhile, guard); body.Add(r); i++; j++; } } else if (S is ModifyStmt) { var skel = (ModifyStmt)S; Contract.Assert(c.ConditionOmitted); var oldModifyStmt = oldS as ModifyStmt; if (oldModifyStmt == null) { reporter.Error(MessageSource.RefinementTransformer, cur.Tok, "modify template does not match inherited statement"); i++; } else { var mod = refinementCloner.CloneSpecFrameExpr(oldModifyStmt.Mod); BlockStmt mbody; if (oldModifyStmt.Body == null && skel.Body == null) { mbody = null; } else if (oldModifyStmt.Body == null) { mbody = skel.Body; } else if (skel.Body == null) { reporter.Error(MessageSource.RefinementTransformer, cur.Tok, "modify template must have a body if the inherited modify statement does"); mbody = null; } else { mbody = MergeBlockStmt(skel.Body, oldModifyStmt.Body); } body.Add(new ModifyStmt(skel.Tok, skel.EndTok, mod.Expressions, mod.Attributes, mbody)); reporter.Info(MessageSource.RefinementTransformer, c.ConditionEllipsis, Printer.FrameExprListToString(mod.Expressions)); i++; j++; } } else { Contract.Assume(false); // unexpected skeleton statement } } else if (cur is AssertStmt) { MergeAddStatement(cur, body); i++; } else if (cur is VarDeclStmt) { var cNew = (VarDeclStmt)cur; bool doMerge = false; Expression addedAssert = null; if (oldS is VarDeclStmt) { var cOld = (VarDeclStmt)oldS; if (LocalVarsAgree(cOld.Locals, cNew.Locals)) { var update = cNew.Update as UpdateStmt; if (update != null && update.Rhss.TrueForAll(rhs => !rhs.CanAffectPreviouslyKnownExpressions)) { // Note, we allow switching between ghost and non-ghost, since that seems unproblematic. if (cOld.Update == null) { doMerge = true; } else if (cOld.Update is AssignSuchThatStmt) { doMerge = true; addedAssert = refinementCloner.CloneExpr(((AssignSuchThatStmt)cOld.Update).Expr); } else { var updateOld = (UpdateStmt)cOld.Update; // if cast fails, there are more ConcreteUpdateStatement subclasses than expected doMerge = true; foreach (var rhs in updateOld.Rhss) { if (!(rhs is HavocRhs)) doMerge = false; } } } } } if (doMerge) { // Go ahead with the merge: body.Add(cNew); i++; j++; if (addedAssert != null) { var tok = new Translator.ForceCheckToken(addedAssert.tok); body.Add(new AssertStmt(tok, tok, addedAssert, null, null)); } } else { MergeAddStatement(cur, body); i++; } } else if (cur is AssignStmt) { var cNew = (AssignStmt)cur; var cOld = oldS as AssignStmt; if (cOld == null && oldS is UpdateStmt) { var us = (UpdateStmt)oldS; if (us.ResolvedStatements.Count == 1) { cOld = us.ResolvedStatements[0] as AssignStmt; } } bool doMerge = false; if (cOld != null && cNew.Lhs.WasResolved() && cOld.Lhs.WasResolved()) { var newLhs = cNew.Lhs.Resolved as IdentifierExpr; var oldLhs = cOld.Lhs.Resolved as IdentifierExpr; if (newLhs != null && oldLhs != null && newLhs.Name == oldLhs.Name) { if (!(cNew.Rhs is TypeRhs) && cOld.Rhs is HavocRhs) { doMerge = true; } } } if (doMerge) { // Go ahead with the merge: body.Add(cNew); i++; j++; } else { MergeAddStatement(cur, body); i++; } } else if (cur is UpdateStmt) { var nw = (UpdateStmt)cur; List<Statement> stmtGenerated = new List<Statement>(); bool doMerge = false; if (oldS is UpdateStmt) { var s = (UpdateStmt)oldS; if (LeftHandSidesAgree(s.Lhss, nw.Lhss)) { doMerge = true; stmtGenerated.Add(nw); foreach (var rhs in s.Rhss) { if (!(rhs is HavocRhs)) doMerge = false; } } } else if (oldS is AssignSuchThatStmt) { var s = (AssignSuchThatStmt)oldS; if (LeftHandSidesAgree(s.Lhss, nw.Lhss)) { doMerge = true; stmtGenerated.Add(nw); var addedAssert = refinementCloner.CloneExpr(s.Expr); var tok = new Translator.ForceCheckToken(addedAssert.tok); stmtGenerated.Add(new AssertStmt(tok, tok, addedAssert, null, null)); } } if (doMerge) { // Go ahead with the merge: Contract.Assert(cce.NonNullElements(stmtGenerated)); body.AddRange(stmtGenerated); i++; j++; } else { MergeAddStatement(cur, body); i++; } } else if (cur is IfStmt) { var cNew = (IfStmt)cur; var cOld = oldS as IfStmt; if (cOld != null && cOld.Guard == null) { var r = new IfStmt(cNew.Tok, cNew.EndTok, cNew.IsExistentialGuard, cNew.Guard, MergeBlockStmt(cNew.Thn, cOld.Thn), MergeElse(cNew.Els, cOld.Els)); body.Add(r); i++; j++; } else { MergeAddStatement(cur, body); i++; } } else if (cur is WhileStmt) { var cNew = (WhileStmt)cur; var cOld = oldS as WhileStmt; if (cOld != null && cOld.Guard == null) { var r = MergeWhileStmt(cNew, cOld, cNew.Guard); body.Add(r); i++; j++; } else { MergeAddStatement(cur, body); i++; } } else if (cur is BlockStmt) { var cNew = (BlockStmt)cur; var cOld = oldS as BlockStmt; if (cOld != null) { var r = MergeBlockStmt(cNew, cOld); body.Add(r); i++; j++; } else { MergeAddStatement(cur, body); i++; } } else { MergeAddStatement(cur, body); i++; } } } // implement the implicit "...;" at the end of each block statement skeleton var hoverText = ""; var sep = ""; for (; j < oldStmt.Body.Count; j++) { var b = oldStmt.Body[j]; body.Add(refinementCloner.CloneStmt(b)); hoverText += sep + Printer.StatementToString(b); sep = "\n"; } if (hoverText.Length != 0) { reporter.Info(MessageSource.RefinementTransformer, skeleton.EndTok, hoverText); } return new BlockStmt(skeleton.Tok, skeleton.EndTok, body); }
/// <summary> /// Create a deep copy if IfStmt /// </summary> /// <param name="stmt"></param> /// <returns></returns> public static IfStmt CopyIfStmt(IfStmt stmt) { return new IfStmt(stmt.Tok, stmt.EndTok, stmt.IsExistentialGuard, CopyExpression(stmt.Guard), CopyBlockStmt(stmt.Thn), CopyStatement(stmt.Els)); }
public override Null Visit(IfStmt node) { base.Visit(node); if (!node.test.computedType.IsBool()) { log.ErrorTypeMismatch(node.test.location, new PrimType { kind = PrimKind.Bool }, node.test.computedType); } return null; }
void IfStmt(out Statement/*!*/ ifStmt) { Contract.Ensures(Contract.ValueAtReturn(out ifStmt) != null); IToken/*!*/ x; Expression guard = null; IToken guardEllipsis = null; bool isExistentialGuard = false; BlockStmt/*!*/ thn; BlockStmt/*!*/ bs; Statement/*!*/ s; Statement els = null; IToken bodyStart, bodyEnd, endTok; List<GuardedAlternative> alternatives; ifStmt = dummyStmt; // to please the compiler Expect(98); x = t; if (IsAlternative()) { AlternativeBlock(true, out alternatives, out endTok); ifStmt = new AlternativeStmt(x, endTok, alternatives); } else if (StartOf(20)) { if (IsExistentialGuard()) { ExistentialGuard(out guard, true); isExistentialGuard = true; } else if (StartOf(21)) { Guard(out guard); } else { Get(); guardEllipsis = t; } BlockStmt(out thn, out bodyStart, out bodyEnd); endTok = thn.EndTok; if (la.kind == 35) { Get(); if (la.kind == 98) { IfStmt(out s); els = s; endTok = s.EndTok; } else if (la.kind == 46) { BlockStmt(out bs, out bodyStart, out bodyEnd); els = bs; endTok = bs.EndTok; } else SynErr(185); } if (guardEllipsis != null) { ifStmt = new SkeletonStatement(new IfStmt(x, endTok, isExistentialGuard, guard, thn, els), guardEllipsis, null); } else { ifStmt = new IfStmt(x, endTok, isExistentialGuard, guard, thn, els); } } else SynErr(186); }
public override Null Visit(IfStmt node) { // Calculate flow for the else branch, adding another // node at the end for analysis inside the branch FlowNode end = next.Get(); next.Set(new FlowNode(end)); if (node.elseBlock != null) { node.elseBlock.Accept(this); } FlowNode elseNode = next.Get(); // Calculate flow for the then branch, adding another // node at the end for analysis inside the branch next.Set(new FlowNode(end)); node.thenBlock.Accept(this); FlowNode thenNode = next.Get(); // Calculate flow for the test expression next.Set(thenNode, elseNode); node.test.Accept(this); return null; }
void PrintIfStatement(int indent, IfStmt s, bool omitGuard) { if (omitGuard) { wr.Write("if ... "); } else { wr.Write("if "); PrintGuard(s.IsExistentialGuard, s.Guard); wr.Write(" "); } PrintStatement(s.Thn, indent); if (s.Els != null) { wr.Write(" else "); PrintStatement(s.Els, indent); } }
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 void SearchIfStmt(IfStmt ifStmt) { Contract.Requires(tcce.NonNull(ifStmt)); SearchBlockStmt(ifStmt.Thn); if (ifStmt.Els == null) return; var els = ifStmt.Els as BlockStmt; if (els != null) { SearchBlockStmt(els); } else if (ifStmt.Els is IfStmt) { SearchIfStmt((IfStmt)ifStmt.Els); } }
private void FindRemovableTypesInIfStmt(IfStmt ifstmt, Method method, WildCardDecreases wildCardParent, ClassDecl classDecl) { FindRemovableTypesInStatement(ifstmt.Thn, ifstmt, method, wildCardParent, classDecl); FindRemovableTypesInStatement(ifstmt.Els, ifstmt, method, wildCardParent, classDecl); }
public void IfStatementWithElseTest(bool conditionValue) { 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) => new Value(conditionValue)); var trueStmt = new Mock<Statement>(); var falseStmt = new Mock<Statement>(); var expr = new IfStmt(condition.Object, trueStmt.Object, falseStmt.Object); target.Visit(expr, _scope); condition.Verify(c => c.Accept(target, _scope), Times.Once); trueStmt.Verify(s => s.Accept(target, _scope), Times.Exactly(conditionValue ? 1 : 0)); falseStmt.Verify(s => s.Accept(target, _scope), Times.Exactly(!conditionValue ? 1 : 0)); }