]> git.ipfire.org Git - thirdparty/gcc.git/commitdiff
gccrs: Generate error for const trait functions
authorNobel Singh <nobel2073@gmail.com>
Tue, 5 Dec 2023 12:27:29 +0000 (18:12 +0545)
committerArthur Cohen <arthur.cohen@embecosm.com>
Tue, 30 Jan 2024 11:36:49 +0000 (12:36 +0100)
Fixes issue #2040

Add check to assure that a function cant be declared const inside trait impl
blocks.

gcc/rust/ChangeLog:

* checks/errors/rust-ast-validation.cc (ASTValidation::visit): Add
check for const funtion.

gcc/testsuite/ChangeLog:

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

Signed-off-by: Nobel Singh <nobel2073@gmail.com>
gcc/rust/checks/errors/rust-ast-validation.cc
gcc/testsuite/rust/compile/issue-2040.rs [new file with mode: 0644]

index 6fb142c78455a3dcad0ba40bff3317f7568f3066..cd197fc1ea7d9c87615d369b4689626ba5593282 100644 (file)
@@ -103,6 +103,10 @@ ASTValidation::visit (AST::Function &function)
     rust_error_at (function.get_locus (),
                   "functions cannot be both %<const%> and %<async%>");
 
+  if (qualifiers.is_const () && context.back () == Context::TRAIT_IMPL)
+    rust_error_at (function.get_locus (), ErrorCode::E0379,
+                  "functions in traits cannot be declared const");
+
   if (valid_context.find (context.back ()) == valid_context.end ()
       && function.has_self_param ())
     rust_error_at (
diff --git a/gcc/testsuite/rust/compile/issue-2040.rs b/gcc/testsuite/rust/compile/issue-2040.rs
new file mode 100644 (file)
index 0000000..fbac168
--- /dev/null
@@ -0,0 +1,12 @@
+trait Foo {
+    fn f() -> u32;
+}
+
+impl Foo for u32 {
+    const fn f() -> u32 {
+        // { dg-error "functions in traits cannot be declared const" "" { target *-*-* } .-1 }
+        22
+    }
+}
+
+fn main() {}