Use structured suggestion when telling user about `for<'a>`
```
error[E0637]: `&` without an explicit lifetime name cannot be used here
--> $DIR/E0637.rs:13:13
|
LL | T: Into<&u32>,
| ^ explicit lifetime name needed here
|
help: consider introducing a higher-ranked lifetime here
|
LL | T: for<'a> Into<&'a u32>,
| +++++++ ++
```
Encode item bounds for `DefKind::ImplTraitPlaceholder`
This was lost in a refactoring -- `hir::ItemKind::OpaqueTy` doesn't always map to `DefKind::Opaque`, specifically for RPITITs, so the check was migrated subtly wrong, and unfortunately I never had a test for this 🙃Fixes#113155
r? ``@cjgillot``
Account for late-bound vars from parent arg-position impl trait
We should be reporting an error like we do for late-bound args coming from a parent APIT.
Fixes#113016
suggest `slice::swap` for `mem::swap(&mut x[0], &mut x[1])` borrowck error
Recently saw someone ask why this code (example slightly modified):
```rs
fn main() {
let mut foo = [1, 2];
std::mem::swap(&mut foo[0], &mut foo[1]);
}
```
triggers this error and how to fix it:
```
error[E0499]: cannot borrow `foo[_]` as mutable more than once at a time
--> src/main.rs:4:33
|
4 | std::mem::swap(&mut foo[0], &mut foo[1]);
| -------------- ----------- ^^^^^^^^^^^ second mutable borrow occurs here
| | |
| | first mutable borrow occurs here
| first borrow later used by call
|
= help: consider using `.split_at_mut(position)` or similar method to obtain two mutable non-overlapping sub-slices
```
The current help message is nice and goes in the right direction, but I think we can do better for this specific instance and suggest `slice::swap`, which makes this compile
```
error[E0637]: `&` without an explicit lifetime name cannot be used here
--> $DIR/E0637.rs:13:13
|
LL | T: Into<&u32>,
| ^ explicit lifetime name needed here
|
help: consider introducing a higher-ranked lifetime here
|
LL | T: for<'a> Into<&'a u32>,
| +++++++ ++
```
This patch adds the `#[rustc_coinductive]` annotation to
`BikeshedIntrinsicFrom`, so that it's possible to compute transmutability for
recursive types.
Normalize opaques with late-bound vars again
We have a hack in the compiler where if an opaque has escaping late-bound vars, we skip revealing it even though we *could* reveal it from a technical perspective. First of all, this is weird, since we really should be revealing all opaques in `Reveal::All` mode. Second of all, it causes subtle bugs (linked below).
I attempted to fix this in #100980, which was unfortunately reverted due to perf regressions on codebases that used really deeply nested futures in some interesting ways. The worst of which was #103423, which caused the project to hang on build. Another one was #104842, which was just a slow-down, but not a hang. I took some time afterwards to investigate how to rework `normalize_erasing_regions` to take advantage of better caching, but that effort kinda fizzled out (#104133).
However, recently, I was made aware of more bugs whose root cause is not revealing opaques during codegen. That made me want to fix this again -- in the process, interestingly, I took the the minimized example from https://github.com/rust-lang/rust/issues/103423#issuecomment-1292947043, and it doesn't seem to hang any more...
Thinking about this harder, there have been some changes to the way we lower and typecheck async futures that may have reduced the pathologically large number of outlives obligations (see description of #103423) that we were encountering when normalizing opaques with bound vars the last time around:
* #104321 (lower `async { .. }` directly as a generator that implements `Future`, removing the `from_generator` shim)
* #104833 (removing an `identity_future` fn that was wrapping desugared future generators)
... so given that I can see:
* No significant regression on rust perf bot (https://github.com/rust-lang/rust/pull/107620#issuecomment-1600070317)
* No timeouts in crater run I did (https://github.com/rust-lang/rust/pull/107620#issuecomment-1605428952, rechecked failing crates in https://github.com/rust-lang/rust/pull/107620#issuecomment-1605973434)
... and given that this PR:
* Fixes#104601
* Fixes#107557
* Fixes#109464
* Allows us to remove a `DefiningAnchor::Bubble` from codegen (75a8f68183)
I'm inclined to give this another shot at landing this. Best case, it just works -- worst case, we get more examples to study how we need to improve the compiler to make this work.
r? types
`early_warn` is called
Skip `colored-session-opt-error.rs` on Windows hosts
This is very cursed as to why it fails on Windows CI specifically:
- The test emits a *warning*.
- *Warnings*, and only warnings *specifically*, have a different
256-color between Windows and non-Windows hosts (other levels
`set_intense(true)` unconditionally):
e69c7306e2/compiler/rustc_errors/src/lib.rs (L1792-L1794)
Therefore, I added `// ignore-windows` test header to skip this test on
Windows (it's sufficient to test color is enabled on at least one
non-Windows host).
Convert `run-make/coverage-reports` tests to use a custom compiletest mode
I was frustrated by the fact that most of the coverage tests are glued together with makefiles and shell scripts, so I tried my hand at converting most of them over to a newly-implemented `run-coverage` mode/suite in compiletest.
This ~~*mostly*~~ resolves#85009, ~~though I've left a small number of the existing tests as-is because they would require more work to fix/support~~.
---
I had time to go back and add support for the more troublesome tests that I had initially skipped over, so this PR now manages to completely get rid of `run-make/coverage-reports`.
---
The patches are arranged as follows:
- Declare the new mode/suite in bootstrap
- Small changes to compiletest that will be used by the new mode
- Implement the new mode in compiletest
- Migrate most of the tests over
- Add more code to bootstrap and compiletest to support the remaining tests
- Migrate the remaining tests (with some temporary hacks to avoid re-blessing them)
- Remove the temporary hacks and re-bless the migrated tests
- Remove the unused remnants of `run-make/coverage-reports`
Setting `RUSTC_LOG_COLOR=always` is sometimes useful if tools that one
pipes `RUSTC_LOG` into support coloured output, but it makes this test
fail.
Signed-off-by: David Wood <david@davidtw.co>
Rollup of 5 pull requests
Successful merges:
- #112946 (Improve cgu naming and ordering)
- #113048 (Fix build on Solaris where fd-lock cannot be used.)
- #113100 (Fix display of long items in search results)
- #113107 (add check for ConstKind::Value(_) to in_operand())
- #113119 (rustdoc: Reduce internal function visibility.)
r? `@ghost`
`@rustbot` modify labels: rollup
Test that we require implementing trait items whose bounds don't hold in the current impl
I initially tried to make most of these pass, but that's a big can of worms, so I'm just adding them as tests, considering we have no tests for these things.
Make associated type bounds in supertrait position implied
`trait A: B<Assoc: C> {}` should be able to imply both `Self: B` and `<Self as B>::Assoc: C`. Adjust the way that we collect implied predicates to do so.
Fixes#112573Fixes#112568
add check for ConstKind::Value(_) to in_operand()
Added check for valtree value to close#113012 which fixes the issue, although I am not sure if adding the check there is sound or not cc `@oli-obk`
add note for non-exhaustive matches with guards
Associated issue: #92197
When a match statement includes guards on every match arm (and is therefore necessarily non-exhaustive), add a note to the error E0004 diagnostic noting this.
Validate fluent variable references in tests
Closes#101109
Under `cfg(test)`, the `fluent_messages` macro will emit a list of variables referenced by each message and its attributes. The derive attribute will now emit a `#[test]` that checks that each referenced variable exists in the structure it's applied to.
To make it easier to verify that the output snapshots have been migrated
faithfully, this change adds some temporary helper code that lets us avoid
having to completely re-bless the existing snapshots.
A later change in this PR will then re-bless the tests and remove the temporary
helper code.
mir opt + codegen: handle subtyping
fixes#107205
the same issue was caused in multiple places:
- mir opts: both copy and destination propagation
- codegen: assigning operands to locals (which also propagates values)
I changed codegen to always update the type in the operands used for locals which should guard against any new occurrences of this bug going forward. I don't know how to make mir optimizations more resilient here. Hopefully the added tests will be enough to detect any trivially wrong optimizations going forward.
Add tests impl via obj unless denied
Fixes#112737
Add simple tests to check feature change in #112320 is performing as expected.
Note:
- Unsure about filenames, locations & function signature names (tried to make them something sensible)
Make `UnwindAction::Continue` explicit in MIR dump
Makes it easier to spot unwinding related issues in MIR by making `UnwindAction::Continue` explicit, just like all other `UnwindAction`s.
Make compiletest aware of targets without dynamic linking
Some parts of the compiletest internals and some tests require dynamic linking to work, which is not supported by all targets. Before this PR, this was handled by if branches matching on the target name.
This PR loads whether a target supports dynamic linking or not from the target spec, and adds a `// needs-dynamic-linking` attribute for tests that require it. Note that I was not able to replace all the old conditions based on the target name, as some targets have `dynamic_linking: true` in their spec but pretend they don't have it in compiletest.
Also, to get this to work I had to *partially* revert #111472 (cc `@djkoloski` `@tmandry` `@bjorn3).` On one hand, only the target spec contains whether a target supports dynamic linking, but on the other hand a subset of the fields can be overridden through `-C` flags (as far as I'm aware only `-C panic=$strategy`). The solution I came up with is to take the target spec as the base, and then override the panic strategy based on `--print=cfg`. Hopefully that should not break y'all again.
rustdoc: render generic params & where-clauses of cross-crate assoc tys in impls
We used to only ever render generic parameters & where-clauses of cross-crate associated types when the item was located inside of a trait and we used to just drop them when it was inside of an impl block (trait or inherent).
Fixes#112904.
`@rustbot` label A-cross-crate-reexports
`hir`: Add `Become` expression kind (explicit tail calls experiment)
This adds `hir::ExprKind::Become` alongside ast lowering. During hir-thir lowering we currently lower `become` as `return`, so that we can partially test `become` without ICEing.
cc `@scottmcm`
r? `@Nilstrieb`
Rollup of 5 pull requests
Successful merges:
- #112976 (Add test for futures with HRTB)
- #113013 (rustdoc: get rid of extra line when line-wrapping fn decls with empty arg list)
- #113030 (Add a regression test for #109071)
- #113031 (Add a regression test for #110933)
- #113036 (Accept `ReStatic` for RPITIT)
r? `@ghost`
`@rustbot` modify labels: rollup
rustdoc: handle assoc const equalities in cross-crate impl-Trait-in-arg-pos
Fixes FIXME (the added test previously lead to an ICE).
`@rustbot` label A-cross-crate-reexports
Revert "Structurally resolve correctly in check_pat_lit"
This reverts commit 54fb5a48b9. Also adds a couple of tests, and downgrades the existing `-Ztrait-solver=next` test to a known-bug.
Fixes#112993
Fix test for #96258#98644 did not properly test enabling the problematic lint as a warning due to improper use of `compile-flags:` (missing `:`). This makes it use `#![warn]` instead, like in the reproducer.
cc #96258
rustdoc: Align search results horizontally for easy scanning
The recent PR #110688 added info about an item's kind before its name in
search results. However, because the kind and name are inline with no
alignment, it's now hard to visually scan downward through the search
results, looking at item names. This PR fixes that by horizontally
aligning search results such that there are now two columns of
information.
r? `@GuillaumeGomez`
[-Ztrait-solver=next, mir-typeck] instantiate hidden types in the root universe
Fixes an ICE in the test `member-constraints-in-root-universe`.
Main motivation is to make #112691 pass under the new solver.
r? ``@compiler-errors``
Fix return type notation associated type suggestion when -Zlower-impl-trait-in-trait-to-assoc-ty
This avoid suggesting the associated types generated for RPITITs when the one the code refers to doesn't exist and rustc looks for a suggestion.
r? `@compiler-errors`
Fix return type notation errors with -Zlower-impl-trait-in-trait-to-assoc-ty
This just adjust the way we check for RPITITs and uses the new helper method to do the "old" and "new" check at once.
r? `@compiler-errors`
Don't emit same goal as input during `wf::unnormalized_obligations`
r? `@aliemjay` cc `@lcnr`
I accidentally pruned the logic to handle `WF(?0)` when writing `wf::unnormalized_obligations`.
idk if you wanted to construct a test first, but this is an obvious fix. Copied the comment from above.
Fixesrust-lang/trait-system-refactor-initiative#36
Implement `Sync` for `mpsc::Sender`
`mpsc::Sender` is currently `!Sync` because the previous implementation contained an optimization where the channel started out as single-producer and was dynamically upgraded on the first clone, which relied on a unique reference to the sender. This optimization is one of the main reasons the old implementation was so complex and was removed in #93563. `mpsc::Sender` can now soundly implement `Sync`.
Note for any potential confusion, this chance does *not* add MPMC behavior. This only affects the already `Send + Clone` *sender*, not *receiver*.
It's technically possible to rely on the `!Sync` behavior in the same way as a `PhantomData<*mut T>`, but that seems very unlikely in practice. Either way, this change is insta-stable and needs an FCP.
`@rustbot` label +T-libs-api -T-libs
Various impl trait in assoc tys cleanups
r? `@compiler-errors`
All commits except for the last are pure refactorings. 274dab5bd658c97886a8987340bf50ae57900c39 allows struct fields to participate in deciding whether a function has an opaque in its signature.
best reviewed commit by commit
Fix rustdoc gui tester
Problem was that the `main` was always exiting with `0`, whether or not there was an error. It led to failing GUI tests being ignored in the CI since no one saw them.
r? ````@klensy````
[tests/rustdoc] Add @files command
The ``````@!has`````` checks is very problematic as it wouldn't catch if the file scheme is updated and the file is generated again. ``````@files`````` allows to ensure that the given folder contains exactly the provided entries (files and folders).
I'm wondering if we should forbid the ``````@!has`````` for files. To be discussed after this PR I suppose.
r? `````@notriddle`````
Stop hiding const eval limit in external macros
fixes#112748
We don't emit a hard error if there was a previous deny lint triggering with the same message. If that lint ends up not being emitted, we ICE and don't emit an error either.
Don't ICE on unnormalized struct tail in layout computation
1. We try to compute a `SizeSkeleton` even if a layout error occurs, but we really only need to do this if we get `LayoutError::Unknown`, since that means our type is too polymorphic to actually compute the full layout. If we have other errors, like `LayoutError::NormalizationError` or `LayoutError::Cycle`, then we can't really make any progress, since this represents an actual error.
2. Avoid using `normalize_erasing_regions` and `struct_tail_erasing_lifetimes` since those ICE on normalization errors, and since we may call `layout_of` in HIR typeck, we don't know for certain that we're on the happy path.
Fixes#112736
Always register sized obligation for argument
Removes a "hack" that skips registering sized obligations for parameters that are simple identifiers. This doesn't seem to affect diagnostics because we're probably already being smart enough about deduplicating identical error messages anyways.
Fixes#112608
rustc_session: default to -Z plt=yes on non-x86_64
Per the discussion in #106380 plt=no isn't a great default, and rust-lang/compiler-team#581 decided that the default should be PLT=yes for everything except x86_64. Not everyone agrees about the x86_64 part of this change, but this at least is an improvement in the state of things without changing the x86_64 situation, so I've attempted making this change in the name of not letting the perfect be the enemy of the good.
Please let me know if I've messed this up somehow - I'm not wholly confident I got this right.
r? `@nikic`
Avoid guessing unknown trait implementation in suggestions
When a trait is used without specifying the implementation (e.g. calling a non-member associated function without fully-qualified syntax) and there are multiple implementations available, use a placeholder comment for the implementation type in the suggestion instead of picking a random implementation.
Example:
```
fn main() {
let _ = Default::default();
}
```
Previous output:
```
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
--> test.rs:2:13
|
2 | let _ = Default::default();
| ^^^^^^^^^^^^^^^^ cannot call associated function of trait
|
help: use a fully-qualified path to a specific available implementation (273 found)
|
2 | let _ = <FileTimes as Default>::default();
| +++++++++++++ +
```
New output:
```
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
--> test.rs:2:13
|
2 | let _ = Default::default();
| ^^^^^^^^^^^^^^^^ cannot call associated function of trait
|
help: use a fully-qualified path to a specific available implementation (273 found)
|
2 | let _ = </* self type */ as Default>::default();
| +++++++++++++++++++ +
```
Fixes#112897
When a trait is used without specifying the implementation (e.g. calling
a non-member associated function without fully-qualified syntax) and
there are multiple implementations available, use a placeholder comment
for the implementation type in the suggestion instead of picking a
random implementation.
Example:
```
fn main() {
let _ = Default::default();
}
```
Previous output:
```
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
--> test.rs:2:13
|
2 | let _ = Default::default();
| ^^^^^^^^^^^^^^^^ cannot call associated function of trait
|
help: use a fully-qualified path to a specific available implementation (273 found)
|
2 | let _ = <FileTimes as Default>::default();
| +++++++++++++ +
```
New output:
```
error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
--> test.rs:2:13
|
2 | let _ = Default::default();
| ^^^^^^^^^^^^^^^^ cannot call associated function of trait
|
help: use a fully-qualified path to a specific available implementation (273 found)
|
2 | let _ = </* self type */ as Default>::default();
| +++++++++++++++++++ +
```
Account for sealed traits in privacy and trait bound errors
On trait bound errors caused by super-traits, identify if the super-trait is publicly accessibly and if not, explain "sealed traits".
```
error[E0277]: the trait bound `S: Hidden` is not satisfied
--> $DIR/sealed-trait-local.rs:17:20
|
LL | impl a::Sealed for S {}
| ^ the trait `Hidden` is not implemented for `S`
|
note: required by a bound in `Sealed`
--> $DIR/sealed-trait-local.rs:3:23
|
LL | pub trait Sealed: self:🅱️:Hidden {
| ^^^^^^^^^^^^^^^ required by this bound in `Sealed`
= note: `Sealed` is a "sealed trait", because to implement it you also need to implelement `a:🅱️:Hidden`, which is not accessible; this is usually done to force you to use one of the provided types that already implement it
```
Deduplicate privacy errors that point to the same path segment even if their deduplication span are different.
When encountering a path that is not reachable due to privacy constraints path segments other than the last, keep metadata for the last path segment's `Res` in order to look for alternative import paths for that item to suggest. If there are none, be explicit that the item is not accessible.
```
error[E0603]: module `b` is private
--> $DIR/re-exported-trait.rs:11:9
|
LL | impl a:🅱️:Trait for S {}
| ^ private module
|
note: the module `b` is defined here
--> $DIR/re-exported-trait.rs:5:5
|
LL | mod b {
| ^^^^^
help: consider importing this trait through its public re-export instead
|
LL | impl a::Trait for S {}
| ~~~~~~~~
```
```
error[E0603]: module `b` is private
--> $DIR/private-trait.rs:8:9
|
LL | impl a:🅱️:Hidden for S {}
| ^ ------ trait `b` is not publicly reachable
| |
| private module
|
note: the module `b` is defined here
--> $DIR/private-trait.rs:2:5
|
LL | mod b {
| ^^^^^
```
Suggest publicly accessible paths for items in private mod:
When encountering a path in non-import situations that are not reachable
due to privacy constraints, search for any public re-exports that the
user could use instead.
Track whether an import suggestion is offering a re-export.
When encountering a path with private segments, mention if the item at
the final path segment is not publicly accessible at all.
Add item visibility metadata to privacy errors from imports:
On unreachable imports, record the item that was being imported in order
to suggest publicly available re-exports or to be explicit that the item
is not available publicly from any path.
In order to allow this, we add a mode to `resolve_path` that will not
add new privacy errors, nor return early if it encounters one. This way
we can get the `Res` corresponding to the final item in the import,
which is used in the privacy error machinery.
When implementing a public trait with a private super-trait, we now emit
a note that the missing bound is not going to be able to be satisfied,
and we explain the concept of a sealed trait.
Print def_id on EarlyBoundRegion debug
It's not the first time that I can't make sense out of the default debug print on `EarlyBoundRegion`. As I was working on #112682 I needed this.
I was doing some git archeology and found that we used to print everything dfbc9608ce/src/librustc/util/ppaux.rs (L425-L430) but we lost the ability in some refactor midway.
Don't substitute a GAT that has mismatched generics in `OpaqueTypeCollector`
Fixes#111828
I didn't put up minimized UI tests for #112510 or #112873 because they'd minimize to literally the same code, but with different substs on the trait/impl. I don't think that warrants duplicate tests given the nature of the fix.
r? `@oli-obk`
----
Side-note: I checked, and this isn't fixed by #112652 -- I think we discussed whether or not that PR fixed it either intentionally or by accident. The code here isn't really touched by that PR either as far as I can tell?
Also, sorry, did some other drive-bys. Hope it doesn't make rebasing #112652 too difficult 😅
Fix union fields display
![Screenshot from 2023-06-21 16-47-24](https://github.com/rust-lang/rust/assets/3050060/833b0fe6-7fb6-4371-86c3-d82fa0c3fe49)
So two bugs in this screenshot: no whitespace between field name and type name, both fields are on the same line. Both problems come from issues in the templates because all whitespace are removed if a askama "command" follows.
r? `@notriddle`
Warn on unused `offset_of!()` result
The usage of `core::hint::must_use()` means that we don't get a specialized message. I figured out that since there are plenty of other methods that just have `#[must_use]` with no message it'll be fine, but it is a bit unfortunate that the error mentions `must_use` and not `offset_of!`.
Fixes#111669.
Add `lazy_type_alias` feature gate
Add the `type_alias_type` to be able to have the weak alias used without restrictions.
Part of #112792.
cc `@compiler-errors`
r? `@oli-obk`
[rustdoc] partially fix invalid files creation
Part of #111249. It only removes generation for modules which shouldn't exist. For files, we need the compiler to keep re-export information alive for external items so we can actually have the right path to their location as it's currently not generating them correctly.
In case the item is inlined, it shouldn't (and neither should its children) get a file generated.
r? ```@notriddle```
Syntactically accept `become` expressions (explicit tail calls experiment)
This adds `ast::ExprKind::Become`, implements parsing and properly gates the feature.
cc `@scottmcm`
There's no need to store it in `Queries`. We can just use a local
variable, because it's always used shortly after it's produced.
The commit also removes the `tcx.analysis()` call in `ongoing_codegen`,
because it's easy to ensure that's done beforehand.
All this makes the dataflow within `run_compiler` easier to follow, at
the cost of making one test slightly more verbose, which I think is a
good tradeoff.
The only regression is one ambiguity in the new trait solver, having to
do with two param-env candidates that may apply. I think this is fine,
since the error message already kinda sucks.
Revert #112758 and add test case
Fixes#112831.
Cannot unwrap `update_resolution` for `resolution.single_imports.remove(&Interned::new_unchecked(import));` because there is a relationship between the `Import` and `&NameBinding` in `NameResolution`. This issue caused by my unfamiliarity with the data structure and I apologize for it.
This PR had been reverted, and test case have been added.
r? `@Nilstrieb`
cc `@petrochenkov`
Sort the errors from arguments checking so that suggestions are handled properly
Fixes#112507
The algorithm of `find_issue` does not make sure the index comes out in order, which will make suggesting `remove` or `add` arguments broken in some cases.
Modifying the algorithm to obey order involves much more trivial change, so it's better to order the `errors` after iterations.