fix unit return for if expression

This commit is contained in:
Robin 2025-02-02 14:55:13 +01:00
parent 9e6e3bd1e4
commit 90bb478537
3 changed files with 13 additions and 7 deletions

View File

@ -158,14 +158,14 @@ func (ie *IfExpression) TokenLiteral() string { return ie.Token.Literal }
func (ie *IfExpression) String() string {
var builder strings.Builder
builder.WriteString("(if\n\t")
builder.WriteString(fmt.Sprintf("(if %s\n\t", ie.Condition.String()))
builder.WriteString(ie.Then.String())
if ie.Else != nil {
builder.WriteString(" else in ")
builder.WriteString(ie.Else.String())
}
builder.WriteString(")")
builder.WriteString(fmt.Sprintf(") :> %s", ie.Type().Name()))
return builder.String()
}

View File

@ -1,5 +1,5 @@
fn main() = {
if 3 == 3
in 4
else 3
{ if 4 == 4 in 3 }
else {}
};

View File

@ -98,20 +98,26 @@ func emitExpression(expr tast.Expression) (Operand, []Instruction) {
// } endOfIf:
elseLabel := tempLabel()
endOfIfLabel := tempLabel()
dst := &Var{Value: temp()}
var dst Operand = &Var{Value: temp()}
condDst, instructions := emitExpression(expr.Condition)
instructions = append(instructions, &JumpIfZero{Value: condDst, Label: elseLabel})
thenDst, thenInstructions := emitExpression(expr.Then)
instructions = append(instructions, thenInstructions...)
instructions = append(instructions, &Copy{Src: thenDst, Dst: dst}, Jump(endOfIfLabel))
if !expr.ReturnType.IsSameType(types.Unit) {
instructions = append(instructions, &Copy{Src: thenDst, Dst: dst}, Jump(endOfIfLabel))
} else {
dst = nil
}
instructions = append(instructions, Label(elseLabel))
if expr.Else != nil {
elseDst, elseInstructions := emitExpression(expr.Else)
instructions = append(instructions, elseInstructions...)
instructions = append(instructions, &Copy{Src: elseDst, Dst: dst})
if !expr.ReturnType.IsSameType(types.Unit) {
instructions = append(instructions, &Copy{Src: elseDst, Dst: dst})
}
}
instructions = append(instructions, Label(endOfIfLabel))
return dst, instructions