antimony-lang/antimony

QBE: match statements

YerinAlexey opened this issue · 0 comments

They would work similarly to nested if-else blocks, comparing on every branch and jumping accordingly.

The flow is:

  • Compare the argument to n match arm
  • Jump to the corresponding arm block if condition is true, otherwise go to the next comparison
  • If no more comparisons left, jump to else branch
  • n++

Every arm block should also jump to the end of match to not skateboard into next ones

For example,

fn main() {
    match (value) {
        1 => {}
        2 => {}
        else => {}
    }
}

Should roughly produce this:

export function $main() {
@start
    %cond.1 =w ceqw %value, 1
    jnz %cond.1, @match.1.case.1, @match.1.cmp.2
@match.1.case.1
    # Do something when value == 1
    jmp @match.1.end
@match.1.cmp.2
    %cond.2 =w ceqw %value, 2
    jnz %cond.2, @match.1.case.2, @match.1.else
@match.1.case.2
    # Do something when value == 2
    jmp @match.1.end
@match.1.else
    # Do something when value is neither 1 nor 2
    # Falltrough here, no need to jmp
@match.1.end
    ret
}