ExpressionType TranslateExpression(IfExpression e) { Types.Type temp; ExpressionType test = TranslateExpression(e.Test); ExpressionType then = TranslateExpression(e.Then); ExpressionType els = e.Else == null ? null : TranslateExpression(e.Else); CheckInteger(e.Test.Pos, test); if (els != null) { if ((temp = CheckIfType(e.Pos, then, els)) != null) { return(new ExpressionType(Translate.TranslateIfThenElseExp(test.Exp, then.Exp, els.Exp), temp)); } else { Error.Report(e.Pos, "Type mismatch in if expression"); return(new ExpressionType(null, Types.Type._void)); } } else { if (then.Type.CoerceTo(Types.Type._void)) { return(new ExpressionType(Translate.TranslateIfThenElseExp(test.Exp, then.Exp, null), Types.Type._void)); } else { Error.Report(e.Pos, "Then clause must return 'void'"); return(new ExpressionType(null, Types.Type._void)); } } }
private void CompileIfExpression(InstructionSet instructionSet, IfExpression exp, Scope scope, LocalTable table) { CompileExpression(instructionSet, exp.Condition, scope, table); var anchor1 = new Anchor(); instructionSet.Define(InstructionType.BranchUnless, anchor1); CompileBlockStatement(instructionSet, exp.Consequence, scope, table); anchor1.Line = instructionSet.Count + 1; if (exp.Alternative == null) { anchor1.Line--; instructionSet.Define(InstructionType.PutNull); return; } var anchor2 = new Anchor(); instructionSet.Define(InstructionType.Jump, anchor2); CompileBlockStatement(instructionSet, exp.Alternative, scope, table); anchor2.Line = instructionSet.Count; }
public int Visit(IfExpression expression) { for (var i = 0; i < expression.Branches.Count; i++) { var branch = expression.Branches[i]; _writer.Write(i == 0 ? "if" : "else if"); _writer.Write(" ("); branch.Condition.Accept(this); _writer.WriteLine(")"); branch.Block.Accept(this); if (expression.Else != null || i < expression.Branches.Count - 1) { _writer.WriteLine(); } } if (expression.Else != null) { _writer.WriteLine("else "); expression.Else.Block.Accept(this); } return(0); }
public void GetAndEvaluateIfExpression() { IfExpression expression = IfExpression.Instance; Assert.IsNotNull(expression); Machine machine = new Machine(); machine.Push(true); machine.Push(new IntegerExpression(1)); machine.Push(new IntegerExpression(2)); expression.Evaluate(machine); Assert.AreEqual(1, machine.StackCount); Assert.AreEqual(1, machine.Pop()); machine.Push(false); machine.Push(new IntegerExpression(1)); machine.Push(new IntegerExpression(2)); expression.Evaluate(machine); Assert.AreEqual(1, machine.StackCount); Assert.AreEqual(2, machine.Pop()); }
protected virtual Expression VisitIf(IfExpression node) { Visit(node.Test); Visit(node.IfTrue); Visit(node.IfFalse); return(node); }
public void EvaluateElseExpression() { IfExpression ifexpr = new IfExpression(new ConstantExpression(false), new ConstantExpression(1), new ConstantExpression(2)); Assert.AreSame(TypeInfo.Int, ifexpr.TypeInfo); Assert.AreEqual(2, ifexpr.Evaluate(null)); }
private Expression ParseIfExpression() { var expression = new IfExpression(); expression.Token = this._curToken; if (!this.ExpectPeek(TokenType.LPAREN)) { throw new ParserException($"Expect peek a {TokenType.LPAREN} but got {this._peekToken}"); } this.NextToken(); expression.Condition = this.ParseExpression(Precedence.LOWEST); if (!this.ExpectPeek(TokenType.RPAREN)) { throw new ParserException($"Expect peek a {TokenType.RPAREN}, but got {this._peekToken}"); } if (!this.ExpectPeek(TokenType.LBRACE)) { throw new ParserException($"Expect peek a {TokenType.LBRACE}, but got {this._peekToken}"); } expression.Consequence = this.ParseBlockStatement(); if (this.PeekTokenIs(TokenType.ELSE)) { this.NextToken(); if (!this.ExpectPeek(TokenType.LBRACE)) { throw new ParserException($"Expect peek a {TokenType.LBRACE}, but got {this._peekToken}"); } expression.Alternative = this.ParseBlockStatement(); } return(expression); }
public void Parser_CanParseIfElseExpressions() { string input = @" if (x < y) { x } else { y } "; AST result = this.subject.ParseProgram(input); Assert.Equal(1, result.Program.Statements.Count); Assert.Empty(result.Errors); ExpressionStatement actual = this.AssertAndCast <ExpressionStatement>(result.Program.Statements[0]); IfExpression ifExpression = this.AssertAndCast <IfExpression>(actual.Expression); Assert.Equal("(x < y)", ifExpression.Condition.StringValue); Assert.Equal(1, ifExpression.Consequence.Statements.Count); ExpressionStatement expr = this.AssertAndCast <ExpressionStatement>(ifExpression.Consequence.Statements[0]); Identifier identifier = this.AssertAndCast <Identifier>(expr.Expression); Assert.Equal("x", identifier.Value); Assert.NotNull(ifExpression.Alternative); Assert.Equal(1, ifExpression.Alternative.Statements.Count); expr = this.AssertAndCast <ExpressionStatement>(ifExpression.Alternative.Statements[0]); identifier = this.AssertAndCast <Identifier>(expr.Expression); Assert.Equal("y", identifier.Value); }
public IExpression Parse(Parser parser, Token token) { if (!parser.LookAhead().IsType(TokenType.Identifier)) { throw new ParseException(token.Position, "Tag name must be a valid identifier."); } IExpression nameEx = parser.ParseExpression <TagExpression>(); string name = ((IdentifierExpression)nameEx).Name; var parameters = new List <IExpression>(); while (parser.LookAhead().IsType(TokenType.Identifier)) { IExpression param = parser.ParseExpression <TagExpression>(); parameters.Add(param); } parser.Match(TokenType.RightBracket); // optional if (new[] { "if", "elsif", "else" }.Contains(name)) { var children = new List <IExpression>(); IfExpression fallback = null; TagExpression childTag; do { IExpression child = parser.ParseExpression <IfExpression>(); childTag = child as TagExpression; var ifChild = childTag as IfExpression; if (childTag == null || childTag.Name != "endif" && (ifChild == null || ifChild.IsRoot)) { children.Add(child); } else { fallback = ifChild; } } while (fallback == null && childTag?.Name != "endif"); return(new IfExpression(name, parameters, children, fallback)); } if (name == "macro") { var children = new List <IExpression>(); TagExpression childTag; do { IExpression child = parser.ParseExpression <IfExpression>(); childTag = child as TagExpression; if (childTag == null || childTag.Name != "endmacro") { children.Add(child); } } while (childTag?.Name != "endmacro"); return(new MacroExpression(name, parameters, children)); } return(new TagExpression(name, parameters)); }
public void ExecuteThenWhenConditionIsZero() { IfExpression cmd = new IfExpression(new ConstantExpression(0), new AssignExpression("one", new ConstantExpression(1))); Context context = new Context(); Assert.AreEqual(1, cmd.Evaluate(context)); Assert.AreEqual(1, context.GetValue("one")); }
public void DontExecuteThenWhenConditionIsNull() { IfExpression cmd = new IfExpression(new ConstantExpression(null), new AssignExpression("one", new ConstantExpression(1))); Context context = new Context(); Assert.IsNull(cmd.Evaluate(context)); Assert.IsNull(context.GetValue("one")); }
public void ExecuteElseWhenConditionIsNull() { IfExpression cmd = new IfExpression(new ConstantExpression(null), new AssignExpression("one", new ConstantExpression(1)), new AssignExpression("two", new ConstantExpression(2))); Context context = new Context(); Assert.AreEqual(cmd.Evaluate(context), 2); Assert.IsNull(context.GetValue("one")); Assert.AreEqual(2, context.GetValue("two")); }
public void TestAppendString() { var expr = new IfExpression(new IntegerConstantExpression(1)); var builder = new StringBuilder(); expr.AppendString(builder); Assert.That(builder.ToString(), Is.EqualTo("if (1) { ... }")); // NOTE: does not output Expressions block }
private IfExpression Parse(string input) { var tokenizer = new PositionalTokenizer(Tokenizer.CreateTokenizer(input)); tokenizer.Match("if"); var expr = IfExpression.Parse(tokenizer); Assert.That(expr, Is.InstanceOf <IfExpression>()); return((IfExpression)expr); }
public void ParseIfCommandWithCompositeThenCommand() { Parser parser = new Parser("if 1\n a=1\n b=2\nend"); var expected = new IfExpression(new ConstantExpression(1), new CompositeExpression(new IExpression[] { new AssignExpression("a", new ConstantExpression(1)), new AssignExpression("b", new ConstantExpression(2)) })); var result = parser.ParseCommand(); Assert.IsNotNull(result); Assert.AreEqual(expected, result); Assert.IsNull(parser.ParseCommand()); }
public void ParseSimpleIfCommandWithSemicolonOneLine() { Parser parser = new Parser("if 1; a=1 end"); var expected = new IfExpression(new ConstantExpression(1), new AssignExpression("a", new ConstantExpression(1))); var result = parser.ParseCommand(); Assert.IsNotNull(result); Assert.AreEqual(expected, result); Assert.IsNull(parser.ParseCommand()); }
public void ParseSimpleIfElseCommand() { Parser parser = new Parser("if 1\n a=1\nelse\n a=2\nend"); var expected = new IfExpression(new ConstantExpression(1), new AssignExpression("a", new ConstantExpression(1)), new AssignExpression("a", new ConstantExpression(2))); var result = parser.ParseCommand(); Assert.IsNotNull(result); Assert.AreEqual(expected, result); Assert.IsNull(parser.ParseCommand()); }
private IfInstruction PopulateIfCondition(ScopePrototype scope, IfExpression ifExpression, ElseExpression elseExpression) { var ifInstruction = new IfInstruction(scope, ifExpression); PopulateInstructions(ifExpression.Instructions, ifInstruction.IfBlock, scope); if (elseExpression != null) { PopulateInstructions(elseExpression.Instructions, ifInstruction.ElseBlock, scope); } return(ifInstruction); }
void PrintExpression(IfExpression e, int d) { SayLn("IfExpression("); PrintExpression(e.Test, d + 1); SayLn(","); PrintExpression(e.Then, d + 1); if (e.Else != null) { /* else is optional */ SayLn(","); PrintExpression(e.Else, d + 1); } Say(")"); }
private AphidObject InterpretIfExpression(IfExpression expression) { if ((bool)ValueHelper.Unwrap(InterpretExpression(expression.Condition))) { InterpretChild(expression.Body); } else if (expression.ElseBody != null) { InterpretChild(expression.ElseBody); } return(null); }
public TypeDenoter VisitIfExpression(IfExpression ast, Void arg) { var e1Type = ast.TestExpression.Visit(this); CheckAndReportError(e1Type == StandardEnvironment.BooleanType, "Boolean expression expected here", ast.TestExpression); var e2Type = ast.TrueExpression.Visit(this); var e3Type = ast.FalseExpression.Visit(this); CheckAndReportError(e2Type.Equals(e3Type), "incompatible limbs in if-expression", ast); return(ast.Type = e2Type); }
private bool EvaluateIf(IfExpression ifExpression, InterpreterScope scope) { ParseErrorExpression error; bool result = ifExpression.Condition.IsTrue(scope, out error); if (error != null) { Error = error; return(false); } return(Evaluate(result ? ifExpression.Expressions : ifExpression.ElseExpressions, scope)); }
public int VisitIfExpression(IfExpression ast, Frame frame) { ast.Type.Visit(this, null); ast.TestExpression.Visit(this, frame); var jumpifAddr = _emitter.Emit(OpCode.JUMPIF, Machine.FalseValue, Register.CB); var valSize = ast.TrueExpression.Visit(this, frame); var jumpAddr = _emitter.Emit(OpCode.JUMP, Register.CB); _emitter.Patch(jumpifAddr); ast.FalseExpression.Visit(this, frame); _emitter.Patch(jumpAddr); return(valSize); }
private CodeStatementCollection GenerateImperativeStatement(IfExpression node) { var condition = GenerateImperativeExpression(node.Condition, isCondition: true); var trueStmts = GenerateImperativeStatements(node.Body).OfType <CodeStatement>().ToArray(); var falseStmts = node.ElseBody != null? GenerateImperativeStatements(node.ElseBody).OfType <CodeStatement>().ToArray() : Array.Empty <CodeStatement>(); var stmt = new CodeConditionStatement(condition, trueStmts, falseStmts); return(new CodeStatementCollection(new[] { stmt })); }
protected override List <AphidExpression> MutateCore(AphidExpression expression, out bool hasChanged) { if (expression.Type != AphidExpressionType.SwitchExpression) { hasChanged = false; return(null); } hasChanged = true; var switchExp = expression.ToSwitch(); var id = NextId(); var idDecl = new BinaryOperatorExpression( id, AphidTokenType.AssignmentOperator, switchExp.Expression); var cases = switchExp.Cases .Select(x => new { Case = x, Condition = CreateCaseCondition(x, id), }); IfExpression rootIfExp = null, ifExp = null; foreach (var c in cases) { if (ifExp != null) { var prev = ifExp; ifExp = CreateIfExpression(c.Condition, c.Case.Body); prev.ElseBody.Add(ifExp); } else { rootIfExp = ifExp = CreateIfExpression(c.Condition, c.Case.Body); } } if (switchExp.DefaultCase != null) { ifExp.ElseBody.AddRange(switchExp.DefaultCase); } return(new List <AphidExpression> { idDecl, rootIfExp }); }
private IExpression ParseIfExpression() { // 'if' var expression = new IfExpression() { Token = currentToken }; // '(' if (!ExpectPeek(TokenType.LParen)) { return(null); } // ??? NextToken(); expression.Condition = ParseExpression(Precedence.Lowest); // ')' if (!ExpectPeek(TokenType.RParen)) { return(null); } // '{' if (!ExpectPeek(TokenType.LBrace)) { return(null); } expression.Consequent = ParseBlockStatement(); // optional else if (PeekTokenIs(TokenType.Else)) { // 'else' NextToken(); // '{' if (!ExpectPeek(TokenType.LBrace)) { return(null); } expression.Alternative = ParseBlockStatement(); } return(expression); }
public virtual T Visit(IfExpression expression) { foreach (var branch in expression.Branches) { branch.Condition.Accept(this); branch.Block.Accept(this); } if (expression.Else != null) { expression.Else.Block.Accept(this); } return(default(T)); }
private void evalIfExpression(Object context, IfExpression ifExpression) { var condition = Eval(context, ifExpression.Condition); if (condition is Bool succ) { if (succ.Value == true) { evalWithScope(ExecutionContext.Peek(), ifExpression.Consequence); } } else { throw new System.Exception("Required a bool!"); } }
private static IObject EvalIfExpression(IfExpression expression, Environment environment) { var condition = Evaluate(expression.Condition, environment); if (IsError(condition)) { return(condition); } if (IsTruthy(condition)) { return(Evaluate(expression.Consequence, environment)); } return(expression.Alternative != null?Evaluate(expression.Alternative, environment) : null); }
private IExpression ParseIfExpression() { var ie = new IfExpression { Token = CurToken }; NextToken(); ie.Condition = ParseExpression(LOWEST); ie.Consequence = ParseBlockStatement(); if (CurTokenIs(TokenType.Else)) { ie.Alternative = ParseBlockStatement(); } return(ie); }
public BinaryExpression(IfExpression e1, string op, IfExpression e2) { LeftChild = e1; Operator = op; RightChild = e2; }
public UnaryExpression(string op, IfExpression e) { this.Operator = op; this.Expression = e; }