gotranspile / cxgo

Tool for transpiling C to Go.
https://gotranspile.dev
MIT License
328 stars 22 forks source link

Bug: Implicit Bool to Float Conversion Fails When Added with a Float in C #76

Open Yeaseen opened 2 weeks ago

Yeaseen commented 2 weeks ago

Original C code

int main() {
    float local_float = 0.0f;
    local_float += (4 < 4.5) + 3;
    local_float += (4 < 4.5) + 3.5;
    return 0;
}

Converted Go Code

package main

import (
    "github.com/gotranspile/cxgo/runtime/libc"
    "os"
)

func main() {
    var local_float float32 = 0.0
    _ = local_float
    local_float += float32(int(libc.BoolToInt(4 < 4.5)) + 3)
    local_float += float32(float64(4 < 4.5) + 3.5)
    os.Exit(0)
}

Go compiler error

# command-line-arguments
./runner.go:12:33: cannot convert 4 < 4.5 (untyped bool constant true) to type float64

Root cause

The root cause is the failure of automatic implicit Bool to Float conversion when the conversion output is added with a floating-point number in C, leading to a type mismatch error in Go. But, CxGo is successful at automatic implicit Bool to Float conversion when the conversion output is added with an integer in C.

Expected Code

Instead of local_float += float32(float64(4 < 4.5) + 3.5), my modification is local_float += float32(float64(int(libc.BoolToInt(4 < 4.5))) + 3.5) And this works fine

package main

import (
    "github.com/gotranspile/cxgo/runtime/libc"
    "os"
)

func main() {
    var local_float float32 = 0.0
    _ = local_float
    local_float += float32(int(libc.BoolToInt(4 < 4.5)) + 3)
    local_float += float32(float64(int(libc.BoolToInt(4 < 4.5))) + 3.5)
    os.Exit(0)
}
dennwc commented 2 weeks ago

Thank you! Clean reproducers are really helpful :bowing_man: