Improved branch compilation

This commit is contained in:
2024-07-07 21:55:32 +02:00
parent 6aad74d6dd
commit ee16774fe7
9 changed files with 160 additions and 113 deletions

View File

@ -9,51 +9,16 @@ import (
// CompileIf compiles a branch instruction.
func (f *Function) CompileIf(branch *ast.If) error {
err := f.Evaluate(branch.Condition)
startLabel := fmt.Sprintf("%s_if_start_%d", f.Name, f.count.branch)
endLabel := fmt.Sprintf("%s_if_end_%d", f.Name, f.count.branch)
err := f.CompileCondition(branch.Condition, startLabel, endLabel)
if err != nil {
return err
}
endLabel := fmt.Sprintf("%s_end_if_%d", f.Name, f.count.branch)
f.JumpIfFalse(branch.Condition.Token.Text(), endLabel)
f.assembler.Label(asm.LABEL, startLabel)
defer f.assembler.Label(asm.LABEL, endLabel)
f.count.branch++
return f.CompileAST(branch.Body)
}
// JumpIfFalse jumps to the label if the previous comparison was false.
func (f *Function) JumpIfFalse(operator string, label string) {
switch operator {
case "==":
f.assembler.Label(asm.JNE, label)
case "!=":
f.assembler.Label(asm.JE, label)
case ">":
f.assembler.Label(asm.JLE, label)
case "<":
f.assembler.Label(asm.JGE, label)
case ">=":
f.assembler.Label(asm.JL, label)
case "<=":
f.assembler.Label(asm.JG, label)
}
}
// JumpIfTrue jumps to the label if the previous comparison was true.
func (f *Function) JumpIfTrue(operator string, label string) {
switch operator {
case "==":
f.assembler.Label(asm.JE, label)
case "!=":
f.assembler.Label(asm.JNE, label)
case ">":
f.assembler.Label(asm.JG, label)
case "<":
f.assembler.Label(asm.JL, label)
case ">=":
f.assembler.Label(asm.JGE, label)
case "<=":
f.assembler.Label(asm.JLE, label)
}
}