61 lines
1.3 KiB
Go
61 lines
1.3 KiB
Go
package commands
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"c65gm/internal/compiler"
|
|
"c65gm/internal/preproc"
|
|
"c65gm/internal/utils"
|
|
)
|
|
|
|
// ElseCommand handles ELSE statements in IF...ELSE...ENDIF blocks
|
|
// Syntax: ELSE
|
|
type ElseCommand struct {
|
|
skipLabel string
|
|
endLabel string
|
|
}
|
|
|
|
func (c *ElseCommand) WillHandle(line preproc.Line) bool {
|
|
params, err := utils.ParseParams(line.Text)
|
|
if err != nil || len(params) == 0 {
|
|
return false
|
|
}
|
|
|
|
return strings.ToUpper(params[0]) == "ELSE"
|
|
}
|
|
|
|
func (c *ElseCommand) Interpret(line preproc.Line, ctx *compiler.CompilerContext) error {
|
|
params, err := utils.ParseParams(line.Text)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if len(params) != 1 {
|
|
return fmt.Errorf("ELSE: wrong number of parameters (%d), expected 1", len(params))
|
|
}
|
|
|
|
// Pop the IF skip label
|
|
label, err := ctx.IfStack.Pop()
|
|
if err != nil {
|
|
return fmt.Errorf("ELSE: %w", err)
|
|
}
|
|
c.skipLabel = label
|
|
|
|
// Push new end label
|
|
c.endLabel = ctx.IfStack.Push()
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c *ElseCommand) Generate(_ *compiler.CompilerContext) ([]string, error) {
|
|
var asm []string
|
|
|
|
// Jump to end (skip else block if condition was true)
|
|
asm = append(asm, fmt.Sprintf("\tjmp %s", c.endLabel))
|
|
|
|
// Place skip label (jumped here if condition was false)
|
|
asm = append(asm, c.skipLabel)
|
|
|
|
return asm, nil
|
|
}
|