Skip to content

Implied bounds by associated types as function parameters are inconsistent in an unsound way. #91068

Closed
@steffahn

Description

@steffahn

Taking a simple trait

trait Trait {
    type Type;
}

impl<T> Trait for T {
    type Type = ();
}

the type <&'a &'b () as Trait>::Type as a function argument gives rise to a 'a: 'b bound, as can be demonstrated by e.g.

fn f<'a, 'b>(s: &'b str, _: <&'a &'b () as Trait>::Type) -> &'a str {
    s
}

However, this bound is apparently not really enforced. I suppose the compiler “simplifies” such a function to f<'a, 'b>(s: &'b str, _: ()) -> &'a str for the caller? So

fn main() {
    let x = String::from("Hello World!");
    let y = f(&x, ());
    drop(x);
    println!("{}", y);
}

compiles fine and produces UB. (playground)

Another implication of the same kind of issue is that a function like

type Type<T> = <T as Trait>::Type;

fn g<'a>(_: Type<&'a ()>) -> &'a str {
    ""
}

fails to compile with a weird error message.

   Compiling playground v0.0.1 (/playground)
error[E0581]: return type references lifetime `'a`, which is not constrained by the fn input types
  --> src/lib.rs:11:30
   |
11 | fn g<'a>(_: Type<&'a ()>) -> &'a str {
   |                              ^^^^^^^

For more information about this error, try `rustc --explain E0581`.

The error code 581 only talks about fn-pointer types (playground)

@rustbot label T-compiler, A-lifetimes, A-typesystem, A-traits, A-associated-items, I-unsound

Originally discovered in a discussion on URLO.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-lifetimesArea: Lifetimes / regionsA-trait-systemArea: Trait systemA-type-systemArea: Type systemC-bugCategory: This is a bug.I-unsoundIssue: A soundness hole (worst kind of bug), see: https://en.wikipedia.org/wiki/SoundnessP-criticalCritical priorityT-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-typesRelevant to the types team, which will review and decide on the PR/issue.regression-from-stable-to-stablePerformance or correctness regression from one stable version to another.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions