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 { func (ie *IfExpression) String() string {
var builder strings.Builder 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()) builder.WriteString(ie.Then.String())
if ie.Else != nil { if ie.Else != nil {
builder.WriteString(" else in ") builder.WriteString(" else in ")
builder.WriteString(ie.Else.String()) builder.WriteString(ie.Else.String())
} }
builder.WriteString(")") builder.WriteString(fmt.Sprintf(") :> %s", ie.Type().Name()))
return builder.String() return builder.String()
} }

View File

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

View File

@ -98,20 +98,26 @@ func emitExpression(expr tast.Expression) (Operand, []Instruction) {
// } endOfIf: // } endOfIf:
elseLabel := tempLabel() elseLabel := tempLabel()
endOfIfLabel := tempLabel() endOfIfLabel := tempLabel()
dst := &Var{Value: temp()} var dst Operand = &Var{Value: temp()}
condDst, instructions := emitExpression(expr.Condition) condDst, instructions := emitExpression(expr.Condition)
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...)
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)) instructions = append(instructions, Label(elseLabel))
if expr.Else != nil { if expr.Else != nil {
elseDst, elseInstructions := emitExpression(expr.Else) elseDst, elseInstructions := emitExpression(expr.Else)
instructions = append(instructions, elseInstructions...) 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)) instructions = append(instructions, Label(endOfIfLabel))
return dst, instructions return dst, instructions