Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Autotrait bounds on dyn-safe trait methods #107082

Merged
merged 2 commits into from
Feb 3, 2023
Merged

Conversation

dtolnay
Copy link
Member

@dtolnay dtolnay commented Jan 19, 2023

This PR is a successor to #106604 implementing the approach encouraged by #106604 (comment).

I propose making it legal to use autotraits as trait bounds on the Self type of trait methods in a trait object. #51443 (comment) justifies why this use case is particularly important in the context of the async-trait crate.

#![feature(auto_traits)]
#![deny(where_clauses_object_safety)]

auto trait AutoTrait {}

trait MyTrait {
    fn f(&self) where Self: AutoTrait;
}

fn main() {
    let _: &dyn MyTrait;
}

Previously this would fail with:

error: the trait `MyTrait` cannot be made into an object
 --> src/main.rs:7:8
  |
7 |     fn f(&self) where Self: AutoTrait;
  |        ^
  |
  = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
  = note: for more information, see issue #51443 <https://github.com/rust-lang/rust/issues/51443>
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
 --> src/main.rs:7:8
  |
6 | trait MyTrait {
  |       ------- this trait cannot be made into an object...
7 |     fn f(&self) where Self: AutoTrait;
  |        ^ ...because method `f` references the `Self` type in its `where` clause
  = help: consider moving `f` to another trait

In order for this to be sound without hitting #50781, I further propose that we disallow handwritten autotrait impls that apply to trait objects. Both of the following were previously allowed (on nightly) and no longer allowed in my proposal:

auto trait AutoTrait {}

trait MyTrait {}
impl AutoTrait for dyn MyTrait {}  // NOT ALLOWED

impl<T: ?Sized> AutoTrait for T {}  // NOT ALLOWED

(impl<T> AutoTrait for T {} remains allowed.)

After this change, traits with a default impl are implemented for a trait object if and only if the autotrait is one of the trait object's trait bounds (or a supertrait of a bound). In other words dyn Trait + AutoTrait always implements AutoTrait while dyn Trait never implements AutoTrait.

Fixes dtolnay/async-trait#228.

r? @lcnr

@dtolnay dtolnay added needs-fcp This change is insta-stable, so needs a completed FCP to proceed. T-types Relevant to the types team, which will review and decide on the PR/issue. labels Jan 19, 2023
@rustbot rustbot added the S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. label Jan 19, 2023
@dtolnay
Copy link
Member Author

dtolnay commented Jan 19, 2023

Mentioning @cjgillot + @nbdd0121 since you had opinions about #106604.

@lcnr
Copy link
Contributor

lcnr commented Jan 20, 2023

see the PR description for details

@rfcbot fcp merge

@rfcbot
Copy link

rfcbot commented Jan 20, 2023

Team member @lcnr has proposed to merge this. The next step is review by the rest of the tagged team members:

No concerns currently listed.

Once a majority of reviewers approve (and at most 2 approvals are outstanding), this will enter its final comment period. If you spot a major issue that hasn't been raised at any point in this process, please speak up!

See this document for info about what commands tagged team members can give me.

@rfcbot rfcbot added proposed-final-comment-period Proposed to merge/close by relevant subteam, see T-<team> label. Will enter FCP once signed off. disposition-merge This issue / PR is in PFCP or FCP with a disposition to merge it. labels Jan 20, 2023
@lcnr lcnr added S-waiting-on-fcp Status: PR is in FCP and is awaiting for FCP to complete. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Jan 20, 2023
@rfcbot rfcbot added final-comment-period In the final comment period and will be merged soon unless new substantive objections are raised. and removed proposed-final-comment-period Proposed to merge/close by relevant subteam, see T-<team> label. Will enter FCP once signed off. labels Jan 23, 2023
@rfcbot
Copy link

rfcbot commented Jan 23, 2023

🔔 This is now entering its final comment period, as per the review above. 🔔

@rfcbot rfcbot added finished-final-comment-period The final comment period is finished for this PR / Issue. to-announce Announce this issue on triage meeting and removed final-comment-period In the final comment period and will be merged soon unless new substantive objections are raised. labels Feb 2, 2023
@rfcbot
Copy link

rfcbot commented Feb 2, 2023

The final comment period, with a disposition to merge, as per the review above, is now complete.

As the automated representative of the governance process, I would like to thank the author for their work and everyone else who contributed.

This will be merged soon.

@dtolnay dtolnay added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-fcp Status: PR is in FCP and is awaiting for FCP to complete. labels Feb 2, 2023
@lcnr
Copy link
Contributor

lcnr commented Feb 3, 2023

@bors r+

@bors
Copy link
Contributor

bors commented Feb 3, 2023

📌 Commit fa84c6f has been approved by lcnr

It is now in the queue for this repository.

@bors bors added S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Feb 3, 2023
@apiraino apiraino removed the to-announce Announce this issue on triage meeting label Feb 3, 2023
Dylan-DPC added a commit to Dylan-DPC/rust that referenced this pull request Feb 3, 2023
Autotrait bounds on dyn-safe trait methods

This PR is a successor to rust-lang#106604 implementing the approach encouraged by rust-lang#106604 (comment).

**I propose making it legal to use autotraits as trait bounds on the `Self` type of trait methods in a trait object.** rust-lang#51443 (comment) justifies why this use case is particularly important in the context of the async-trait crate.

```rust
#![feature(auto_traits)]
#![deny(where_clauses_object_safety)]

auto trait AutoTrait {}

trait MyTrait {
    fn f(&self) where Self: AutoTrait;
}

fn main() {
    let _: &dyn MyTrait;
}
```

Previously this would fail with:

```console
error: the trait `MyTrait` cannot be made into an object
 --> src/main.rs:7:8
  |
7 |     fn f(&self) where Self: AutoTrait;
  |        ^
  |
  = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
  = note: for more information, see issue rust-lang#51443 <rust-lang#51443>
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
 --> src/main.rs:7:8
  |
6 | trait MyTrait {
  |       ------- this trait cannot be made into an object...
7 |     fn f(&self) where Self: AutoTrait;
  |        ^ ...because method `f` references the `Self` type in its `where` clause
  = help: consider moving `f` to another trait
```

In order for this to be sound without hitting rust-lang#50781, **I further propose that we disallow handwritten autotrait impls that apply to trait objects.** Both of the following were previously allowed (_on nightly_) and no longer allowed in my proposal:

```rust
auto trait AutoTrait {}

trait MyTrait {}
impl AutoTrait for dyn MyTrait {}  // NOT ALLOWED

impl<T: ?Sized> AutoTrait for T {}  // NOT ALLOWED
```

(`impl<T> AutoTrait for T {}` remains allowed.)

After this change, traits with a default impl are implemented for a trait object **if and only if** the autotrait is one of the trait object's trait bounds (or a supertrait of a bound). In other words `dyn Trait + AutoTrait` always implements AutoTrait while `dyn Trait` never implements AutoTrait.

Fixes dtolnay/async-trait#228.

r? `@lcnr`
@dtolnay dtolnay force-pushed the autotraits branch 2 times, most recently from 94ad442 to 182ebb5 Compare February 3, 2023 16:32
@dtolnay
Copy link
Member Author

dtolnay commented Feb 3, 2023

@bors r=lcnr

@bors
Copy link
Contributor

bors commented Feb 3, 2023

📌 Commit 4501d3a has been approved by lcnr

It is now in the queue for this repository.

bors added a commit to rust-lang-ci/rust that referenced this pull request Feb 3, 2023
Rollup of 6 pull requests

Successful merges:

 - rust-lang#107082 (Autotrait bounds on dyn-safe trait methods)
 - rust-lang#107427 (Add candidates for DiscriminantKind builtin)
 - rust-lang#107539 (Emit warnings on unused parens in index expressions)
 - rust-lang#107544 (Improve `TokenCursor`.)
 - rust-lang#107585 (Don't cause a cycle when formatting query description that references a FnDef)
 - rust-lang#107633 (Fix suggestion for coercing Option<&String> to Option<&str>)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
@bors bors merged commit 7221383 into rust-lang:master Feb 3, 2023
@rustbot rustbot added this to the 1.69.0 milestone Feb 3, 2023
@dtolnay dtolnay deleted the autotraits branch February 5, 2023 02:45
wip-sync pushed a commit to NetBSD/pkgsrc-wip that referenced this pull request Apr 24, 2023
Pkgsrc changes:
 * Adjust patches and cargo checksums to new versions.
 * Sadly, the patch to reduce the cargo verbosity no longer applies,
   so I've asked upstream about the proper way to get the old result.
   (so the build log becomes Quite Bloated for now).

Upstream changes:

Version 1.69.0 (2023-04-20)
==========================

Language
--------

- [Deriving built-in traits on packed structs works with `Copy` fields.]
  (rust-lang/rust#104429)
- [Stabilize the `cmpxchg16b` target feature on x86 and x86_64.]
  (rust-lang/rust#106774)
- [Improve analysis of trait bounds for associated types.]
  (rust-lang/rust#103695)
- [Allow associated types to be used as union fields.]
  (rust-lang/rust#106938)
- [Allow `Self: Autotrait` bounds on dyn-safe trait methods.]
  (rust-lang/rust#107082)
- [Treat `str` as containing `[u8]` for auto trait purposes.]
  (rust-lang/rust#107941)

Compiler
--------

- [Upgrade `*-pc-windows-gnu` on CI to mingw-w64 v10 and GCC 12.2.]
  (rust-lang/rust#100178)
- [Rework min_choice algorithm of member constraints.]
  (rust-lang/rust#105300)
- [Support `true` and `false` as boolean flags in compiler arguments.]
  (rust-lang/rust#107043)
- [Default `repr(C)` enums to `c_int` size.]
  (rust-lang/rust#107592)

Libraries
---------

- [Implement the unstable `DispatchFromDyn` for cell types, allowing
  downstream experimentation with custom method receivers.]
  (rust-lang/rust#97373)
- [Document that `fmt::Arguments::as_str()` may return `Some(_)`
  in more cases after optimization, subject to change.]
  (rust-lang/rust#106823)
- [Implement `AsFd` and `AsRawFd` for `Rc`.]
  (rust-lang/rust#107317)

Stabilized APIs
---------------

- [`CStr::from_bytes_until_nul`]
  (https://doc.rust-lang.org/stable/core/ffi/struct.CStr.html#method.from_bytes_until_nul)
- [`core::ffi::FromBytesUntilNulError`]
  (https://doc.rust-lang.org/stable/core/ffi/struct.FromBytesUntilNulError.html)

These APIs are now stable in const contexts:

- [`SocketAddr::new`]
  (https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.new)
- [`SocketAddr::ip`]
  (https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.ip)
- [`SocketAddr::port`]
  (https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.port)
- [`SocketAddr::is_ipv4`]
  (https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.is_ipv4)
- [`SocketAddr::is_ipv6`]
  (https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.is_ipv6)
- [`SocketAddrV4::new`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.new)
- [`SocketAddrV4::ip`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.ip)
- [`SocketAddrV4::port`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.port)
- [`SocketAddrV6::new`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.new)
- [`SocketAddrV6::ip`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.ip)
- [`SocketAddrV6::port`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.port)
- [`SocketAddrV6::flowinfo`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.flowinfo)
- [`SocketAddrV6::scope_id`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.scope_id)

Cargo
-----

- [Cargo now suggests `cargo fix` or `cargo clippy --fix` when compilation warnings are auto-fixable.]
  (rust-lang/cargo#11558)
- [Cargo now suggests `cargo add` if you try to install a library crate.]
  (rust-lang/cargo#11410)
- [Cargo now sets the `CARGO_BIN_NAME` environment variable also for binary examples.]
  (rust-lang/cargo#11705)

Rustdoc
-----

- [Vertically compact trait bound formatting.]
  (rust-lang/rust#102842)
- [Only include stable lints in `rustdoc::all` group.]
  (rust-lang/rust#106316)
- [Compute maximum Levenshtein distance based on the query.]
  (rust-lang/rust#107141)
- [Remove inconsistently-present sidebar tooltips.]
  (rust-lang/rust#107490)
- [Search by macro when query ends with `!`.]
  (rust-lang/rust#108143)

Compatibility Notes
-------------------

- [The `rust-analysis` component from `rustup` now only contains
  a warning placeholder.]
  (rust-lang/rust#101841) This was primarily
  intended for RLS, and the corresponding `-Zsave-analysis` flag
  has been removed from the compiler as well.
- [Unaligned references to packed fields are now a hard error.]
  (rust-lang/rust#102513) This has been
  a warning since 1.53, and denied by default with a future-compatibility
  warning since 1.62.
- [Update the minimum external LLVM to 14.]
  (rust-lang/rust#107573)
- [Cargo now emits errors on invalid characters in a registry token.]
  (rust-lang/cargo#11600)
- [When `default-features` is set to false of a workspace dependency,
  and an inherited dependency of a member has `default-features =
  true`, Cargo will enable default features of that dependency.]
  (rust-lang/cargo#11409)
- [Cargo denies `CARGO_HOME` in the `[env]` configuration table.
  Cargo itself doesn't pick up this value, but recursive calls to
  cargo would, which was not intended.]
  (rust-lang/cargo#11644)
- [Debuginfo for build dependencies is now off if not explicitly
  set. This is expected to improve the overall build time.]

  (rust-lang/cargo#11252)

Internal Changes
----------------

These changes do not affect any public interfaces of Rust, but they represent
significant improvements to the performance or internals of rustc and related
tools.

- [Move `format_args!()` into AST (and expand it during AST lowering)]
  (rust-lang/rust#106745)
netbsd-srcmastr pushed a commit to NetBSD/pkgsrc that referenced this pull request May 4, 2023
Pkgsrc changes:
 * Adjust patches and cargo checksums to new versions.

Upstream changes:

Version 1.69.0 (2023-04-20)
==========================

Language
--------

- [Deriving built-in traits on packed structs works with `Copy` fields.]
  (rust-lang/rust#104429)
- [Stabilize the `cmpxchg16b` target feature on x86 and x86_64.]
  (rust-lang/rust#106774)
- [Improve analysis of trait bounds for associated types.]
  (rust-lang/rust#103695)
- [Allow associated types to be used as union fields.]
  (rust-lang/rust#106938)
- [Allow `Self: Autotrait` bounds on dyn-safe trait methods.]
  (rust-lang/rust#107082)
- [Treat `str` as containing `[u8]` for auto trait purposes.]
  (rust-lang/rust#107941)

Compiler
--------

- [Upgrade `*-pc-windows-gnu` on CI to mingw-w64 v10 and GCC 12.2.]
  (rust-lang/rust#100178)
- [Rework min_choice algorithm of member constraints.]
  (rust-lang/rust#105300)
- [Support `true` and `false` as boolean flags in compiler arguments.]
  (rust-lang/rust#107043)
- [Default `repr(C)` enums to `c_int` size.]
  (rust-lang/rust#107592)

Libraries
---------

- [Implement the unstable `DispatchFromDyn` for cell types, allowing
  downstream experimentation with custom method receivers.]
  (rust-lang/rust#97373)
- [Document that `fmt::Arguments::as_str()` may return `Some(_)`
  in more cases after optimization, subject to change.]
  (rust-lang/rust#106823)
- [Implement `AsFd` and `AsRawFd` for `Rc`.]
  (rust-lang/rust#107317)

Stabilized APIs
---------------

- [`CStr::from_bytes_until_nul`]
  (https://doc.rust-lang.org/stable/core/ffi/struct.CStr.html#method.from_bytes_until_nul)
- [`core::ffi::FromBytesUntilNulError`]
  (https://doc.rust-lang.org/stable/core/ffi/struct.FromBytesUntilNulError.html)

These APIs are now stable in const contexts:

- [`SocketAddr::new`]
  (https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.new)
- [`SocketAddr::ip`]
  (https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.ip)
- [`SocketAddr::port`]
  (https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.port)
- [`SocketAddr::is_ipv4`]
  (https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.is_ipv4)
- [`SocketAddr::is_ipv6`]
  (https://doc.rust-lang.org/stable/std/net/enum.SocketAddr.html#method.is_ipv6)
- [`SocketAddrV4::new`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.new)
- [`SocketAddrV4::ip`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.ip)
- [`SocketAddrV4::port`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV4.html#method.port)
- [`SocketAddrV6::new`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.new)
- [`SocketAddrV6::ip`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.ip)
- [`SocketAddrV6::port`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.port)
- [`SocketAddrV6::flowinfo`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.flowinfo)
- [`SocketAddrV6::scope_id`]
  (https://doc.rust-lang.org/stable/std/net/struct.SocketAddrV6.html#method.scope_id)

Cargo
-----

- [Cargo now suggests `cargo fix` or `cargo clippy --fix` when compilation warnings are auto-fixable.]
  (rust-lang/cargo#11558)
- [Cargo now suggests `cargo add` if you try to install a library crate.]
  (rust-lang/cargo#11410)
- [Cargo now sets the `CARGO_BIN_NAME` environment variable also for binary examples.]
  (rust-lang/cargo#11705)

Rustdoc
-----

- [Vertically compact trait bound formatting.]
  (rust-lang/rust#102842)
- [Only include stable lints in `rustdoc::all` group.]
  (rust-lang/rust#106316)
- [Compute maximum Levenshtein distance based on the query.]
  (rust-lang/rust#107141)
- [Remove inconsistently-present sidebar tooltips.]
  (rust-lang/rust#107490)
- [Search by macro when query ends with `!`.]
  (rust-lang/rust#108143)

Compatibility Notes
-------------------

- [The `rust-analysis` component from `rustup` now only contains
  a warning placeholder.]
  (rust-lang/rust#101841) This was primarily
  intended for RLS, and the corresponding `-Zsave-analysis` flag
  has been removed from the compiler as well.
- [Unaligned references to packed fields are now a hard error.]
  (rust-lang/rust#102513) This has been
  a warning since 1.53, and denied by default with a future-compatibility
  warning since 1.62.
- [Update the minimum external LLVM to 14.]
  (rust-lang/rust#107573)
- [Cargo now emits errors on invalid characters in a registry token.]
  (rust-lang/cargo#11600)
- [When `default-features` is set to false of a workspace dependency,
  and an inherited dependency of a member has `default-features =
  true`, Cargo will enable default features of that dependency.]
  (rust-lang/cargo#11409)
- [Cargo denies `CARGO_HOME` in the `[env]` configuration table.
  Cargo itself doesn't pick up this value, but recursive calls to
  cargo would, which was not intended.]
  (rust-lang/cargo#11644)
- [Debuginfo for build dependencies is now off if not explicitly
  set. This is expected to improve the overall build time.]

  (rust-lang/cargo#11252)

Internal Changes
----------------

These changes do not affect any public interfaces of Rust, but they represent
significant improvements to the performance or internals of rustc and related
tools.

- [Move `format_args!()` into AST (and expand it during AST lowering)]
  (rust-lang/rust#106745)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-auto-traits Area: auto traits (`auto trait Send`) A-coherence Area: Coherence disposition-merge This issue / PR is in PFCP or FCP with a disposition to merge it. F-auto_traits `#![feature(auto_traits)]` finished-final-comment-period The final comment period is finished for this PR / Issue. needs-fcp This change is insta-stable, so needs a completed FCP to proceed. S-waiting-on-bors Status: Waiting on bors to run and complete tests. Bors will change the label on completion. T-types Relevant to the types team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

warn: where_clauses_object_safety when adding default implementation for async_trait
6 participants