Skip to content

Values that need to be dropped are promoted in const / static initializers #91009

Closed
@tmiasko

Description

@tmiasko

For example, promotion succeeds in the example below, although compilation nevertheless fails due to checks for live drops:

pub const fn id<T>(x: T) -> T { x }
pub const C: () = {
    let _: &'static _ = &String::new();
    // Promotion failed, two errors:
    // ERROR: destructors cannot be evaluated at compile-time
    // ERROR: temporary value dropped while borrowed

    let _: &'static _ = &id(&String::new());
    // Promoted. Only one error:
    // ERROR: destructors cannot be evaluated at compile-time

    let _: &'static _ = &std::mem::ManuallyDrop::new(String::new());
    // Promoted. No errors.
};

With const_precise_live_drops, checking for live drops is delayed until after the promotion, so the following example compiles successfully:

#![feature(const_precise_live_drops)]
pub const fn id<T>(x: T) -> T { x }
pub const C: () = {
    let _: &'static _ = &id(&String::new());
};

The check for live drops can also be passed by providing a const drop implementation. The following example compiles successfully as well:

#![feature(const_fn_trait_bound)]
#![feature(const_mut_refs)]
#![feature(const_trait_impl)]
struct Panic;
impl const Drop for Panic { fn drop(&mut self) { panic!(); } }
pub const fn id<T>(x: T) -> T { x }
pub const C: () = {
    let _: &'static _ = &id(&Panic);
};

@rustbot label +A-const-eval

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-const-evalArea: Constant evaluation, covers all const contexts (static, const fn, ...)C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions