]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
gccrs: add error check if derive has wrong item
authorLucas Ly Ba <lucas.ly-ba@outlook.com>
Tue, 14 Oct 2025 13:40:04 +0000 (13:40 +0000)
committerArthur Cohen <arthur.cohen@embecosm.com>
Tue, 25 Nov 2025 22:00:51 +0000 (23:00 +0100)
Derive may only be applied to structs, enums and unions.

gcc/rust/ChangeLog:

* expand/rust-derive.cc (DeriveVisitor::derive):
Add check and error.

gcc/testsuite/ChangeLog:

* rust/compile/issue-3971.rs: New test.

Signed-off-by: Lucas Ly Ba <lucas.ly-ba@outlook.com>
gcc/rust/expand/rust-derive.cc
gcc/testsuite/rust/compile/issue-3971.rs [new file with mode: 0644]

index 55147df26f247b58de50f8896158466a0de3479c..2777f076f0243807d6feafe64058ac5385c524a9 100644 (file)
@@ -25,6 +25,7 @@
 #include "rust-derive-ord.h"
 #include "rust-derive-partial-eq.h"
 #include "rust-derive-hash.h"
+#include "rust-system.h"
 
 namespace Rust {
 namespace AST {
@@ -39,6 +40,16 @@ DeriveVisitor::derive (Item &item, const Attribute &attr,
 {
   auto loc = attr.get_locus ();
 
+  using Kind = AST::Item::Kind;
+  auto item_kind = item.get_item_kind ();
+  if (item_kind != Kind::Enum && item_kind != Kind::Struct
+      && item_kind != Kind::Union)
+    {
+      rust_error_at (loc,
+                    "derive may only be applied to structs, enums and unions");
+      return {};
+    }
+
   switch (to_derive)
     {
     case BuiltinMacro::Clone:
diff --git a/gcc/testsuite/rust/compile/issue-3971.rs b/gcc/testsuite/rust/compile/issue-3971.rs
new file mode 100644 (file)
index 0000000..5607d2d
--- /dev/null
@@ -0,0 +1,11 @@
+#[lang = "copy"]
+trait Copy {}
+
+// since the macro expansion fails, the current nameres fixpoint error is emitted - just accept it for now
+#[derive(Copy)]
+// { dg-error "derive may only be applied to structs, enums and unions" "" { target *-*-* } .-1 }
+// { dg-excess-errors "could not resolve trait" }
+
+pub fn check_ge(a: i32, b: i32) -> bool {
+    a >= b
+}