From: Lucas Ly Ba <[email protected]>

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 <[email protected]>
---
This change was merged into the gccrs repository and is posted here for
upstream visibility and potential drive-by review, as requested by GCC
release managers.
Each commit email contains a link to its details on github from where you can
find the Pull-Request and associated discussions.


Commit on github: 
https://github.com/rust-GCC/gccrs/commit/f06a3c4564e5dc3661c05a0fc1a57560626f74bf
 gcc/rust/expand/rust-derive.cc           | 11 +++++++++++
 gcc/testsuite/rust/compile/issue-3971.rs | 11 +++++++++++
 2 files changed, 22 insertions(+)
 create mode 100644 gcc/testsuite/rust/compile/issue-3971.rs

diff --git a/gcc/rust/expand/rust-derive.cc b/gcc/rust/expand/rust-derive.cc
index 55147df26..2777f076f 100644
--- a/gcc/rust/expand/rust-derive.cc
+++ b/gcc/rust/expand/rust-derive.cc
@@ -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
index 000000000..5607d2d74
--- /dev/null
+++ b/gcc/testsuite/rust/compile/issue-3971.rs
@@ -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
+}

base-commit: 6e5929aea5eb223459ad691398ec7239f4babe7b
-- 
2.51.2

Reply via email to