id
int64 37.9M
1.25B
| issue_num
int64 15.7k
97.4k
| title
stringlengths 20
90
| body
stringlengths 59
9.59k
| comments
stringlengths 152
26.7k
| labels
stringlengths 93
311
| comment_count
int64 1
465
| url
stringlengths 56
56
| html_url
stringlengths 46
46
| comments_url
stringlengths 65
65
|
---|---|---|---|---|---|---|---|---|---|
1,246,842,349 | 97,362 | Tracking Issue for RFC 3216: "Allow using `for<'a>` syntax when declaring closures" | <!--
NOTE: For library features, please use the "Library Tracking Issue" template instead.
Thank you for creating a tracking issue! 📜 Tracking issues are for tracking a
feature from implementation to stabilisation. Make sure to include the relevant
RFC for the feature if it has one. Otherwise provide a short summary of the
feature and link any relevant PRs or issues, and remove any sections that are
not relevant to the feature.
Remember to add team labels to the tracking issue.
For a language team feature, this would e.g., be `T-lang`.
Such a feature should also be labeled with e.g., `F-my_feature`.
This label is used to associate issues (e.g., bugs and design questions) to the feature.
-->
This is a tracking issue for the RFC "Allow using `for<'a>` syntax when declaring closures" (rust-lang/rfcs#3216).
The feature gate for the issue is `#![feature(closure_lifetime_binder)]`.
### About tracking issues
Tracking issues are used to record the overall progress of implementation.
They are also used as hubs connecting to other relevant issues, e.g., bugs or open design questions.
A tracking issue is however *not* meant for large scale discussion, questions, or bug reports about a feature.
Instead, open a dedicated issue for the specific matter and add the relevant feature gate label.
### Steps
<!--
Include each step required to complete the feature. Typically this is a PR
implementing a feature, followed by a PR that stabilises the feature. However
for larger features an implementation could be broken up into multiple PRs.
-->
- [X] Implement the RFC - implemented in https://github.com/rust-lang/rust/pull/98705
- [ ] Adjust documentation ([see instructions on rustc-dev-guide][doc-guide])
- [ ] Stabilization PR ([see instructions on rustc-dev-guide][stabilization-guide])
[stabilization-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#stabilization-pr
[doc-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#documentation-prs
### Unresolved Questions
<!--
Include any open questions that need to be answered before the feature can be
stabilised.
-->
None at this time
### Implementation history
* Initial implementation in https://github.com/rust-lang/rust/pull/98705
<!--
Include a list of all the PRs that were involved in implementing the feature.
-->
<!-- TRIAGEBOT_START -->
<!-- TRIAGEBOT_ASSIGN_START -->
<!-- TRIAGEBOT_ASSIGN_DATA_START$${"user":"WaffleLapkin"}$$TRIAGEBOT_ASSIGN_DATA_END -->
<!-- TRIAGEBOT_ASSIGN_END -->
<!-- TRIAGEBOT_END --> | I'd like to work on implementing this 👀
@rustbot claim<|endoftext|>The implementation section needs to be updated to mention #98705.<|endoftext|>I bumped on this issue and I would like to share some code that maybe someone knowledgeable could comment on whether we are likely to get the features demonstrated or similar (in summary it's getting `for<>` for async closures):
```rust
#![feature(closure_lifetime_binder)]
#![feature(trait_alias)]
use core::future::Ready;
use core::future::ready;
use core::future::Future;
// Don't read too much into the implementation of `S`
struct S<'a>(&'a ());
trait AsyncF<'a, F> = Fn(S<'a>) -> F where F: Future<Output = S<'a>>;
async fn asyncF<F>(f: impl for<'a> AsyncF<'a, F>) {
let a = ();
f(S(&a)).await;
}
fn main() {
// We can't seem to do this because for<> does not seem to extend to the
// argument.
asyncF(for<'a> |x: S<'a>| -> Ready<S<'a>> {ready(x)});
// Ideally we would like this to do anything useful with for<> and async.
// asyncF(for<'a> async move |x: &'a ()| -> &'a () {ready(x)});
}
```
[playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=75475a141e376a2c0711ecac8461d20e)<|endoftext|>@fakedrake I think your `AsyncF`/`asyncF` are wrong. You are using a single `F` type, that is supposed to implement `for<'a> Future<Output = S<'a>>`, where in reality you have a `for<'a> F<'a>: Future<Output = S<'a>>` type.
If you change the `AsyncF` trait to be something like the following:
```rust
trait AsyncF<'a, Input>: Fn(Input) -> Self::Future {
type Future: Future<Output = Self::Out>;
type Out;
}
impl<'a, F, Fut, In> AsyncF<'a, In> for F
where
F: Fn(In) -> Fut,
Fut: Future,
{
type Future = Fut;
type Out = Fut::Output;
}
```
Then your example [works](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=a0db8d120af26cbcab4e20dc309b4adc). Though I want to warn you that such traits are a pain to work with and especially extend.
----
As for `for<'a> async move |x: &'a ()| -> &'a ()` kind of thing, I think it generally desired, but was ruled out of the scope of the RFC. So, if we'll ever add it, it would first need its own RFC.
It appears that async closures are currently in a very rough shape ([eg](https://github.com/rust-lang/rust/blob/b8c0a01b2b651416f5e7461209ff1a93a98619e4/compiler/rustc_ast_lowering/src/expr.rs#L962)) so a good place to start would probably be to fix/complete the implementation of async closures first.<|endoftext|>Thank you very much. I have seen people vaguely complaining about the primitive state of async closures but besides this niche case I have found that they have worked pretty well. Is there an issue tracking the problems with them?<|endoftext|>There is a tracking issue for async closures: #62290<|endoftext|>Found an ICE involving this feature: https://github.com/rust-lang/rust/issues/103736
(Maybe we could use an `F-closure_lifetime_binder` tag?)<|endoftext|>Suggestion: could it be allowed to elide the return type of an explicitly higher-ranked closure when it is `()`? Currently, Rust allows eliding `()` returns in all other function signatures, even when nothing else can be elided.<|endoftext|>@Jules-Bertholet I don't think it's a good idea, we may want to allow inferring return type in the future, just like with normal closures.<|endoftext|>@WaffleLapkin "Infer return type when it is `()`" should be forward-compatible with "infer return type always."<|endoftext|>@Jules-Bertholet oh, I misunderstood this as "make `for<> || { some expression... }` return type always `()`, same as with normal function". Inferring it is probably fine.<|endoftext|>It appears that this will not work well for returning closures as their type can not be explicitly specified as a closure return type. This is likely known but I think worth pointing it out. This will however work for return types that you can specify.
```rust
let f = for<'a> |a: &'a u8| -> impl 'a + Fn() -> &'a u8 {
|| a
};
```
```
error[[E0562]](https://doc.rust-lang.org/nightly/error_codes/E0562.html): `impl Trait` only allowed in function and inherent method return types, not in closure return types
--> src/main.rs:5:36
|
5 | let f = for<'a> |a: &'a u8| -> impl 'a + Fn() -> &'a u8 {
| ^^^^^^^^^^^^^^^^^^^^^^^^
```
[Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=7aa83bd601924e751507bc7062715256)<|endoftext|>@kevincox: I believe that is a general limitation of what return types you can write when declaring closures, and not related to this RFC. | T-lang<|endoftext|>C-tracking-issue<|endoftext|>S-tracking-needs-summary<|endoftext|>T-types<|endoftext|>F-closure_lifetime_binder | 13 | https://api.github.com/repos/rust-lang/rust/issues/97362 | https://github.com/rust-lang/rust/issues/97362 | https://api.github.com/repos/rust-lang/rust/issues/97362/comments |
1,100,848,356 | 92,827 | Tracking Issue for Associated Const Equality | This is a tracking issue for the feature Associated Const Equality brought up in #70256.
The feature gate for the issue is `#![feature(associated_const_equality)]`.
### About tracking issues
Tracking issues are used to record the overall progress of implementation.
They are also used as hubs connecting to other relevant issues, e.g., bugs or open design questions.
A tracking issue is however *not* meant for large scale discussion, questions, or bug reports about a feature.
Instead, open a dedicated issue for the specific matter and add the relevant feature gate label.
### Steps
- [ ] Fully implement the feature
- [ ] Teach Chalk about terms (enum Ty or Const relating an associated type or const respectively)
- [ ] Remove all FIXME(associated_const_equality)
- [ ] Adjust documentation ([see instructions on rustc-dev-guide][doc-guide])
- [ ] Stabilization PR ([see instructions on rustc-dev-guide][stabilization-guide])
[stabilization-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#stabilization-pr
[doc-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#documentation-prs
### Unresolved Questions
<!--
Include any open questions that need to be answered before the feature can be
stabilised.
-->
XXX --- list all the "unresolved questions" found in the RFC to ensure they are
not forgotten
### Implementation history
- Originally proposed in #70256 with support but no official RFC, but implementation delayed.
- Initial effort to implement which includes parsing and use of `term` throughout the codebase in #87648, but still lacking a complete implementation.
- More thorough implementation which works for basic cases in #93285. This allowed for consts to actually be bound, more than just parsing them.
| Hello!
Is there a corresponding RFC, or any context whatsoever concerning those changes ?
This is the first occurrence of language syntax change that is not backed by RFC and community feedback
@Centril @oli-obk <|endoftext|>Well, we have https://github.com/rust-lang/rust/issues/70256 which indeed has basically no discussion of the feature. It just seemed like an oversight to have associated types + associated type bounds, but only associated consts without any bounds for them. <|endoftext|>I probably should've tagged the original issue in this at the start (it was in the original PR if I remember correctly) but I'm bad at leaving a thorough paper trail. I'll add a reference to the original issue in the issue itself, and if there's more work that needs to be done please let know<|endoftext|>You did everything correctly. I found the issue because you did link it in the first sentence in this issue 😄
We should probably do a lang team MCP for it along with some medium sized doc explaining what is going on and why. I'll open a hackmd and then we can collab on it<|endoftext|>What's the current state of this? How much is implemented, and how functional is it?<|endoftext|>@joshtriplett I've started work on it, and the syntax/parsing is in place, but the implementation currently does not work. I started working on Chalk, but that has stalled since I wasn't really able to know whether it was necessary for implementing it in rustc. I've also gotten a bit sidetracked working on other things.<|endoftext|>Is it planned to recognize Associated Constant Equality as disjoint cases?
```rs
trait Foo{
const DECIDER: bool;
}
trait Bar{ /*stuff*/ }
impl<T: Foo<DECIDER = true>> Bar for T{ /*stuff*/ }
impl<T: Foo<DECIDER = false>> Bar for T{ /*stuff*/ }
```<|endoftext|>@rustbot label F-associated_const_equality<|endoftext|>@urben1680 I believe this would be the main point of this, but I have not got around to actually implementing it<|endoftext|>```rust
pub struct ConstNum<const N: usize>;
pub trait Is<const N: usize> {}
impl<const N: usize> Is<N> for ConstNum<N> {}
struct Bar<const N: usize>([u8; N]);
fn foo<const N: usize>(_input: Bar<N>) where ConstNum<N>: Is<2> {
}
fn main() {
foo(Bar([0u8; 2])); //works
foo(Bar([0u8; 3])); //doesn't
}
```<|endoftext|>Another use case would be checking tensor shapes. I hit this issue when compiling my code that constrains the shapes of input tensors to have the same dimensionality and/or rank.
For example, dumb code like the below
```rust
pub trait TensorShape1D {
const SHAPE: usize; // i.e. length
}
pub fn add<const L: usize, LEFT_TENSOR: TensorShape1D<SHAPE=L>, RIGHT_TENSOR: TensorShape1D<SHAPE=L>>(left: LEFT_TENSOR, right: RIGHT_TENSOR) {
todo!()
}
```
Any two structs that implement `TensorShape1D` and have the same `SHAPE` can be the input of this function.
Right now, I have to use `typenum` crate and associated type to do the same checking, but it would be great to not have to type-dance like `typenum`. I think when this is implemented, `typenum` can be greatly simplified.<|endoftext|>I am locking this, as it is a tracking issue. Please open a thread on zulip for discussions or open issues for any issues you encounter. | A-associated-items<|endoftext|>T-lang<|endoftext|>C-tracking-issue<|endoftext|>A-const-generics<|endoftext|>S-tracking-needs-summary<|endoftext|>F-associated_const_equality | 12 | https://api.github.com/repos/rust-lang/rust/issues/92827 | https://github.com/rust-lang/rust/issues/92827 | https://api.github.com/repos/rust-lang/rust/issues/92827/comments |
1,081,306,965 | 91,971 | Tracking issue for pref_align_of intrinsic | This intrinsic returns the "preferred" alignment of a type, which can be different from the *minimal* alignment exposed via `mem::align_of`. It is not currently exposed through any wrapper method, but can still be accessed by unstable code using the `intrinsics` or `core_intrinsics` features.
See https://github.com/rust-lang/rust/pull/90877 for why it cannot be removed; the short summary is some code is actually using it. So let's have a place to centralize discussion about the intrinsics. (This is not a regular tracking issue because there is no associated feature gate, but close enough I think.) | Context for labels applied: it sounds like we need a summary of what precisely this means, as distinct from `align_of`, in a way that isn't tied to the LLVM backend. | T-lang<|endoftext|>T-libs-api<|endoftext|>C-tracking-issue<|endoftext|>A-intrinsics<|endoftext|>S-tracking-design-concerns<|endoftext|>S-tracking-needs-summary | 1 | https://api.github.com/repos/rust-lang/rust/issues/91971 | https://github.com/rust-lang/rust/issues/91971 | https://api.github.com/repos/rust-lang/rust/issues/91971/comments |
1,014,017,064 | 89,460 | Tracking Issue for `deref_into_dyn_supertrait` compatibility lint | ## What is this lint about
We're planning to add the dyn upcasting coercion language feature (see https://github.com/rust-lang/dyn-upcasting-coercion-initiative). Unfortunately this new coercion rule will take priority over certain other coercion rules, which will mean some behavior change. See #89190 for initial bug report.
## How to fix this warning/error
Ensure your own `Deref` implementation is consistent with the `trait_upcasting` feature brings and `allow` this lint. Or avoid this code pattern altogether.
## Current status
Implementation: #89461 | Could we get a more detailed summary of the case this lint is addressing? dyn upcasting / coercion seems to have made a lot of progress, but this aspect of it doesn't seem to have gotten much discussion that I recall.<|endoftext|>@joshtriplett Sure.
It is known that from user's perspective, coercions has "priorities", and dyn upcasting coercion has a higher priority than user defined `Deref`-based coercions. In the end, this coercion "shadows" a rare certain setup of user `Deref` implementation, which mimicks dyn upcasting coercion manually(see #89190 for an example).
For now we don't want to affect user's code, since dyn upcasting coercion might take a little while before it's stablized. Though, if user provided code decide to do other things in the `Deref`/`DerefMut` implementation, (even rarer, but possible, like running a hook or something), there will be a silent behavior change, when dyn upcasting gets stablized in the future. This lint emits a warning for this matter, to make sure that user doesn't write such code in their `Deref`/`DerefMut` implementations, then the future migration to dyn upcasting coercion will be smooth.
<|endoftext|>I'm curious -- why wasn't this implemented as a lint on the `impl`?<|endoftext|>@compiler-errors It could be implemented that way, and thinking about it from current view, that would be a better way (No removal of the lint is needed with that approach)<|endoftext|>For future reference: the lint change suggested by @compiler-errors was implemented in https://github.com/rust-lang/rust/pull/104742 (I just tried to do that again because I forgor). The lint now lints against `Deref` impls for `dyn Trait` with `type Target = dyn SupertraitOfTrait` (instead of linting against the *use* of such `Deref` impl like it used to). | A-lint<|endoftext|>T-lang<|endoftext|>T-compiler<|endoftext|>C-future-compatibility<|endoftext|>C-tracking-issue<|endoftext|>S-tracking-needs-summary | 5 | https://api.github.com/repos/rust-lang/rust/issues/89460 | https://github.com/rust-lang/rust/issues/89460 | https://api.github.com/repos/rust-lang/rust/issues/89460/comments |
927,632,656 | 86,555 | Tracking Issue for RFC 2528: type-changing struct update syntax | This is a tracking issue for RFC 2528 (rust-lang/rfcs#2528), type-changing struct update syntax.
The feature gate for the issue will be `#![feature(type_changing_struct_update)]`.
There is a dedicated Zulip stream: [`#project-type-changing-struct-update`](https://rust-lang.zulipchat.com/#narrow/stream/293397-project-type-changing-struct-update)
### About tracking issues
Tracking issues are used to record the overall progress of implementation.
They are also used as hubs connecting to other relevant issues, e.g., bugs or open design questions.
A tracking issue is however *not* meant for large scale discussion, questions, or bug reports about a feature.
Instead, open a dedicated issue for the specific matter and add the relevant feature gate label.
### Steps
- [x] Implementation: https://github.com/rust-lang/rust/issues/86618
- [ ] https://github.com/rust-lang/rust/issues/101970
- [ ] Adjust documentation ([see instructions on rustc-dev-guide][doc-guide])
- [ ] Stabilization PR ([see instructions on rustc-dev-guide][stabilization-guide])
[stabilization-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#stabilization-pr
[doc-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#documentation-prs
### Unresolved Questions
- [ ] Type inference: when implementing this, we need to confirm that it won't adversely affect type inference.
"Further generalization" in the RFC would be the subject of future RFCs, not something we need to track in this tracking issue.
### Implementation history
<!--
Include a list of all the PRs that were involved in implementing the feature.
-->
* Feature gate: https://github.com/rust-lang/rust/pull/89730
* Implementation: https://github.com/rust-lang/rust/pull/90035 | It looks like this has been implemented; are there any further known issues or blockers with it?<|endoftext|>I'm eagerly awaiting stabilisation of this feature! Is there anything that still needs to be done?<|endoftext|>> It looks like this has been implemented; are there any further known issues or blockers with it?
Yes, i created #101970 to track it<|endoftext|>This feature would be useful in bootloader development when different stages of bootloading would handover structures with small modifications. For example, bootstrap module would provide main function like:
```rust
fn main(param: Parameters) -> Handover {
// ....
}
```
where `Handover` share most of fields with `Parameters`, but only small subset of fields are changed in declaration. This will be ideal to express the way Rust ownership works in embedded: one peripheral is wrapped in a structure to show it cannot be initialized or dropped twice. Thus, the wrapper struct should be provided as-is in `Handover`. We can do like this:
```rust
fn main(param: Parameters) -> Handover {
let serial = Serial::new(param.uart0, /* ... */);
// ....
Handover { serial, ..param }
// instead of: Handover { serial, periph_1: param.periph_1, periph_2: param.periph_2, periph_3: param.periph_3, /* ... */ }
}
```
We can now avoid repeat passing peripheral fields in bootload stage handovering, where there would typically be dozens of peripheral fields whose ownerships are going to be transfered.
I'll express my idea in playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=7fb79bb65cce97cc785b78d9aca1e656
In this way, type changing struct update syntax will have an obvious code size reduction, which will help a lot in embedded development.<|endoftext|>@luojia65 This feature is only for changing the generic arguments of the struct, e.g: going from `Foo<Bar>` to `Foo<Baz>`.
What you want sound like what's [in the Rationales and Alternatives section of the RFC for this feature](https://github.com/rust-lang/rfcs/blob/master/text/2528-type-changing-struct-update-syntax.md#further-generalization), except that it doesn't talk about going between structs with an intersection of fields. | B-RFC-approved<|endoftext|>T-lang<|endoftext|>C-tracking-issue<|endoftext|>F-type-changing-struct-update<|endoftext|>S-tracking-needs-summary | 5 | https://api.github.com/repos/rust-lang/rust/issues/86555 | https://github.com/rust-lang/rust/issues/86555 | https://api.github.com/repos/rust-lang/rust/issues/86555/comments |
849,330,204 | 83,788 | Tracking issue for the unstable "wasm" ABI | This issue is intended to track the stabilization of the `"wasm"` ABI added in https://github.com/rust-lang/rust/pull/83763. This new ABI is notably different from the "C" ABI where the "C" ABI's purpose is to match whatever the C ABI for the platform is (in this case whatever clang does). The "wasm" ABI, however, is intended to match the WebAssembly specification and should be used for functions that need to be exported/imported from a wasm module to precisely match a desired WebAssembly signature.
One of the main features of the "wasm" ABI is that it automatically enables the multi-value feature in LLVM which means that functions can return more than one value. Additionally parameters are never passed indirectly and are always passed by-value when possible to ensure that what was written is what shows up in the ABI on the other end.
It's expected that one day the "C" ABI will be updated within clang to use multi-value, but even if that happens the ABI is likely to optimize for the performance of C itself rather than for binding the WebAssembly platform. The presence of a "wasm" ABI in Rust guarantees that there will always be an ABI to match the exact WebAssembly signature desired.
Another nice effect of stabilizing this ABI is that the `wasm32-unknown-unknown` target's default C ABI can be switched back to matching clang. This longstanding mismatch is due to my own personal mistake with the original definition and the reliance on the mistake in `wasm-bindgen`. Once the "wasm" ABI is stable, however, I can switch `wasm-bindgen` to using the "wasm" ABI everywhere and then the compiler can switch the default ABI of the `wasm32-unknown-unknown` target to match the C ABI of clang. | For folks wanting to give this a try, is there an experimental branch of `wasm-bindgen` that uses this "wasm" ABI?<|endoftext|>There is not a branch at this time, no.<|endoftext|>What is the current state of this? Is there wasm-bindgen support or tooling support for this? Is anything using this?
cc @alexcrichton<|endoftext|>@joshtriplett
> Is anything using this?
Searching sourcegraph and github, I've so far only found one project previously using it then switched to "C" ABI due to a couple of issues <https://github.com/oasisprotocol/oasis-sdk/issues/561>
> * problems with u128 https://github.com/rust-lang/rust/issues/88207
> * problems with compiling multivalue functions https://github.com/ptrus/wasm-bug (todo: should probably open an upstream issue for this)
<|endoftext|>The `wasm-bindgen` crate hasn't updated to using this since it requires nightly Rust and it otherwise wants to compile on stable. I'm otherwise unaware of any other tooling using this myself.<|endoftext|>@alexcrichton Is there a chicken and egg problem there? I think we were waiting to consider stabilization until it was clear this was being used. :)<|endoftext|>Personally I think this is more of a "what is C going to do" problem for stabilization. I don't think Rust is in the position to blaze a trail here when C/C++ otherwise can't access it. One of the main purposes of this ABI is to give access to the ability to define a multi-return function in WebAssembly, but C/C++ have no corresponding mechanism to do that. Until C/C++ figure out how they're going to return multiple values then multi-return is unlikely to be used in the wasm ecosystem so stabilizing this wouldn't provide much benefit. Additionally if this were stabilized and then C/C++ picked a different way to use multi-return then that would be yet-another ABI that Rust would have to implement.<|endoftext|>Rust isn’t C. Rust is Rust and Rust shouldn’t care what C (clang) does for anything not explicitly using the term `C` (`repr(C)` and `extern "C"`).
Rust on wasm’s first priority will always be compatibility with wasm and web standards not with C/C++ on wasm, especially considering wasm doesn’t even have a good way of interoperating betweeen Rust and C that isn’t already mangled through javascript. multiple returns are natively supported by wasm, and Rust should take advantage of this whether clang likes it or not.
perhaps we should maintain `extern "C"` as “C/C++ compatible wasm bindings” but we most definitely should not block the addition of a feature explicitly designed for decoupling Rust on wasm from C because it might not match what C is going to do.
i also see absolutely no reason that Rust shouldn’t be a trailblazer in this field, as it’s at least as favourable as C/C++ in the wasm community.
i don’t think C or C++ even belong in this discussion.<|endoftext|>just wanted to know if this affects https://github.com/rustwasm/team/issues/291 where we can't compile c/cpp binding crates to `wasm32-unknown-unknown` yet. eg: `sdl2-sys` or `zstd-sys` etc..<|endoftext|>Yes - adding the `"wasm"` ABI would allow `wasm-bindgen` to switch to it, and then the `"C"` ABI should be able to be fixed to match `clang` since there wouldn't be anything relying on it. That would fix the ABI-incompatibility issue.
A different way to fix it would be to change `wasm-bindgen` to generate code which works the same no matter whether the current, incorrect `"C"` ABI or the standard one is being used (i.e. explicitly passing structs by pointer). That could be a performance hit, but I doubt it'd be huge.<|endoftext|>@alexcrichton
> Another nice effect of stabilizing this ABI is that the `wasm32-unknown-unknown` target's default C ABI can be switched back to matching clang.
> …and then the compiler can switch the default ABI of the `wasm32-unknown-unknown` target to match the C ABI of clang.
This suggests that maybe there’s a way to use something other than the default C ABI.
Is there a way to opt-in to using a C ABI that isn’t the default but does match clang?
I’m targeting `wasm32-unknown-unknown` but not using `wasm-bindgen` in case that’s relevant.
Please forgive my ignorance on this. I’m in way over my head here 😄<|endoftext|>I'm not aware of any mechanism at this time to use something else to match clang. That's the purpose of the `"C"` ABI so I've at least personally been reluctant to add another name for that.<|endoftext|>is there a place i can track the progress of this clang's C multi-return ABI thing?
also, any idea as to how long it will take? 2024? or even longer?
https://github.com/rust-lang/rust/issues/73755 ?<|endoftext|>Have there been any attempts to form a committee around this? Ideally this would be a W3C subgroup. <|endoftext|>> The "wasm" ABI, however, is intended to match the WebAssembly specification and should be used for functions that need to be exported/imported from a wasm module to precisely match a desired WebAssembly signature.
This is not how `extern "wasm"` is implemented. As it is currently implemented it is effectively `extern "unadjusted"` + integer promotion. `extern "unadjusted"` is perma-unstable as it depends ob the exact LLVM types the backend uses to represent Rust types and the exact rules LLVM uses to legalize non-primitive and non-byref arguments. For example unions like `#[repr(C)] union Foo { a: [u8; 9] }` are currently represented in LLVM ir using `type_padding_filler` whose return value is for example `[9 x i8]` for `Foo` (as this is is an array with the exact same size as the union and using bigger element types will leave a rest) and this is lowered by current LLVM versions as 9 32bit integer arguments for `extern "unadjusted"` and thus `extern "wasm"`. I believe LLVM in case of nested types even recursively picks out primitive fields. The only types that can match the Webassembly specification are primitives. Anything else and you are inventing your own ABI and in this case it is an ABI which depends on implementation details.
```
$ echo '#![feature(wasm_abi)] #[repr(C)] pub union Foo { b: [u8; 9] } #[no_mangle] pub extern "wasm" fn foo(a: Foo) {}' | rustc +nightly --target wasm32-unknown-unknown --crate-type lib --emit asm=/dev/stdout,llvm-ir=/dev/stdout -
[...]
.globl foo
.type foo,@function
foo:
.functype foo (i32, i32, i32, i32, i32, i32, i32, i32, i32) -> ()
end_function
[...]
%Foo = type { [9 x i8] }
; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn
define dso_local void @foo(%Foo %0) unnamed_addr #0 {
start:
ret void
}
[...]
```
https://github.com/rust-lang/rust/issues/76916 is likely caused by this.<|endoftext|>@alexcrichton I was going down the rabbit hole of why `wasm32-unknown-unknown` is currently incompatible with C and eventually landed here. I didn't fully understand why `extern "wasm"` is blocked on "what is C going to do" about multivalue: https://github.com/rust-lang/rust/issues/83788#issuecomment-1191564068.
> Until C/C++ figure out how they're going to return multiple values then multi-return is unlikely to be used in the wasm ecosystem so stabilizing this wouldn't provide much benefit.
But stabilizing this has a huge benefit even without any multivalue support: be compatible with C!
> Additionally if this were stabilized and then C/C++ picked a different way to use multi-return then that would be yet-another ABI that Rust would have to implement.
So that's the part I'm confused about, I thought the whole point of this new ABI is to separate C and Wasm ABI concerns. `extern "wasm"` will always correspond to the Wasm ABI, the one we are using in `wasm-bindgen`, and `extern "C"` will always follow the C ABI. So whenever C figures out multivalue, we can apply it to the C ABI. Why would that require another ABI?
If the concern is to support both a C ABI with and without multivalue support, then that should probably be gated by `-Ctarget-feature=+multivalue`. In any case, I don't see the conflict with `extern "wasm"` here.<|endoftext|>There is no "Wasm ABI". `extern "wasm"` implements some weird ABI that is decided by the interaction between LLVM (maybe stable?) and the exact way rustc_codegen_llvm uses struct types in arguments (definitively not stable!). `extern "wasm"` only makes sense to me if it is restricted to `i32`, `i64`, `f32,` `f64` and (when enabling the simd feature) `core::arch::wasm::v128` for arguments and those types + (when enabling the multivalue feature) tuples of those types. Anything else is not representable by wasm and as such needs an ABI to decide how to lower it. The only stable ABI for wasm is the C ABI.<|endoftext|>Thanks for the clarification! I went back and read your last comment again too: https://github.com/rust-lang/rust/issues/83788#issuecomment-1477045004.
So does this effectively mean that we can never stabilize `extern "wasm"`? Or are we happy to say that `extern "wasm"` is an unofficial ABI that Rust made to support multivalue and `wasm-bindgen`?
Honestly I'm not too sure how else to proceed on the issue of Wasm and C incompatibility. The other alternative is to just drop all enhancements `wasm-bindgen` did and go back to only following the C ABI.<|endoftext|>In my opinion `extern "wasm"` as currently implemented should not be stabilized. If it is restricted to primitive types representable directly in wasm I did be fine with stabilizing it. I'm not on the language team though, so it is not up to me to decide on stabilizing it or not.
Wasm-bindgen currently attempts to pass `struct WasmSlice { ptr: u32, len: u32 }` as a single argument and expects it to be decomposed into two arguments for `ptr` and `len` respectively at the ABI boundary while the wasm C ABI says that it must be passed by-reference. There is however no guarantee that future LLVM or rustc versions will keep decomposing `WasmSlice` into `ptr` and `len`. Especially for enums and unions the exact way we represent them in LLVM ir has changed over time. This shouldn't normally matter, but because both the current `extern "C"` abi for wasm32-unknown-unknown and the `extern "wasm" abi lack the abi adjustments that normally determine how to pass arguments and return types, the internal representation of types in LLVM ir determines the abi, thus breaking the abi if we change this representation.<|endoftext|>The way to make wasm-bindgen work even if we start using the official C abi for webassembly on wasm32-unknown-unknown would be to either do the decomposition of `WasmSlice` in wasm-bindgen itself or to explicitly pass it by-ref in wasm-bindgen. In either case no struct types would cross the abi and for primitive types the official C abi and the currently used abi agree with each other.<|endoftext|>> There is no "Wasm ABI".
I believe there is: https://github.com/WebAssembly/tool-conventions/blob/main/BasicCABI.md, I'm not sure if it differs from the C ABI, but presumably this is v1 and they planned to add multivalue support to it. In any case, the ABI `wasm-bindgen` currently uses doesn't follow it either. See https://github.com/WebAssembly/tool-conventions/issues/88.
> The way to make wasm-bindgen work even if we start using the official C abi for webassembly on wasm32-unknown-unknown would be to either do the decomposition of `WasmSlice` in wasm-bindgen itself or to explicitly pass it by-ref in wasm-bindgen.
If this really is the whole issue, then I would argue this is fixable. I will proceed to figure out what needs to be done on `wasm-bindgen`s side and hopefully work on it.<|endoftext|>> I believe there is: https://github.com/WebAssembly/tool-conventions/blob/main/BasicCABI.md, I'm not sure if it differs from the C ABI
That is the C abi I was talking about. `extern "wasm"` does not implement that abi however. `extern "C"` on all wasm targets except wasm32-unknown-unknown does.<|endoftext|>So after finding and reading https://github.com/rust-lang/lang-team/blob/master/design-meeting-minutes/2021-04-21-wasm-abi.md, which basically answers and explains all questions I had, I'm coming to the following conclusions:
- The only difference between the Wasm and the C ABI is splatting and mutlivalue support.
- Multivalue isn't even supported right now in Rust (https://github.com/rust-lang/rust/issues/73755) and I don't think it's worth breaking Wasm/C compatibility over it.
- https://github.com/WebAssembly/tool-conventions/blob/main/BasicCABI.md outlines the C ABI we should follow, which in the future might include splatting and multivalue support, but doesn't right now. E.g. https://github.com/WebAssembly/tool-conventions/issues/88.
I think the path forward is to drop splatting in `wasm-bindgen` and fix the C ABI in `wasm32-unknown-unknown` (as bjorn3 was suggesting earlier).<|endoftext|>I don't have much more to add over what's been said already. I would concur that the ideal course of action would be to get `wasm-bindgen` not passing structs-by-value.
As for the `"wasm"` ABI itself, I think the future story heavily depends on what happens with C and how it integrates multi-value. If it's done by "simply" changing the default, then there's no need for `"wasm"`. If it does it by allowing an opt-in, then `"wasm"` makes sense to keep (perhaps renaming of course to match C and also changing the semantics to whatever C requires).
Changing the C ABI or adding a new one is not trivial due to the number of people using it. In that sense by far the easiest thing to do is to update `wasm-bindgen`, delete `"wasm"`, and then wait for C/Clang/upstream to do something. That does, however, place Rust at a bit of a disadvantage where it's no longer attempting to gather feedback on a possible design, it's simply stepping out hoping someone else will fill the gap (but arguably that's the position everyone's already in, waiting for someone else to come fix issues like this)<|endoftext|>> That does, however, place Rust at a bit of a disadvantage where it's no longer attempting to gather feedback on a possible design, [..]
We could leave `"wasm"` in place and add a flag in `wasm-bindgen` that makes use of it, which would require nightly. I guess that's better then nothing.<|endoftext|>I want to point out that the "wasm_abi" feature is currently buggy. An `extern "wasm"` function affects the ABI of *other* functions in the same compilation unit that are *not* tagged as `extern "wasm"`. [Example Godbolt.](https://godbolt.org/z/GGKPMxKeh)
This is because LLVM target-features like +multivalue apply to the whole module, not just a single function: [Godbolt](https://godbolt.org/z/z8zc7Esj1).
I had a [discussion on the LLVM forums](https://discourse.llvm.org/t/is-this-a-bug-multivalue-attribute-contaminates-non-multivalue-functions/72668), and for the time being this seems to be the intended behaviour of target-features.
The tests/run-make/wasm-abi test uses the `extern "wasm"` feature, and mixes it with `extern "C"` as well as the default ABI in all the imported panicking code. This likely makes the test fragile. We should consider disabling it, or at least adding a note to it, in case it randomly breaks for someone else. | A-ffi<|endoftext|>T-lang<|endoftext|>B-unstable<|endoftext|>O-wasm<|endoftext|>C-tracking-issue<|endoftext|>S-tracking-needs-summary<|endoftext|>A-abi | 26 | https://api.github.com/repos/rust-lang/rust/issues/83788 | https://github.com/rust-lang/rust/issues/83788 | https://api.github.com/repos/rust-lang/rust/issues/83788/comments |
777,464,477 | 80,619 | Tracking Issue for infallible promotion | <!--
Thank you for creating a tracking issue! 📜 Tracking issues are for tracking a
feature from implementation to stabilisation. Make sure to include the relevant
RFC for the feature if it has one. Otherwise provide a short summary of the
feature and link any relevant PRs or issues, and remove any sections that are
not relevant to the feature.
Remember to add team labels to the tracking issue.
For a language team feature, this would e.g., be `T-lang`.
Such a feature should also be labeled with e.g., `F-my_feature`.
This label is used to associate issues (e.g., bugs and design questions) to the feature.
-->
This is a tracking issue for the RFC "3027" (rust-lang/rfcs#3027).
The RFC does not have a feature gate.
### About tracking issues
Tracking issues are used to record the overall progress of implementation.
They are also used as hubs connecting to other relevant issues, e.g., bugs or open design questions.
A tracking issue is however *not* meant for large scale discussion, questions, or bug reports about a feature.
Instead, open a dedicated issue for the specific matter and add the relevant feature gate label.
### Steps
<!--
Include each step required to complete the feature. Typically this is a PR
implementing a feature, followed by a PR that stabilises the feature. However
for larger features an implementation could be broken up into multiple PRs.
-->
- [x] Implement the RFC
- [ ] Adjust documentation ([see instructions on rustc-dev-guide][doc-guide])
[stabilization-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#stabilization-pr
[doc-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#documentation-prs
### Unresolved Questions
<!--
Include any open questions that need to be answered before the feature can be
stabilised.
-->
* What should we do about promoting `const fn` calls in `const`/`static` initializers? See [this crater analysis](https://github.com/rust-lang/rust/pull/80243#issuecomment-751885520) and [this Zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Promotion.20of.20const.20fn.20calls.20in.20const.2Fstatic.20initializers/near/221361952).
### Implementation history
* https://github.com/rust-lang/rust/pull/77526
* https://github.com/rust-lang/rust/pull/78363
* https://github.com/rust-lang/rust/pull/80579
| In https://github.com/rust-lang/rust/pull/80243 we learned that there is at least some code (e.g. https://github.com/rodrimati1992/abi_stable_crates/issues/46) that relies in non-trivial ways on `const fn` calls being promoted in a `const`/`static` initializer. We need to figure out how to move forward with such code. I see these options:
* Live with the fact that promoteds in const/static initializers can fail even if they are not required for said initializer. This means no breaking change here, but it will require care in MIR optimizations, MIR printing, maybe more.
* Make sure that all potentally-failing promoteds in const/static initializers are required to compute the value of the const. This will require some break change. There are different alternatives here:
- Never promote anything that might fail -- this breaks some real code (no idea how much, it's only 2 crates in crater), but leads to a rather clean situation.
- Only promote things that fail if they are in parts of the CFG that will definitely be evaluated -- that will however be rather surprising behavior, so maybe we want to do this only for old editions. In particular, a proper post-dominance analysis might be too expensive, so we might just check if the *entire* CFG is linear, or we only promote on the "linear head" of the CFG; in either case, adding a conditional somewhere in the code will stop promotion of things further down that code, which is rather odd.<|endoftext|>> Never promote anything that might fail -- this breaks some real code (no idea how much, it's only 2 crates in crater), but leads to a rather clean situation.
Can that code be made to compile with inline `const` blocks?<|endoftext|>@Aaron1011 yes it can, but only once inline const blocks can use generics of the surrounding context. <|endoftext|>I think this is probably the best option:
> Live with the fact that promoteds in const/static initializers can fail even if they are not required for said initializer. This means no breaking change here, but it will require care in MIR optimizations, MIR printing, maybe more.
https://github.com/rust-lang/rust/pull/85112 ensures that at least a normal build handles this correctly. @oli-obk any idea how to check other MIR consumers such as MIR printing for this?<|endoftext|>MIR printing should just print the path to unevaluated constants and not eval them at all. The only other thing would be optimizations, but these aren't run for constants' bodies<|endoftext|>> MIR printing should just print the path to unevaluated constants and not eval them at all.
As in, it already does that, or it should be changed to do that?<|endoftext|>I believe it does that. At least I specifically remember seeing paths being printed for things that could have been evaluated. <|endoftext|>If we end up deciding we are okay with promoting `const fn` calls in `const`/`static` bodies, we might then also accept other things like general array indexing or division -- we could accept basically everything that qualifies syntactically, i.e., anything that does not depend on surrounding variables. I am not sure what is the better choice -- this makes the rules even more inconsistent, but the rules already *are* wildly inconsistent to the extend that people do get confused by it (e.g., https://github.com/rust-lang/rust/issues/85181).<|endoftext|>What items from RFC 3027 remain to be implemented?
We talked about this in today's @rust-lang/lang meeting, and we know that `const { ... }` still needs further implementation, but we weren't sure if that was a blocker for this or if all the work specified by the RFC was complete.<|endoftext|>@joshtriplett the main open question is what is listed as unresolved question in the issue:
> What should we do about promoting const fn calls in const/static initializers? See [this crater analysis](https://github.com/rust-lang/rust/pull/80243#issuecomment-751885520) and [this Zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Promotion.20of.20const.20fn.20calls.20in.20const.2Fstatic.20initializers/near/221361952).
Basically we still promote arbitrary function calls inside const/static initializers. We need to decide whether we want to
- Live with this technical debt
- Try to slowly phase it out in favor of `const` blocks (once those are stable)
This is a MIR building thing so it could potentially be done at an edition boundary. However, as long as *any* edition promotes arbitrary fn calls, MIR optimizations need to be careful and not overeagerly evaluate constants they find to determine their value. So the technical debt does not become any better by making this an edition thing. I am not sure whether doing this only for the sake of "rules of the latest edition are easier to explain" is worth it.<|endoftext|>Looks like inline_const will be stabilized soon. :D https://github.com/rust-lang/rust/pull/104087
I wonder if that could let us move towards deprecating promotion more?
- Entirely stop promoting function calls in a future edition (only promoting trivial things like `&3`)? Is "easier to explain language" sufficient reason to do that?
- I guess we can't remove this for older editions but maybe we can desugar it to const blocks somewhere early, and thus simplify the promotion machinery? | T-lang<|endoftext|>C-tracking-issue<|endoftext|>A-const-eval<|endoftext|>S-tracking-needs-summary | 11 | https://api.github.com/repos/rust-lang/rust/issues/80619 | https://github.com/rust-lang/rust/issues/80619 | https://api.github.com/repos/rust-lang/rust/issues/80619/comments |
687,493,937 | 76,001 | Tracking Issue for inline const expressions and patterns (RFC 2920) | This is a tracking issue for the RFC "Inline `const` expressions and patterns" (rust-lang/rfcs#2920).
The feature gate for the issue is `#![feature(inline_const)]`.
### About tracking issues
Tracking issues are used to record the overall progress of implementation.
They are also uses as hubs connecting to other relevant issues, e.g., bugs or open design questions.
A tracking issue is however *not* meant for large scale discussion, questions, or bug reports about a feature.
Instead, open a dedicated issue for the specific matter and add the relevant feature gate label.
### Steps
<!--
Include each step required to complete the feature. Typically this is a PR
implementing a feature, followed by a PR that stabilises the feature. However
for larger features an implementation could be broken up into multiple PRs.
-->
- [x] Implement the RFC (#77124 does most of it, modulo some bugs around range patterns that should be fixed in #78116)
- [x] Adjust documentation ([see instructions on rustc-dev-guide][doc-guide]) [Unstable Book docs in #78250]
- [ ] Handle inner attributes. https://github.com/rust-lang/rust/pull/94985
- [ ] resolve expr fragment specifier issue (#86730)
- [ ] Stabilization PR ([see instructions on rustc-dev-guide][stabilization-guide])
[stabilization-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#stabilization-pr
[doc-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#documentation-prs
### Unresolved Questions
* Naming: "inline const", "const block", or "anonymous const"?
* Lint about `&const { 4 }` vs `const { &4 }`?
* How should this work for the special has-block syntax rules? <https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/const.20blocks.20differ.20from.20normal.20and.20from.20unsafe.20blocks/near/290229453>
### Implementation history
<!--
Include a list of all the PRs that were involved in implementing the feature.
-->
- Primary implementation PR: #77124
- Unstable Book documentation: #78250
- `FnDef` type is disallowed in patterns: #114668
| With regard to the lint, is there any semantic difference between the two? Intuitively I would expect them to behave identically (static lifetimes).<|endoftext|>They behave identically. The point of the lint is to have a single "idiomatic" form.
> Naming: "inline const", "const block", or "anonymous const"?
The issue title calls it "const expressons" so maybe that should also be on the list.
I prefer "inline const" because it emphasizes that this is a totally separate body of code that is just written inline. That's much more like a closure than normal blocks.
---
Also, is anyone up for implementing this? (I can't even mentor this I am afraid, this affects surface-level syntax and MIR building which is way outside what I know.^^)<|endoftext|>"const block" is clearly correct.
it matches "unsafe block" that way.<|endoftext|>That false parallel with "unsafe block" is exactly why it is not correct. An unsafe block inherits scope, execution environment, everything from its parent block. An inline const does not.<|endoftext|>I'm happy to mentor, although by no means am I an expert on all the parts of the compiler you'll need to touch. There's already an `AnonConst` type in the AST and the HIR that should for the most part have the same rules as an inline `const` (e.g. no outside generic parameters), which should make the lowering part of this pretty easy.
If no one volunteers in the next few weeks, I'll try to set aside a day or two to implement this. However, I'm mostly in maintenance/review mode as far as Rust is concerned.<|endoftext|>Does `const { }` differ from normal [block expressions](https://doc.rust-lang.org/reference/expressions/block-expr.html), however?
I think either "inline const" or "const expression" should be favored. Everyone's going to call it a constexpr anyways because of C++ user bleedover, and I don't think it's worth offering that much pushback this time. :^)
Hm... I need to fix my computer still. Guess I have a good reason today.<|endoftext|>> Does const { } differ from normal block expressions, however?
`const {}` does not inherit the same scopes as block expressions do.
> Everyone's going to call it a constexpr anyways because of C++
It can be a useful comparison when introducing C++ users to Rust's `const` and `const fn`, yet I have not seen most users conflate them. Additionally, C++ does not have `constexpr { ... }`.
> I don't think it's worth offering that much pushback this time.
There are no mentions of `constexpr` or C++ on this issue before or the RFC. I find it unproductive to label it as pushback from _that_. The concerns about naming are mentioned in the RFC https://rust-lang.github.io/rfcs/2920-inline-const.html and the comments.<|endoftext|>~~Alas, I was trying to make a rather more casual and conversational remark rather than something that I expected to be picked over with a fine-tooth comb and labeled "unproductive".~~ Resolved.
However, when discussing consts, someone literally referred to a similar expression as a "constexpr", to me, **today**, when they were thinking about trying to write a macro that attempted to implement this feature.<|endoftext|>I was not responding to the idea of using constexpr unproductive, and I mentioned that the comparison to it can still be useful. I specifically referred to describing current naming discussions as "pushback" to be unproductive. I believe we have had a misunderstanding, and I would be open to discussing this more in a direct message on discord. I do not think we should continue this here.<|endoftext|>@ecstatic-morse I'd like to take this issue if it's not taken yet.<|endoftext|>Go for it @spastorino!<|endoftext|>I forgot to link this issue from the PR but the PR is now merged https://github.com/rust-lang/rust/pull/77124<|endoftext|>I would like to write the documentation.<|endoftext|>> I would like to write the documentation.
@camelid please once you have something up cc me so I can review.<|endoftext|>Note that right now the feature is named inline-const pretty much everywhere.<|endoftext|>> * [x] Implement the RFC (#77124 does most of it, modulo some bugs around range patterns that should be fixed in #78116)
As the above checkbox has been checked and both #77124 and #78116 have been merged, I assume this feature is fully implemented. Why is it still [in the `INCOMPLETE_FEATURES` list](https://github.com/rust-lang/rust/blob/5b104fc1bdd5b35891614ad9163ebef31442cc0c/compiler/rustc_feature/src/active.rs#L646)?<|endoftext|>I think that's just an oversight, we should remove it from the incomplete features list.<|endoftext|>> I think that's just an oversight, we should remove it from the incomplete features list.
@oli-obk I'm willing to submit a PR, so I can use this in my code without warning.<|endoftext|>Great! Feel free to `r? @oli-obk` it<|endoftext|>While working on promotion recently, here's something I wondered about... would it make sense for `const {}` to use the promotion machinery? After all, that machinery already has all the support we need to let the const refer to generics of the surrounding context.
The check for the code in there should be the usual const check of course, not the implicit promotion check. But arguably the same is true for explicit promotion contexts, isn't it? `const {}` would be as explicit as it gets for promotion contexts. ;)
The current explicit promotion contexts are `rustc_args_required_const` and inline assembly const operands... do we still have time to take away promotion from both of them and require a const literal or inline const block?<|endoftext|>@RalfJung I am not sure if i understood your question correctly
> would it make sense for `const {}` to use the promotion machinery?
I personally don't know what exactly you are thinking of here. At least from where I am approaching this the way const blocks should deal with the generics of the surrounding context is quite different to promotion. Especially considering potentially failing operations like `const { 64 / mem::size_of::<T>() }` which we probably want to allow but imo should require `feature(const_evaluatable_checked)`. I can't really see that working well with promoteds as it happens during typeck while promotion happens afterwards.
> The current explicit promotion contexts are rustc_args_required_const and inline assembly const operands... do we still have time to take away promotion from both of them and require a const literal or inline const block?
idk, it would sure be nice to do so. Don't know too much about either of those, I am however surprised that inline assembly const operands rely on promotion at all rn :laughing: would have expected them to use an `AnonConst` instead.<|endoftext|>> I personally don't know what exactly you are thinking of here.
Basically, compile `const { expr }` like `expr` during MIR building (except with restrictions for which local variables are in scope), and then use this as a promotion site in `transform/promote_consts.rs`.
`const {}` is primarily a means to replace implicit promotion with something more explicit. Promotion already does everything we want `const {}` to do, except that it is subject to some serious restrictions because it is implicit. So using promotion to implement `const {}` seems like the easiest option.
> Especially considering potentially failing operations like const { 64 / mem::size_of::<T>() } which we probably want to allow but imo should require feature(const_evaluatable_checked).
Uh, that's a big move compared to any prior discussion I am aware of.^^ This might smash all hopes I had of stabilizing this any time soon, which could be quite problematic for getting promotion cleaned up before it is too late.
I expected this would work just like promoteds and associated consts work today. No need to treat these likes const generics. (I know basically nothing about `const_evaluatable_checked`, just that it is somehow related to ensuring that const generic parameters do not fail to evaluate.)
> idk, it would sure be nice to do so. Don't know too much about either of those, I am however surprised that inline assembly const operands rely on promotion at all rn laughing would have expected them to use an AnonConst instead.
If `AnonConst` is the same as inline const expressions, then `asm!` predates that by quite a bit.<|endoftext|>`AnonConst` are used to represent constant expressions, so they are used for array lengths and associated constants.
----
moving this to zulip until I have a more solid understanding of our goals here. https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/inline.20consts<|endoftext|>Independent of the discussion around `const_evaluatable_checked`, another way to phrase my point is: I think it is a bad idea to have both "explicit promotion" and inline consts. The two serve *almost the same purpose*, so having to come up with, maintain, and test two separate sets of rules is a lot of extra work for no gain that I can see.
I think we should aim at unifying the two. This means treating `rustc_args_required_const` arguments (I assume some of the functions decorated with this are already stable?) as inline consts (and potentially, with an edition change, requiring the `const { ... }` keyword if the argument isn't a literal or named const); for `asm!` `const` arguments there's still time to work out the details since this isn't stable yet.<|endoftext|>Replying to @oli-obk's comment [here](https://github.com/rust-lang/rust/issues/72016#issuecomment-753468228)
> For rustc_args_required_const we can't do this because the invocation of the function would need to resolve the call before knowing that the argument is a const.
Name resolution happens before MIR construction, so we could still do it on that level... not sure how well that would work with the current implementaton of inline consts though.
---
Also, besides the point I made above about unifying explicit promotion and inline consts, here's another one: inline consts (with support for using generics) and implicit promotion seem to have a lot in common -- both are expressions that are syntactically "embedded" in their parent context and want to inherit at least some of its information (generics; possibly type inference information as well). So maybe it makes sense to implement them in similar ways?
It is this point together with the above that lead to [my first message on the subject](https://github.com/rust-lang/rust/issues/76001#issuecomment-753353110). The feedback I got helped tease the two points apart. :) I think the first one is much stronger than the second.<|endoftext|>> Name resolution happens before MIR construction, so we could still do it on that level... not sure how well that would work with the current implementaton of inline consts though.
Ah, good point, we could do this as an "expansion" in `AST` -> `HIR` lowering<|endoftext|>> both are expressions that are syntactically "embedded" in their parent context and want to inherit at least some of its information (generics; possibly type inference information as well). So maybe it makes sense to implement them in similar ways?
While not generally possible for anonymous constants, *just* for inline consts, that could be doable, but we'd need some sort of marker on the local that contains the final value of the inline const, so that "promotion" can reliably pick it up and uplift its creating MIR statements to a promoted MIR. Though considering that we had all the relevant information about what expressions are part of it before creating the MIR, picking it apart again later seems odd.
The oppsite way of unifying the systems would be to figure out what code is (implicitly) promotable on the HIR, but we explicitly moved away from such a system due to various problems with it.
An intermediate way could be to give inline consts (and possibly repeat expression lengths) their own wrapper type around `AnonConst`, which does not give them their own `DefId`, but THIR lowering will just create promoteds at MIR creation time instead of putting them into their own MIR body that may end up having cycles with their parent MIR body queries. That would still not unify the creation systems of promotion and inline consts, but it would treat them exactly the same once we are not processing HIR anymore.<|endoftext|>> Ah, good point, we could do this as an "expansion" in AST -> HIR lowering
Ah right, HIR is already name-resolved... so this should not be so bad.
> The oppsite way of unifying the systems would be to figure out what code is (implicitly) promotable on the HIR, but we explicitly moved away from such a system due to various problems with it.
Yeah... I guess on the HIR, `+` might still be a function call using the `Add` trait. So that's probably not a good idea.
So, together with everything else you said, I tend to agree that it makes more sense to immediately build separate MIR bodies. That probably also makes it easier to use the normal const-expr checks here.
The key simplification that we can hopefully achieve, then, is to make `transform/promote_consts.rs` *only* about (implicit) lifetime extension, and nothing else. "Promotion" and "lifetime extension" might mean the same thing again, as they once did. ;)
> That would still not unify the creation systems of promotion and inline consts, but it would treat them exactly the same once we are not processing HIR anymore.
Promoteds are already very similar to regular consts on the MIR, so I don't think this would buy us much.<|endoftext|>> So, together with everything else you said, I tend to agree that it makes more sense to immediately build separate MIR bodies. That probably also makes it easier to use the normal const-expr checks here.
> Promoteds are already very similar to regular consts on the MIR, so I don't think this would buy us much.
These two statements seem at odd to each other (since the first one may mean the "build promoteds at THIR time, but the second one says that doesn't gain us much), so just to be clear, so we are all on the same page: We don't change anything in the current system except that we generate `AnonConst` in HIR lowering for `rustc_args_required_const`, thus giving it its own `DefId` and thus `MIR`.<|endoftext|>Sorry, to be more clear: in the second statement I meant the way they look once promotion is done messing up the MIR. Then promoteds are just an `Operand::Const`, just like regular consts and inline const blocks, right? | B-RFC-approved<|endoftext|>T-lang<|endoftext|>T-compiler<|endoftext|>C-tracking-issue<|endoftext|>A-const-eval<|endoftext|>F-inline_const<|endoftext|>S-tracking-needs-summary | 74 | https://api.github.com/repos/rust-lang/rust/issues/76001 | https://github.com/rust-lang/rust/issues/76001 | https://api.github.com/repos/rust-lang/rust/issues/76001/comments |
674,921,649 | 75,251 | Tracking Issue for const MaybeUninit::as(_mut)_ptr (feature: const_maybe_uninit_as_ptr) | <!--
Thank you for creating a tracking issue! 📜 Tracking issues are for tracking a
feature from implementation to stabilisation. Make sure to include the relevant
RFC for the feature if it has one. Otherwise provide a short summary of the
feature and link any relevant PRs or issues, and remove any sections that are
not relevant to the feature.
Remember to add team labels to the tracking issue.
For a language team feature, this would e.g., be `T-lang`.
Such a feature should also be labeled with e.g., `F-my_feature`.
This label is used to associate issues (e.g., bugs and design questions) to the feature.
-->
This is a tracking issue for const `MaybeUninit::as(_mut)_ptr`.
The feature gate for the issue is `#![feature(const_maybe_uninit_as_ptr)]`.
### About tracking issues
Tracking issues are used to record the overall progress of implementation.
They are also uses as hubs connecting to other relevant issues, e.g., bugs or open design questions.
A tracking issue is however *not* meant for large scale discussion, questions, or bug reports about a feature.
Instead, open a dedicated issue for the specific matter and add the relevant feature gate label.
### Steps
<!--
Include each step required to complete the feature. Typically this is a PR
implementing a feature, followed by a PR that stabilises the feature. However
for larger features an implementation could be broken up into multiple PRs.
-->
- [x] Implement
- [ ] Adjust documentation ([see instructions on rustc-dev-guide][doc-guide])
- [ ] Stabilization PR ([see instructions on rustc-dev-guide][stabilization-guide])
[stabilization-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#stabilization-pr
[doc-guide]: https://rustc-dev-guide.rust-lang.org/stabilization_guide.html#documentation-prs
### Unresolved Questions
<!--
Include any open questions that need to be answered before the feature can be
stabilised.
-->
### Implementation history
<!--
Include a list of all the PRs that were involved in implementing the feature.
-->
* Added in https://github.com/rust-lang/rust/pull/75250 | There doesn't appear to be any blockers for the non-mut version, unless I'm missing something?<|endoftext|>Visiting for T-compiler backlog bonanza. This seems likely to be ready to stabilize, but since I'm not certain, I'm tagging with "needs summary"
Also, we think the question of whether to stabilize these methods falls under T-libs domain, so tagging with that team label
@rustbot label: +T-libs +S-tracking-needs-summary<|endoftext|>(@m-ou-se pointed out that this is a libs-api team issue, not a libs implementation issue.)<|endoftext|>@rfcbot merge<|endoftext|>Team member @m-ou-se has proposed to merge this. The next step is review by the rest of the tagged team members:
* [x] @Amanieu
* [x] @BurntSushi
* [x] @dtolnay
* [ ] @joshtriplett
* [x] @m-ou-se
* [x] @yaahc
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](https://github.com/rust-lang/rfcbot-rs/blob/master/README.md) for info about what commands tagged team members can give me.<|endoftext|>Cc @rust-lang/wg-const-eval but this should be uncontroversial<|endoftext|>No concerns with this.<|endoftext|>I'm marking @yaahc's box because she has stepped down from T-libs-api after the point that this feature got proposed for FCP.<|endoftext|>:bell: **This is now entering its final comment period**, as per the [review above](https://github.com/rust-lang/rust/issues/75251#issuecomment-1256323045). :bell:<|endoftext|>The final comment period, with a disposition to **merge**, as per the [review above](https://github.com/rust-lang/rust/issues/75251#issuecomment-1256323045), 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.<|endoftext|>Status: `as_ptr` has been stabilized. `as_mut_ptr` is blocked on #57349 | T-libs-api<|endoftext|>C-tracking-issue<|endoftext|>disposition-merge<|endoftext|>finished-final-comment-period<|endoftext|>S-tracking-needs-summary | 11 | https://api.github.com/repos/rust-lang/rust/issues/75251 | https://github.com/rust-lang/rust/issues/75251 | https://api.github.com/repos/rust-lang/rust/issues/75251/comments |
637,330,037 | 73,255 | Tracking issue for `#![feature(const_precise_live_drops)]` | Feature gate for the more precise version of const-checking in #71824.
(Potential) blockers:
- https://github.com/rust-lang/rust/issues/91009 | Cc @rust-lang/wg-const-eval (which I think never happened for this feature or the PR)<|endoftext|>Is there particular reason why this was moved to be a feature?
It is more or less bug fix to inaccurate drop detection.
So shouldn't it be already stable?
This would make it easier to create builders with generic parameters as we currently cannot mutate `self`<|endoftext|>cc @rust-lang/lang I am nominating this feature for stabilization
citing @ecstatic-morse from the impl PR:
This isn't really a "feature" but a refinement to const-checking, and it's kind of non-obvious what the user opts in to with the feature gate, since drop elaboration is an implementation detail. A relevant precedent is `#![feature(nll)]`, but that was much larger and more fundamental than this change would be.
This is also somewhat relevant to the stabilization of `#![feature(const_if_match)]`. Nothing in this PR is specifically related to branching in constants. For instance, it makes the example below compile as well. However, I expect users will commonly want to move out of `Option::<T>::Some` within a `match`, which won't work without this PR if `T: !Copy`
```rust
const _: Vec<i32> = {
let vec_tuple = (Vec::new(),);
vec_tuple.0
};
```
> To clarify, this PR makes that code compile because previously we were dropping the vec_tuple which had type Option<(Vec<i32>,)>?
This code is functionally no different from the following, which currently works on stable because `x` is moved into the return place unconditionally.
```rust
const X: Option<Vec<i32>> = { let x = Vec::new(); x };
```
Const-checking only considers whole locals for const qualification, but drop elaboration is more precise: It works on projections as well. Because drop elaboration sees that all fields of the tuple have been moved from by the end of the initializer, no `Drop` terminator is left in the MIR, despite the fact that the tuple *itself* is never moved from.<|endoftext|>@oli-obk how do things look like in implementation complexity and the risk of locking us into a scheme that might be hard to maintain or make compatible with other future extensions?<|endoftext|>I believe implementation complexity should not be an issue considering current behavior is bug as compiler incorrectly reports error on drop being executed in const fn.
Such things ought to be fixed in any case. Unless we're fine with compiler incorrectly reporting error as right now?<|endoftext|>> I believe implementation complexity should not be an issue considering current behavior is bug as compiler incorrectly reports error on drop being executed in const fn.
> Such things ought to be fixed in any case. Unless we're fine with compiler incorrectly reporting error as right now?
We may be able to achieve the same result (allowing these kind of `const fn`) with a different scheme. So Ralf's question is absolutely reasonable to ask and I will answer it after reviewing the implementation again in detail so I can give an educated answer.
<|endoftext|>@DoumanAsh due to the [halting problem](https://en.wikipedia.org/wiki/Halting_problem), rustc will *always* report "incorrect errors". It is impossible to predict at compiletime if e.g. `drop` will be executed when a piece of code is being run. Similarly, the borrow checker will always reject some correct programs. That's just a fact of programming languages. Neither of these are a bug.
So there's always a trade-off between analysis complexity and "incorrect errors", but even the best analysis will sometimes show "incorrect errors". My impression after looking at the PR here is that the analysis complexity is totally reasonable (it mostly implicitly reuses the analysis performed by drop elaboration), but this is still a decision we should make explicitly, not implicitly.
More precise drop analysis in `const fn` is a new feature, not a bugfix. (Just like, for example, NLL was a new feature, not a bugfix.)
@oli-obk Thanks. :) As you probably saw, I also [left some questions in the PR that implemented the analysis](https://github.com/rust-lang/rust/pull/71824#pullrequestreview-611608120).<|endoftext|>I did see these comments, just didn't have time to look more deeply yet.
Cross posting from the comments on that PR:
I am guessing the difference between the `needs_drop` analysis, and drop elaboration's use of `MaybeInitializedPlaces` and `MaybeUninitializedPlaces` is the reason that this feature gate exists at all. We could probably rewrite drop elaboration in terms of the `NeedsDrop` qualif, which would (afaict) allow `post_drop_elaboration` to not do any checks except for looking for `Drop` terminators.
Of course such a change would insta-stabilize the feature gate from this PR without any reasonable way to avoid said stabilization. So I'm tempted to stabilize the feature but leave a FIXME on this function to merge its qualif checks into `elaborate_drops`<|endoftext|>> We could probably rewrite drop elaboration in terms of the NeedsDrop qualif, which would (afaict) allow post_drop_elaboration to not do any checks except for looking for Drop terminators.
> Of course such a change would insta-stabilize the feature gate from this PR without any reasonable way to avoid said stabilization.
Even worse, it would change drop elaboration, which is a rather tricky part of the compiler.^^ That should be done with utmost care.<|endoftext|>r? @nikomatsakis <|endoftext|>Dropping the nomination here as it's waiting on Niko; that's tracked in the language team action item list.<|endoftext|>What remains to be done before this can be stabilized?<|endoftext|>Hey y'all. I'll try to summarize exactly what this feature gate does to help inform a decision on stabilization. Oli and Ralf probably already know this information, and can skip the next section.
### Background
Currently, it is forbidden to run custom `Drop` implementations during const-eval. This is because `Drop::drop` is a trait method, and there's no (stable) way to declare that trait methods are const-safe. MIR uses a special terminator (`Drop`) to indicate that something is dropped. When building the MIR initially, a `Drop` terminator is inserted for every variable that has drop glue (`ty.needs_drop()`). Typically, const-checks are run on the newly built MIR. This is to prevent MIR optimizations from eliminating or transforming code that would fail const-checking into code that passes it, which would make compilation success dependent on MIR optimizations. In general, we try very hard to avoid this.
However, some `Drop` terminators that we generate during MIR building will never actually execute. For example,
- A `struct` has a field with a custom `Drop` impl (e.g. `Foo(Box<i32>)`), but that field is always moved out of before the variable goes out of scope.
- An `enum` has a variant with a custom `Drop` impl, but we are in a `match` arm for a different variant without a custom `Drop` impl.
We rely on a separate MIR pass, `elaborate_drops`, to remove these terminators prior to codegen (it also does some extra stuff, like adding dynamic drop flags). This happens pretty early in the optimization pipeline, but it is still an optimization, so it runs after const-checking. As a result, the stable version of const-checking sees some `Drop` terminators that will never actually run, and raises an error.
### Current Implementation
`#![feature(const_precise_live_drops)]` defers the `Drop` terminator const-checks until *after* drop elaboration is run. As I mention above, this is unusual, since it makes compilation success dependent on the result of an optimization. On the other hand,
- Drop elaboration doesn't change very often. Unlike some other optimizations, it is conceptually pretty simple to determine whether a `Drop` terminator is frivolous along a given code path. It depends solely on whether some set of move paths are initialized at that point in the CFG.
- It is always profitable to remove drop terminators from the MIR when we can. This makes it unlikely that we will ever want to "dial back" drop-elaboration.
- Despite being conceptually straightforward, drop elaboration is not free to compute and having two separate implementations of it (one in const-checking and one in the optimization pipeline) is both inefficient and bad for maintainability.
- If there *is* bug in drop elaboration that causes us to wrongly eliminate `Drop`s, wrongly accepting some `const fn`s will be the least of our worries, relatively speaking.
For these reasons, I chose the current implementation strategy. I realize that none of these arguments are dispositive, and I don't think it's unreasonable to gate stabilization of this feature on reimplementing the relevant bits of drop elaboration inside const-checking, although I still think it's overly conservative.
Besides that big question, I think there were also some concerns from `const-eval` members around the use of the `NeedsDrop` qualif and test coverage (e.g. https://github.com/rust-lang/rust/pull/71824#discussion_r594392980). I'll try to answer those so they can provide a recommendation.<|endoftext|>I'm not educated on the details, but it would be super nice to see this stabilized in some form. There are a comparatively large number of new APIs that rely on this. For examples, see issues #76654, #82814, and PR #84087, the last of which is an approved stabilization PR that can't be merged until this is stabilized.
That's why I was checking in on the progress towards stabilization a few days ago. I'm sorry about that, by the way. I know that that sort of message can be annoying, but I wanted to know there if there was anything I could do to help move this along.<|endoftext|>The fact that the main blocker (and why this was feature gated in the first place) is the implementation makes it somewhat unusual (see https://github.com/rust-lang/rust/pull/71824#discussion_r421675954). That makes it more the domain of the compiler-team rather than the lang-team. Niko reviewed #71824 and is assigned to this issue, but I'm hesitant to ping them specifically unless their expertise is required.
So, if you want to see this stabilized I would figure out some process for getting consent from the compiler team. I think they use the MCP process for this exclusively? Oli is a member, so there's at least one potential sponsor. The team might require documenting the drop-elaboration/const-checking dependency in the dev-guide and maybe the module itself, which I'm happy to do if asked. After that, I can write a stabilization report with some examples and we can do lang-team FCP (assuming any lingering concerns from @rust-lang/wg-const-eval have been addressed).
I'm, uh, not great at navigating bureaucratic systems with many veto points, so if you want to drive this forward your help would be greatly appreciated. However, unless we end up reimplementing drop-elaboration in const-checking like I mention above, I don't think much of the remaining work is technical. <|endoftext|>I think your summary post contains most of what we need for a stabilization report (full instructions [here](https://rustc-dev-guide.rust-lang.org/stabilization_guide.html?highlight=stabilization%20report#write-a-stabilization-report)). We can just mark this issue as requiring sign-off from both T-compiler and T-lang and do all of this at once.<|endoftext|># Request for stabilization
I would like to stabilize the `const_precise_live_drops` feature.
## Summary
It enables more code to be accepted in const fn. Caveat: const checking is now dependent on drop elaboration, so changes to drop elaboration can silently change what code is allowed in const fn. Details can be found at https://github.com/rust-lang/rust/issues/73255#issuecomment-889420241
A prominent example that doesn't work right now, but would with this feature is `Option::unwrap`:
```rust
const fn unwrap<T>(opt: Option<T>) -> T {
match opt {
Some(x) => x,
None => panic!(),
}
}
```
rustc believes that `opt` will still get dropped in the panic arm (when const checks are running), because the MIR still contains a `Drop` terminator on that arm.
## Documentation
There is none. This feature solely reorders existing passes.
## Tests
* [Demonstrate field and variants being moved out of](https://github.com/rust-lang/rust/blob/673d0db5e393e9c64897005b470bfeb6d5aec61b/src/test/ui/consts/control-flow/drop-precise.rs) (without the feature const checks think that the original aggregate may still get dropped and thus execute a non-const destructor)
* [check that only unstable const fn can use the feature](https://github.com/rust-lang/rust/blob/673d0db5e393e9c64897005b470bfeb6d5aec61b/src/test/ui/consts/unstable-precise-live-drops-in-libcore.rs), see also [this test](https://github.com/rust-lang/rust/blob/18587b14d1d820d31151d5c0a633621a67149e78/src/test/ui/consts/stable-precise-live-drops-in-libcore.rs)
* [check that previously accepted code still works](https://github.com/rust-lang/rust/blob/673d0db5e393e9c64897005b470bfeb6d5aec61b/src/test/ui/consts/control-flow/drop-pass.rs)
* [interaction with const drop](https://github.com/rust-lang/rust/blob/cdeba02ff71416e014f7130f75166890688be986/src/test/ui/rfc-2632-const-trait-impl/const-drop-fail.rs), and [more of the same](https://github.com/rust-lang/rust/blob/003d8d3f56848b6f3833340e859b089a09aea36a/src/test/ui/rfc-2632-const-trait-impl/const-drop.rs)
* [Show limits of the feature](https://github.com/rust-lang/rust/blob/673d0db5e393e9c64897005b470bfeb6d5aec61b/src/test/ui/consts/control-flow/drop-fail.rs)
@rfcbot fcp merge<|endoftext|>Team member @oli-obk has proposed to merge this. The next step is review by the rest of the tagged team members:
* [x] @Aaron1011
* [x] @cramertj
* [x] @davidtwco
* [x] @eddyb
* [ ] @estebank
* [x] @joshtriplett
* [x] @lcnr
* [x] @matthewjasper
* [ ] @michaelwoerister
* [x] @nagisa
* [ ] @nikomatsakis
* [x] @oli-obk
* [x] @petrochenkov
* [ ] @pnkfelix
* [ ] @scottmcm
* [ ] @wesleywiser
Concerns:
* reference-material (https://github.com/rust-lang/rust/issues/73255#issuecomment-946942927)
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](https://github.com/rust-lang/rfcbot-rs/blob/master/README.md) for info about what commands tagged team members can give me.<|endoftext|>> because the MIR still contains a Drop terminator on that arm
Specifically, the "early" MIR that most of const checking runs on still has it. After drop elaboration, it is gone, which is why running the 'drop' part of const checking later makes such a difference.<|endoftext|>We run some passes early in the MIR pipeline (e.g. borrowck) which are considered to be an integral part of the language. I not sure if I would consider drop elaboration materially different from these and thus an (optional) optimization today. In that context I don't see an issue with it becoming a mechanism through which some programs are allowed to build.<|endoftext|>> const checking is now dependent on drop elaboration, so changes to drop elaboration can silently change what code is allowed in const fn.
Do we have anything resembling a specification (RFC, reference, etc.) for drop elaboration that could be used to justify why certain `const` code does or does not compile? I'm not familiar with that part of the codebase, so it isn't clear to me whether there are lots of potentially implementation-dependent decision points that would be locked in as part of this stabilization, or whether the implementation is relatively unique and therefore unlikely to change in ways that would affect the code that compiles.
Additionally, it'd be nice to have some sort of specification for what code we expect to compile independent of the implementation, since that'd allow us to justify the resulting compiler errors to users without referring to the implementation details.<|endoftext|>No. Up until now, whether or not a stack-local drop flag could be optimized away for some variable didn't affect program semantics. [RFC 320](https://github.com/rust-lang/rfcs/blob/master/text/0320-nonzeroing-dynamic-drop.md), which introduced the current dynamic drop rules, simply mentions that
> Some compiler analysis may be able to identify dynamic drop obligations that do not actually need to be tracked.
That analysis, which is (part of) what came to be known as "drop elaboration", was implemented alongside the rest of the RFC in #33622. It remains mostly identical today modulo a few tweaks (e.g. #68943, which allowed it to make use of the more precise dataflow analysis around enum variants in #68528). As far as I know, there's no documentation besides the discussion on #33622 and the code itself, mostly in [this file](https://github.com/rust-lang/rust/blob/master/compiler/rustc_mir_dataflow/src/elaborate_drops.rs).
I can write up a description of what the algorithm is currently doing, but I wouldn't call that a "specification" without some form of operational semantics for the MIR. Regarding a specification that's "independent of the implemention": How do we describe a flow-sensitive analysis on the MIR besides describing its implementation? We already have some examples of what works and what doesn't (see [Oli's comment](https://github.com/rust-lang/rust/issues/73255#issuecomment-938086246)). For comparison, the borrow-checker is not defined in the reference using normal Rust syntax but [in terms of the MIR](https://github.com/rust-lang/rfcs/blob/master/text/2094-nll.md).<|endoftext|>> No. Up until now, whether or not a stack-local drop flag could be optimized away for some variable didn't affect program semantics.
Doesn't it affect the borrow checker? Locals need to be live when they are dropped, so whether or not it can be optimized away can affect whether or not a function is accepted by the borrow checker or not. That was my understanding, anyway.
(Not sure what exactly you are including in 'program semantics', but even with this feature gate, the dynamic semantics of CTFE are not affected. Both borrow checker and const checking are static analyses, so them being affected by this seems very comparable in impact.)<|endoftext|>True. I've always been unclear about how much work is duplicated between drop elaboration and the borrow checker, since the latter runs first. The NLL RFC talks about things in terms of lifetimes and `#[may_dangle]` instead of initializedness, which makes it hard for me to equate the two. Perhaps Niko or Felix could say more?
<|endoftext|>From what I remember borrowck relies upon the variable liveness annotations (`StorageLive` and `StorageDead` MIR statements) and does not rely on drop elaboration in any way or form. Drop elaboration IIRC works by deriving knowledge from these same annotations as well.<|endoftext|>@rfcbot concern reference-material
I'm raising @cramertj's point to an actual concern. I don't think we need a "formal specification" but I do think we need documentation in the reference. It doesn't have to be enough to implement things independently, but I think that it should be enough that humans can understand it. @ecstatic-morse let's sync up about it a bit.<|endoftext|>Do I understand correctly that all of the drop elaboration details become irrelevant once const evaluator actually starts running `Drop::drop` impls?
After that the difference between "not running this because drop elaboration optimized it out" and "not running this because it's a noop" disappears, and all of these cases "just work" simplifying the specification significantly.
So the state in which the language spec depends on the drop elaboration pass details is more or less temporary?<|endoftext|>No, we still need to check upfront if the destructors (the ones that remain after drop elaboration) actually can be run at const-time. It will always be possible for destructors to do non-const stuff, so we will always need a check like that.<|endoftext|>@RalfJung
>It will always be possible for destructors to do non-const stuff
I don't understand, if the destructor can be optimized away by drop elaboration, then it certainly doesn't do any non-const stuff (because it doesn't do anything).
UPD: Ah, I see, the drop method has a "nominal" constexprness (as opposed to "actual" ability to run it at compile time), which may prevent it from being called from const context, but won't prevent it from being eliminated by drop elaboration.<|endoftext|>Yes, that is correct.
Drop elaboration details will remain relevant because when we consider some type `T` whose destructor is called, we cannot know if it does non-const stuff. So we can accept that destruction in `const fn` if and only if the destructor is optimized away by const elaboration.
You seemed to say that somehow future work on `const Drop` would remove the dependency of const checking on drop elaboration. That is not the case, and I do not understand how you propose we could remove the dependency in that future world. Consider a function like
```rust
const fn something<T>(x: T) {}
```
If we added `T: const Drop` (or whatever the syntax will end up being), this is fine, but as written it is not. So whether the destructor for `x` can be optimized out by drop elaboration remains relevant. | A-destructors<|endoftext|>T-lang<|endoftext|>T-compiler<|endoftext|>B-unstable<|endoftext|>C-tracking-issue<|endoftext|>A-const-eval<|endoftext|>S-tracking-needs-summary | 50 | https://api.github.com/repos/rust-lang/rust/issues/73255 | https://github.com/rust-lang/rust/issues/73255 | https://api.github.com/repos/rust-lang/rust/issues/73255/comments |
606,453,799 | 71,520 | Use lld by default on x64 msvc windows | This is a metabug, constraining the unbound scope of #39915.
# What is lld
[A linker that's part of the llvm project](https://lld.llvm.org/index.html), which is desirable for two reasons:
* it's very friendly to cross compilation (hence its emphasis for embedded targets)
* it's very fast (often runs in half the time as Gold -- linking can take several minutes for big projects (rustc, servo, etc.) and linking can be a huge % of the compile with incremental builds, so halving this runtime is a Big Deal.)
Rust currently ships its own copy of lld which it calls rust-lld. This is used by default to link bare-metal targets and wasm.
# Goal
The goal of this metabug is to use rust-lld by default when targeting x64 msvc windows (as opposed to e.g. mingw windows). It's possible this will incidentally get other windows targets working, but I'm constraining scope for the sake of focusing efforts.
This configuration is already in a decent state, with backend support already implemented. It's just a matter of making that configuration stable enough to use by default.
**To test using rust-lld for msvc targets, use `-C linker=lld`**
# Blocking Issues
[lld on windows status page](https://lld.llvm.org/windows_support.html)
* [x] #68647 - linking libtest results in undefined symbols
* [x] #71504 - rust-analyser segfault with lto=thin, linker=lld-link
* [x] #72145 - LLD/COFF does not correctly align TLS section
* [x] https://github.com/rust-lang/rust/issues/81408 - ACCESS_VIOLATION when dereferencing once_cell::Lazy in closure with LTO
* [x] https://github.com/rust-lang/rust/issues/85642 - Windows rust-lld does not support the MSVC manifestdependency .drectve
* [ ] https://github.com/rust-lang/rust/issues/111480 | >(TODO: how is it accessed? -C link-flavor?)
`-C linker=lld` (but `-C linker-flavor=lld` should also work).<|endoftext|>This ought to be a bit more straightforward than using lld with gcc since with MSVC you do conventionally invoke the linker directly, and lld has an [`lld-link.exe` binary](https://lld.llvm.org/windows_support.html) that tries to be a drop-in replacement for `link.exe`. You can also run `lld -flavor link` and pass MSVC-style commandline arguments after that. I would expect that if you set up the environment correctly you ought to be able to simply invoke `lld-link.exe` instead of `link.exe` and have it Just Work.
Note that you still need a Visual C++ install (they have a smaller "Build Tools for Visual Studio" install that doesn't include the IDE) or maybe just a Windows SDK in order to have the system .lib files it wants to link to.<|endoftext|>Yes, as noted in the main comment (which I update to track current status) the infra is already hooked up here for invoking it. It's just a bit buggy, and requires a more thorough investigation of failure-modes and how we can smooth them over, e.g.:
* if you don't have Visual C++ installed *what happens*?
* do we provide lld-link.exe, or do we look for a system one? both? is
* does it work just as well on win 8 and 7? should we restrict efforts to win 10?
* can we directly invoke the lld-link binary on macos/linux when cross-compiling to windows?
* how important are the [missing features on the lld-link status page](https://lld.llvm.org/windows_support.html)? can we recover and fallback to link when encountering them?
Once someone's done a quick audit of basic failure modes, we should do some community outreach asking people to test `-C linker=lld` and report how it affects their build times (clean build, big change incremental, tiny change incremental, etc.).
Definitely looking for someone to champion this effort, since my primary goal was just creating more focused initiatives / clarifying the status confusion in the main lld bug.
<|endoftext|>Ah, apologies, I did read that comment but must have missed that.
> if you don't have Visual C++ installed what happens?
This is a good question but I think the better question is "if you try to use lld-link but don't have Visual C++ installed is it any worse than what happens in the default case without Visual C++ installed?" Currently rustc does try to locate MSVC but will apparently just try its best if it can't find it:
https://github.com/rust-lang/rust/blob/f8d394e5184fe3af761ea1e5ba73f993cfb36dfe/src/librustc_codegen_ssa/back/link.rs#L164
<|endoftext|>> if you don't have Visual C++ installed what happens?
IIRC lld-link errors listing all Windows SDK libraries it cannot find.
> can we directly invoke the lld-link binary on macos/linux when cross-compiling to windows?
You cannot cross-compile to MSVC from other OSes unless you find a way to extract Windows SDK and feed it to the LLD. AFAIK MinGW with `ld.lld` is the only *somewhat* supported way to cross compile for Windows.<|endoftext|>Cross-compiling to Windows is not much different than any other OS these days now that LLVM has good support for generating Windows binaries. You do need all the import libs from MSVC at the very least, and probably a Windows SDK for anything non-trivial, but you can absolutely do it:
https://github.com/ProdriveTechnologies/clang-msvc-sdk
Given that requirement it's probably not worth really worrying about as long as it doesn't error in a way that's any more confusing than trying to cross-compile to Windows without specifying an alternate linker. That fails like this for me on Linux with Rust 1.42.0:
```
luser@eye7:/build/snippet$ cargo build --target=x86_64-pc-windows-msvc
Compiling itoa v0.3.4
Compiling snippet v0.1.4-alpha.0 (/build/snippet)
error: linker `link.exe` not found
|
= note: No such file or directory (os error 2)
note: the msvc targets depend on the msvc linker but `link.exe` was not found
note: please ensure that VS 2013, VS 2015, VS 2017 or VS 2019 was installed with the Visual C++ option
error: aborting due to previous error
error: could not compile `snippet`.
To learn more, run the command again with --verbose.
```
Once #58713 is fixed it is probably worth revisiting that topic since it'll become feasible to write pure-Rust descriptions of Windows import libraries and generate working binaries without having MSVC or a Windows SDK.
<|endoftext|>> do we provide lld-link.exe, or do we look for a system one? both?
If Rust is already shipping an `lld` binary it makes sense to allow using it, but given the myriad ways people build software there will assuredly be a desire to use specific `lld`/`lld-link` binaries. Given that `-C linker` already exists and works and there's a corresponding cargo config setting to set it, and that [the `-C linker-flavor` docs](https://doc.rust-lang.org/rustc/codegen-options/index.html#linker-flavor) say that passing a path to `-C linker` will automatically detect the correct flavor it doesn't sound like there's anything else that would need to be done to make it work for those scenarios.
> does it work just as well on win 8 and 7? should we restrict efforts to win 10?
This definitely bears some investigation but I suspect it's not a terribly big deal in practice. [The LLVM docs about building clang for use in Visual Studio](https://releases.llvm.org/10.0.0/docs/GettingStartedVS.html) say "Any system that can adequately run Visual Studio 2017 is fine". [The Visual Studio 2017 System Requirements documentation](https://docs.microsoft.com/en-us/visualstudio/productinfo/vs2017-system-requirements-vs) says it supports Windows 7 SP1 or newer.
> how important are the missing features on the lld-link status page? can we recover and fallback to link when encountering them?
Given that both Firefox and Chrome use `lld-link` for linking their Windows builds nowadays I'd hazard a guess that any missing features are not incredibly important. If someone were to propose making `lld-link` the *default* linker I would worry more about that, but anyone opting-in to using it and also relying on niche linker features can presumably just...not use it?<|endoftext|>The issue says "To test using rust-lld for msvc targets, use -C linker=lld". Shouldn't it be `-C linker=rust-lld`? At least, that's what i need to put in .cargo/config to make this work ([my experiments](https://github.com/rust-analyzer/rust-analyzer/pull/5813)):
```
[target.x86_64-pc-windows-msvc]
linker = "rust-lld"
```<|endoftext|>~Potential blocker - https://github.com/rust-lang/rust/issues/76398 "Rust + MSVC + LLD = Segfault on attempt to access TLS".
This issue currently prevents bootstrap of rustc on `x86_64-pc-windows-msvc` using LLD as a linker.~
Already mentioned under the "LLD/COFF does not correctly align TLS section" item.<|endoftext|>It looks like all the known issues with lld for this target have been fixed! 🎉
Shall we look into flipping it on by default?<|endoftext|>FWIW, lld-link has problems running on Windows 7. https://bugzilla.mozilla.org/show_bug.cgi?id=1699228<|endoftext|>@glandium Apparently only for some build jobs or maybe for some versions of LLD? I'm using it on Windows 7 without running into that issue.<|endoftext|>Yeah, apparently the problem is not happening with the build from llvm.org.<|endoftext|>@glandium I'm using the build that rustup installs.<|endoftext|>Chromium had the same issue on Windows 7 as Firefox, and their answer was that building requires Windows 10. I don't want to be harsh on people with older hardware, but mainstream support for Windows 7 ended before Rust 1.0 even released, and extended support ended over a year ago... I suspect that LLVM itself will stop supporting Windows 7 within the next year, if their deprecation timeline of Windows XP was any indication.<|endoftext|>The firefox lld-link problems mentioned in the comment above (https://github.com/rust-lang/rust/issues/71520#issuecomment-801484987) sound *extremely* similar to those we've had in rust in https://github.com/rust-lang/rust/issues/81051.
They were [fixed](https://reviews.llvm.org/rG64ab2b6825c5aeae6e4afa7ef0829b89a6828102) in LLVM trunk, but given that firefox (as they mention in the thread) have their own fork of LLVM, it's possible that they didn't adopt the fix (as it happened after LLVM 12 cutoff?)?
I don't have the time to test it right now, but if - as per @AndreKR - things are working currently, then i'm cautiously optimistic that they would keep working in the short-medium term as well.<|endoftext|>> It looks like all the known issues with lld for this target have been fixed!
Well, there is another one last time I tried:
> rust-lld: error: `/manifestdependency:` is not allowed in `.drectve`
Looks like `lld-link` doesn't fully support MSVC linker.<|endoftext|>In the blocking issues section
> #71504 - rust-analyser segfault with lto=thin, linker=lld-link
is checked off as being resolved since the issue went away; however, there is a recent open issue that similarly needs thin-lto and lld to be used together to produce a segfault https://github.com/rust-lang/rust/issues/81408<|endoftext|>@pravic Can you file a bug with a reproduction so that I can link it from the tracking issue?<|endoftext|>@bstrie @pravic I hope you don't mind but I filled a minimal report as I already had something similar laying around.<|endoftext|>#85642 is now resolved in nightly (Rust 1.60.0).<|endoftext|>Visited during T-compiler backlog bonanza.
The work that @lqd is doing for https://github.com/rust-lang/compiler-team/issues/510 are partly blocking this, but I am also not sure whether there are other blocking issues. (It sounds like #81408 may be a blocking issue, for example.)
(Furthermore, we are not certain we even will *want* lld to be the default on x64 msvc windows.)
@rustbot label: S-tracking-needs-summary<|endoftext|>link.exe performance seems to have improved a lot in VS2019 and VS2022. in some unscientific testing, i'm not seeing gains from switching to rust-lld.exe.<|endoftext|>> (Furthermore, we are not certain we even will _want_ lld to be the default on x64 msvc windows.)
What are the arguments against having lld as default on windows? To me just the better cross compilation support and getting rid of the need to manually install the MSVC toolchain just for the linker seem like they make lld the preferred choice.<|endoftext|>> getting rid of the need to manually install the MSVC toolchain
Not only _install_, but also _buy_ because MSVC toolchain isn't free under certain circumstances. Is `link.exe` the only used component from MSVC currently? If this change allows to get rid of MSVC completely so only free Windows SDK is required, it is a _very_ strong reason to move forward IMO.<|endoftext|>MSVC provides more than the linker and Windows SDK. It also provides the C runtime (e.g. startup code), core functions such as memcpy, memcmp, etc as well as the panic handling runtime. Perhaps these all could be replaced but as it stands simply switching out the linker doesn't remove the dependency on MSVC.<|endoftext|>I'm on Windows 10 x64 with:
`rustup 1.25.1 (bb60b1e89 2022-07-12)`
`rustc 1.66.1 (90743e729 2023-01-10)`
`MSVC v143` installed with Visual Studio Installer from Microsoft.
If I open a Rust project and change a simple char in code (eg: a variable value from 1 to 2) it re-builds the project (using watchexec) in 12 seconds.
I installed `llvm` and used this in global cargo config file (`C:/Users/<username>/.cargo/config`)
```
[target.x86_64-pc-windows-msvc]
linker = "lld-link.exe"
```
After a `cargo clean` and an initial re-build (debug mode, 2 minutes, the same as without `lld`) the time is the same (maybe even worse than 1 second).
So no change with or without LLD.
**Can you confirm or am I wrong?**
How to get faster incremental (development) builds?<|endoftext|>It might be better to test this using larger projects like RustPython or even Servo?<|endoftext|>I found a new STATUS_ACCESS_VIOLATION with MSVC+LLD+thinLTO (in both debug and release builds of rend3), haven't tried to narrow the scope down yet. (on both 1.69 stable and 1.71 nightly)
https://github.com/rust-lang/rust/issues/111480 | A-linkage<|endoftext|>metabug<|endoftext|>C-tracking-issue<|endoftext|>S-tracking-needs-summary | 29 | https://api.github.com/repos/rust-lang/rust/issues/71520 | https://github.com/rust-lang/rust/issues/71520 | https://api.github.com/repos/rust-lang/rust/issues/71520/comments |
587,887,630 | 70,401 | Tracking Issue for `-Z src-hash-algorithm` | This is the tracking issue for the unstable option `-Z src-hash-algorithm`
### Steps
- [x] Implementation PR #69718
- [ ] Adjust documentation
- [ ] Stabilization PR
### Unresolved Questions
- Should we have a separate option in the target specification to specify the preferred hash algorithm, or continue to use `is_like_msvc`?
- Should continue to have a command line option to override the preferred option? Or is it acceptable to require users to create a custom target specification to override the hash algorithm?
| #73526 has been merged, updating LLVM to 11 and making it possible to support SHA256 as well. I guess for now one still has to give compatibility for older LLVMs though, so one maybe has to place a few cfg's here and there.<|endoftext|>Are there documentation changes needed for this? I'd be happy to help!<|endoftext|>☝️ @eddyb <|endoftext|>@pierwill It is currently documented as an unstable option here: https://doc.rust-lang.org/beta/unstable-book/compiler-flags/src-hash-algorithm.html
I think the next step here would be to make a stabilization PR and adjust the documentation move it to the stable list of codegen options.<|endoftext|>Visited during T-compiler [backlog bonanza](https://rust-lang.zulipchat.com/#narrow/stream/238009-t-compiler.2Fmeetings/topic/.5Bsteering.20meeting.5D.202022-09-09.20compiler-team.23484.20backlog.20b'za/near/297985391)
It sounds like this is either ready to stabilize as is (with a shift from a `-Z` option to something stable), or it should move into something that is specified as part of of the target specification, and we just aren't even sure which of those modes we want this in for the stable form.
Can we maybe get a summary of the current implementation status, as well as the tradeoffs between those two options, to inform that decision?
@rustbot label: S-tracking-needs-summary | A-debuginfo<|endoftext|>T-compiler<|endoftext|>B-unstable<|endoftext|>C-tracking-issue<|endoftext|>S-tracking-needs-summary<|endoftext|>A-cli | 5 | https://api.github.com/repos/rust-lang/rust/issues/70401 | https://github.com/rust-lang/rust/issues/70401 | https://api.github.com/repos/rust-lang/rust/issues/70401/comments |
574,486,204 | 69,664 | Tracking Issue for the `avr-interrupt`/`avr-non-blocking-interrupt` calling convention/ABI | <!--
Thank you for creating a tracking issue! 📜 Tracking issues are for tracking a
feature from implementation to stabilisation. Make sure to include the relevant
RFC for the feature if it has one. Otherwise provide a short summary of the
feature and link any relevant PRs or issues, and remove any sections that are
not relevant to the feature.
Remember to add team labels to the tracking issue.
For a language team feature, this would e.g., be `T-lang`.
Such a feature should also be labeled with e.g., `F-my_feature`.
This label is used to associate issues (e.g., bugs and design questions) to the feature.
-->
This is a tracking issue for the RFC "XXX" (rust-lang/rfcs#NNN).
The feature gate for the issue is `#![feature(FFF)]`.
### Steps
- [x] Implement the RFC
- [ ] Adjust documentation ([see instructions on rustc-guide][doc-guide])
- [ ] Stabilization PR ([see instructions on rustc-guide][stabilization-guide])
[stabilization-guide]: https://rust-lang.github.io/rustc-guide/stabilization_guide.html#stabilization-pr
[doc-guide]: https://rust-lang.github.io/rustc-guide/stabilization_guide.html#documentation-prs
### Unresolved Questions
None yet.
### Implementation history
* #69478 introduces AVR as a tier-3 target upstream
| Raised to appease `tidy` in #69478.<|endoftext|>In https://github.com/rust-lang/rust/issues/40180 we mentioned wanting a (single) RFC for target-specific interrupt calling conventions, and that work is in progress in https://github.com/rust-lang/rfcs/pull/3246; you may want to coordinate with that work in progress. | T-lang<|endoftext|>B-unstable<|endoftext|>C-tracking-issue<|endoftext|>WG-embedded<|endoftext|>O-AVR<|endoftext|>S-tracking-needs-summary | 2 | https://api.github.com/repos/rust-lang/rust/issues/69664 | https://github.com/rust-lang/rust/issues/69664 | https://api.github.com/repos/rust-lang/rust/issues/69664/comments |
551,594,354 | 68,318 | Tracking issue for negative impls | Generalized negative impls were introduced in https://github.com/rust-lang/rust/pull/68004. They were split out from "opt-in builtin traits" (https://github.com/rust-lang/rust/issues/13231).
## Work in progress
This issue was added in advance of #68004 landed so that I could reference it from within the code. It will be closed if we opt not to go this direction. A writeup of the general feature is available in [this hackmd](https://hackmd.io/2FYm23s0R-igRnTLaFoo8w), but it will need to be turned into a proper RFC before this can truly advance.
## Current plans
* [ ] Forbid conditional negative impls or negative impls for traits with more than one type parameter (https://github.com/rust-lang/rust/issues/79098)
* [ ] Forbid `!Drop` (negative impls of `Drop`)
## Unresolved questions to be addressed through design process
* What should the WF requirements be? ([Context](https://github.com/rust-lang/rust/pull/68004#discussion_r367586615))
* Should we permit combining default + negative impls like `default impl !Trait for Type { }`? ([Context](https://github.com/rust-lang/rust/pull/68004#discussion_r367588811)) | Odd possibly off topic question about this. The following compiles:
```
#![feature(negative_impls)]
pub struct Test{
}
impl !Drop for Test {}
fn foo(){
drop(Test{})
}
```
Should it? <|endoftext|>> Odd possibly off topic question about this. The following compiles:
>
> ```
> #![feature(negative_impls)]
>
> pub struct Test{
>
> }
>
> impl !Drop for Test {}
>
> fn foo(){
> drop(Test{})
> }
> ```
>
> Should it?
I would say no, because if you wanted to shift the error to runtime you could implement Drop as:
```
pub struct Test{
}
impl Drop for Test {
fn drop() {
panic!("Do not drop Test.")
}
}
```
I generally like to catch anything at compile time that can be caught at compile time.<|endoftext|>[According to the documentation](https://doc.rust-lang.org/nightly/std/mem/fn.drop.html)
> This function is not magic; it is literally defined as
> ```rust
> pub fn drop<T>(_x: T) { }
> ```
As a trait bound, `T: Drop` means that the type has defined a custom `Drop::drop` method, nothing more (see the warn-by-default `drop_bounds` lint). It does not mean that `T` has non-trivial drop glue (e.g. `String: Drop` does not hold). Conversely, `T: !Drop` only says that writing `impl Drop for T { … }` in the future is a breaking change, it does not imply anything about `T`'s drop glue and definitely does not mean that values of type `T` cannot be dropped (plenty of people have tried to design such a feature for Rust with no success so far).
(If you did not already know, **drop glue** is the term for all the code that `std::mem::drop(…)` expands to, recursively gathering all `Drop::drop` methods of the type, its fields, the fields of those fields, and so on.)
Yes, the `Drop` trait is *very* counter-intuitive. I suggest extending `drop_bounds` to cover `!Drop` as well. Maybe even mentioning `!Drop` *at all* should be a hard error for now (neither `impl`s nor bounds make sense IMO). Can @nikomatsakis or anyone else add this concern to the unresolved questions section in the description?<|endoftext|>Not sure if this is the right place to report a bug with the current nightly implementation, but a negative implementation and its converse seem to "cancel each other out".
For example:
```rust
trait A {}
trait B {}
// logically equivalent negative impls
impl<T: A> !B for T {}
impl<T: B> !A for T {}
// this should not be possible, but compiles:
impl A for () {}
impl B for () {}
```
The above compiles without errors on nightly, though it shouldn't. Removing one of the negative impls fixes the issue and results in an error as expected.<|endoftext|>Allowing negative trait bounds would make my code much better by allowing to express [di-](https://en.wikipedia.org/wiki/Dichotomy) and [poly-chotomy](https://en.wikipedia.org/wiki/Polychotomy).
In Rust 1.57.0 the following doesn't compile:
```rust
#![feature(negative_impls)]
trait IntSubset {}
impl <T> IntSubset for T where T: FixedSizeIntSubset + !ArbitrarySizeIntSubset {}
impl <T> IntSubset for T where T: !FixedSizeIntSubset + ArbitrarySizeIntSubset {}
trait FixedSizeIntSubset {}
impl<T: FixedSizeIntSubset> !ArbitrarySizeIntSubset for T {}
trait ArbitrarySizeIntSubset {}
impl<T: ArbitrarySizeIntSubset> !FixedSizeIntSubset for T {}
```<|endoftext|>Coming here from a compiler error, how do I "use marker types" to indicate a struct is not Send on stable Rust? I don't see any "PhantomUnsend" or similar anywhere in std.
> error[E0658]: negative trait bounds are not yet fully implemented; use marker types for now<|endoftext|>@mwerezak I think I've seen `PhantomData<*mut ()>`. If I understand correctly, `*mut ()` is not `Send`, so neither is the enclosing `PhantomData` nor your struct. (Did not test)
`PhantomUnsend` might be a good alias/newtype for better readability – I had no idea what `PhantomData<*mut ()>` meant at first :D<|endoftext|>@rMazeiks Thanks, I wouldn't have known really what type would be the appropriate choice to use with `PhantomData` for this.
A `PhantomUnsend` sounds like a good idea.<|endoftext|>I think we should just rule out `!Drop` -- drop is a very special trait.<|endoftext|>Can we add "negative super traits" to the unwritten RFC? That is,
```rust
pub trait Foo {}
pub trait Bar: !Foo {}
// We now know that the two traits are exclusive, thus can write:
trait X {}
impl<T: Foo> X for T {}
impl<T: Bar> X for T {}
```
Quote from the Hackmd:
> This implies you cannot add a negative impl for types defined in upstream crates and so forth.
Negative super traits should get around this: the above snippet should work even if `Foo` is imported from another crate.
The potential issue here is that adding implementations to any trait exported by a library is technically a breaking change (though I believe it is already in some circumstances due to method resolution, and also is with any other aspect of negative trait bounds).<|endoftext|>I would prefer to leave that for future work, @dhardy -- I'd rather not open the door on negative where clauses just now, but also I think that it'd be interesting to discuss the best way to model mutually exclusive traits (e.g., maybe we want something that looks more like enums).<|endoftext|>Should manually implementing `!Copy` be allowed (~~#70849~~ #101836)? I assume it should.<|endoftext|>@fmease when is `Copy` ever implemented automatically?<|endoftext|>@Alxandr Never, I know. This is just a corner case lacking practical relevance I think. I am just asking here to be able to decide whether the issue I linked is a diagnostics problem only or if the compiler is actually too strict / lax. There should be no harm in implementing `!Copy` as a signal to library users.
Edit: There might even be some benefit in doing that with *negative coherence* enabled.<|endoftext|>> I think we should just rule out `!Drop` -- drop is a very special trait.
I found a use case for this while working on [async-local](https://crates.io/crates/async-local); for types that don't impl Drop, the thread_local macro won't register destructor functions, and the lifetime of these types can be extended by using Condvar making it possible to hold references to thread locals owned by runtime worker threads in an async context or on any runtime managed thread so long as worker threads rendezvous while destroying thread local data. For types that do impl Drop, they will immediately deallocate regardless of whether the owning thread blocks and so synchronized shutdowns cannot mitigate the possibility of pointers being invalidated, making the safety of this dependent on types not implementing Drop. <|endoftext|>Conditional negative impls seem to be broken?
```rust
#![feature(auto_traits, negative_impls)]
unsafe auto trait Unmanaged {}
unsafe trait Trace {}
struct GcPtr(*const ());
unsafe impl Trace for GcPtr {}
// It seems like rustc ignores the `T: Trace` bound.
impl<T: Trace> !Unmanaged for T {}
fn check<T: Unmanaged>(_: T) {}
fn main() {
let a = (0, 0);
// error: the trait bound `({integer}, {integer}): Unmanaged` is not satisfied
check(a);
}
```<|endoftext|>> Conditional negative impls seem to be broken?
As far as I can tell this has never had defined semantics. See https://github.com/rust-lang/rust/issues/79098 also.
| A-traits<|endoftext|>T-lang<|endoftext|>B-unstable<|endoftext|>C-tracking-issue<|endoftext|>F-negative_impls<|endoftext|>S-tracking-impl-incomplete<|endoftext|>S-tracking-needs-summary | 17 | https://api.github.com/repos/rust-lang/rust/issues/68318 | https://github.com/rust-lang/rust/issues/68318 | https://api.github.com/repos/rust-lang/rust/issues/68318/comments |
493,756,545 | 64,490 | Tracking issue for RFC 2582, `&raw [mut | const] $place` (raw_ref_op) | This is a tracking issue for the RFC "an operator to take a raw reference" (rust-lang/rfcs#2582), feature(raw_ref_op).
**Steps:**
- [ ] Implement the RFC (see [this comment](https://github.com/rust-lang/rust/issues/64490#issuecomment-531579111) for a detailed checklist)
- [ ] Adjust documentation ([see instructions on rustc-guide][doc-guide])
- [ ] Stabilization PR ([see instructions on rustc-guide][stabilization-guide])
[stabilization-guide]: https://rust-lang.github.io/rustc-guide/stabilization_guide.html#stabilization-pr
[doc-guide]: https://rust-lang.github.io/rustc-guide/stabilization_guide.html#documentation-prs
**Unresolved questions:**
- [ ] Maybe the lint should also cover cases that look like `&[mut] <place> as *[mut|const] ?T` in the surface syntax but had a method call inserted, thus manifesting a reference (with the associated guarantees). The lint as described would not fire because the reference actually gets used as such (being passed to `deref`). However, what would the lint suggest to do instead? There just is no way to write this code without creating a reference.
**Implementation history:**
* Initial implementation: https://github.com/rust-lang/rust/pull/64588 | I'll try to get a PR open for this soon.<|endoftext|>I would suggest splitting the implementation work up into phases to make each part thoroughly reviewed and tested. However, think of this list as a bunch of tasks that need to be done at some point.
1. [x] Implement `&raw [mut | const] $expr` in the parser and AST.
- [x] Ensure the `unused_parens` lint works alright.
- [x] Handle interactions in librustc_resolve.
2. [x] Push things down from AST => HIR
- [x] Handle lowering
- [x] Handle type checking
3. [x] Push things down from HIR => HAIR
4. [x] Push things down from HAIR => MIR -- here, the actual MIR operation is introduced.
5. [ ] Introduce lints for statically detectable UB as per the RFC.
6. [ ] Make `safe_packed_borrows` a hard error when the feature gate is active, and make this the case as well for `unsafe` equivalents.
------------------
...but it seems @matthewjasper already has a PR heh.<|endoftext|>> Make safe_packed_borrows a hard error when the feature gate is active, and make this the case as well for unsafe equivalents.
I'm not sure that this is a good idea. This would make it impossible to gradually migrate a codebase over to using raw references - once the feature gate is enabled, all references to packed structs must be fixed at once in order to get the crate building again.<|endoftext|>I wonder why not `&raw $expr` but `&raw
const $expr`. Is there a discussion about this?<|endoftext|>@moshg Yes, this was discussed. See [here (and the following comments) for an initial discussion](https://github.com/rust-lang/rfcs/pull/2582#issuecomment-465519395). And [here (and the following comments) for a signoff from grammar-wg](https://github.com/rust-lang/rfcs/pull/2582#issuecomment-483439054). And [here for an example that `&raw (expr)` can be ambiguous](https://github.com/rust-lang/rfcs/pull/2582#issuecomment-489468105).
I think it might be worth amending the RFC to state why `&raw const $expr` was chosen over `&raw $expr`.<|endoftext|>The RFC thread noted a couple times (including [in the FCP comment](https://github.com/rust-lang/rfcs/pull/2582#issuecomment-515640943)) that `&raw expr` without the `const` conflicts with existing syntax and would break real code. https://github.com/rust-lang/rfcs/pull/2582#issuecomment-465515012 goes into some detail. My understanding is that it is still possible to migrate to `&raw expr` with breaking changes in an edition, and I didn't see much explicit discussion of that, but I think everyone agrees that there's enough urgency here that we definitely prefer making `&raw const expr` a thing over blocking any solution on waiting for another edition.<|endoftext|>@mjbshaw @lxrec
Thank you for your explanations! I've understood why `&raw $expr` is breaking change.<|endoftext|>> I think it might be worth amending the RFC to state why &raw const $expr was chosen over &raw $expr.
https://github.com/rust-lang/rfcs/pull/2764<|endoftext|>@RalfJung I'm addressing the points you've made in https://github.com/rust-lang/rfcs/pull/2582#issuecomment-539906767
> promotion being confusing here seems mostly orthogonal to raw-vs-ref, doesn't it?
While it would be helpful to have at least a warning for a promotion in `&mut <rvalue>` case, disabling it is a backward incompatible change to the language. In `&raw mut <rvalue>` case it can be done from the beginning.
> If no promotion happens with raw ptrs, what would you expect to happen instead?
I would expect `&raw mut <rvalue>` to result in compilation error, as `&<rvalue>` does in C.
> I would expect &raw mut (1+2) to be promoted the same way &mut (1+2) is; not doing that seems even more confusing and very error-prone
I have an impression that silently allowing such promotions is more error prone, as it violates the principle of least surprise.
```
trait AddTwo {
fn add_two(&mut self);
}
impl AddTwo for u32 {
fn add_two(&mut self) { *self += 2; }
}
const N: u32 = 0;
// somewhere else
assert_eq!(N, 0);
// N += 2; // doesn't compile
N.add_two(); // compiles with no warnings
assert_eq!(N, 2); // fails
```
<|endoftext|>> promotion being confusing here seems mostly orthogonal to raw-vs-ref, doesn't it?
yes, promotion has nothing to do with it as far as I can tell.
> I would expect &raw mut <rvalue> to result in compilation error, as &<rvalue> does in C.
I agree. We should error on any `&raw place` where `place`
1. has no `Deref` projections (`*`) or `Index` (`[i]`) projections
2. *and* has a temporary local as base
since we still want to permit `&raw *foo()` I would assume. Or more concretely `&raw foo().bar` when `foo()` returns a reference.
If "erroring if not" has too many negations (i confused myself in the process of writing this), here's a version of what I think we should permit (and only that):
We should permit `&raw place` only if `place`
1. has `Deref` projections or `Index` projections
2. or has a static or local variable as the base<|endoftext|>> While it would be helpful to have at least a warning for a promotion in &mut <rvalue> case, disabling it is a backward incompatible change to the language. In &raw mut <rvalue> case it can be done from the beginning.
Note that *not* promoting here means this becomes a very short-lived temporary and the code has UB (or fails to compile, when only safe references are used)! Is that really what you want? `ptr as T` is *not* a place like `ptr` is and cannot be used as such; in particular it cannot be mutated.
> I have an impression that silently allowing such promotions is more error prone, as it violates the principle of least surprise.
I have a hard time imagining that silently causing UB is less of a surprise than promoting...
> `N.add_two(); // compiles with no warnings`
You are conflating some things here; what you are seeing here are implicit deref coercions. Promotion is not involved in this example.
> We should permit &raw place only if place
Oh I see, you want to cause some static errors. Yeah I can imagine that there are reasonable things we could do here.<|endoftext|>> You are conflating some things here; what you are seeing here are implicit deref coercions. Promotion is not involved in this example.
There's a bit of misunderstanding. I used a wrong term. When I said "rvalue promotion", I had "creation of a temporary memory location for an rvalue" in mind, not "promotion of a temporary to `'static`". <|endoftext|>@red75prime oh I see. Well currently, with promotion, we do *not* create a temporary memory location, but just a global one. But I suppose your desired behavior is more like what @oli-obk described, where we have static compiler errors?
I am not sure to what extend we can reliably produce those though. But MIR construction *should* know when it builds temporaries, so couldn't it refuse to do that when `&raw` is involved? Cc @matthewjasper <|endoftext|>Is there any plan to eventually add `&raw` pointer support to pattern matching? It could enable getting rid of [various forms of deliberate UB in abomonation](https://github.com/rust-lang/unsafe-code-guidelines/issues/77#issuecomment-544139277).<|endoftext|>@HeroicKatora actually wrote an RFC for that, though it was originally meant as an *alternative* to `&raw`: https://github.com/rust-lang/rfcs/pull/2666<|endoftext|>I'd be fine with it being interpreted as complementary, and can rewrite portions of it as necessary :)<|endoftext|>I can't recall if this was discussed in the RFC (and failed to find any comments on it), but can `<place>` be a pointer (to allow pointer-to-field computations)? Example:
```Rust
struct Struct {
field: f32,
}
let base_ptr = core::mem::MaybeUninit::<Struct>::uninit().as_ptr();
let field_ptr = &raw const base_ptr.field; // Is this allowed by this RFC?
```
Currently `field_ptr` has to be initialized with `unsafe { &(*base_ptr).field as *const _ }`. Using `unsafe { &raw const(*base_ptr).field }` is a bit better, but avoiding the `*base_ptr` dereference entirely would be ideal.
I assume the RFC doesn't permit this (since `base_ptr.field` isn't a place), but I just wanted to confirm (to be clear: I'm not trying to advocate for this RFC to do that if it doesn't already; I would like to draft a separate RFC exploring ways to avoid the `*base_ptr` dereference).<|endoftext|>> I can't recall if this was discussed in the RFC (and failed to find any comments on it), but can <place> be a pointer (to allow pointer-to-field computations)?
That question is ill-typed. A pointer is a kind of value, which is a class of things separate from places.
> `let field_ptr = &raw const base_ptr.field; // Is this allowed by this RFC?`
No, because there is no deref coercion for raw ptrs. But `&raw const (*base_ptr).field` is allowed, because `(*base_ptr).field` is a place.
> avoiding the *base_ptr dereference entirely would be ideal.
That has nothing to do with places though, that's just a deref coercion. When you write similar things with references, they work because the compiler adds the `*` for you -- and not because of anything having to do with places.
> since base_ptr.field isn't a place
It's not even well-typed.
> I would like to draft a separate RFC exploring ways to avoid the *base_ptr dereference).
Agreed, the current syntax is bad -- but mostly because of the parenthesis and the use of a prefix operator. I think we should have posfix-deref, e.g. `base_ptr.*.field`. That has been discussed before... somewhere...<|endoftext|>> That question is ill-typed. A pointer is a kind of value, which is a class of things separate from places.
You're right. Sorry for my poor choice of words.
> > ```Rust
> > let field_ptr = &raw const base_ptr.field; // Is this allowed by this RFC?
> > ```
>
> No
Thanks for answering my question. I'll follow up to your other points in a new thread on internals.rust-lang.org.<|endoftext|>Small nit: a deref coercion is `&T` to `&U` via deref(s). Dot access has its own implicit deref.<|endoftext|>Hey,the RFC document doesn't link to this tracking issue,it's linking to https://github.com/rust-lang/rust/issues/ .<|endoftext|>So, wait, would `let field_ptr = &raw const (*base_ptr).field;` work *without unsafe* with this RFC? Or would it still need to be wrapped in an `unsafe {}` block due to the "dereference" in `(*base_ptr)`?<|endoftext|>given that people try to write offset calculation code using null pointers, that expression shouldn't produce a real deref, and it should then actually work in safe code. wrapping_offset is safe, and offset is only unsafe because you _could_ go out of bounds, but a field pointer will always be in-bounds so there's not that danger.<|endoftext|>No, it requires unsafe. The place expression does not access the memory `base_ptr` points at, but it is (in effect for the current implementation) an `offset` operation and as such a dangling `base_ptr` causes UB.
Even if we take the separate & not-even-formally-proposed step of dropping the "must point to an allocated object" requirement for field projections to retroactively make `offsetof` implementations using null pointers defined, there's still the separate matter of wraparound in the address calculation (e.g. if `base_ptr as usize == usize::MAX`). Such wraparound is currently UB as well (it enables some nice optimizations) and does not affect any `offsetof` implementation, so it would be an even tougher sell to drop that UB.<|endoftext|>ahhhh I agree that you're correct but I don't like it.<|endoftext|>In terms of the [reference](https://doc.rust-lang.org/reference/behavior-considered-undefined.html), `&raw const (*base_ptr).field` still hits the clause saying
> Dereferencing (using the * operator on) a dangling or unaligned raw pointer.
This RFC does not actually change that list of UB. It just makes it so that one can avoid the clause in the reference that refers to `&[mut]` types.
That said, I just realized that the reference declares `&raw const (*packed_field).subfield` UB if `packed_field` is an unaligned raw pointer (e.g. to a field of a packed struct). That is probably not what we want...
The reason I phrased that clause as referring to "dereferencing" as opposed to actual memory accesses is precisely @roblabla's question.
Looks like we need two clauses?
> * Dereferencing (using the `*` operator on) a dangling raw pointer.
> * Reading from or writing to an unaligned raw pointer. (This refers only to `*ptr` reads and `*ptr = val` writes; raw pointer *methods* have their own rules which are spelled out in their documentation.)<|endoftext|>Should we also add `raw ref` bindings in patterns? For implementing `offset_of!`, https://internals.rust-lang.org/t/discussion-on-offset-of/7440/2 recommends using a struct pattern instead of a field access expression, in order to protect against accidentally accessing the field of another struct through `Deref`:
```rust
let u = $crate::mem::MaybeUninit::<$Struct>::uninitialized();
let &$Struct { $field: ref f, .. } = unsafe { &*u.as_ptr() };
```<|endoftext|>The current implementation does not prevent `&raw const foo().as_str()` where `fn foo() -> String` as far as I can tell. Repeating my post from https://github.com/rust-lang/rust/pull/64588#discussion_r357969199
The check for `&raw const 2` not being permitted is done on the HIR, and already mentions the downside to doing it on the HIR:
https://github.com/rust-lang/rust/blob/8843b28e64b02c2245f5869ad90cafa6d85ab0d9/src/librustc_typeck/check/expr.rs#L494-L496
The check could be implemented on the MIR by bailing out if any `Rvalue::AddressOf`'s `Place` is a temporary. Although that will probably start failing `&raw const *&*local` (reborrowing a local and then reading from it). I think it would be best if we somehow reuse the logic that causes
```rust
fn foo() -> String {
unimplemented!()
}
fn main() {
let x = foo().as_str();
println!("{}", x);
}
```
to emit
```
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:6:13
|
6 | let x = foo().as_str();
| ^^^^^ - temporary value is freed at the end of this statement
| |
| creates a temporary which is freed while still in use
7 | println!("{}", x);
| - borrow later used here
|
= note: consider using a `let` binding to create a longer lived value
```
I believe we should block stabilization on resolving this in a nonfragile way.<|endoftext|>The initial implementation PRs (#64588, #66671) for this are now merged and will be available from the next nightly.
> The current implementation does not prevent `&raw const foo().as_str()` where `fn foo() -> String` as far as I can tell.
It does: https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=7b0161f073236977f626102b9f3de81d
<|endoftext|>Is this fully implemented? Several PRs have been merged, but the "Implement the RFC" box is still unchecekd. | B-RFC-approved<|endoftext|>T-lang<|endoftext|>C-tracking-issue<|endoftext|>requires-nightly<|endoftext|>F-raw_ref_op<|endoftext|>S-tracking-needs-summary | 77 | https://api.github.com/repos/rust-lang/rust/issues/64490 | https://github.com/rust-lang/rust/issues/64490 | https://api.github.com/repos/rust-lang/rust/issues/64490/comments |
486,862,701 | 63,997 | Tracking issue for const fn pointers | Sub-tracking issue for https://github.com/rust-lang/rust/issues/57563.
This tracks `const fn` types and calling `fn` types in `const fn`.
---
From the RFC (https://github.com/oli-obk/rfcs/blob/const_generic_const_fn_bounds/text/0000-const-generic-const-fn-bounds.md#const-function-pointers):
## `const` function pointers
```rust
const fn foo(f: fn() -> i32) -> i32 {
f()
}
```
is illegal before and with this RFC. While we can change the language to allow this feature, two
questions make themselves known:
1. fn pointers in constants
```rust
const F: fn() -> i32 = ...;
```
is already legal in Rust today, even though the `F` doesn't need to be a `const` function.
2. Opt out bounds might seem unintuitive?
```rust
const fn foo(f: ?const fn() -> i32) -> i32 {
// not allowed to call `f` here, because we can't guarantee that it points to a `const fn`
}
const fn foo(f: fn() -> i32) -> i32 {
f()
}
```
Alternatively one can prefix function pointers to `const` functions with `const`:
```rust
const fn foo(f: const fn() -> i32) -> i32 {
f()
}
const fn bar(f: fn() -> i32) -> i32 {
f() // ERROR
}
```
This opens up the curious situation of `const` function pointers in non-const functions:
```rust
fn foo(f: const fn() -> i32) -> i32 {
f()
}
```
Which is useless except for ensuring some sense of "purity" of the function pointer ensuring that
subsequent calls will only modify global state if passed in via arguments.
| I think that, at the very least, this should work:
```rust
const fn foo() {}
const FOO: const fn() = foo;
const fn bar() { FOO() }
const fn baz(x: const fn()) { x() }
const fn bazz() { baz(FOO) }
```
For this to work:
* `const` must be part of `fn` types (just like `unsafe`, the `extern "ABI"`, etc.)
* we should allow calling `const fn` types from const fn
Currently, `const fn`s already coerce to `fn`s, so `const fn` types should too:
```rust
const fn foo() {}
let x: const fn() = foo;
let y: fn() = x; // OK: const fn => fn coercion
```
I don't see any problems with supporting this. The RFC mentions some issues, but I don't see anything against just supporting this restricted subset.
This subset would be **super** useful. For example, you could do:
```rust
struct Foo<T>(T);
trait Bar { const F: const fn(Self) -> Self; }
impl<T: Bar> Foo<T> {
const fn new(x: T) -> Self { Foo(<T as Bar>::F(x)) }
}
const fn map_i32(x: i32) -> i32 { x * 2 }
impl Bar for i32 { const F: const fn(Self) -> Self = map_i32; }
const fn map_u32(x: i32) -> i32 { x * 3 }
impl Bar for u32 { const F: const fn(Self) -> Self = map_u32; }
```
which is a quite awesome work around for the lack of `const` trait methods, but much simpler since dynamic dispatch isn't an issue, as opposed to:
```rust
trait Bar { const fn map(self) -> Self; }
impl Bar for i32 { ... }
impl Bar for u32 { ... }
// or const impl Bar for i32 { ... {
```
This is also a way to avoid having to use `if`/`match` etc. in `const fn`s, since you can create a trait with a const, and just dispatch on it to achieve "conditional" control-flow at least at compile-time.<|endoftext|>AFAIK `const fn` types are not even RFC'd, isn't it too early for a tracking issue?<|endoftext|>Don't know, @centril suggested that I open one.
I have no idea why `const fn` types aren't allowed. AFAICT, whether a function is `const` or not is part of its type, and the fact that `const fn` is rejected in a type is an implementation / original RFC oversight. If this isn't the case, what is the case?
EDIT: If I call a non-`const fn` from a `const fn`, that code fails to type check, so for that to happen `const` must be part of a `fn` type.<|endoftext|>> AFAIK `const fn` types are not even RFC'd, isn't it too early for a tracking issue?
Lotsa things aren't RFCed with respect to `const fn`. I want these issues for targeted discussion so it doesn't happen on the meta issue.<|endoftext|>> If I call a non-const fn from a const fn, that code fails to type check, so for that to happen const must be part of a fn type.
it is.
you can do
```rust
const fn f() {}
let x = f;
x();
```
inside a constant. But this information is lost when casting to a function pointer. Function pointers just don't have the concept of of constness.<|endoftext|>Figuring out constness in function pointers or dyn traits is a tricky questions, with a lot of prior discussion in [the RFC](https://github.com/rust-lang/rfcs/pull/2632) and [the pre-RFC](https://github.com/rust-rfcs/const-eval/pull/8).<|endoftext|>whats about?
``
pub trait Reflector {
fn Reflect(&mut self)-> (const fn(Cow<str>)->Option<Descriptor>);
}
``<|endoftext|>I was fiddling with something while reading [some of the discussion](https://github.com/rust-lang/rfcs/pull/2788) around adding a `lazy_static` equivalent to std and found that this check forbids even *storing* a `fn` pointer in a value returned from a `const fn` which seems unnecessarily restrictive given that storing them in `const` already works. The [standard lazy types RFC](https://github.com/rust-lang/rfcs/pull/2788) winds up defining `Lazy` like:
```rust
pub struct Lazy<T, F = fn() -> T> { ... }
```
[Here's a simple (but not very useful) example](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=047129b241a002f657b29bbf787c891f) that hits this.
[Adding another type parameter for the function](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018) makes it work on stable but it feels unnecessary.
Could this specific case be allowed without stabilizing the entire ball of wax here? (Specifically: referencing and storing `fn` pointers in `const fn` but not calling them.)<|endoftext|>> Could this specific case be allowed without stabilizing the entire ball of wax here? (Specifically: referencing and storing fn pointers in const fn but not calling them.)
The reason we can't do this is that this would mean we'd lock ourselves into the syntax that `fn()` means a not callable function pointer (which I do realize constants already do) instead of unifying the syntax with trait objects and trait bounds as shown in the main post of this issue<|endoftext|>Just in case other people run into this being unstable: It's still possible to use function pointers in `const fn` as long as they're wrapped in some other type (eg. a `#[repr(transparent)]` newtype or an `Option<fn()>`):
```rust
#[repr(transparent)]
struct Wrap<T>(T);
extern "C" fn my_fn() {}
const FN: Wrap<extern "C" fn()> = Wrap(my_fn);
struct Struct {
fnptr: Wrap<extern "C" fn()>,
}
const fn still_const() -> Struct {
Struct {
fnptr: FN,
}
}
```<|endoftext|>If const is a qualifier of function like `unsafe` or `extern` we have next issue:
```rust
const fn foo() { }
fn bar() { }
fn main() {
let x = if true { foo } else { bar };
}
```
It compiles now but not compiles with these changes because `if` and `else` have incompatible types.
So it breaks an old code. <|endoftext|>> If const is a qualifier of function like `unsafe` or `extern` we have next issue:
>
> ```rust
> const fn foo() { }
> fn bar() { }
>
> fn main() {
> let x = if true { foo } else { bar };
> }
> ```
>
> It compiles now but not compiles with these changes because `if` and `else` have incompatible types.
> So it breaks an old code.
Const fn's are still fns, the type won't be charged. In fact const qualifier only allows const fn appear in const contexes, and be evaluated at compile time. You can think of this like implicit casting. <|endoftext|>```rust
unsafe fn foo() { }
fn bar() { }
fn main() {
let x = if true { foo } else { bar };
}
```
This code does not compile for the same reason. Unsafe fn's are still fns too, why we haven't implicit casting in this situation?
<|endoftext|>> ```rust
> unsafe fn foo() { }
> fn bar() { }
>
> fn main() {
> let x = if true { foo } else { bar };
> }
> ```
>
> This code does not compile for the same reason. Unsafe fn's are still fns too, why we haven't implicit casting in this situation?
This leads to possible unsafety in our code, and all which comes with it. `const ` fn casting on otherside don't brings any unsafety, so is allowed, const fn must not have any side effects only, it is compatible with fn contract.
```rust
fn bar() {}
const fn foo(){}
const fn foo_bar(){
if true { foo() } else { bar() };
}
```
This must not compile, because bar is not const and therefore can't be evaluated at compile time. Btw, it raises(?) "can't call non const fn inside of const one", and can be considered incorrect downcasting. (set of valid const fns is smaller than set of fns at all)<|endoftext|>> > fn main() {
> > let x = if true { foo } else { bar };
> > }
> > ```
> >
> >
> > This code does not compile for the same reason. Unsafe fn's are still fns too, why we haven't implicit casting in this situation?
>
> This leads to possible unsafety in our code, and all which comes with it. `const ` fn casting on otherside don't brings any unsafety, so is allowed, const fn must not have any side effects only, it is compatible with fn contract.
I think you're missing the point. With implicit coercions, the type of `x` would be `unsafe fn()`, not `fn()`. There's nothing about that which leads to possible unsafety. Generally, `const fn()` can be coerced to `fn()` and `fn()` can be coerced to `unsafe fn()`. It just doesn't happen automatically, which is why changing `const fn foo()` to coerce into `const fn()` rather than `fn()` implicitly is a breaking change.
> ```rust
> fn bar() {}
>
> const fn foo(){}
>
> const fn foo_bar(){
> if true { foo() } else { bar() };
> }
> ```
>
> This must not compile, because bar is not const and therefore can't be evaluated at compile time. Btw, it raises(?) "can't call non const fn inside of const one", and can be considered incorrect downcasting. (set of valid const fns is smaller than set of fns at all)
Of course this must not compile, but I don't think that's related to what @filtsin was talking about.<|endoftext|>Personally I would love to see more implicit coercions for function pointers. Not sure how feasible that is though. I've previously wanted trait implementations for function pointer types to be considered when passing a function (which has a unique type) to a higher-order generic function. I posted about it on internals, but it didn't receive much attention.<|endoftext|>> Generally, `const fn()` can be coerced to `fn()` and `fn()` can be coerced to `unsafe fn()`. It just doesn't happen automatically, which is why changing `const fn foo()` to coerce into `const fn()` rather than `fn()` implicitly is a breaking change.
>
But not in oposite direction - thats what i wanted to say.
<|endoftext|>```rust
impl<T> Cell<T> {
pub fn with<U>(&self, func: const fn(&mut T) -> U) -> U;
}
```
Wouldn't const fn pointers make this sound? A const fn can't access a static or a thread-local, which would make this unsound.
Edit: a cell containing a reference to itself makes this unsound<|endoftext|>It seems assignment is currently broken, complaining about casts, even though no such casts are actually performed. (A const function simply assigning a function ptr basically). https://github.com/rust-lang/rust/issues/83033<|endoftext|>See my response at https://github.com/rust-lang/rust/issues/83033#issuecomment-831089437 -- short summary: there is in fact a cast going on here; see [the reference on "function item types"](https://doc.rust-lang.org/nightly/reference/types/function-item.html) for more details.<|endoftext|>> Just in case other people run into this being unstable: It's still possible to use function pointers in `const fn` as long as they're wrapped in some other type (eg. a `#[repr(transparent)]` newtype or an `Option<fn()>`):
I've found a case where this isn't true. ([playground link](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c9a6f0f5d7bb211de352e33ad11bd012))
```rust
struct Handlers([Option<fn()>; _]);
impl Handlers {
const fn new() -> Self {
Self([None; _])
}
}
```<|endoftext|>Yea, just like with dyn Trait or generic trait bounds, there are workarounds to our checks and I'm convinced now we should just allow all of these like we do in const items. You can't call them, but you can pass them around.<|endoftext|>For const closures a lot has happened in 2022.
This now works since `rustc 1.61.0-nightly (03918badd 2022-03-07)` (commit range is 38a0b81b1...03918badd but I can't narrow it down to a single PR... maybe a side effect of #93827 ???):
```Rust
#![feature(const_trait_impl)]
const fn foo<T: ~const Fn() -> i32>(f: &T) -> i32 {
f()
}
```
And since `rustc 1.68.0-nightly (9c07efe84 2022-12-16)` (I suppose the PR was #105725) you can even use `impl Trait` syntax:
```Rust
#![feature(const_trait_impl)]
const fn foo(f: &impl ~const Fn() -> i32) -> i32 {
f()
}
```
For const fn pointers, nothing much has happened though. This still errors:
```Rust
const fn foo(f: ~const fn() -> i32) -> i32 {
f()
}
```
gives
<details>
```
error: expected identifier, found keyword `fn`
--> src/lib.rs:2:24
|
2 | const fn foo(f: ~const fn() -> i32) -> i32 {
| ^^
|
help: use `Fn` to refer to the trait
|
2 | const fn foo(f: ~const Fn() -> i32) -> i32 {
| ~~
error: `~const` is not allowed here
--> src/lib.rs:2:17
|
2 | const fn foo(f: ~const fn() -> i32) -> i32 {
| ^^^^^^^^^^^^^^^^^^
|
= note: trait objects cannot have `~const` trait bounds
error[E0782]: trait objects must include the `dyn` keyword
--> src/lib.rs:2:17
|
2 | const fn foo(f: ~const fn() -> i32) -> i32 {
| ^^^^^^^^^^^^^^^^^^
|
help: add `dyn` keyword before this trait
|
2 | const fn foo(f: dyn ~const fn() -> i32) -> i32 {
| +++
For more information about this error, try `rustc --explain E0782`.
error: could not compile `playground` (lib) due to 3 previous errors
```
</details>
Edit: note that while what I said is great progress, the two aren't *well* comparable, as the `Fn` trait support is for monomorphized generics cases, as in those where we know the type at const eval time and can derive the function from the type. `dyn Fn` trait support is still not existent. This gives a bunch of errors:
```Rust
#![feature(const_trait_impl)]
const fn foo(f: &dyn ~const Fn() -> i32) -> i32 {
f()
}
``` | T-lang<|endoftext|>A-const-fn<|endoftext|>C-tracking-issue<|endoftext|>S-tracking-needs-summary | 23 | https://api.github.com/repos/rust-lang/rust/issues/63997 | https://github.com/rust-lang/rust/issues/63997 | https://api.github.com/repos/rust-lang/rust/issues/63997/comments |
473,762,264 | 63,084 | Tracking issue for `const fn` `type_name` | This is a tracking issue for making and stabilizing `type_name` as `const fn`. It is not clear whether this is sound. Needs some T-lang discussion probably, too.
Steps needed:
* [x] Implementation (essentially add `const` and `#[rustc_const_unstable(feature = "const_type_name")` to the function and add tests showing that it works at compile-time.
* [ ] fix https://github.com/rust-lang/rust/issues/94187
* [ ] check if https://github.com/rust-lang/rust/issues/97156 replicates for `type_name`, too
* [ ] Stabilization
* Note that stabilization isn't happening any time soon. This function can change its output between rustc compilations and allows breaking referential transparency. Doing so at compile-time has not been discussed fully and has various points that are problematic.
| > This function can change its output between rustc compilations
Can the output change between compiling a library crate, and a binary crate using that library? Or only when switching rustc versions?<|endoftext|>> Can the output change between compiling a library crate, and a binary crate using that library?
No, we're using global paths now.
> Or only when switching rustc versions?
Yes, there needs to be a change in rustc that causes a change in output.<|endoftext|>I might take a look at this. (I implemented the support for using the actual `type_name` intrinsic in `const fn` contexts, if you don't remember me, haha.)
I think we definitely know it works at compile time though, don't we? That's what [this test I added at the time](https://github.com/rust-lang/rust/blob/4560cb830fce63fcffdc4558f4281aaac6a3a1ba/src/test/ui/consts/const-fn-type-name.rs) checks for.<|endoftext|>Sorry it took me a bit to get to this. [Just opened a PR.](https://github.com/rust-lang/rust/pull/63123)<|endoftext|>How does this break referential transparency? I'd like to see that elaborated upon.<|endoftext|>I might be wrong, but I think the first "checkbox" can be checked since my PR was merged?
@lfairy:
Personally, I disagree, but some people seem to think that despite the fact Rust has fully reified generics, it's somehow a "dangerous" concept for your "average Joe/Jane" to be able to access the (100%-guaranteed-correct) name of a generic parameter.
Something about "Java programmers I used to work with did Some Bad Thing and I don't want Rust programmers to also do Some Bad Thing".
I don't know anything about Java though so I'm probably not overly qualified to get too much into that.<|endoftext|>Hi, is there a stabilization issue for this `const`-ification?<|endoftext|>This is the tracking issue, so it will get closed on stabilization. I don't know what the next steps for stabilizing it are though. The discussion around referential transparency needs to be had (although with specialization it'd become obsolete, because then we'd get this feature anyway, but in a less convenient way). I think posting use cases would be very helpful for the discussion. Since this works with feature gates, you can always show a use case with nightly.<|endoftext|>Hi, certainly I can write about a use case that I am working on!
I'm part of the Embedded WG where I am currently working on an instrumentation/logging tool for embedded targets. Here, as you probably know, we have strict requirements on code size as the micro controllers have very little memory.
And a huge hog of memory is when strings are placed in memory.
To this end I place formating strings and (I want) type strings in an `INFO` linker section so they are available in the ELF but not loaded onto the target. That is the following code as an example:
```rust
// test1 is some variable
mylog::log!("Look what I got: {}", &test1);
//
// Expands to:
//
const fn get_type_str<T>(_: &T) -> &'static str {
// type_name needs to be a const fn for this to work
core::any::type_name::<T>()
}
// ugly hack to tranform `&'static str` -> `[u8; str.len()]`
union Transmute<T: Copy, U: Copy> {
from: T,
to: U,
}
const FMT: &'static str = "Look what I got: {}";
const TYP: &'static str = get_type_str(&test1);
// Transform string into byte arrays at compile time so
// they can be placed in a specific memory region
// Formating string placed in a specific linker section
#[link_section = ".some_info_section"]
static F: [u8; FMT.as_bytes().len()] = unsafe {
*Transmute::<*const [u8; FMT.len()], &[u8; FMT.as_bytes().len()]> {
from: FMT.as_ptr() as *const [u8; FMT.as_bytes().len()],
}
.to
};
// Type string placed in a specific linker section
#[link_section = ".some_info_section"]
static T: [u8; TYP.as_bytes().len()] = unsafe {
*Transmute::<*const [u8; TYP.len()], &[u8; TYP.as_bytes().len()]> {
from: TYP.as_ptr() as *const [u8; TYP.as_bytes().len()],
}
.to
};
// Here we send where the strings are stored in the ELF + the data to the host
write_frame_to_host(&F, &T, &test1)
```
Link script:
```
SECTIONS {
.some_info_section (INFO) :
{
*(.some_info_section .some_info_section.*);
}
}
```
By doing this the strings are available in the generated ELF but not loaded onto the target, and the type can be reconstructed through DWARF with help of the type string.
And with complex types the space used for the type is getting very large for example any type that uses `GenericArray` (which we use extensively).
Currently the string is placed in `.rodata` which means that the compiler fully knows that this is a static string, and I made an issue on how to control where strings are placed which can use a trick outlined in here: https://github.com/rust-lang/rust/issues/70239
However this trick only works if the string is available in const context.
This is why I am asking about stabilization here.<|endoftext|>I would also like to get this stabilized and can present a use-case.
I'm working on [firestorm](https://github.com/That3Percent/firestorm): a low overhead intrusive flame graph profiler. I created `firestorm` because existing solutions have too much overhead to be useful for [Tree-Buf](https://github.com/That3Percent/tree-buf): the self-describing serialization system that produces files smaller than GZip faster than uncompressed formats.
Part of keeping the overhead of `firestorm` low is to delay string formatting/allocation until outside of the profiled region. So, there is an enum that allows for arbitrary amounts of `&'static str` to be concatenated. In order to keep the amount of data writing to a minimum during the execution of the profiled region, we only write `&'static EventData` so that `EventData` can be large. Supporting concatenation of fn name and struct name for a method is only possible if `type_name` is a `const fn`.
TLDR: I need this to be `const fn` for performance.<|endoftext|>To elaborate here's code I would like to have be able to compile:
```rust
#[macro_export]
macro_rules! profile_method {
($($t:tt)*) => {
let _firestorm_method_guard = {
const FIRESTORM_STRUCT_NAME: &'static str = ::std::any::type_name::<Self>();
let event_data: &'static _ = &$crate::internal::EventData::Start(
$crate::internal::Start::Method {
signature: stringify!($($t)*),
typ: FIRESTORM_STRUCT_NAME,
}
);
$crate::internal::start(event_data);
$crate::internal::SpanGuard
};
};
}
```
It seems there are at least 2 problems here though. First, is that `type_name` is not a const fn. The second is that the compiler complains about the use of `Self` as the generic for the const fn. I do not really understand why that's a problem when each monomorphized function could have its own value here.
<|endoftext|>@That3Percent I don't think the `Self` part is something that can be solved at present, even if we stabilize `type_name`. You can test this out by using nightly and activating the feature gate for `const_type_name`<|endoftext|>@oli-obk Yes, you are right. Both issues would need to be resolved to support my use-case in the way that I would like.<|endoftext|>I found a bug with `type_name`: `type_name` works in array lengths of arrays used in associated consts, even if it is `type_name::<Self>`. This doesn't even work for `size_of`. The bug is that `type_name` just returns `_` in that case:
https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=4404a9b3635b4bf5047c2493ac9a5082
If you comment out the first panic, you get the correct type name.<|endoftext|>> I found a bug with type_name: type_name works in array lengths of arrays used in associated consts, even if it is type_name::<Self>. This doesn't even work for size_of. The bug is that type_name just returns _ in that case:
This seems to be fixed now?<|endoftext|>Has there been any progress on the stabilization of `type_name`?<|endoftext|>Ping again on the status of stabilization?<|endoftext|>`type_id` (https://github.com/rust-lang/rust/issues/77125) has a bunch of issues which is why its stabilization actually got reverted; not sure if those issues also apply to `type_name`.<|endoftext|>Would you believe I clicked the wrong link in Rustdoc? Sorry.<|endoftext|>Is there any outlook on stabilization/progress towards it?<|endoftext|>There's a rendering bug and a soundness bug that we need to fix before we can stabilize. Both are linked from the main post | T-lang<|endoftext|>T-libs-api<|endoftext|>B-unstable<|endoftext|>A-const-fn<|endoftext|>C-tracking-issue<|endoftext|>requires-nightly<|endoftext|>Libs-Tracked<|endoftext|>Libs-Small<|endoftext|>S-tracking-needs-summary | 21 | https://api.github.com/repos/rust-lang/rust/issues/63084 | https://github.com/rust-lang/rust/issues/63084 | https://api.github.com/repos/rust-lang/rust/issues/63084/comments |
473,431,185 | 63,012 | Tracking issue for -Z binary-dep-depinfo | This is a tracking issue for `-Z binary-dep-depinfo` added in #61727.
The cargo side is implemented in https://github.com/rust-lang/cargo/pull/7137.
Blockers:
- [ ] Canonicalized paths on Windows. The dep-info file includes a mix of dos-style and extended-length (`\\?\`) paths, and I think we want to use only one style (whatever is compatible with make and other tools). See the PR for details.
- [ ] Codegen backends are not tracked.
cc @Mark-Simulacrum @alexcrichton
| In https://github.com/rust-lang/rust/pull/68298 we fixed binary dep-depinfo to be less eager to emit dependencies on dylib/rlib files when emitting rlibs and rmeta files, as we only need rmeta input in that case.
It was also noted that we currently do not correctly emit plugin dependencies (I'm not entirely sure of this, but seems not implausible).<|endoftext|>MCP: https://github.com/rust-lang/compiler-team/issues/464<|endoftext|>I wonder if the Cargo side of `binary-dep-info` could also be taught specifically about the [hashes in `rustc` metadata](https://github.com/rust-lang/rust/blob/fee75fbe11b1fad5d93c723234178b2a329a3c03/compiler/rustc_metadata/src/locator.rs#L665-L674) so that it doesn't _just_ use timestamps for artifacts where a more reliable metric is (I think?) readily available (without going all the way to https://github.com/rust-lang/rust/pull/75594 / https://github.com/rust-lang/cargo/pull/8623 / https://github.com/rust-lang/cargo/issues/6529).<|endoftext|>Separately, repeating the sentiment from https://github.com/rust-lang/cargo/issues/10664#issuecomment-1125438398 that tracking codegen backends should probably not be considered a blocker for landing this — the feature can very much be useful without that I think, and it could be added later on.<|endoftext|>> I wonder if the Cargo side of binary-dep-info could also be taught specifically about the [hashes in rustc metadata](https://github.com/rust-lang/rust/blob/fee75fbe11b1fad5d93c723234178b2a329a3c03/compiler/rustc_metadata/src/locator.rs#L665-L674) so that it doesn't just use timestamps for artifacts where a more reliable metric is (I think?) readily available
1. That requires some way for cargo to read it directly from the metadata file.
2. It shouldn't be tied to -Zbinary-dep-depinfo IMO.<|endoftext|>Discussed in T-compiler [backlog bonanza](https://rust-lang.zulipchat.com/#narrow/stream/238009-t-compiler.2Fmeetings/topic/.5Bsteering.20meeting.5D.202022-08-12.20compiler-team.23484.20backlog.20b'za/near/293120445)
We had some confusion about who the target audience for this feature is. From reading the comments, we understand it was added for certain things in `rustbuild`. There had been some discussion of making binary-dep-depinfo the default (see e.g. https://github.com/rust-lang/compiler-team/issues/464 ), but we are not clear on whether that is a reasonable thing to do. Likewise, we are not clear on whether upgrading the `-Z` flag here to a `-C` flag would be a reasonable thing to do.
Independent of that, there were design questions, e.g. what things should be included. (It doesn't track native dependencies, for example.)
So, I'm adding the design concerns label below, but I would be interested to know if I should also be adding S-tracking-perma-unstable
@rustbot label: S-tracking-design-concerns<|endoftext|>Given the confusion we had in our conversation about this, I'm also going to request a summary of this feature and its status. :)
@rustbot label: S-tracking-needs-summary<|endoftext|>I can speak to the use-case in my case: we're using a large distributed build system at $work in which packages are automatically re-built if their dependencies change. Which, for example, means that if we for example need a patch to `rustc` to work around some internal issue, then `rustc` is re-built. And then anything that _uses_ `rustc` is re-built. But without `-Zbinary-dep-depinfo` Cargo doesn't understand that `rustc` has changed since the version number remains the same, and so doesn't realize that it must also re-build the various Rust artifacts.<|endoftext|>`cargo-udeps` uses the feature since the 0.1.33 release to figure out which dependencies were actually used during compilation, since save-analysis is going to be removed.<|endoftext|>The linux kernel uses the flag too: https://github.com/Rust-for-Linux/linux/issues/2
> Used by: Kbuild.
>
> Status: we could get around it by making the build system more complicated (particularly if the kernel does not upgrade the minimum Make version), but it would be best to avoid that.<|endoftext|>> The linux kernel uses the flag too: [Rust-for-Linux/linux#2](https://github.com/Rust-for-Linux/linux/issues/2)
>
> > Used by: Kbuild.
> > Status: we could get around it by making the build system more complicated (particularly if the kernel does not upgrade the minimum Make version), but it would be best to avoid that.
Apparently it is necessary to avoid recompiling in some scenarios: https://github.com/Rust-for-Linux/linux/issues/2#issuecomment-1307818144
> Without `-Zbinary-dep-depinfo` rustc will only put the source files and the compiled output in the depinfo file. With `-Zbinary-dep-depinfo` rustc will also add .rmeta, .rlib, ... dependencies to the depinfo file. Without this changing a depensency wouldn't cause make to rebuild dependent crates. Cargo doesn't have this issue as it already knows the dependencies on it's own and only needs the depinfo file for the source file list, but make really needs everything.
<|endoftext|>> I can speak to the use-case in my case: we're using a large distributed build system at $work in which packages are automatically re-built if their dependencies change. Which, for example, means that if we for example need a patch to `rustc` to work around some internal issue, then `rustc` is re-built. And then anything that _uses_ `rustc` is re-built. But without `-Zbinary-dep-depinfo` Cargo doesn't understand that `rustc` has changed since the version number remains the same, and so doesn't realize that it must also re-build the various Rust artifacts.
I am confused by this statement. binary-dep-depinfo does *not* emit the path to the toolchain currently: https://github.com/rust-lang/rust/blob/1fa1f5932b487a2ac4105deca26493bb8013a9a6/compiler/rustc_interface/src/passes.rs#L490-L511
Exactly what is your setup? I don't understand why this would be working for you but not for bootstrap.<|endoftext|>Ah, so, to be clear, we don't _currently_ use `-Zbinary-dep-depinfo`. Instead, incremental builds currently just break if we ever happen to have to do this. What I wrote was aspirational: we _want_ depinfo tracking in the hopes that it will _let_ Cargo/rustc detect this situation (rustc changing without the version changing) and handle it correctly.<|endoftext|>We do currently use `-Zbinary-dep-depinfo` for making cargo rebuild everything, however when incremental compilation is enabled, it is not enough to trigger a rebuild. The incr comp cache needs to be cleared too. In addition if a crate version changes, that seems to cause issues too.<|endoftext|>Cc https://github.com/rust-lang/rust/pull/111329#issuecomment-1538303474 which I believe should help explain why it's not currently enough for dependency version changes, I suspect a similar change for incremental may also be helpful but I haven't looked at incremental encoding/decoding.<|endoftext|>For incremental it wouldn't help. Even if the encoding is exactly identical the encoded query results may have changed between versions. We need to clear the incr cache unconditionally if rustc changes.<|endoftext|>To loop in some other tickets that have touched on "re-building if rustc changes" in the past: https://github.com/rust-lang/cargo/issues/10664 and https://github.com/rust-lang/cargo/issues/10367 are possibly relevant.<|endoftext|>https://github.com/rust-lang/cargo/issues/10367 is a different problem. That's about if the *path* to the compiler changes; the problem in this issue happens when the path and version output stay the same and only the *mtine* is different. | T-compiler<|endoftext|>B-unstable<|endoftext|>C-tracking-issue<|endoftext|>requires-nightly<|endoftext|>S-tracking-design-concerns<|endoftext|>S-tracking-needs-summary<|endoftext|>A-cli | 18 | https://api.github.com/repos/rust-lang/rust/issues/63012 | https://github.com/rust-lang/rust/issues/63012 | https://api.github.com/repos/rust-lang/rust/issues/63012/comments |
462,983,150 | 62,290 | Tracking issue for `#![feature(async_closure)]` (RFC 2394) | This is a tracking issue for `#![feature(async_closure)]` (rust-lang/rfcs#2394).
The feature gate provides the `async |...| expr` closure syntax.
**As with all tracking issues for the language, please file anything unrelated to implementation history, that is: bugs and design questions, as separate issues as opposed to leaving comments here. The status of the feature should also be covered by the feature gate label. Please do not ask about developments here.**
**Steps:**
- [x] Implement the RFC
- [ ] Adjust documentation ([see instructions on rustc-guide][doc-guide])
- [ ] Stabilization PR ([see instructions on rustc-guide][stabilization-guide])
[stabilization-guide]: https://rust-lang.github.io/rustc-guide/stabilization_guide.html#stabilization-pr
[doc-guide]: https://rust-lang.github.io/rustc-guide/stabilization_guide.html#documentation-prs
**Unresolved questions:**
None as of yet. | Hi, what's the next step for this issue?<|endoftext|>@Centril am bumping into this one quite often in beta... from an ergonomics point of view it would be great to get this stable if there's no outstanding concerns / issues... - is this something we might consider putting 'on-deck', or does it need more settlement time?<|endoftext|>Despite "Implement the RFC" being checked this feature is still largely unimplemented (other than the trivial case of `async move || {}` which is equivalent to `move || async move {}`), and as far as I'm aware also requires more design work before it can even really be implemented.<|endoftext|>@rustbot modify labels to +AsyncAwait-OnDeck
Closures are a very commonly used language feature, especially in APIs like `itertools`. Enabling such APIs to be async has obvious benefits.<|endoftext|>As @Nemo157 points out this is largely unimplemented and is entirely secondary to fixing *all* the outstanding bugs with the stable part of async/await that we are shipping in 1.39.0.
(Personally I think async closures should be considered holistically with other types of effect-modified closures. Moreover I think they might be largely redundant atop of the combination of closures with async blocks inside them.)<|endoftext|>Does this will allow ? on Result which have different Error type in the same async closure? currently, there is no way to done that, which is really frustrating<|endoftext|>@CGQAQ do you have an example that fails now? Some [quick testing](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f0b10306b1897b06600f87cdb4eec13b) in the playground makes it look like inference is able to handle at least simple cases correctly (I definitely could see it being possible that the two layers of generics with inferred outputs might cause some issues for inference, and async closures could potentially improve on that by tying those inferred outputs together somehow).<|endoftext|>@Nemo157
```rust
async fn a() -> Result<(), reqwest::Error> {Ok(())}
async fn b() -> Result<(), std::io::Error> {Ok(())}
fn c() {
async {
a().await?;
b().await?;
Ok(())
};
}
```
```
error[E0282]: type annotations needed
--> src/x.rs:6:9
|
6 | a().await?;
| ^^^^^^^^^^ cannot infer type
error: aborting due to previous error
```
```rust
async fn a() -> Result<(), reqwest::Error> {Ok(())}
async fn b() -> Result<(), std::io::Error> {Ok(())}
fn c() {
async {
a().await?;
b().await?;
Ok::<(), impl std::error::Error>(())
};
}
```
```
error[E0562]: `impl Trait` not allowed outside of function and inherent method return types
--> src/x.rs:8:18
|
8 | Ok::<(), impl std::error::Error>(())
| ^^^^^^^^^^^^^^^^^^^^^^
error: aborting due to previous error
```<|endoftext|>@CGQAQ the former _is_ unconstrained, there's no way rustc can know what the error type should be, changing it to be used in a closure returning an async block passed to a function which constrains it [works fine](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6f18274ebfcf720b5ec9da45aff65f5d) (and the equivalent blocking code [also fails](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=5a517860b9922f238d852f6ba98d3c20)). The latter already [works](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f6c962ab0c758c76327a2201b3c10734) after replacing `impl Error` with a concrete error type (as far as I'm aware `impl Trait` in that position is not supported and has not been RFCed). (I also switched both to use `serde_json::Error` instead of `reqwest::Error` as it provides the necessary conversion into `io::Error`).
If you want to continue this it would be best to open a new issue and ping me there (or discord) to avoid notifying subscribers of this issue.<|endoftext|>Any recent news/updates for this feature?<|endoftext|>The purpose of this issue to track the development by noting relevant PRs and whatnot as they happen. The feature gate label is also available to route you to relevant places. You can assume that if no recent developments have been noted here, or linked, or provided in the issues with the label, that there are no such developments, so please avoid asking about it here.<|endoftext|>Sorry if I missed it, but what's the motivation under this feature? IMO It just adds a slightly different syntax for existing thing (`async ||` vs `|| async`), introducing confusion with no foreseeable benefit. Or at least this is what I see here.
Could you elaborate on that, please?<|endoftext|>`|| async { }` is not an async closure, it's a closure that contains an async block.<|endoftext|>Yes, I see it, but what's the difference from the user perspective?<|endoftext|>There may be differences in how lifetimes in the arguments are treated once they’re supported. Also elaborating the return type is not possible with the closure to async block ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=5340a05b0a17feba7309a80765b5edd9))<|endoftext|>Does this feature introduce an `AsyncFn` trait, similar to `core::ops::Fn`? I cannot find it in the RFC.<|endoftext|>What is the progress with async closures? Thanks.<|endoftext|>Could someone pls explain what are the **REAL** differences if i do:
1.
```
let handler = thread::spawn(async || {
// ....
});
```
vs 2.
```
let handler = thread::spawn(|| async {
// ....
});
```
vs 3.
```
let handler = thread::spawn(|| {
async {
// ....
}
});
```
Currently 1 gives me compiling error directly, i guess there is no difference between 2 and 3?<|endoftext|>@lnshi
Version 1 is an async closure.
Version 2 and 3 are identical, a normal closure that runs an async block.<|endoftext|>Aren't async closures just like normal closures but without the redundant `move` keyword? As in:
```rust
move | _ | async move { /* ... */}
```
vs
```rust
async move | _ | { /* ... */ }
```
is there any other difference other than this?<|endoftext|>@Inshi @tvallotton I wrote about a key draw of them in [this comment](https://www.reddit.com/r/rust/comments/pqajgf/_/hdbt7qw), which should help explain the difference.
---
In @Inshi's example there is no difference between 2 and 3. You get a compiler error on 1 because it isn't valid syntax yet.<|endoftext|>When will this become stable?<|endoftext|>How async closures would be expressed as a function parameter? i feel that
```rust
fn takes_async_closure<F: Future<Output = ()>>(_: impl Fn() -> F)
```
would be too verbose, something like `AsyncFn`, `AsyncFnMut` and `AsyncFnOnce` would be better.
Also, closures that return futures don't work well when a closure parameter is a reference.<|endoftext|>What's the current status of this issue? According to the description, it says only the stabilization is left. How can one help push this to stabilization?<|endoftext|>If this feature stable, will both of these code work like same:
1. without feature
```rust
async fn sayer() {
let mut hs = Vec::new();
for n in (0..5).rev() {
hs.push(tokio::spawn(sleep_n(n)));
}
for h in hs {
h.await.unwrap();
}
}
```
2. with feature
```rust
async fn sayer() {
let mut hs = Vec::new();
for n in (0..5).rev() {
hs.push(tokio::spawn(sleep_n(n)));
}
let _ = hs.into_iter().map(async |i| i.await.unwrap());
}
```<|endoftext|>> How async closures would be expressed as a function parameter? i feel that
>
> ```rust
> fn takes_async_closure<F: Future<Output = ()>>(_: impl Fn() -> F)
> ```
>
> would be too verbose, something like `AsyncFn`, `AsyncFnMut` and `AsyncFnOnce` would be better. Also, closures that return futures don't work well when a closure parameter is a reference.
Except from these potential keywords being added for convenience, is there any reason to not add async closures?<|endoftext|>> Aren't async closures just like normal closures but without the redundant `move` keyword? As in:
>
> ```rust
> move | _ | async move { /* ... */}
> ```
>
> vs
>
> ```rust
> async move | _ | { /* ... */ }
> ```
>
> is there any other difference other than this?
The first thing is a closure which returns parameterless async block.
The second one is the actual async closure.<|endoftext|>As @Nemo157 said in [their comment](https://github.com/rust-lang/rust/issues/62290#issuecomment-538782482)
> Despite "Implement the RFC" being checked this feature is still largely unimplemented
Why is this still incorrectly marked as implemented, 4 years later? | B-RFC-approved<|endoftext|>A-closures<|endoftext|>T-lang<|endoftext|>B-unstable<|endoftext|>B-RFC-implemented<|endoftext|>C-tracking-issue<|endoftext|>A-async-await<|endoftext|>AsyncAwait-Triaged<|endoftext|>F-async_closures<|endoftext|>requires-nightly<|endoftext|>S-tracking-needs-summary<|endoftext|>WG-async | 28 | https://api.github.com/repos/rust-lang/rust/issues/62290 | https://github.com/rust-lang/rust/issues/62290 | https://api.github.com/repos/rust-lang/rust/issues/62290/comments |
408,461,314 | 58,329 | Tracking issue for #[ffi_pure] | Annotates an extern C function with C [`pure`](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes) attribute. | This corresponds to the `readonly` LLVM attribute.<|endoftext|>Is this fully implemented and ready for potential stabilization, or is there any blocker? | A-ffi<|endoftext|>T-lang<|endoftext|>B-unstable<|endoftext|>C-tracking-issue<|endoftext|>S-tracking-needs-summary | 2 | https://api.github.com/repos/rust-lang/rust/issues/58329 | https://github.com/rust-lang/rust/issues/58329 | https://api.github.com/repos/rust-lang/rust/issues/58329/comments |
408,461,263 | 58,328 | Tracking issue for #[ffi_const] | Annotates an extern C function with C [`const`](https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes) attribute.
https://doc.rust-lang.org/beta/unstable-book/language-features/ffi-const.html | This corresponds to the LLVM `readnone` attribute.<|endoftext|>Is this fully implemented and ready for potential stabilization, or is there any blocker? | A-ffi<|endoftext|>T-lang<|endoftext|>B-unstable<|endoftext|>C-tracking-issue<|endoftext|>S-tracking-needs-summary | 2 | https://api.github.com/repos/rust-lang/rust/issues/58328 | https://github.com/rust-lang/rust/issues/58328 | https://api.github.com/repos/rust-lang/rust/issues/58328/comments |
376,960,106 | 55,628 | Tracking issue for `trait alias` implementation (RFC 1733) | This is the tracking issue for **implementing** (*not* discussing the design) RFC https://github.com/rust-lang/rfcs/pull/1733. It is a subissue of https://github.com/rust-lang/rust/issues/41517.
## Current status
Once #55101 lands, many aspects of trait aliases will be implemented. However, some known limitations remain. These are mostly pre-existing limitations of the trait checker that we intend to lift more generally (see each case below for notes).
**Well-formedness requirements.** We currently require the trait alias to be well-formed. So, for example, `trait Foo<T: Send> { } trait Bar<T> = Foo<T>` is an error. We intend to modify this behavior as part of implementing the implied bounds RFC (https://github.com/rust-lang/rust/issues/44491).
**Trait object associated types.** If you have `trait Foo = Iterator<Item =u32>`, you cannot use the trait object type `dyn Foo`. This is a duplicate of https://github.com/rust-lang/rust/issues/24010.
**Trait object equality.** If you have `trait Foo { }` and `trait Bar = Foo`, we do not currently consider `dyn Foo` and `dyn Bar` to be the same type. Tracking issue https://github.com/rust-lang/rust/issues/55629.
## Pending issues to resolve
- [x] https://github.com/rust-lang/rust/issues/56006 - ICE when used in a library crate
## Deviations and/or clarifications from the RFC
This section is for us to collect notes on deviations from the RFC text, or clarifications to unresolved questions.
## PR history
- [x] https://github.com/rust-lang/rust/pull/45047 by @durka
- [x] https://github.com/rust-lang/rust/pull/55101 by @alexreg
## Other links
- Test scenarios drawn up by @nikomatsakis from the RFC: [gist](https://gist.github.com/nikomatsakis/e4dd2807581fc868ba308382855e68f6) | Good summary. Thanks for writing this up.<|endoftext|>Have we considered blocking stabilization on lazy normalization?
That is, I'm worried that these are equivalent problems:
```rust
trait Foo<X> {}
type Bar<X: ExtraBound> = dyn Foo<X>;
fn bad<X>(_: &Bar<X>) {}
trait Foo2<X: ExtraBound> = Foo<X>;
fn bad2<X>(_: &dyn Foo2<X>) {}
```
The alternative, to consider `Foo2` its own trait, has its own issues, IMO.<|endoftext|>@eddyb Actually, they're not, under the current implementation, which is nice. The `X: ExtraBound` bound is enforced. [Example](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=fa657352533684a9764ea1f92bf6a900).<|endoftext|>@nikomatsakis I just realised you never got around to factoring out the part of my old PR https://github.com/rust-lang/rust/pull/55994 that banned multi-trait objects via trait aliases... did you still want to tackle that? | A-traits<|endoftext|>B-unstable<|endoftext|>B-RFC-implemented<|endoftext|>C-tracking-issue<|endoftext|>S-tracking-needs-summary<|endoftext|>T-types<|endoftext|>S-types-deferred | 4 | https://api.github.com/repos/rust-lang/rust/issues/55628 | https://github.com/rust-lang/rust/issues/55628 | https://api.github.com/repos/rust-lang/rust/issues/55628/comments |
End of preview. Expand
in Dataset Viewer.
- Downloads last month
- 42