手拉手教你实现一门编程语言 Enkel, 系列 10

本文系 Creating JVM language 翻译的第 10 篇。 原文中的代码和原文有不一致的地方均在新的代码仓库中更正过,建议参考新的代码仓库。

源码

Github

1. 语法规则更改

实现条件语句需要对语法规则作如下两处改动:

  • 添加新规则 ifStatement
  • 添加 conditionalExpressions 表达式
ifStatement :  'if'  '('? expression ')'? trueStatement=statement ('else' falseStatement=statement)?;
expression : varReference #VARREFERENCE
           | value        #VALUE
           //other expression alternatives
           | expression cmp='>' expression #conditionalExpression
           | expression cmp='<' expression #conditionalExpression
           | expression cmp='==' expression #conditionalExpression
           | expression cmp='!=' expression #conditionalExpression
           | expression cmp='>=' expression #conditionalExpression
           | expression cmp='<=' expression #conditionalExpression
           ;
复制代码

ifStatement 规则定义:

  • expression 是一个真值表达式
  • 真值表达式放到括号里是非必要的,问号 ?意味着是可选的
  • 为 true 时 trueStatement 会被执行
  • if 后面可以跟随者 else
  • 当 false 时 falseStatement 会被执行
  • ifStatement 是语句,因此可以子在 trueStatement 或者 falseStatement 使用(形如 if ... else if ...else )

条件表达式的目的是比较两个表达式,并且返回另一个表达式(布尔值)。

为了更好的理解 if 和 else 是如何被用来表示 else if,请看下面代码片段:

if(0) {
        
} else if(1) {
        
}
复制代码

AST 表示如下图所示:

如图所示,第二个 if 其实就是 else 的子语句。他们在不同的层级。因此没有必要指明 else if 规则。ifstatement 规则本质是一个语句,因此其他 ifStatements 可以嵌套用在 ifStatements。

2. 匹配 Antlr 上下文对象

Antlr 会生成 IfStatementContext 对象并转化成 POJO IfStatement 对象:

public class StatementVisitor extends EnkelBaseVisitor<Statement> {
    //other stuff
    @Override
    public Statement visitIfStatement(@NotNull EnkelParser.IfStatementContext ctx) {
        ExpressionContext conditionalExpressionContext = ctx.expression();
        Expression condition = conditionalExpressionContext.accept(expressionVisitor); //Map conditional expression
        Statement trueStatement = ctx.trueStatement.accept(this); //Map trueStatement antlr object
        Statement falseStatement = ctx.falseStatement.accept(this); //Map falseStatement antlr object

        return new IfStatement(condition, trueStatement, falseStatement);
    } 
}
复制代码

条件表达式会被匹配成下面这样:

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);
    }
}
复制代码

CompareSign 是一个对象,表示比较符号(==,< 等)。它保存了字节码指令(IF_ICMPEQ, IF_ICMPLE 等)。

3. 生成字节码

JVM 中有一些指令来做分支判断:

  • if<eq,ne,lt,le,gt,ge> - 操作数栈出栈,和 0 比较
  • if_icmp_<eq,ne,lt,le,gt,ge> - 从栈上出栈两个值,比较是否相等
  • if[non]null - 检查空值

本节中我们只是用第二个指令。 该指令的操作数是分支的偏移量(遇到 if 后,需要执行的指令)。

4. 生成条件表达式

ifcmpne(比较两个值不相等)会在 ConditionalExpression 中首次被用到。

public void generate(ConditionalExpression conditionalExpression) {
    Expression leftExpression = conditionalExpression.getLeftExpression();
    Expression rightExpression = conditionalExpression.getRightExpression();
    Type type = leftExpression.getType();
    if(type != rightExpression.getType()) {
        throw new ComparisonBetweenDiferentTypesException(leftExpression, rightExpression); //not yet supported
    }
    leftExpression.accept(this);
    rightExpression.accept(this);
    CompareSign compareSign = conditionalExpression.getCompareSign();
    Label trueLabel = new Label(); //represents an adress in code (to which jump if condition is met)
    Label endLabel = new Label();
    methodVisitor.visitJumpInsn(compareSign.getOpcode(),trueLabel);
    methodVisitor.visitInsn(Opcodes.ICONST_0);
    methodVisitor.visitJumpInsn(Opcodes.GOTO, endLabel);
    methodVisitor.visitLabel(trueLabel);
    methodVisitor.visitInsn(Opcodes.ICONST_1);
    methodVisitor.visitLabel(endLabel);
}
复制代码

compareSign.getOpcode() 返回条件表达式的字节码指令。

public enum CompareSign {
    EQUAL("==", Opcodes.IF_ICMPEQ),
    NOT_EQUAL("!=", Opcodes.IF_ICMPNE),
    LESS("<",Opcodes.IF_ICMPLT),
    GREATER(">",Opcodes.IF_ICMPGT),
    LESS_OR_EQUAL("<=",Opcodes.IF_ICMPLE),
    GRATER_OR_EQAL(">=",Opcodes.IF_ICMPGE);
    //getters
}
复制代码

条件指令的操作数是分支的偏移量。compareSign.getOpcode() 从操作数栈上出栈两个值,比较。

如果表达式是真,那么指令跳到 trueLabel 处继续执行。trueLabel 指令包含 methodVisitor.visitInsn(Opcodes.ICONST_1);,即把值 1 入栈。

如果表达式假,不会发生指令跳转。接下来的指令是 ICONST_0, 把值 0 入栈。然后 GOTO (非分支指令)跳到 endLabel 处。这样,表达式为真的时候执行的语句块则会略过不执行。

上述过程保证了真值表达式只可能是 1 或者 0(入栈的整数)。

这样 conditonalExpression 可以用作表达式。可以赋值给变量,作为参数传递给函数,打印或者当做返回值。

5. 生成 IfStatement

public void generate(IfStatement ifStatement) {
        Expression condition = ifStatement.getCondition();
        condition.accept(expressionGenrator);
        Label trueLabel = new Label();
        Label endLabel = new Label();
        methodVisitor.visitJumpInsn(Opcodes.IFNE,trueLabel);
        ifStatement.getFalseStatement().accept(this);
        methodVisitor.visitJumpInsn(Opcodes.GOTO,endLabel);
        methodVisitor.visitLabel(trueLabel);
        ifStatement.getTrueStatement().accept(this);
        methodVisitor.visitLabel(endLabel);
    }
复制代码

IfStatement 依赖了 ConditionalExpression 用到的思想,它保证了最终会在入栈 0 或者 1。

这样简化了对表达式的求值(condition.accept(expressionGenrator);)并且检查值是否入栈(condition.accept(expressionGenrator);)。如果不等于 0 ,跳到 trueLable 处执行(ifStatement.getTrueStatement().accept(this);), 否则继续执行 falseStatement, 并且跳到(GOTO)endLabel 处。

6. 示例

假设有如何 Enkel 代码:

SumCalculator {

    main(string[] args) {
        var expected = 8
        var actual = sum(3,5)

        if( actual == expected ) {
            print "test passed"
        } else {
            print "test failed"
        }
    }

    int sum (int x ,int y) {
        x+y
    }
    
}
复制代码

生成后的字节码如下:

$ 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
}
复制代码

转载于:https://juejin.im/post/5b914be86fb9a05d1013be49

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值