about summary refs log tree commit diff
path: root/compiler
AgeCommit message (Collapse)AuthorLines
2022-02-15Auto merge of #93176 - danielhenrymantilla:stack-pinning-macro, r=m-ou-sebors-0/+4
Add a stack-`pin!`-ning macro to `core::pin`. - https://github.com/rust-lang/rust/issues/93178 `pin!` allows pinning a value to the stack. Thanks to being implemented in the stdlib, which gives access to `macro` macros, and to the private `.pointer` field of the `Pin` wrapper, [it was recently discovered](https://rust-lang.zulipchat.com/#narrow/stream/187312-wg-async-foundations/topic/pin!.20.E2.80.94.20the.20.22definitive.22.20edition.20.28a.20rhs-compatible.20pin-nin.2E.2E.2E/near/268731241) ([archive link](https://zulip-archive.rust-lang.org/stream/187312-wg-async-foundations/topic/A.20rhs-compatible.20pin-ning.20macro.html#268731241)), contrary to popular belief, that it is actually possible to implement and feature such a macro: ```rust let foo: Pin<&mut PhantomPinned> = pin!(PhantomPinned); stuff(foo); ``` or, directly: ```rust stuff(pin!(PhantomPinned)); ``` - For context, historically, this used to require one of the two following syntaxes: - ```rust let foo = PhantomPinned; pin!(foo); stuff(foo); ``` - ```rust pin! { let foo = PhantomPinned; } stuff(foo); ``` This macro thus allows, for instance, doing things like: ```diff fn block_on<T>(fut: impl Future<Output = T>) -> T { // Pin the future so it can be polled. - let mut fut = Box::pin(fut); + let mut fut = pin!(fut); // Create a new context to be passed to the future. let t = thread::current(); let waker = Arc::new(ThreadWaker(t)).into(); let mut cx = Context::from_waker(&waker); // Run the future to completion. loop { match fut.as_mut().poll(&mut cx) { Poll::Ready(res) => return res, Poll::Pending => thread::park(), } } } ``` - _c.f._, https://doc.rust-lang.org/1.58.1/alloc/task/trait.Wake.html And so on, and so forth. I don't think such an API can get better than that, barring full featured language support (`&pin` references or something), so I see no reason not to start experimenting with featuring this in the stdlib already 🙂 - cc `@rust-lang/wg-async-foundations` \[EDIT: this doesn't seem to have pinged anybody 😩, thanks `@yoshuawuyts` for the real ping\] r? `@joshtriplett` ___ # Docs preview https://user-images.githubusercontent.com/9920355/150605731-1f45c2eb-c9b0-4ce3-b17f-2784fb75786e.mp4 ___ # Implementation The implementation ends up being dead simple (so much it's embarrassing): ```rust pub macro pin($value:expr $(,)?) { Pin { pointer: &mut { $value } } } ``` _and voilà_! - The key for it working lies in [the rules governing the scope of anonymous temporaries](https://doc.rust-lang.org/1.58.1/reference/destructors.html#temporary-lifetime-extension). <details><summary>Comments and context</summary> This is `Pin::new_unchecked(&mut { $value })`, so, for starters, let's review such a hypothetical macro (that any user-code could define): ```rust macro_rules! pin {( $value:expr ) => ( match &mut { $value } { at_value => unsafe { // Do not wrap `$value` in an `unsafe` block. $crate::pin::Pin::<&mut _>::new_unchecked(at_value) }} )} ``` Safety: - `type P = &mut _`. There are thus no pathological `Deref{,Mut}` impls that would break `Pin`'s invariants. - `{ $value }` is braced, making it a _block expression_, thus **moving** the given `$value`, and making it _become an **anonymous** temporary_. By virtue of being anonynomous, it can no longer be accessed, thus preventing any attemps to `mem::replace` it or `mem::forget` it, _etc._ This gives us a `pin!` definition that is sound, and which works, but only in certain scenarios: - If the `pin!(value)` expression is _directly_ fed to a function call: `let poll = pin!(fut).poll(cx);` - If the `pin!(value)` expression is part of a scrutinee: ```rust match pin!(fut) { pinned_fut => { pinned_fut.as_mut().poll(...); pinned_fut.as_mut().poll(...); }} // <- `fut` is dropped here. ``` Alas, it doesn't work for the more straight-forward use-case: `let` bindings. ```rust let pinned_fut = pin!(fut); // <- temporary value is freed at the end of this statement pinned_fut.poll(...) // error[E0716]: temporary value dropped while borrowed // note: consider using a `let` binding to create a longer lived value ``` - Issues such as this one are the ones motivating https://github.com/rust-lang/rfcs/pull/66 This makes such a macro incredibly unergonomic in practice, and the reason most macros out there had to take the path of being a statement/binding macro (_e.g._, `pin!(future);`) instead of featuring the more intuitive ergonomics of an expression macro. Luckily, there is a way to avoid the problem. Indeed, the problem stems from the fact that a temporary is dropped at the end of its enclosing statement when it is part of the parameters given to function call, which has precisely been the case with our `Pin::new_unchecked()`! For instance, ```rust let p = Pin::new_unchecked(&mut <temporary>); ``` becomes: ```rust let p = { let mut anon = <temporary>; &mut anon }; ``` However, when using a literal braced struct to construct the value, references to temporaries can then be taken. This makes Rust change the lifespan of such temporaries so that they are, instead, dropped _at the end of the enscoping block_. For instance, ```rust let p = Pin { pointer: &mut <temporary> }; ``` becomes: ```rust let mut anon = <temporary>; let p = Pin { pointer: &mut anon }; ``` which is *exactly* what we want. Finally, we don't hit problems _w.r.t._ the privacy of the `pointer` field, or the unqualified `Pin` name, thanks to `decl_macro`s being _fully_ hygienic (`def_site` hygiene). </details> ___ # TODO - [x] Add compile-fail tests with attempts to break the `Pin` invariants thanks to the macro (_e.g._, try to access the private `.pointer` field, or see what happens if such a pin is used outside its enscoping scope (borrow error)); - [ ] Follow-up stuff: - [ ] Try to experiment with adding `pin!` to the prelude: this may require to be handled with some extra care, as it may lead to issues reminiscent of those of `assert_matches!`: https://github.com/rust-lang/rust/issues/82913 - [x] Create the tracking issue.
2022-02-15Auto merge of #93863 - pierwill:fix-93676, r=Mark-Simulacrumbors-4/+4
Update `sha1`, `sha2`, and `md-5` dependencies This replaces the deprecated [`cpuid-bool`](https://crates.io/crates/cpuid-bool) dependency with [`cpufeatures`](https://crates.io/crates/cpufeatures), while adding [`crypto-common`](https://crates.io/crates/crypto-common) as a new dependency. Closes #93676.
2022-02-15Auto merge of #93752 - eholk:drop-tracking-break-continue, r=nikomatsakisbors-10/+95
Generator drop tracking: improve break and continue handling This PR fixes two related issues. One, sometimes break or continue have a block target instead of an expression target. This seems to mainly happen with try blocks. Since the drop tracking analysis only works on expressions, if we see a block target for break or continue, we substitute the last expression of the block as the target instead. Two, break and continue were incorrectly being treated as the same, so continue would also show up as an exit from the loop or block. This patch corrects the way continue is handled by keeping a stack of loop entry points and uses those to find the target of the continue. Fixes #93197 r? `@nikomatsakis`
2022-02-14Update unsafe_pin_internals unstable version.Mara Bos-1/+1
2022-02-14Auto merge of #93652 - spastorino:fix-negative-overlap-check-regions, ↵bors-27/+86
r=nikomatsakis Fix negative overlap check regions r? `@nikomatsakis`
2022-02-14Mark `unsafe_pin_internals` as `incomplete`.Daniel Henry-Mantilla-0/+4
This thus still makes it technically possible to enable the feature, and thus to trigger UB without `unsafe`, but this is fine since incomplete features are known to be potentially unsound (labelled "may not be safe"). This follows from the discussion at https://github.com/rust-lang/rust/pull/93176#discussion_r799413561
2022-02-14reveal_defining_opaque_types field doesn't exist after rebaseSantiago Pastorino-1/+0
2022-02-14Inline loose_check fn on call siteSantiago Pastorino-11/+1
2022-02-14Add comments about outlives_envSantiago Pastorino-0/+7
2022-02-14Call the method fork instead of clone and add proper commentsSantiago Pastorino-3/+36
2022-02-14Properly check regions on negative overlap checkSantiago Pastorino-8/+34
2022-02-14Add debug calls for negative impls in coherenceSantiago Pastorino-4/+10
2022-02-14Move FIXME text to the right placeSantiago Pastorino-3/+3
2022-02-14Remove extra negative_impl_exists checkSantiago Pastorino-3/+1
2022-02-14Auto merge of #93298 - lcnr:issue-92113, r=cjgillotbors-149/+138
make `find_similar_impl_candidates` even fuzzier continues the good work of `@BGR360` in #92223. I might have overshot a bit and we're now slightly too fuzzy :sweat_smile: with this we can now also simplify `simplify_type`, which is nice :3
2022-02-14Auto merge of #93938 - BoxyUwU:fix_res_self_ty, r=lcnrbors-72/+91
Make `Res::SelfTy` a struct variant and update docs I found pattern matching on a `(Option<DefId>, Option<(DefId, bool)>)` to not be super readable, additionally the doc comments on the types in a tuple variant aren't visible anywhere at use sites as far as I can tell (using rust analyzer + vscode) The docs incorrectly assumed that the `DefId` in `Option<(DefId, bool)>` would only ever be for an impl item and I also found the code examples to be somewhat unclear about which `DefId` was being talked about. r? `@lcnr` since you reviewed the last PR changing these docs
2022-02-14further update `fuzzy_match_tys`lcnr-35/+53
2022-02-14fast_reject: remove `StripReferences`lcnr-68/+20
2022-02-14fuzzify `fuzzy_match_tys`lcnr-102/+38
2022-02-14Make `find_similar_impl_candidates` a little fuzzier.Ben Reeves-32/+115
2022-02-14Auto merge of #93937 - bjorn3:simplifications3, r=cjgillotbors-22/+4
Remove Config::stderr 1. It captured stdout and not stderr 2. It isn't used anywhere 3. All error messages should go to the DiagnosticOutput instead 4. It modifies thread local state Marking as blocked as it will conflict a bit with https://github.com/rust-lang/rust/pull/93936.
2022-02-13Update `sha1`, `sha2`, and `md5` dependenciespierwill-4/+4
This removes the `cpuid-bool` dependency, which is deprecated, while adding `crypto-common` as a new dependency.
2022-02-13rustc_target: Remove compiler-rt linking hack on AndroidVadim Petrochenkov-7/+1
2022-02-13Remove Config::stderrbjorn3-22/+4
1. It captured stdout and not stderr 2. It isn't used anywhere 3. All error messages should go to the DiagnosticOutput instead 4. It modifies thread local state
2022-02-13Rollup merge of #93936 - bjorn3:simplifications2, r=cjgillotMatthias Krüger-198/+157
Couple of driver cleanups * Remove the `RustcDefaultCalls` struct, which hasn't been necessary since the introduction of `rustc_interface`. * Move the `setup_callbacks` call around for a tiny code deduplication. * Remove the `SPAN_DEBUG` global as it isn't actually necessary.
2022-02-13Rollup merge of #93810 - matthewjasper:chalk-and-canonical-universes, r=jackh726Matthias Krüger-107/+243
Improve chalk integration - Support subtype bounds in chalk lowering - Handle universes in canonicalization - Handle type parameters in chalk responses - Use `chalk_ir::LifetimeData::Empty` for `ty::ReEmpty` - Remove `ignore-compare-mode-chalk` for tests that no longer hang (they may still fail or ICE) This is enough to get a hello world program to compile with `-Zchalk` now. Some of the remaining issues that are needed to get Chalk integration working on larger programs are: - rust-lang/chalk#234 - rust-lang/chalk#548 - rust-lang/chalk#734 - Generators are handled differently in chalk and rustc r? `@jackh726`
2022-02-13Rollup merge of #90532 - fee1-dead:improve-const-fn-err-msg, r=oli-obkMatthias Krüger-288/+550
More informative error message for E0015 Helps with #92380
2022-02-13Auto merge of #93670 - erikdesjardins:noundef, r=nikicbors-3/+18
Apply noundef attribute to &T, &mut T, Box<T>, bool This doesn't handle `char` because it's a bit awkward to distinguish it from `u32` at this point in codegen. Note that this _does not_ change whether or not it is UB for `&`, `&mut`, or `Box` to point to undef. It only applies to the pointer itself, not the pointed-to memory. Fixes (partially) #74378. r? `@nikic` cc `@RalfJung`
2022-02-12Auto merge of #91403 - cjgillot:inherit-async, r=oli-obkbors-88/+78
Inherit lifetimes for async fn instead of duplicating them. The current desugaring of `async fn foo<'a>(&usize) -> &u8` is equivalent to ```rust fn foo<'a, '0>(&'0 usize) -> foo<'static, 'static>::Opaque<'a, '0, '_>; type foo<'_a, '_0>::Opaque<'a, '0, '1> = impl Future<Output = &'1 u8>; ``` following the RPIT model. Duplicating all the inherited lifetime parameters and setting the inherited version to `'static` makes lowering more complex and causes issues like #61949. This PR removes the duplication of inherited lifetimes to directly use ```rust fn foo<'a, '0>(&'0 usize) -> foo<'a, '0>::Opaque<'_>; type foo<'a, '0>::Opaque<'1> = impl Future<Output = &'1 u8>; ``` following the TAIT model. Fixes https://github.com/rust-lang/rust/issues/61949
2022-02-12Address review commentMatthew Jasper-2/+5
canonicalize_chalk_query -> canonicalize_query_preserving_universes
2022-02-12trailing whitespaceEllen-6/+6
2022-02-12change docs on `Res::SelfTy`Ellen-27/+35
2022-02-12change to a struct variantEllen-48/+59
2022-02-12Remove SPAN_DEBUG globalbjorn3-40/+13
The only difference between the default and rustc_interface set version is that the default accesses the source map from SESSION_GLOBALS while the rustc_interface version accesses the source map from the global TyCtxt. SESSION_GLOBALS is always set while running the compiler while the global TyCtxt is not always set. If the global TyCtxt is set, it's source map is identical to the one in SESSION_GLOBALS
2022-02-12Move setup_callbacks call to create_compiler_and_runbjorn3-7/+6
This ensures that it is called even when run_in_thread_pool_with_globals is avoided and reduces code duplication between the parallel and non-parallel version of run_in_thread_pool_with_globals
2022-02-12Remove the RustcDefaultCalls structbjorn3-151/+138
It is a leftover from before the introduction of rustc_interface
2022-02-12Rollup merge of #93898 - GuillaumeGomez:error-code-check, r=Mark-SimulacrumMatthias Krüger-3/+5
tidy: Extend error code check We discovered in https://github.com/rust-lang/rust/pull/93845 that the error code tidy check didn't check everything: if you remove an error code from the listing even if it has an explanation, then it should error. It also allowed me to put back `E0192` in that listing as well. r? ```@Mark-Simulacrum```
2022-02-12Rollup merge of #93759 - dtolnay:usetree, r=nagisaMatthias Krüger-15/+39
Pretty print ItemKind::Use in rustfmt style This PR backports the formatting for `use` items from https://github.com/dtolnay/prettyplease into rustc_ast_pretty. Before: ```rust use core::{cmp::{Eq, Ord, PartialEq, PartialOrd}, convert::{AsMut, AsRef, From, Into}, iter::{DoubleEndedIterator, ExactSizeIterator, Extend, FromIterator, IntoIterator, Iterator}, marker::{Copy as Copy, Send as Send, Sized as Sized, Sync as Sync, Unpin as U}, ops::{*, Drop, Fn, FnMut, FnOnce}}; ``` After: ```rust use core::{ cmp::{Eq, Ord, PartialEq, PartialOrd}, convert::{AsMut, AsRef, From, Into}, iter::{ DoubleEndedIterator, ExactSizeIterator, Extend, FromIterator, IntoIterator, Iterator, }, marker::{ Copy as Copy, Send as Send, Sized as Sized, Sync as Sync, Unpin as U, }, ops::{*, Drop, Fn, FnMut, FnOnce}, }; ```
2022-02-12Rollup merge of #93595 - compiler-errors:ice-on-lifetime-arg, r=jackh726Matthias Krüger-3/+3
fix ICE when parsing lifetime as function argument I don't really like this, but we basically need to emit an error instead of just delaying an bug, because there are too many places in the AST that aren't covered by my previous PRs... cc: https://github.com/rust-lang/rust/issues/93282#issuecomment-1028052945
2022-02-12Report the selection error when possibleDeadbeef-15/+36
2022-02-12Adapt new changeDeadbeef-4/+11
2022-02-12Handle Fn family trait call errrorDeadbeef-6/+43
2022-02-12Rebased and improved errorsDeadbeef-7/+8
2022-02-12Improve error messages even moreDeadbeef-238/+432
2022-02-12More informative error message for E0015Deadbeef-49/+51
2022-02-12Auto merge of #93691 - compiler-errors:mir-tainted-by-errors, r=oli-obkbors-157/+229
Implement `tainted_by_errors` in MIR borrowck, use it to skip CTFE Putting this up for initial review. The issue that I found is when we're evaluating a const, we're doing borrowck, but doing nothing with the fact that borrowck fails. This implements a `tainted_by_errors` field for MIR borrowck like we have in infcx, so we can use that information to return an `Err` during const eval if our const fails to borrowck. This PR needs some cleaning up. I should probably just use `Result` in more places, instead of `.expect`ing in the places I am, but I just wanted it to compile so I could see if it worked! Fixes #93646 r? `@oli-obk` feel free to reassign
2022-02-12Auto merge of #93671 - Kobzol:stable-hash-const, r=the8472bors-46/+39
Use const generics in SipHasher128's short_write This was proposed by `@michaelwoerister` [here](https://github.com/rust-lang/rust/pull/93615#discussion_r799485554). A few comments: 1) I tried to pass `&[u8; LEN]` instead of `[u8; LEN]`. Locally, it resulted in small icount regressions (about 0.5 %). When passing by value, there were no regressions (and no improvements). 2) I wonder if we should use `to_ne_bytes()` in `SipHasher128` to keep it generic and only use `to_le_bytes()` in `StableHasher`. However, currently `SipHasher128` is only used in `StableHasher` and the `short_write` method was private, so I couldn't use it directly from `StableHasher`. Using `to_le()` in the `StableHasher` was breaking this abstraction boundary before slightly. ```rust debug_assert!(LEN <= 8); ``` This could be done at compile time, but actually I think that now we can remove this assert altogether. r? `@the8472`
2022-02-11Update expr.rsMichael Goulet-16/+8
Revert spurious changes included in PR
2022-02-12Bless nll tests.Camille GILLOT-0/+18
2022-02-12Update error code documentation.Camille GILLOT-3/+3