rust-lang / rust-lang/rust

Decision on "must define before use" for opaque types

Open
#117,866 9 comments 3 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-impl-trait F-type_alias_impl_trait T-lang
Dominant language
Rust
Stars
119k
Forks
16.2k
PR merge metrics
PR metrics pending

Description

Nominating for T-lang to decide whether the following rule should hold for opaque types:

If the body of an item that may define the hidden type of some opaque does define that hidden type, it must do so syntactically before using the opaque type in a non-defining way.

This restriction is called "must define before use."

Consider:

use core::convert::identity;

struct I;
struct IShow;
impl I { fn show(&self) -> IShow { IShow } }

struct OnIShow;
trait OnI { fn show(&self) -> OnIShow { OnIShow } }
impl OnI for I {}

fn test(n: bool) -> impl OnI {
    let true = n else { loop {} };
    let x = test(!n); //~ NOTE this is the opaque type
    let _: OnIShow = x.show(); //~ NOTE this is a non-defining use
    //~^ ERROR if the body registers a hidden type for the opaque, it
    //         must do so *before* using it opaquely
    let _: IShow = identity::<I>(x).show();
    //~^ NOTE this registers a hidden type for the opaque, but does so
    //        too late
    loop {}
}

fn main() {}

Because the code above works today, this would be a breaking change for RPIT.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the issue's RPIT example and the stated “must define before use” rule for opaque types. Determine whether the T-lang decision has been made and, if so, identify the compiler entry points and tests for the affected behavior; done requires an agreed language decision and corresponding validation.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.