GNOME Bugzilla – Bug 786943
Cannot zero initialize structs with non-null members
Last modified: 2018-05-22 15:51:50 UTC
The example from https://valadoc.org/glib-2.0/GLib.OptionContext.html doesn't compile when --enable-experimental-non-null is passed. I think it's because zero-initialization of structs is not possible when the types of the fields are not explicitly marked nullable. test.vala:35.5-35.8: error: Expected initializer of type `string' but got `null' { null } ^^^^ test.vala:35.3-35.3: error: expression type not allowed as initializer { null } ^ The only way to make the example work is by disabling the non-null support :(
I think the problem is with creating a null terminated array. At present the example uses: private const GLib.OptionEntry[] options = { // --version { "version", 0, 0, OptionArg.NONE, ref version, "Display version number", null }, // list terminator { null } }; This array is then passed to OptionContext's add_main_entries (). There are a number of options: Ideally null would be allowed as the terminator, instead of { null }: private const GLib.OptionEntry[] options = { // --version { "version", 0, 0, OptionArg.NONE, ref version, "Display version number", null }, // list terminator null }; This produces an error "Expected initializer of type `GLib.OptionEntry' but got `null'" The error is from vala/valainitializerlist.vala, but also look at how this is used in vala/valaarraycreationexpression.vala. An alternative would be to use a CCode attribute detail. So using the existing array_null_terminated detail: [CCode (array_null_terminate = true)] private const GLib.OptionEntry[] options = { // --version { "version", 0, 0, OptionArg.NONE, ref version, "Display version number", null } }; This is currently ignored and results in a segmentation fault when the program is run. The final alternative is to make the array of nullable type: private const GLib.OptionEntry?[] options = { // --version { "version", 0, 0, OptionArg.NONE, ref version, "Display version number", null }, // list terminator null }; and to modify the binding in vapi/glib-2.0.vapi for add_main_entries to: public void add_main_entries ([CCode (array_length = false)] OptionEntry?[] entries, string? translation_domain); The would break all existing users of add_main_entries though.
As an after thought, the add_main_entries () binding should probably validate the type of array. So adding the detail, array_null_terminated = true, to the binding: public void add_main_entries ([CCode (array_length = false, array_null_terminated = true)] OptionEntry[] entries, string? translation_domain); would ideally give an error that the array passed to it has not been created as null terminated.
-- GitLab Migration Automatic Message -- This bug has been migrated to GNOME's GitLab instance and has been closed from further activity. You can subscribe and participate further through the new bug through this link to our GitLab instance: https://gitlab.gnome.org/GNOME/vala/issues/594.