about summary refs log tree commit diff
path: root/compiler/rustc_borrowck
AgeCommit message (Collapse)AuthorLines
2023-11-08Auto merge of #117560 - lqd:issue-117146, r=matthewjasperbors-13/+14
Compute polonius loan scopes over the region graph In issue #117146 a loan flows into an SCC containing a placeholder, and whose representative is an existential region. Since we currently compute loan scopes by looking at SCCs and their representatives only, polonius would compute kill points for this loan here whereas NLLs would not of course. There are a few ways to fix this: - don't try to be efficient by doing the computation over SCCs, and simply look for free regions and placeholders in the successors of the issuing region. - change how the SCC representatives are picked, biasing towards placeholders over existential regions. They *shouldn't* matter much, but some downstream code may subtly depend on the current scheme (though no tests fail if we do such a change). This is for unrelated reasons also the way #116891 changes the representative computation. So that PR would also fix issue #117146. - try to remove placeholders from the main path, and contain them to a pre-pass + a post-pass kind of polonius leak check. If possible, it would fix this issue by turning an outlives constraints to a placeholder into a constraint to 'static. This should also fix the issue, as the representative would be the free region in the SCC. We want to prototype this change to see if it's possible to try to simplify the borrowck main path from having to deal with placeholders and higher-ranked subtyping 🤞. I'd like to take advantage of fuzzing and a crater run sooner rather than later, so that we grow more confidence that the 2 models are indeed equivalent empirically. Therefore this PR implements option 1 to fix the issue now. We can take care of efficiency later after validation, and once we implement option 3 (which could also impact option 2 and that associated PR, maybe the lack of placeholders could remove the need to change the representative computation) to traverse SCCs and their representative again. (Or we maybe will have some kind of naive position-dependent outlives propagation by then and this code would have been changed) Fixes #117146. r? `@matthewjasper`
2023-11-07Auto merge of #117511 - gurry:117406-err-packed-structs, r=compiler-errorsbors-1/+19
Emit explanatory note for move errors in packed struct derives Derive expansions for packed structs with non-`Copy` fields cause move errors because they prefer copying over borrowing since borrowing the fields of a packed struct can result in unaligned access. This underlying cause of the errors, however, is not apparent to the user. This PR adds a diagnostic note to make it clear to the user (the new note is on the second last line): ``` tests/ui/derives/deriving-with-repr-packed-move-errors.rs:13:16 | 12 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Default)] | ----- in this derive macro expansion 13 | struct StructA(String); | ^^^^^^ move occurs because `self.0` has type `String`, which does not implement the `Copy` trait | = note: `#[derive(Debug)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour = note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info) ``` Fixes #117406 Partially addresses #110777
2023-11-04traverse region graph instead of SCCs to compute polonius loan scopesRémy Rakic-13/+14
By using SCC for better performance, we also have to take into account SCCs whose representative is an existential region but also contains a placeholder. By only checking the representative, we may miss that the loan escapes the function. This can be fixed by picking a better representative, or removing placeholders from the main path. This is the simplest fix: forgo efficiency and traverse the region graph instead of the SCCs.
2023-11-03Emit explanatory note for move errors in packed struct derivesGurinder Singh-1/+19
Derive expansions for packed structs cause move errors because they prefer copying over borrowing since borrowing the fields of a packed struct can result in unaligned access and therefore undefined behaviour. This underlying cause of the errors, however, is not apparent to the user. We add a diagnostic note here to remedy that.
2023-11-02Minimize `pub` usage in `source_map.rs`.Nicholas Nethercote-3/+2
Most notably, this commit changes the `pub use crate::*;` in that file to `use crate::*;`. This requires a lot of `use` items in other crates to be adjusted, because everything defined within `rustc_span::*` was also available via `rustc_span::source_map::*`, which is bizarre. The commit also removes `SourceMap::span_to_relative_line_string`, which is unused.
2023-10-31prepopulate opaque ty storage before using it :>lcnr-6/+8
2023-10-30Rollup merge of #117357 - tmiasko:terminate, r=wesleywiserGuillaume Gomez-1/+1
Rename a few remaining references to abort terminator Follow up to e3f2edc75bf2becb57d7d770bba20606da1c4224
2023-10-30Clean up `rustc_*/Cargo.toml`.Nicholas Nethercote-6/+6
- Sort dependencies and features sections. - Add `tidy` markers to the sorted sections so they stay sorted. - Remove empty `[lib`] sections. - Remove "See more keys..." comments. Excluded files: - rustc_codegen_{cranelift,gcc}, because they're external. - rustc_lexer, because it has external use. - stable_mir, because it has external use.
2023-10-29Auto merge of #116733 - compiler-errors:alias-liveness-but-this-time-sound, ↵bors-20/+23
r=aliemjay Consider alias bounds when computing liveness in NLL (but this time sound hopefully) This is a revival of #116040, except removing the changes to opaque lifetime captures check to make sure that we're not triggering any unsoundness due to the lack of general existential regions and the currently-existing `ReErased` hack we use instead. r? `@aliemjay` -- I appreciate you pointing out the unsoundenss in the previous iteration of this PR, and I'd like to hear that you're happy with this iteration of this PR before this goes back into FCP :> Fixes #116794 as well --- (mostly copied from #116040 and reworked slightly) # Background Right now, liveness analysis in NLL is a bit simplistic. It simply walks through all of the regions of a type and marks them as being live at points. This is problematic in the case of aliases, since it requires that we mark **all** of the regions in their args[^1] as live, leading to bugs like #42940. In reality, we may be able to deduce that fewer regions are allowed to be present in the projected type (or "hidden type" for opaques) via item bounds or where clauses, and therefore ideally, we should be able to soundly require fewer regions to be live in the alias. For example: ```rust trait Captures<'a> {} impl<T> Captures<'_> for T {} fn capture<'o>(_: &'o mut ()) -> impl Sized + Captures<'o> + 'static {} fn test_two_mut(mut x: ()) { let _f1 = capture(&mut x); let _f2 = capture(&mut x); //~^ ERROR cannot borrow `x` as mutable more than once at a time } ``` In the example above, we should be able to deduce from the `'static` bound on `capture`'s opaque that even though `'o` is a captured region, it *can never* show up in the opaque's hidden type, and can soundly be ignored for liveness purposes. # The Fix We apply a simple version of RFC 1214's `OutlivesProjectionEnv` and `OutlivesProjectionTraitDef` rules to NLL's `make_all_regions_live` computation. Specifically, when we encounter an alias type, we: 1. Look for a unique outlives bound in the param-env or item bounds for that alias. If there is more than one unique region, bail, unless any of the outlives bound's regions is `'static`, and in that case, prefer `'static`. If we find such a unique region, we can mark that outlives region as live and skip walking through the args of the opaque. 2. Otherwise, walk through the alias's args recursively, as we do today. ## Limitation: Multiple choices This approach has some limitations. Firstly, since liveness doesn't use the same type-test logic as outlives bounds do, we can't really try several options when we're faced with a choice. If we encounter two unique outlives regions in the param-env or bounds, we simply fall back to walking the opaque via its args. I expect this to be mostly mitigated by the special treatment of `'static`, and can be fixed in a forwards-compatible by a more sophisticated analysis in the future. ## Limitation: Opaque hidden types Secondly, we do not employ any of these rules when considering whether the regions captured by a hidden type are valid. That causes this code (cc #42940) to fail: ```rust trait Captures<'a> {} impl<T> Captures<'_> for T {} fn a() -> impl Sized + 'static { b(&vec![]) } fn b<'o>(_: &'o Vec<i32>) -> impl Sized + Captures<'o> + 'static {} ``` We need to have existential regions to avoid [unsoundness](https://github.com/rust-lang/rust/pull/116040#issuecomment-1751628189) when an opaque captures a region which is not represented in its own substs but which outlives a region that does. ## Read more Context: https://github.com/rust-lang/rust/pull/115822#issuecomment-1731153952 (for the liveness case) More context: https://github.com/rust-lang/rust/issues/42940#issuecomment-455198309 (for the opaque capture case, which this does not fix) [^1]: except for bivariant region args in opaques, which will become less relevant when we move onto edition 2024 capture semantics for opaques.
2023-10-29Auto merge of #116447 - oli-obk:gen_fn, r=compiler-errorsbors-6/+32
Implement `gen` blocks in the 2024 edition Coroutines tracking issue https://github.com/rust-lang/rust/issues/43122 `gen` block tracking issue https://github.com/rust-lang/rust/issues/117078 This PR implements `gen` blocks that implement `Iterator`. Most of the logic with `async` blocks is shared, and thus I renamed various types that were referring to `async` specifically. An example usage of `gen` blocks is ```rust fn foo() -> impl Iterator<Item = i32> { gen { yield 42; for i in 5..18 { if i.is_even() { continue } yield i * 2; } } } ``` The limitations (to be resolved) of the implementation are listed in the tracking issue
2023-10-29Rename a few remaining references to abort terminatorTomasz MiÄ…sko-1/+1
Follow up to e3f2edc75bf2becb57d7d770bba20606da1c4224
2023-10-27Use targetted diagnostic for borrow across yield errorOli Scherer-1/+2
2023-10-27Handle `move` generatorsOli Scherer-5/+11
2023-10-26Quietly fail if an error has already occurredOli Scherer-2/+3
2023-10-26Add hir::GeneratorKind::GenOli Scherer-0/+19
2023-10-25Rename `AsyncCoroutineKind` to `CoroutineSource`Oli Scherer-6/+6
similar to how we have `MatchSource`, it explains where the desugaring came from.
2023-10-24Rollup merge of #116792 - JonasAlaif:renumber-fix, r=b-naberMatthias Krüger-0/+4
Avoid unnecessary renumbering during borrowck Currently, after renumbering there are always unused `RegionVid`s if the return type contains any regions, this is due to `visit_ty` being called twice on the same `Ty`: once with `TyContext::ReturnTy` and once with `TyContext::LocalDecl { local: _0 }`. This PR skips renumbering the first time around.
2023-10-24Auto merge of #116300 - cjgillot:split-move, r=petrochenkovbors-119/+280
Separate move path tracking between borrowck and drop elaboration. The primary goal of this PR is to skip creating a `MovePathIndex` for path that do not need dropping in drop elaboration. The 2 first commits are cleanups. The next 2 commits displace `move` errors from move-path builder to borrowck. Move-path builder keeps the same logic, but does not carry error information any more. The remaining commits allow to filter `MovePathIndex` creation according to types. This is used in drop elaboration, to avoid computing dataflow for paths that do not need dropping.
2023-10-23Rollup merge of #116859 - Nilstrieb:more-more-funny-pretty-printers, r=oli-obkMatthias Krüger-2/+4
Make `ty::print::Printer` take `&mut self` instead of `self` based on #116815 This simplifies the code by removing all the `self` assignments and makes the flow of data clearer - always into the printer. Especially in v0 mangling, which already used `&mut self` in some places, it gets a lot more uniform.
2023-10-23Rollup merge of #116960 - lqd:applied-member-constraints-scope, r=matthewjasperMatthias Krüger-18/+21
Location-insensitive polonius: consider a loan escaping if an SCC has member constraints applied only The location-insensitive analysis considered loans to escape if there were member constraints, which makes *some* sense for scopes and matches the scopes that NLL computes on all the tests. However, polonius and NLLs differ on the fuzzed case #116657, where an SCC has member constraints but no applied ones (and is kinda surprising). The existing UI tests with member constraints impacting scopes all have some constraint applied. This PR changes the location-insensitive analysis to consider a loan to escape if there are applied member constraints, and for extra paranoia/insurance via fuzzing and crater: actually checks the constraint's min choice is indeed a universal region as we expect. (This could be turned into a `debug_assert` and early return as a slight optimization after these periods of verification) The 4 UI tests where member constraints are meaningful for computing scopes still pass obviously, and this also fixes #116657. r? `@matthewjasper`
2023-10-21Remove redundant checks.Camille GILLOT-16/+2
2023-10-21Parametrize gather_moves by filter.Camille GILLOT-2/+2
2023-10-21Stop computing error info in move path builder.Camille GILLOT-7/+24
2023-10-21Avoid using a magic value for untracked locals.Camille GILLOT-6/+9
2023-10-21Do not report errors from move path builder.Camille GILLOT-112/+267
2023-10-21Make `ty::print::Printer` take `&mut self` instead of `self`Nilstrieb-2/+4
This simplifies the code by removing all the `self` assignments and makes the flow of data clearer - always into the printer. Especially in v0 mangling, which already used `&mut self` in some places, it gets a lot more uniform.
2023-10-21Rollup merge of #116990 - estebank:issue-68445, r=cjgillotMatthias Krüger-0/+22
Mention `into_iter` on borrow errors suggestions when appropriate If we encounter a borrow error on `vec![1, 2, 3].iter()`, suggest `into_iter`. Fix #68445.
2023-10-20Rename `CoroutineKind::Gen` to `::Coroutine`Oli Scherer-2/+2
2023-10-20s/generator/coroutine/Oli Scherer-125/+125
2023-10-20s/Generator/Coroutine/Oli Scherer-69/+69
2023-10-20consider a loan escapes the function via applied member constraintsRémy Rakic-12/+14
2023-10-20Mention `into_iter` on borrow errors suggestions when appropriateEsteban Küber-0/+22
If we encounter a borrow error on `vec![1, 2, 3].iter()`, suggest `into_iter`. Fix #68445.
2023-10-19make `applied_member_constraints` accept an SCC instead of a regionRémy Rakic-6/+7
2023-10-18revert rust-lang/rust#114586Ali MJ Al-Nasrawy-20/+13
2023-10-17Auto merge of #116822 - notriddle:notriddle/rust-logo, r=fmeasebors-1/+3
docs: add Rust logo to more compiler crates c6e6ecb1afea9695a42d0f148ce153536b279eb5 added it to some of the compiler's crates, but avoided adding it to all of them to reduce bit-rot. This commit adds to more. r? `@GuillaumeGomez`
2023-10-17Use a visitor that could be reused by opaque type capture check laterMichael Goulet-99/+13
2023-10-16docs: add Rust logo to more compiler cratesMichael Howell-1/+3
c6e6ecb1afea9695a42d0f148ce153536b279eb5 added it to some of the compiler's crates, but avoided adding it to all of them to reduce bit-rot. This commit adds to more.
2023-10-16Remove `DefiningAnchor::Bubble` from opaque wf checkMichael Goulet-8/+8
2023-10-16Avoid unnecessary renumberingJonáš Fiala-0/+4
2023-10-14Consider static speciallyMichael Goulet-8/+20
2023-10-14Consider param-env candidates, tooMichael Goulet-1/+21
2023-10-14Consider alias bounds when considering lliveness for alias types in NLLMichael Goulet-19/+76
2023-10-13Format all the let chains in compilerMichael Goulet-195/+183
2023-10-12Auto merge of #113487 - estebank:sugg-113174, r=oli-obkbors-23/+149
Use structured suggestion for #113174 When encountering a for loop that is rejected by the borrow checker because it is being advanced within its body, provide a structured suggestion for `while let Some(pat) = iter.next()`.
2023-10-11Use structured suggestion for #113174Esteban Küber-23/+149
When encountering a for loop that is rejected by the borrow checker because it is being advanced within its body, provide a structured suggestion for `while let Some(pat) = iter.next()`.
2023-10-11Auto merge of #113218 - lqd:polonius-scopes, r=jackh726bors-34/+360
Compute NLL loan scopes using the polonius model For a *location-insensitive* analysis (that is, without expressiveness improvements for users yet), this PR implements loans going out of scope using reachability and liveness, rather than checking if the issuing region's values contain a given CFG point. This is equivalent to NLL scopes and computes the same data. r? `@matthewjasper` A couple of notes: - there are some assumptions about SCC representatives, placeholders, free regions, and member constraints that I believe hold, and they're documented in the code - this passes all the UI tests with `-Zpolonius=next` -- the perf is [not terrible](https://github.com/rust-lang/rust/pull/112432#issuecomment-1749685862) and there are a bunch of ways to improve it in the future. - there's a fixme left, hopefully Matthew you know a clean way to get the information it mentions.
2023-10-06Auto merge of #114811 - estebank:impl-ambiguity, r=wesleywiserbors-1/+1
Show more information when multiple `impl`s apply - When there are `impl`s without type params, show only those (to avoid showing overly generic `impl`s). ``` error[E0283]: type annotations needed --> $DIR/multiple-impl-apply.rs:34:9 | LL | let y = x.into(); | ^ ---- type must be known at this point | note: multiple `impl`s satisfying `_: From<Baz>` found --> $DIR/multiple-impl-apply.rs:14:1 | LL | impl From<Baz> for Bar { | ^^^^^^^^^^^^^^^^^^^^^^ ... LL | impl From<Baz> for Foo { | ^^^^^^^^^^^^^^^^^^^^^^ = note: required for `Baz` to implement `Into<_>` help: consider giving `y` an explicit type | LL | let y: /* Type */ = x.into(); | ++++++++++++ ``` - Lower the importance of `T: Sized`, `T: WellFormed` and coercion errors, to prioritize more relevant errors. The pre-existing deduplication logic deals with hiding redundant errors better that way, and we show errors with more metadata that is useful to the user. - Show `<SelfTy as Trait>::assoc_fn` suggestion in more cases. ``` error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type --> $DIR/cross-return-site-inference.rs:38:16 | LL | return Err(From::from("foo")); | ^^^^^^^^^^ cannot call associated function of trait | help: use a fully-qualified path to a specific available implementation | LL | return Err(</* self type */ as From>::from("foo")); | +++++++++++++++++++ + ``` Fix #88284.
2023-10-05compute NLL loan scopes with liveness in `-Zpolonius=next`Rémy Rakic-28/+339
2023-10-05allow access to liveness' `PointIndex`esRémy Rakic-0/+5
2023-10-05add note why a function is pubRémy Rakic-0/+1