v icon indicating copy to clipboard operation
v copied to clipboard

cgen: Initialising optional field from optional variable is broken

Open edam opened this issue 2 years ago • 1 comments

Describe the bug

When

  • initialising an optional field in a struct

From

  • an optional variable

Then cgen attempts to "dereference" the optional value (access its data member) and assign that underlying type directly to the optional field.

Expected Behavior

Initialisation of optional fields with optional variables should detect the type of the thing being assigned is optional and not dereference it.

Current Behavior

Optional value is "dereferenced" (data is accessed) during assignment, which results in assigning the actual type to an optional field. (C compiler error).

Reproduction Steps

struct Foo {
    x ?string
}
fn main() {
    x := ?string("hi")
    foo := Foo{
        x: x // ERROR: attempts to assign x.data (a string) to Foo.x (a ?string)
    }
}

Generated C compiler error:

error: initializing 'byte' (aka 'unsigned char') with an expression of incompatible type 'string' (aka 'struct string')
        main__Foo foo = ((main__Foo){.x = /*opt*/(*(string*)x.data),});
                                                 ^~~~~~~~~~~~~~~~~~
1 warning and 1 error generated.

(The byte it refers to being initialised is the state field of _option_string.)

Possible Solution

No response

Additional Information/Context

No response

V version

V 0.3.3 35e5445

Environment details (OS name and version, etc.)

MacOS

edam avatar Mar 07 '23 11:03 edam

Note: assigning an optional directly works ok:

    foo := Foo{
        x: ?string("hi") // works
    }

edam avatar Mar 07 '23 11:03 edam