gccrs icon indicating copy to clipboard operation
gccrs copied to clipboard

Rustc behaviour with loops in const/static context

Open philberty opened this issue 7 months ago • 3 comments

          Nice work but i just realised yes this need another change sorry. This null_tree check should still stay but you need another check the error should be:
error[E0658]: `loop` is not allowed in a `static`
 --> <source>:1:17
  |
1 | static _X: () = loop {};
  |                 ^^^^^^^
  |
  = note: see issue #52000 <https://github.com/rust-lang/rust/issues/52000> for more information

error: aborting due to previous error

So what you need to do is add a catch here: https://github.com/Rust-GCC/gccrs/blob/fc6b54365731c2ebfa1974058c48772e03203fdd/gcc/rust/backend/rust-compile-expr.cc#L671

if (ctx->const_context_p ())
 {
     rich_location r;
     rust_error_at (r, ErrorCode::0658, "%<loop%> is not allowed in const context");
     return;
  }

Originally posted by @philberty in https://github.com/Rust-GCC/gccrs/issues/3781#issuecomment-2862764681

philberty avatar May 08 '25 15:05 philberty

It looks like most loops are allowed since 1.46.0, seemingly with the single exception of for loops.

powerboat9 avatar May 08 '25 16:05 powerboat9

good find!

philberty avatar May 09 '25 08:05 philberty

I wonder is it if iterators are not fully const in libcore yet or something

philberty avatar May 09 '25 08:05 philberty

Hi, I’d like to work on this issue! @philberty

Just to clarify, should this patch reject all loop inside const and static (with if (ctx->const_context_p ())), or should it also allow loop inside const fn()?

I tried using if (ctx->const_context_p () && !ctx->in_fn ()) to allow loops in const fn, but it doesn't seem to work. Should I include that support as part of this patch as well, or leave it for a separate issue? Thank you!

Lishin1215 avatar Jul 13 '25 21:07 Lishin1215