q/src/core/CompileIf.go
2025-03-13 16:57:13 +01:00

58 lines
1.0 KiB
Go

package core
import (
"git.urbach.dev/cli/q/src/asm"
"git.urbach.dev/cli/q/src/ast"
)
// CompileIf compiles a branch instruction.
func (f *Function) CompileIf(branch *ast.If) error {
for _, register := range f.CPU.Input {
f.SaveRegister(register)
}
f.count.branch++
var (
end asm.Label
success = f.CreateLabel("if true", f.count.branch, asm.ControlLabel)
fail = f.CreateLabel("if false", f.count.branch, asm.ControlLabel)
err = f.CompileCondition(branch.Condition, success, fail)
)
if err != nil {
return err
}
f.AddLabel(success)
f.PushScope(branch.Body, f.File.Bytes)
err = f.CompileAST(branch.Body)
if err != nil {
return err
}
if branch.Else != nil {
end = f.CreateLabel("if end", f.count.branch, asm.ControlLabel)
f.Jump(asm.JUMP, end)
}
f.PopScope()
f.AddLabel(fail)
if branch.Else != nil {
f.PushScope(branch.Else, f.File.Bytes)
err = f.CompileAST(branch.Else)
if err != nil {
return err
}
f.PopScope()
f.AddLabel(end)
return nil
}
return nil
}