return new IfStatement(condition, trueStatement, falseStatement); } }
条件表达式会被匹配成下面这样:
1 2 3 4 5 6 7 8 9 10 11 12
public class ExpressionVisitor extends EnkelBaseVisitor<Expression> { @Override public ConditionalExpression visitConditionalExpression(@NotNull EnkelParser.ConditionalExpressionContext ctx) { EnkelParser.ExpressionContext leftExpressionCtx = ctx.expression(0); //get left side expression ( ex. 1 < 5 -> it would mean get "1") EnkelParser.ExpressionContext rightExpressionCtx = ctx.expression(1); //get right side expression Expression leftExpression = leftExpressionCtx.accept(this); //get mapped (to POJO) left expression using this visitor //rightExpression might be null! Example: 'if (x)' checks x for nullity. The solution for this case is to assign integer 0 to the rightExpr Expression rightExpression = rightExpressionCtx != null ? rightExpressionCtx.accept(this) : new Value(BultInType.INT,"0"); CompareSign cmpSign = ctx.cmp != null ? CompareSign.fromString(ctx.cmp.getText()) : CompareSign.NOT_EQUAL; //if there is no cmp sign use '!=0' by default return new ConditionalExpression(leftExpression, rightExpression, cmpSign); } }
$ javap -c SumCalculator public class SumCalculator { public static void main(java.lang.String[]); Code: 0: bipush 8 2: istore_1 //store 8 in local variable 1 (expected) 3: bipush 3 //push 3 5: bipush 5 //push 5 7: invokestatic #10 //Call metod sum (5,3) 10: istore_2 //store the result in variable 2 (actual) 11: iload_2 //push the value from variable 2 (actual=8) onto the stack 12: iload_1 //push the value from variable 1 (expected=8) onto the stack 13: if_icmpeq 20 //compare two top values from stack (8 == 8) if false jump to label 20 16: iconst_0 //push 0 onto the stack 17: goto 21 //go to label 21 (skip true section) 20: iconst_1 //label 21 (true section) -> push 1 onto the stack 21: ifne 35 //if the value on the stack (result of comparison 8==8 != 0 jump to label 35 24: getstatic #16 // get static Field java/lang/System.out:Ljava/io/PrintStream; 27: ldc #18 // push String test failed 29: invokevirtual #23 // call print Method "Ljava/io/PrintStream;".println:(Ljava/lang/String;)V 32: goto 43 //jump to end (skip true section) 35: getstatic #16 38: ldc #25 // String test passed 40: invokevirtual #23 43: return
public static int sum(int, int); Code: 0: iload_0 1: iload_1 2: iadd 3: ireturn }