-
Notifications
You must be signed in to change notification settings - Fork 1.6k
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
RFC: inherent trait implementation #2375
base: master
Are you sure you want to change the base?
Conversation
cc @nikomatsakis, @aturon This RFC assumes that rust-lang/rust#48444 will be treated as a feature and not as a bug. |
To clarify: #2309 was postponed until we figure out the story for delegation. While you talk about it a bit in this new RFC, it's not clear what in this proposal changes the situation compared to when the lang team previous took up this question. Can you expand on your thinking here? |
I was under impression that the previous RFC was closed due to the lack of reaction from @Diggsey to add requested changes, and not postponed. (ctrl+f "postpone" yields zero results) While I agree that delegation RFC and inherent traits should be discussed together, in my opinion RFCs have orthogonal scopes and similar only in the end effect. As was shown in the text, delegation can be nicely composed with Yes, the new delegation RFC draft mentions inherent trait impls as a possible future extension, but I don't think that using |
@newpavlov I don't think that's an accurate assessment. The RFC was closed because:
ie. the lang team wanted a more general solution |
@Diggsey @aturon |
@newpavlov Sorry for the delay, was out on vacation. Yes, I think it should probably be closed for the time being, especially since there's now a delegation RFC. Would be good to revisit after Rust 2018 ships! |
Where's the delegation RFC? My searches failed to find anything. |
@aturon |
``` | ||
|
||
Any questions regarding coherence, visibility or syntax can be resolved by | ||
comparing against this expansion, although the feature need not be implemented |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this should be explicitly specced out, especially since this expansion actually introduces an ambiguity in method calls.
|
||
# Reference-level explanation | ||
[reference-level-explanation]: #reference-level-explanation | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This should be fleshed out, including:
- What impl blocks it can be applied to (can the trait be foreign?)
- Whether it works with
#[fundamental]
- Does it error if you have an inherent method with the same name?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'd think it should error if you have an inherent method with the same name, like if you had two inherent methods with the same name.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What impl blocks it can be applied to (can the trait be foreign?)
Yes, it can. One of the main use-cases for inherent trait implementations is implementation of crates defined in external crates.
Whether it works with #[fundamental]
I am not sure why it should not, though I can't say I fully understand #[fundamental]
semantics.
Does it error if you have an inherent method with the same name?
Initially I though it should error, but as I wrote below probably it may be better to issue a warning and shadow inherent trait methods by true inherent methods.
I will try to update the text based on your review! Thanks!
[drawbacks]: #drawbacks | ||
|
||
- Increased complexity of the language. | ||
- Hides use of traits from users. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If this works the way I think it does, this actually changes our trait stability story, and that's a major drawback.
Currently, adding a defaulted method to a trait is not a major breaking change, at worst it will cause ambiguity errors, so it's considered minor.
Now, a dependency can add a method to a trait you #[inherent]
impl, which can clash with a method of your own, causing your build to fail in a way that requires you to change your API to fix. We're largely okay with builds failing due to new ambiguities (clashing method names across traits, adding something to a module that's glob imported, etc) and such things are categorized as minor, which basically means it's fine to do as long as the fallout isn't too much. With this RFC, adding a defaulted method has the potential to break a library user in a way that requires them to rename a method in their public API, causing a breaking change for them.
This should be explored and addressed in this RFC, and as a bare minimum should be called out in this section.
(One "fix" is to only allow local traits)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Another fix is to list out the method names that are inherent, although that becomes quite a burden for e.g. iterator methods.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm unsure if the existing situation should be classified as so minor because you interact with many types almost exclusively through their traits. As an example, there are definitely traits with a new()
method that defies the convention of being inherent new()
, so those traits adding new()
created exactly the same breakage you describe here.
As a fix, I'd suggest #[inherent]
being a method attribute for items inside an impl
, so
impl TraitWIthBadMethodNames for MyType {
fn new() -> Self { .. } // Not inherent
#[inherent]
fn new_plus() -> Self; // Inherent but default body used
#[inherent]
fn foo() { .. } // Inherent with body supplied here
}
And #[inherent]
applied to the impl
is equivalent to it being applied to all methods and associated types and constants.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As an example, there are definitely traits with a new() method that defies the convention of being inherent new(), so those traits adding new() created exactly the same breakage you describe here.
Yes, but this breakage is easily fixed by using UFCS. This is not true for breakage caused in the world of #[inherent]
.
The "minor" terminology comes from the API evolution RFC, such changes may cause crates to stop compiling, however:
- This can be fixed with a trivial change local to the crate
- The fix does not break upstream crates
Without this notion of "minor" being allowed, crates wouldn't be able to add anything new (types, traits, functions, or methods) without it being considered a breaking change.
Furthermore, the API evolution RFC mentions in the trait method case that you should check to ensure the fallout isn't too great; which is where your new()
example falls short: a trait adding a new()
method would probably have lots of fallout.
In other words, when I use the term "minor" here, I'm using a precisely defined term from another RFC. Whether or not it is actually "minor" is irrelevant, I'm talking about what we do and don't consider breaking, which we have specced in terms of this major/minor categorization.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Will it be possible to implement shadowing of inherent trait methods by true inherent methods? Compiler will warn on clashing inherent names while building crate which uses #[inherent]
, but will use true inherent method by default and for trait method you will have to use explicit Trait::foo(value)
. This way we will avoid code breakage on "minor" upstream changes.
Though I think in practice such collisions should be extremely rare.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Will it be possible to implement shadowing of inherent trait methods by true inherent methods?
I think that would be the ideal fix here: an inherent trait's methods get shadowed by the type's own methods. They could produce a warning lint when compiling the crate itself, so that people notice, and then cap-lints will suppress that when compiling a dependency.
How are polymorphic traits handled? I'd presume
works roughly like
Yet, how should separate
We'd likely want roughly
|
@burdges |
is there a reason (that I'm not seeing) that this cannot be done with a macro that just implements the wrapping functions in a generated |
It can be done, but will result in code and documentation bloat. Also use of procedural macros will increase compilation times. |
|
Does this need to be an RFC? As far as I'm aware, it could be implemented using a normal procedural macro and uploaded to crates.io. That also gives us a place to iterate on the implementation before anything is merged. Kinda like how we used the work from |
Specialization isn't in stable Rust, and referencing specialization makes the explanation more complex.
We reviewed this in a @rust-lang/lang meeting today, and would like to move ahead with it. Regarding the concern of Regarding the concern of Another option would be to augment the desugaring to say that " @programmerjake also made the observation that we might want the ability to have a blanket impl for a variety of types and then have a way to make that impl inherent for a specific type. Proposal: let's similarly add that as potential future work. @rfcbot merge @rfcbot concern decide-on-handling-for-breakage-with-new-trait-methods |
Team member @joshtriplett has proposed to merge this. The next step is review by the rest of the tagged team members: Concerns:
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! cc @rust-lang/lang-advisors: FCP proposed for lang, please feel free to register concerns. |
Apologies if I've missed something obvious -- I can see here a lot of discussion about the mechanical aspects of this feature, but, curiously, I haven't seen much about the plans for usage recommendations, despite the far reaching possibilities. I feel that, once this feature becomes widely available, "Should I implement this trait for my type inherently or not?" will be a question for every library author, so there should be at least a broad guideline planned before then. For example, should we say that types existing primarily for satisfying specific traits, such as A more concrete point on how being opinionated about usage of this feature could impact things: [1] As seen, for example, in infobox for return type of Iterator::map. |
Per the discussion on zulip, I have become convinced that it would be better to make this feature use the syntax impl SomeType {
pub use SomeTrait::*; // re-export the methods for the trait implementation
} This syntax has a few advantages:
However, in writing this, I realize an obvious disadvantage -- if the trait has more generics and things, it's not obvious how those should map. i.e., consider struct MyType<T> {
}
impl<T> MyType<T> {
pub use MyTrait::foo;
}
impl<T: Debug> MyTrait for MyType<T> {
fn foo(&self) { }
} This would be weird -- is this an error, because the impl block says it's for all |
If I like the idea, but to make it feel like a natural part of the language and not an overloading of the |
I don't entirely understand this sentence, why is there a "but" there? Or is there a negation missing somewhere? |
I'd say drop the type parameters entirely like
or even
or
|
struct MyType<T> {
}
impl<T> MyType<T> {
pub use MyTrait::foo;
}
impl<T: Debug> MyTrait for MyType<T> {
fn foo(&self) { }
} Lets break this down:
That said, the syntax is still weird. I think I'd prefer this: impl<T: Debug> MyType<T> {
pub use <Self as MyTrait>::foo;
// or the fully-qualified variant:
pub use <MyType<T> as MyTrait>::foo;
} |
@dhardy #![feature(fn_delegation)]
#![allow(incomplete_features)]
struct MyType<T> { field: T }
trait MyTrait {
fn foo(&self) {}
fn bar(&self) {}
fn baz(&self) {}
}
impl<T: std::fmt::Debug> MyTrait for MyType<T> {}
impl<T: std::fmt::Debug> MyType<T> {
pub reuse MyTrait::foo;
pub reuse <Self as MyTrait>::bar;
pub reuse <MyType<T> as MyTrait>::baz;
} , except generics are not fully supported yet. UPD: Works without generics - https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=d7d92cc51a2cd01b325f97eaaa65a01e |
re: concern decide-on-handling-for-breakage-with-new-trait-methods: An alternative formulation without the breakage could be to, instead of desugaring to an additional "real" inherent implementation, have
|
Nominating so we can address the possible syntaxes ( |
It was phrased poorly. What I meant is: it's inconsistent to permit |
@rfcbot cancel This FCP has been outstanding so long that let's just cancel it. My sense is that we do want something like this, but that we probably want some revisions to the RFC, perhaps along the lines of the When making these updates and before restarting pFCP, let's be sure that the concern that Josh raised here is addressed (resolving this point was one of the motivations of the |
@traviscross proposal cancelled. |
Continuation of #2309.
Fixes: #1880,#1971
This RFC allows us to write the following code:
Which allows methods from
Bar
trait to be used onFoo
instances without havingBar
in the scope.Rendered