rustdoc-search: handle `impl Into<X>` better
This PR fixes two bugs I ran into while searching the compiler docs:
- It omitted an `impl Trait` entry in the type signature field, producing `TyCtxt, , Symbol -> bool`
- It didn't let me search for `TyCtxt, DefId, Symbol -> bool` even though that's a perfectly good description of the function I was looking for (the function actually used `impl Into<DefId>`
r? ``@GuillaumeGomez`` cc ``@lolbinarycat``
Correctly handle comments in attributes in doctests source code
Fixes https://github.com/rust-lang/rust/issues/134221.
The problem was that attributes are "inlined" (backlines are stripped), then when there is an inline comment inside it, the attribute is never considered valid (since unclosed). Fix was to simply put back backlines in case it's a multiline attribute.
r? ``@notriddle``
Update spelling of "referring"
I noticed that `referring` was spelled incorrectly in the output of `unexpected 'cfg' condition name` warnings; it looks like it was also incorrectly spelled in a doc comment. I've update both instances.
Fix `trimmed_def_paths` ICE in the function ptr comparison lint
This PR fixes an ICE with `trimmed_def_paths` ICE in the function ptr comparison lint, specifically when pretty-printing user types but then not using the resulting pretty-printing.
Fixes#134345
r? `@saethlin`
Make sure to use normalized ty for unevaluated const in default struct value
This cleans up the way that we construct the `mir::Const::Unevaluated` for default struct values. We were previously using `from_unevaluated`, which doesn't normalize the type, and is really only used for inline assembly. Other codepaths (such as `ExprKind::NamedConst`) use the type from the body.
Also, let's stop using `literal_operand`, which also is really not meant for calls other than for literal comparisons in pattern lowering.
Also move all of the tests to a separate subdirectory so they don't need to have the same prefix on all the test files.
Fixes#134298
r? estebank or reassign
Hir attributes
This PR needs some explanation, it's somewhat large.
- This is step one as described in https://github.com/rust-lang/compiler-team/issues/796. I've added a new `hir::Attribute` which is a lowered version of `ast::Attribute`. Right now, this has few concrete effects, however every place that after this PR parses a `hir::Attribute` should later get a pre-parsed attribute as described in https://github.com/rust-lang/compiler-team/issues/796 and transitively https://github.com/rust-lang/rust/issues/131229.
- an extension trait `AttributeExt` is added, which is implemented for both `ast::Attribute` and `hir::Atribute`. This makes `hir::Attributes` mostly compatible with code that used to parse `ast::Attribute`. All its methods are also added as inherent methods to avoid having to import the trait everywhere in the compiler.
- Incremental can not not hash `ast::Attribute` at all.
Pass `TyCtxt` to early diagostics decoration
This PR pass a `TyCtxt` to the early diagnostics decoration code so that diagnostics code that take advantage of (a very limited but still useful) `TyCtxt` in their note, help, suggestions, ...
This is particulary useful for #133221 which wants to get the crate name of a `DefId`, which is possible with `tcx.crate_name(...)`.
I highly recommend reviewing this PR commit by commit.
r? `@jieyouxu`
reject aarch64 target feature toggling that would change the float ABI
~~Stacked on top of https://github.com/rust-lang/rust/pull/133099. Only the last two commits are new.~~
The first new commit lays the groundwork for separately controlling whether a feature may be enabled or disabled. The second commit uses that to make it illegal to *disable* the `neon` feature (which is only possible via `-Ctarget-feature`, and so the new check just adds a warning). Enabling the `neon` feature remains allowed on targets that don't disable `neon` or `fp-armv8`, which is all our built-in targets. This way, the entire PR is not a breaking change.
Fixes https://github.com/rust-lang/rust/issues/131058 for hardfloat targets (together with https://github.com/rust-lang/rust/pull/133102 which fixed it for softfloat targets).
Part of https://github.com/rust-lang/rust/issues/116344.
Modifies the index instruction from `gep [0 x %Type]` to `gep %Type`
Fixes#133979.
This PR modifies the index instruction from `gep [0 x %Type]` to `gep %Type`, which is the same with pointer offset calculation.
This will help LLVM calculate various formats of GEP instructions. According to [[RFC] Replacing getelementptr with ptradd](https://discourse.llvm.org/t/rfc-replacing-getelementptr-with-ptradd/68699), we ultimately aim to canonicalize everything to `gep i8`. Based on the results from https://github.com/rust-lang/rust/pull/134117#issuecomment-2531717076, I think we still need to investigate some missing optimizations, so this PR is just a small step forward.
r? compiler
Don't make a def id for `impl_trait_in_bindings`
The def collector is awkward, so for now just wrap let statements in a new `ImplTraitContext::InBinding` which tells `visit_ty` not to make a def id for the type. This will not generalize to other ITIB cases, like if we allow them in turbofishes (e.g. `foo::<impl Fn()>(|| {})`).
Fixes#134307
r? oli-obk
don't show the full linker args unless `--verbose` is passed
the linker arguments can be *very* long, especially for crates with many dependencies. often they are not useful. omit them unless the user specifically requests them.
split out from https://github.com/rust-lang/rust/pull/119286. fixes https://github.com/rust-lang/rust/issues/109979.
r? `@bjorn3`
try-build: i686-mingw
Remove support for specializing ToString outside the standard library
This is the only trait specializable outside of the standard library. Before stabilizing specialization we will probably want to remove support for this. It was originally made specializable to allow a more efficient ToString in libproc_macro back when this way the only way to get any data out of a TokenStream. We now support getting individual tokens, so proc macros no longer need to call it as often.
the linker arguments can be *very* long, especially for crates with many dependencies. some parts of them are not very useful. unless specifically requested:
- omit object files specific to the current invocation
- fold rlib files into a single braced argument (in shell expansion format)
this shortens the output significantly without removing too much information.
Rollup of 7 pull requests
Successful merges:
- #132939 (Suggest using deref in patterns)
- #133293 (Updates Solaris target information, adds Solaris maintainer)
- #133392 (Fix ICE when multiple supertrait substitutions need assoc but only one is provided)
- #133986 (Add documentation for anonymous pipe module)
- #134022 (Doc: Extend for tuples to be stabilized in 1.85.0)
- #134259 (Clean up `infer_return_ty_for_fn_sig`)
- #134264 (Arbitrary self types v2: Weak & NonNull diagnostics)
r? `@ghost`
`@rustbot` modify labels: rollup
Arbitrary self types v2: Weak & NonNull diagnostics
This builds on top of #134262 which is more urgent to review and merge first. I'll likely rebase this PR once that lands.
This is the first part of the diagnostic enhancements planned for Arbitrary Self Types v2.
Various types can be used as method receivers, such as `Rc<>`, `Box<>` and `Arc<>`. The arbitrary self types v2 work allows further types to be made method receivers by implementing the Receiver trait.
With that in mind, it may come as a surprise to people when certain common types do not implement Receiver and thus cannot be used as a method receiver.
The RFC for arbitrary self types v2 therefore proposes emitting specific
lint hints for these cases:
* `NonNull`
* `Weak`
* Raw pointers
The code already emits a hint for this third case, in that it advises folks that the `arbitrary_self_types_pointers` feature may meet their need. This PR adds diagnostic hints for the `Weak` and `NonNull` cases.
Tracking issue #44874
r? `@wesleywiser`
Fix ICE when multiple supertrait substitutions need assoc but only one is provided
Dyn traits must have all of their associated types constrained either by:
1. writing them in the dyn trait itself as an associated type bound, like `dyn Iterator<Item = u32>`,
2. A supertrait bound, like `trait ConstrainedIterator: Iterator<Item = u32> {}`, then you may write `dyn ConstrainedIterator` which doesn't need to mention `Item`.
However, the object type lowering code did not consider the fact that there may be multiple supertraits with different substitutions, so it just used the associated type's *def id* as a key for keeping track of which associated types are missing:
1fc691e6dd/compiler/rustc_hir_analysis/src/hir_ty_lowering/dyn_compatibility.rs (L131)
This means that we can have missing associated types when there are mutliple supertraits with different substitutions and only one of them is constrained, like:
```rust
trait Sup<T> {
type Assoc: Default;
}
impl<T: Default> Sup<T> for () {
type Assoc = T;
}
impl<T: Default, U: Default> Dyn<T, U> for () {}
trait Dyn<A, B>: Sup<A, Assoc = A> + Sup<B> {}
```
The above example allows you to name `<dyn Dyn<i32, u32> as Sup<u32>>::Assoc` even though it is not possible to project since it's neither constrained by a manually written projection bound or a supertrait bound. This successfully type-checks, but leads to a codegen ICE since we are not able to project the associated type.
This PR fixes the validation for checking that a dyn trait mentions all of its associated type bounds. This is theoretically a breaking change, since you could technically use that `dyn Dyn<A, B>` type mentionedin the example above without actually *projecting* to the bad associated type, but I don't expect it to ever be relevant to a user since it's almost certainly a bug. This is corroborated with the crater results[^crater], which show no failures[^unknown].
Crater: https://github.com/rust-lang/rust/pull/133392#issuecomment-2508769703Fixes#133388
[^crater]: I cratered this originally with #133397, which is a PR that is stacked on top, then re-ran crater with just the failures from that PR.
[^unknown]: If you look at the crater results, it shows all of the passes as "unknown". I believe this is a crater bug, since looking at the results manually shows them as passes.
Suggest using deref in patterns
Fixes#132784
This changes the following code:
```rs
use std::sync::Arc;
fn main() {
let mut x = Arc::new(Some(1));
match x {
Some(_) => {}
None => {}
}
}
```
to output
```rs
error[E0308]: mismatched types
--> src/main.rs:5:9
|
LL | match x {
| - this expression has type `Arc<Option<{integer}>>`
...
LL | Some(_) => {}
| ^^^^^^^ expected `Arc<Option<{integer}>>`, found `Option<_>`
|
= note: expected struct `Arc<Option<{integer}>>`
found enum `Option<_>`
help: consider dereferencing to access the inner value using the Deref trait
|
LL | match *x {
| ~~
```
instead of
```rs
error[E0308]: mismatched types
--> src/main.rs:5:9
|
4 | match x {
| - this expression has type `Arc<Option<{integer}>>`
5 | Some(_) => {}
| ^^^^^^^ expected `Arc<Option<{integer}>>`, found `Option<_>`
|
= note: expected struct `Arc<Option<{integer}>>`
found enum `Option<_>`
```
This makes it more obvious that a Deref is available, and gives a suggestion on how to use it in order to fix the issue at hand.
Bounds-check with PtrMetadata instead of Len in MIR
Rather than emitting `Len(*_n)` in array index bounds checks, emit `PtrMetadata(copy _n)` instead -- with some asterisks for arrays and `&mut` that need it to be done slightly differently.
We're getting pretty close to removing `Len` entirely, actually. I think just one more PR after this (for slice drop shims).
r? mir
Various types can be used as method receivers, such as Rc<>, Box<> and
Arc<>. The arbitrary self types v2 work allows further types to be made
method receivers by implementing the Receiver trait.
With that in mind, it may come as a surprise to people when certain
common types do not implement Receiver and thus cannot be used as a
method receiver.
The RFC for arbitrary self types v2 therefore proposes emitting specific
lint hints for these cases:
* NonNull
* Weak
* Raw pointers
The code already emits a hint for this third case, in that it advises
folks that the `arbitrary_self_types_pointers` feature may meet their
need. This PR adds diagnostic hints for the Weak and NonNull cases.
Rollup of 6 pull requests
Successful merges:
- #133221 (Add external macros specific diagnostics for check-cfg)
- #133386 (Update linux_musl base to dynamically link the crt by default)
- #134191 (Make some types and methods related to Polonius + Miri public)
- #134227 (Update wasi-sdk used to build WASI targets)
- #134279 ((Re-)return adjustment target if adjust kind is never-to-any)
- #134295 (Encode coroutine-closures in SMIR)
r? `@ghost`
`@rustbot` modify labels: rollup
(Re-)return adjustment target if adjust kind is never-to-any
This PR fixes#134162 where we ICE'd on
```rs
fn main() {
struct X;
let _ = [X] == [panic!(); 2];
}
```
In https://github.com/rust-lang/rust/pull/121208#discussion_r1494187622, there was a change
```diff
- if let Some(adjustments) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
- let reported = self.dcx().span_delayed_bug(
- expr.span,
- "expression with never type wound up being adjusted",
- );
- return if let [Adjustment { kind: Adjust::NeverToAny, target }] = &adjustments[..] {
- target.to_owned()
- } else {
- Ty::new_error(self.tcx(), reported)
- };
- }
+ if let Some(_) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
+ self.dcx()
+ .span_bug(expr.span, "expression with never type wound up being adjusted");
+ }
```
It turned out returning the adjustment target if the adjustment kind is `NeverToAny` is necessary, as otherwise we will go through a series of `delay_bug`s and eventually find that we constructed a `TyKind::Error` without having actually emitted an error.
This PR addresses that by re-returning the adjustment target if the adjustment kind is `NeverToAny`, partially reverting this change from #121208.
This PR has two commits:
1. The first commit adds a regression test for #134162, which will ICE (on stable 1.83.0, beta and nightly 2024-12-13).
2. The second commit is the partial revert, which will fix the ICE.
cc `@nnethercote` FYI as this is related to #121208 changes. The changes from #121208 exposed that we lacked test coverage for the code pattern reported in #134162.
Update linux_musl base to dynamically link the crt by default
However, don't change the behavior of any existing targets at this time. For targets that used the old default, explicitly set `crt_static_default = true`.
This makes it easier for new targets to use the correct defaults while leaving the changing of individual targets to future PRs.
Related to https://github.com/rust-lang/compiler-team/issues/422
Add external macros specific diagnostics for check-cfg
This PR adds specific check-cfg diagnostics for unexpected cfg in external macros.
As well as hiding the some of the Cargo specific help/suggestions as they distraction for external macros and are generally not the right solution.
Follow-up to #132577
`@rustbot` label +L-unexpected_cfgs
r? compiler
Rollup of 6 pull requests
Successful merges:
- #132150 (Fix powerpc64 big-endian FreeBSD ABI)
- #133942 (Clarify how to use `black_box()`)
- #134081 (Try to evaluate constants in legacy mangling)
- #134192 (Remove `Lexer`'s dependency on `Parser`.)
- #134208 (coverage: Tidy up creation of covmap and covfun records)
- #134211 (On Neutrino QNX, reduce the need to set archiver via environment variables)
r? `@ghost`
`@rustbot` modify labels: rollup
(Re-)Implement `impl_trait_in_bindings`
This reimplements the `impl_trait_in_bindings` feature for local bindings.
"`impl Trait` in bindings" serve as a form of *trait* ascription, where the type basically functions as an infer var but additionally registering the `impl Trait`'s trait bounds for the infer type. These trait bounds can be used to enforce that predicates hold, and can guide inference (e.g. for closure signature inference):
```rust
let _: impl Fn(&u8) -> &u8 = |x| x;
```
They are implemented as an additional set of bounds that are registered when the type is lowered during typeck, and then these bounds are tied to a given `CanonicalUserTypeAscription` for borrowck. We enforce these `CanonicalUserTypeAscription` bounds during borrowck to make sure that the `impl Trait` types are sensitive to lifetimes:
```rust
trait Static: 'static {}
impl<T> Static for T where T: 'static {}
let local = 1;
let x: impl Static = &local;
//~^ ERROR `local` does not live long enough
```
r? oli-obk
cc #63065
---
Why can't we just use TAIT inference or something? Well, TAITs in bodies have the problem that they cannot reference lifetimes local to a body. For example:
```rust
type TAIT = impl Display;
let local = 0;
let x: TAIT = &local;
//~^ ERROR `local` does not live long enough
```
That's because TAITs requires us to do *opaque type inference* which is pretty strict, since we need to remap all of the lifetimes of the hidden type to universal regions. This is simply not possible here.
---
I consider this part of the "impl trait everywhere" experiment. I'm not certain if this needs yet another lang team experiment.
Rollup of 8 pull requests
Successful merges:
- #134252 (Fix `Path::is_absolute` on Hermit)
- #134254 (Fix building `std` for Hermit after `c_char` change)
- #134255 (Update includes in `/library/core/src/error.rs`.)
- #134261 (Document the symbol Visibility enum)
- #134262 (Arbitrary self types v2: adjust diagnostic.)
- #134265 (Rename `ty_def_id` so people will stop using it by accident)
- #134271 (Arbitrary self types v2: better feature gate test)
- #134274 (Add check-pass test for `&raw`)
r? `@ghost`
`@rustbot` modify labels: rollup
Remove `Lexer`'s dependency on `Parser`.
Lexing precedes parsing, as you'd expect: `Lexer` creates a `TokenStream` and `Parser` then parses that `TokenStream`.
But, in a horrendous violation of layering abstractions and common sense, `Lexer` depends on `Parser`! The `Lexer::unclosed_delim_err` method does some error recovery that relies on creating a `Parser` to do some post-processing of the `TokenStream` that the `Lexer` just created.
This commit just removes `unclosed_delim_err`. This change removes `Lexer`'s dependency on `Parser`, and also means that `lex_token_tree`'s return value can have a more typical form.
The cost is slightly worse error messages in two obscure cases, as shown in these tests:
- tests/ui/parser/brace-in-let-chain.rs: there is slightly less explanation in this case involving an extra `{`.
- tests/ui/parser/diff-markers/unclosed-delims{,-in-macro}.rs: the diff marker detection is no longer supported (because that detection is implemented in the parser).
In my opinion this cost is outweighed by the magnitude of the code cleanup.
r? ```````@chenyukang```````
Try to evaluate constants in legacy mangling
Best reviewed commit by commit.
It seems kind of odd to treat literals differently from unevaluated free constants. So let's evaluate those constants and only fall back to `_` rendering if that fails to result in an integral constant