hsutter / cppfront

A personal experimental C++ Syntax 2 -> Syntax 1 compiler
Other
5.56k stars 249 forks source link

[BUG] `is` type for `std::optional` can return unexpected results #1328

Open bluetarpmedia opened 4 weeks ago

bluetarpmedia commented 4 weeks ago

Describe the bug An expression testing if a std::optional is a type can return unexpected results, depending on whether the optional's type is convertible to the target type. (I'm assuming this behaviour is unintended.)

To Reproduce Run cppfront on the following and then compile with a C++ compiler:

main: () -> int = {
    o: std::optional<int> = 5;
    if o is int {
        std::cout << "int!\n";
    }
    if o is bool {
        std::cout << "bool!\n";
    }
    if o is float {
        std::cout << "float!\n";
    }
    if o is std::string {
        std::cout << "std::string!\n";
    }
    return 0;
}

The output is:

int!
bool!
float!

Repro on Godbolt.

I think this behaviour is due to this cast: https://github.com/hsutter/cppfront/blob/ddde3d833bec373081a3c0f419250f8e8b553805/include/cpp2util.h#L2042

CC @filipsajdak