Add a new `mismatched-lifetime-syntaxes` lint
The lang-team [discussed this](https://hackmd.io/nf4ZUYd7Rp6rq-1svJZSaQ) and I attempted to [summarize](https://github.com/rust-lang/rust/pull/120808#issuecomment-2701863833) their decision. The summary-of-the-summary is:
- Using two different kinds of syntax for elided lifetimes is confusing. In rare cases, it may even [lead to unsound code](https://github.com/rust-lang/rust/issues/48686)! Some examples:
```rust
// Lint will warn about these
fn(v: ContainsLifetime) -> ContainsLifetime<'_>;
fn(&'static u8) -> &u8;
```
- Matching up references with no lifetime syntax, references with anonymous lifetime syntax, and paths with anonymous lifetime syntax is an exception to the simplest possible rule:
```rust
// Lint will not warn about these
fn(&u8) -> &'_ u8;
fn(&'_ u8) -> &u8;
fn(&u8) -> ContainsLifetime<'_>;
```
- Having a lint for consistent syntax of elided lifetimes will make the [future goal](https://github.com/rust-lang/rust/issues/91639) of warning-by-default for paths participating in elision much simpler.
---
This new lint attempts to accomplish the goal of enforcing consistent syntax. In the process, it supersedes and replaces the existing `elided-named-lifetimes` lint, which means it starts out life as warn-by-default.
Rollup of 9 pull requests
Successful merges:
- rust-lang/rust#141554 (Improve documentation for codegen options)
- rust-lang/rust#141817 (rustc_llvm: add Windows system libs only when cross-compiling from Wi…)
- rust-lang/rust#141843 (Add `visit_id` to ast `Visitor`)
- rust-lang/rust#141881 (Subtree update of `rust-analyzer`)
- rust-lang/rust#141898 ([rustdoc-json] Implement PartialOrd and Ord for rustdoc_types::Id)
- rust-lang/rust#141921 (Disable f64 minimum/maximum tests for arm 32)
- rust-lang/rust#141930 (Enable triagebot `[concern]` functionality)
- rust-lang/rust#141936 (Decouple "reporting in deps" from `FutureIncompatibilityReason`)
- rust-lang/rust#141949 (move `test-float-parse` tool into `src/tools` dir)
r? `@ghost`
`@rustbot` modify labels: rollup
Add `visit_id` to ast `Visitor`
This helps with efforts to deduplicate the `MutVisitor` and the `Visitor` code. All users of `Visitor`'s methods that have extra `NodeId` as parameters really just want to visit the id on its own.
Also includes some methods deduplicated and cleaned up as a result of this change.
r? oli-obk
Don't declare variables in `ExprKind::Let` in invalid positions
Handle `let` expressions in invalid positions specially during resolve in order to avoid making destructuring-assignment expressions that reference (invalid) variables that have not yet been delcared yet.
See further explanation in test and comment in the source.
Fixesrust-lang/rust#141844
`UsePath` contains a `SmallVec<[Res; 3]>`. This holds up to three `Res`
results, one per namespace (type, value, or macro). `lower_import_res`
takes a `PerNS<Option<Res<NodeId>>>` result and lowers it into the
`SmallVec`. This is pretty weird. The input `PerNS` makes it clear which
`Res` belongs to which namespace, but the `SmallVec` throws that
information away.
And code that operates on the `SmallVec` tends to use iteration (or even
just grabbing the first entry!) without knowing which namespace the
`Res` belongs to. Even weirder! Also, `SmallVec` is an overly flexible
type to use here, because it can contain any number of elements (even
though it's optimized for 3 in this case).
This commit changes `UsePath` so it also contains a
`PerNS<Option<Res<HirId>>>`. This type preserves more information and is
more self-documenting. The commit also changes a lot of the use sites to
access the result for a particular namespace. E.g. if you're looking up
a trait, it will be in the `Res` for the type namespace if it's present;
it's silly to look in the `Res` for the value namespace or macro
namespace. Overall I find the new code much easier to understand.
However, some use sites still iterate. These now use `present_items`
because that filters out the `None` results.
Also, `redundant_pub_crate.rs` gets a bigger change. A
`UseKind:ListStem` item gets no `Res` results, which means the old `all`
call in `is_not_macro_export` would succeed (because `all` succeeds on
an empty iterator) and the `ListStem` would be ignored. This is what we
want, but was more by luck than design. The new code detects `ListStem`
explicitly. The commit generalizes the name of that function
accordingly.
Finally, the commit also removes the `use_path` arena, because
`PerNS<Option<Res>>` impls `Copy` (unlike `SmallVec`) and it can be
allocated in the arena shared by all `Copy` types.
source_span_for_markdown_range: fix utf8 violation
it is non-trivial to reproduce this bug through rustdoc, which uses this function less than clippy, so the regression test was added as a unit test instead of an integration test.
fixes https://github.com/rust-lang/rust/issues/141665
r? ``@GuillaumeGomez``
Improve diagnostics for usage of qualified paths within tuple struct exprs/pats
For patterns the old diagnostic was just incorrect, but I also added machine applicable suggestions.
For context, this special cases errors for `<T as Trait>::Assoc(..)` patterns and expressions (latter is just a call). Tuple struct patterns and expressions both live in the value namespace, so they are not forwarded through associated *types*.
r? ``@jdonszelmann``
cc ``@petrochenkov`` in https://github.com/rust-lang/rust/pull/80080#issuecomment-800630582 you were wondering why it doesn't work for types, that's why — tuple patterns are resolved in the value namespace.
This helps with efforts to deduplicate the `MutVisitor` and the
`Visitor` code. All users of `Visitor`'s methods that have extra
`NodeId` as parameters really just want to visit the id on its
own.
Also includes some methods deduplicated and cleaned up as
a result of this change.
it is non-trivial to reproduce this bug through rustdoc,
which uses this function less than clippy,
so the regression test was added as a unit test
instead of an integration test.
Use `cfg_attr_trace` in AST with a placeholder attribute for accurate suggestion
In rust-lang/rust#138515, we insert a placeholder attribute so that checks for attributes can still know about the placement of `cfg` attributes. When we suggest removing items with `cfg_attr`s (fixrust-lang/rust#56328) and make them verbose. We tweak the wording of the existing "unused `extern crate`" lint.
```
warning: unused `extern crate`
--> $DIR/removing-extern-crate.rs:9:1
|
LL | extern crate removing_extern_crate as foo;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unused
|
note: the lint level is defined here
--> $DIR/removing-extern-crate.rs:6:9
|
LL | #![warn(rust_2018_idioms)]
| ^^^^^^^^^^^^^^^^
= note: `#[warn(unused_extern_crates)]` implied by `#[warn(rust_2018_idioms)]`
help: remove the unused `extern crate`
|
LL - #[cfg_attr(test, macro_use)]
LL - extern crate removing_extern_crate as foo;
|
```
r? `@petrochenkov`
try-job: x86_64-gnu-aux
PR 138515, we insert a placeholder attribute so that checks for attributes can still know about the placement of `cfg` attributes. When we suggest removing items with `cfg_attr`s (fix Issue 56328) and make them verbose. We tweak the wording of the existing "unused `extern crate`" lint.
```
warning: unused extern crate
--> $DIR/removing-extern-crate.rs:9:1
|
LL | extern crate removing_extern_crate as foo;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ unused
|
note: the lint level is defined here
--> $DIR/removing-extern-crate.rs:6:9
|
LL | #![warn(rust_2018_idioms)]
| ^^^^^^^^^^^^^^^^
= note: `#[warn(unused_extern_crates)]` implied by `#[warn(rust_2018_idioms)]`
help: remove the unused `extern crate`
|
LL - #[cfg_attr(test, macro_use)]
LL - extern crate removing_extern_crate as foo;
LL +
|
```
Reorder `ast::ItemKind::{Struct,Enum,Union}` fields.
So they match the order of the parts in the source code, e.g.:
```
struct Foo<T, U> { t: T, u: U }
<-><----> <------------>
/ | \
ident generics variant_data
```
r? `@fee1-dead`
So they match the order of the parts in the source code, e.g.:
```
struct Foo<T, U> { t: T, u: U }
<-><----> <------------>
/ | \
ident generics variant_data
```
Improve handling of rustdoc lints when used with raw doc fragments.
1. `rustdoc::bare_urls` no longer outputs incoherent suggestions if `source_span_for_markdown_range` returns None, instead outputting no suggestion
2. `source_span_for_markdown_range` has one more heuristic, so it will return `None` less often.
3. add ui test to make sure we don't emit nonsense suggestions.
fixes https://github.com/rust-lang/rust/issues/135851
1. rustdoc::bare_urls doesn't output
invalid suggestions if source_span_for_markdown_range
fails to find a span
2. source_span_for_markdown_range tries harder to
return a span by applying an additional diagnostic
fixes https://github.com/rust-lang/rust/issues/135851
only resolve top-level guard patterns' guards once
We resolve guard patterns' guards in `resolve_pattern_inner`, so to avoid resolving them multiple times, we must avoid doing so earlier. To accomplish this, `LateResolutionVisitor::visit_pat` contains a case for guard patterns that avoids visiting their guards while walking patterns.
This PR fixes#141265, which was due to `visit::walk_pat` being used instead; this meant guards at the top level of a pattern would be visited twice. e.g. it would ICE on `for x if x in [] {}`, but not `for (x if x) in [] {}`. `visit_pat` was already used for the guard pattern in the second example, on account of the top-level pattern being parens.
Suggest use "{}", self.x instead of {self.x} when resolve x as field of `self`
Fixes#141136
Changes can be seen in the second commit: 9de7fff0d8
r? compiler
We resolve guard patterns' guards in `resolve_pattern_inner`, so to
avoid resolving them multiple times, we must avoid doing so earlier. To
accomplish this, `LateResolutionVisitor::visit_pat` contains a case for
guard patterns that avoids visiting their guards while walking patterns.
This fixes an ICE due to `visit::walk_pat` being used instead, which
meant guards at the top level of a pattern would be visited twice.
make `rustc_attr_parsing` less dominant in the rustc crate graph
It has/had a glob re-export of `rustc_attr_data_structures`, which is a crate much lower in the graph, and a lot of crates were using it *just* (or *mostly*) for that re-export, while they can rely on `rustc_attr_data_structures` directly.
Previous graph:

Graph with this PR:

The first commit keeps the re-export, and just changes the dependency if possible. The second commit is the "breaking change" which removes the re-export, and "explicitly" adds the `rustc_attr_data_structures` dependency where needed. It also switches over some src/tools/*.
The second commit is actually a lot more involved than I expected. Please let me know if it's a better idea to back it out and just keep the first commit.
name resolution for guard patterns
This PR provides an initial implementation of name resolution for guard patterns [(RFC 3637)](https://github.com/rust-lang/rfcs/blob/master/text/3637-guard-patterns.md). This does not change the requirement that the bindings on either side of an or-pattern must be the same [(proposal here)](https://github.com/rust-lang/rfcs/blob/master/text/3637-guard-patterns.md#allowing-mismatching-bindings-when-possible); the code that handles that is separate from what this PR touches, so I'm saving it for a follow-up.
On a technical level, this separates "collecting the bindings in a pattern" (which was already done for or-patterns) from "introducing those bindings into scope". I believe the approach used here can be extended straightforwardly in the future to work with `if let` guard patterns, but I haven't tried it myself since we don't allow those yet.
Tracking issue for guard patterns: #129967
cc ``@Nadrieril``
Prefer to suggest stable candidates rather than unstable ones
Fixes#140240
The logic is to replace unstable suggestions if we meet a new stable one, and do nothing if any other situation. In old logic, we just use the first candidate we meet as the suggestion for the same items.
E.g., `std::range::legacy::Range` vs `std::ops::Range`, `legacy` in the former is unstable, we prefer to suggest use the latter.
All uses have been removed. And it's nonsensical: an identifier by
definition has at least one char.
The commits adds an is-non-empty assertion to `Ident::new` to enforce
this, and converts some `Ident` constructions to use `Ident::new`.
Adding the assertion requires making `Ident::new` and
`Ident::with_dummy_span` non-const, which is no great loss.
The commit amends a couple of places that do path splitting to ensure no
empty identifiers are created.
This splits introduction of bindings into scope
(`apply_pattern_bindings`) apart from manipulation of the pattern's
binding map (`fresh_binding`). By delaying the latter, we can keep
bindings from appearing in-scope in guards.
Since `fresh_binding` is now specifically for manipulating a pattern's
bindings map, this commit also inlines a use of `fresh_binding` that was
only adding to the innermost rib.
I'll be modifying it in future commits, so I think it's cleanest to
abstract it out. Possibly a newtype would be ideal, but for now this is
least disruptive.
Remove global `next_disambiguator` state and handle it with a `DisambiguatorState` type
This removes `Definitions.next_disambiguator` as it doesn't guarantee deterministic def paths when `create_def` is called in parallel. Instead a new `DisambiguatorState` type is passed as a mutable reference to `create_def` to help create unique def paths. `create_def` calls with distinct `DisambiguatorState` instances must ensure that that the def paths are unique without its help.
Anon associated types did rely on this global state for uniqueness and are changed to use (method they're defined in + their position in the method return type) as the `DefPathData` to ensure uniqueness. This also means that the method they're defined in appears in error messages, which is nicer.
`DefPathData::NestedStatic` is added to use for nested data inside statics instead of reusing `DefPathData::AnonConst` to avoid conflicts with those.
cc `@oli-obk`
Simplify `LazyAttrTokenStream`
`LazyAttrTokenStream` is an unpleasant type: `Lrc<Box<dyn ToAttrTokenStream>>`. Why does it look like that?
- There are two `ToAttrTokenStream` impls, one for the lazy case, and one for the case where we already have an `AttrTokenStream`.
- The lazy case (`LazyAttrTokenStreamImpl`) is implemented in `rustc_parse`, but `LazyAttrTokenStream` is defined in `rustc_ast`, which does not depend on `rustc_parse`. The use of the trait lets `rustc_ast` implicitly depend on `rustc_parse`. This explains the `dyn`.
- `LazyAttrTokenStream` must have a `size_of` as small as possible, because it's used in many AST nodes. This explains the `Lrc<Box<_>>`, which keeps it to one word. (It's required `Lrc<dyn _>` would be a fat pointer.)
This PR moves `LazyAttrTokenStreamImpl` (and a few other token stream things) from `rustc_parse` to `rustc_ast`. This lets us replace the `ToAttrTokenStream` trait with a two-variant enum and also remove the `Box`, changing `LazyAttrTokenStream` to `Lrc<LazyAttrTokenStreamInner>`. Plus it does a few cleanups.
r? `@petrochenkov`
This commit does the following.
- Changes it from `Lrc<Box<dyn ToAttrTokenStream>>` to
`Lrc<LazyAttrTokenStreamInner>`.
- Reworks `LazyAttrTokenStreamImpl` as `LazyAttrTokenStreamInner`, which
is a two-variant enum.
- Removes the `ToAttrTokenStream` trait and the two impls of it.
The recursion limit must be increased in some crates otherwise rustdoc
aborts.