From: Yotam Nachum Date: Sat, 6 Nov 2021 17:05:13 +0000 (+0200) Subject: vala: Don't allow casting real structs to classes or simple-types X-Git-Tag: 0.55.1~77 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=af730d4eef2879b487fff6f949a01b69b3b78f5f;p=thirdparty%2Fvala.git vala: Don't allow casting real structs to classes or simple-types This led to C compiler errors or obvious runtimes failures. Fixes https://gitlab.gnome.org/GNOME/vala/issues/1249 --- diff --git a/tests/Makefile.am b/tests/Makefile.am index 9a6c4b3f2..ad65913ce 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -345,6 +345,8 @@ TESTS = \ enums/bug763831.vala \ enums/bug780050.vala \ structs/cast-struct-boxed.vala \ + structs/cast-struct-to-class.test \ + structs/cast-struct-to-simple-struct.test \ structs/struct_only.vala \ structs/struct-base-types.vala \ structs/struct-boxed-cast.vala \ diff --git a/tests/structs/cast-struct-to-class.test b/tests/structs/cast-struct-to-class.test new file mode 100644 index 000000000..c87931ea0 --- /dev/null +++ b/tests/structs/cast-struct-to-class.test @@ -0,0 +1,10 @@ +Invalid Code + +struct Foo { + public int i; +} + +void main () { + Foo foo = { 42 }; + Object bar = (Object) foo; +} diff --git a/tests/structs/cast-struct-to-simple-struct.test b/tests/structs/cast-struct-to-simple-struct.test new file mode 100644 index 000000000..3cb6681fc --- /dev/null +++ b/tests/structs/cast-struct-to-simple-struct.test @@ -0,0 +1,10 @@ +Invalid Code + +struct Foo { + public int i; +} + +void main () { + Foo foo = { 42 }; + int bar = (int) foo; +} diff --git a/vala/valacastexpression.vala b/vala/valacastexpression.vala index 732b99a71..5d0783e41 100644 --- a/vala/valacastexpression.vala +++ b/vala/valacastexpression.vala @@ -170,6 +170,15 @@ public class Vala.CastExpression : Expression { return false; } + // Allow casting to array or pointer type + if (!(type_reference is ArrayType || type_reference is PointerType)) { + if (!type_reference.is_real_struct_type () && inner.value_type.is_real_struct_type () + && (context.profile != Profile.GOBJECT || !(is_gvariant (context, inner.value_type) || is_gvalue (context, inner.value_type)))) { + error = true; + Report.error (source_reference, "Casting of struct `%s' to `%s' is not allowed", inner.value_type.to_qualified_string (), type_reference.to_qualified_string ()); + } + } + if (type_reference is DelegateType && inner.value_type is MethodType) { if (target_type != null) { inner.value_type.value_owned = target_type.value_owned;