手拉手教你實現一門程式語言 Enkel, 系列 10

KevinOfNeu發表於2018-09-06

本文系 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 表示如下圖所示:

手拉手教你實現一門程式語言 Enkel, 系列 10

如圖所示,第二個 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
}
複製程式碼

相關文章