fixed if expressions

This commit is contained in:
Robin Bärtschi 2025-02-26 15:18:56 +01:00
parent e9a1ee0bab
commit b0b7ede252
3 changed files with 23 additions and 5 deletions

View File

@ -104,9 +104,10 @@ func cgInstruction(i ttir.Instruction) []Instruction {
return []Instruction{JmpInstruction(i)} return []Instruction{JmpInstruction(i)}
case *ttir.Copy: case *ttir.Copy:
return []Instruction{&SimpleInstruction{Opcode: Mov, Lhs: toAsmOperand(i.Dst), Rhs: toAsmOperand(i.Src)}} return []Instruction{&SimpleInstruction{Opcode: Mov, Lhs: toAsmOperand(i.Dst), Rhs: toAsmOperand(i.Src)}}
default:
panic(fmt.Sprintf("unexpected ttir.Instruction: %#v", i))
} }
return []Instruction{}
} }
func cgBinary(b *ttir.Binary) []Instruction { func cgBinary(b *ttir.Binary) []Instruction {

View File

@ -1,8 +1,9 @@
fn main() = { fn main() = {
hi := 4; hi := 4;
if hi == 2 in hi = 3 if hi == 4 in
else hi = 2; hi = 0
else hi = 1;
hi hi
}; };

View File

@ -105,8 +105,11 @@ func emitExpression(expr tast.Expression) (Operand, []Instruction) {
instructions = append(instructions, &JumpIfZero{Value: condDst, Label: elseLabel}) instructions = append(instructions, &JumpIfZero{Value: condDst, Label: elseLabel})
thenDst, thenInstructions := emitExpression(expr.Then) thenDst, thenInstructions := emitExpression(expr.Then)
instructions = append(instructions, thenInstructions...) instructions = append(instructions, thenInstructions...)
if !expr.ReturnType.IsSameType(types.Unit) { if expr.Else != nil {
instructions = append(instructions, &Copy{Src: thenDst, Dst: dst}, Jump(endOfIfLabel)) if !expr.ReturnType.IsSameType(types.Unit) {
instructions = append(instructions, &Copy{Src: thenDst, Dst: dst})
}
instructions = append(instructions, Jump(endOfIfLabel))
} else { } else {
dst = nil dst = nil
} }
@ -122,8 +125,21 @@ func emitExpression(expr tast.Expression) (Operand, []Instruction) {
instructions = append(instructions, Label(endOfIfLabel)) instructions = append(instructions, Label(endOfIfLabel))
return dst, instructions return dst, instructions
case *tast.AssignmentExpression: case *tast.AssignmentExpression:
ident := expr.Lhs.(*tast.VariableReference)
rhsDst, instructions := emitExpression(expr.Rhs)
instructions = append(instructions, &Copy{Src: rhsDst, Dst: &Var{Value: ident.Identifier}})
return nil, instructions
case *tast.VariableDeclaration: case *tast.VariableDeclaration:
rhsDst, instructions := emitExpression(expr.InitializingExpression)
instructions = append(instructions, &Copy{Src: rhsDst, Dst: &Var{Value: expr.Identifier}})
return nil, instructions
case *tast.VariableReference: case *tast.VariableReference:
return &Var{Value: expr.Identifier}, []Instruction{}
default: default:
panic(fmt.Sprintf("unexpected tast.Expression: %#v", expr)) panic(fmt.Sprintf("unexpected tast.Expression: %#v", expr))
} }