Commit graph

1965 commits

Author SHA1 Message Date
Michael Goulet abada5fdca Only walk ribs to collect possibly shadowed params if we are adding params in our new rib 2024-08-02 11:07:38 -04:00
Matthias Krüger 20379e4d4e
Rollup merge of #123813 - compiler-errors:redundant-lint, r=petrochenkov
Add `REDUNDANT_IMPORTS` lint for new redundant import detection

Defaults to Allow for now. Stacked on #123744 to avoid merge conflict, but much easier to review all as one.

r? petrochenkov
2024-07-31 23:20:09 +02:00
Matthias Krüger 336a378fcd
Rollup merge of #128151 - estebank:missing-extern-crate, r=petrochenkov
Structured suggestion for `extern crate foo` when `foo` isn't resolved in import

When encountering a name in an import that could have come from a crate that wasn't imported, use a structured suggestion to suggest `extern crate foo;` pointing at the right place in the crate.

When encountering `_` in an import, do not suggest `extern crate _;`.

```
error[E0432]: unresolved import `spam`
  --> $DIR/import-from-missing-star-3.rs:2:9
   |
LL |     use spam::*;
   |         ^^^^ maybe a missing crate `spam`?
   |
help: consider importing the `spam` crate
   |
LL + extern crate spam;
   |
```
2024-07-31 15:36:30 +02:00
Michael Goulet f6f587e7ea Introduce REDUNDANT_IMPORTS lint 2024-07-31 00:07:42 -04:00
Esteban Küber b61570ac11 Structured suggestion for extern crate foo when foo isn't resolved in import
When encountering a name in an import that could have come from a crate that wasn't imported, use a structured suggestion to suggest `extern crate foo;` pointing at the right place in the crate.

When encountering `_` in an import, do not suggest `extern crate _;`.

```
error[E0432]: unresolved import `spam`
  --> $DIR/import-from-missing-star-3.rs:2:9
   |
LL |     use spam::*;
   |         ^^^^ maybe a missing crate `spam`?
   |
help: consider importing the `spam` crate
   |
LL + extern crate spam;
   |
```
2024-07-29 23:49:51 +00:00
Michael Goulet 454c600004 Detect non-lifetime binder params shadowing item params 2024-07-29 14:26:21 -04:00
Nicholas Nethercote 84ac80f192 Reformat use declarations.
The previous commit updated `rustfmt.toml` appropriately. This commit is
the outcome of running `x fmt --all` with the new formatting options.
2024-07-29 08:26:52 +10:00
Trevor Gross c5788d618e
Rollup merge of #127557 - linyihai:issue-126694, r=compiler-errors
Add a label to point to the lacking macro name definition

Fixes https://github.com/rust-lang/rust/issues/126694, but adopts the suggestion from https://github.com/rust-lang/rust/issues/118295

```
 --> src/main.rs:1:14
  |
1 | macro_rules! {
  |            ^ put a macro name here
```
2024-07-26 02:20:30 -04:00
Lin Yihai 2fca4ea317 Add a label to point to the lacking macro name definition 2024-07-26 10:51:55 +08:00
Esteban Küber 850faea030 Do not use question as label
We don't want to have questions in the diagnostic output. Instead, we use wording that communicates uncertainty, like "might":

```
error[E0432]: unresolved import `spam`
  --> $DIR/import-from-missing-star-3.rs:2:9
   |
LL |     use spam::*;
   |         ^^^^ you might be missing crate `spam`
   |
   = help: consider adding `extern crate spam` to use the `spam` crate
```
2024-07-24 21:03:27 +00:00
Michael Goulet 3862095bd2 Just totally fully deny late-bound consts 2024-07-20 19:45:24 -04:00
Yuri Astrakhan aef0e346de Avoid ref when using format! in compiler
Clean up a few minor refs in `format!` macro, as it has a performance cost. Apparently the compiler is unable to inline `format!("{}", &variable)`, and does a run-time double-reference instead (format macro already does one level referencing).  Inlining format args prevents accidental `&` misuse.
2024-07-19 14:52:07 -04:00
bors 3811f40d27 Auto merge of #127957 - matthiaskrgr:rollup-1u5ivck, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #127350 (Parser: Suggest Placing the Return Type After Function Parameters)
 - #127621 (Rewrite and rename `issue-22131` and `issue-26006` `run-make` tests to rmake)
 - #127662 (When finding item gated behind a `cfg` flag, point at it)
 - #127903 (`force_collect` improvements)
 - #127932 (rustdoc: fix `current` class on sidebar modnav)
 - #127943 (Don't allow unsafe statics outside of extern blocks)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-19 13:39:12 +00:00
Matthias Krüger 98fdfcb11b
Rollup merge of #127662 - estebank:gate-span, r=TaKO8Ki
When finding item gated behind a `cfg` flag, point at it

Previously we would only mention that the item was gated out, and opportunisitically mention the feature flag name when possible. We now point to the place where the item was gated, which can be behind layers of macro indirection, or in different modules.

```
error[E0433]: failed to resolve: could not find `doesnt_exist` in `inner`
  --> $DIR/diagnostics-cross-crate.rs:18:23
   |
LL |     cfged_out::inner::doesnt_exist::hello();
   |                       ^^^^^^^^^^^^ could not find `doesnt_exist` in `inner`
   |
note: found an item that was configured out
  --> $DIR/auxiliary/cfged_out.rs:6:13
   |
LL |     pub mod doesnt_exist {
   |             ^^^^^^^^^^^^
note: the item is gated here
  --> $DIR/auxiliary/cfged_out.rs:5:5
   |
LL |     #[cfg(FALSE)]
   |     ^^^^^^^^^^^^^
```
2024-07-19 10:48:05 +02:00
bors 8c3a94a1c7 Auto merge of #125915 - camelid:const-arg-refactor, r=BoxyUwU
Represent type-level consts with new-and-improved `hir::ConstArg`

### Summary

This is a step toward `min_generic_const_exprs`. We now represent all const
generic arguments using an enum that differentiates between const *paths*
(temporarily just bare const params) and arbitrary anon consts that may perform
computations. This will enable us to cleanly implement the `min_generic_const_args`
plan of allowing the use of generics in paths used as const args, while
disallowing their use in arbitrary anon consts. Here is a summary of the salient
aspects of this change:

- Add `current_def_id_parent` to `LoweringContext`

  This is needed to track anon const parents properly once we implement
  `ConstArgKind::Path` (which requires moving anon const def-creation
  outside of `DefCollector`).

- Create `hir::ConstArgKind` enum with `Path` and `Anon` variants. Use it in the
  existing `hir::ConstArg` struct, replacing the previous `hir::AnonConst` field.

- Use `ConstArg` for all instances of const args. Specifically, use it instead
  of `AnonConst` for assoc item constraints, array lengths, and const param
  defaults.

- Some `ast::AnonConst`s now have their `DefId`s created in
  rustc_ast_lowering rather than `DefCollector`. This is because in some
  cases they will end up becoming a `ConstArgKind::Path` instead, which
  has no `DefId`. We have to solve this in a hacky way where we guess
  whether the `AnonConst` could end up as a path const since we can't
  know for sure until after name resolution (`N` could refer to a free
  const or a nullary struct). If it has no chance as being a const
  param, then we create a `DefId` in `DefCollector` -- otherwise we
  decide during ast_lowering. This will have to be updated once all path
  consts use `ConstArgKind::Path`.

- We explicitly use `ConstArgHasType` for array lengths, rather than
  implicitly relying on anon const type feeding -- this is due to the
  addition of `ConstArgKind::Path`.

- Some tests have their outputs changed, but the changes are for the
  most part minor (including removing duplicate or almost-duplicate
  errors). One test now ICEs, but it is for an incomplete, unstable
  feature and is now tracked at https://github.com/rust-lang/rust/issues/127009.

### Followup items post-merge

- Use `ConstArgKind::Path` for all const paths, not just const params.
- Fix (no github dont close this issue) #127009
- If a path in generic args doesn't resolve as a type, try to resolve as a const
  instead (do this in rustc_resolve). Then remove the special-casing from
  `rustc_ast_lowering`, so that all params will automatically be lowered as
  `ConstArgKind::Path`.
- (?) Consider making `const_evaluatable_unchecked` a hard error, or at least
  trying it in crater

r? `@BoxyUwU`
2024-07-19 08:44:51 +00:00
bors 5753b30676 Auto merge of #117967 - adetaylor:fix-lifetime-elision-bug, r=lcnr
Fix ambiguous cases of multiple & in elided self lifetimes

This change proposes simpler rules to identify the lifetime on `self` parameters which may be used to elide a return type lifetime.

## The old rules

(copied from [this comment](https://github.com/rust-lang/rust/pull/117967#discussion_r1420554242))

Most of the code can be found in [late.rs](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html) and acts on AST types. The function [resolve_fn_params](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html#2006), in the success case, returns a single lifetime which can be used to elide the lifetime of return types.

Here's how:
* If the first parameter is called self then we search that parameter using "`self` search rules", below
* If no unique applicable lifetime was found, search all other parameters using "regular parameter search rules", below

(In practice the code does extra work to assemble good diagnostic information, so it's not quite laid out like the above.)

### `self` search rules

This is primarily handled in [find_lifetime_for_self](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html#2118) , and is described slightly [here](https://github.com/rust-lang/rust/issues/117715#issuecomment-1813115477) already. The code:

1. Recursively walks the type of the `self` parameter (there's some complexity about resolving various special cases, but it's essentially just walking the type as far as I can see)
2. Each time we find a reference anywhere in the type, if the **direct** referent is `Self` (either spelled `Self` or by some alias resolution which I don't fully understand), then we'll add that to a set of candidate lifetimes
3. If there's exactly one such unique lifetime candidate found, we return this lifetime.

### Regular parameter search rules

1. Find all the lifetimes in each parameter, including implicit, explicit etc.
2. If there's exactly one parameter containing lifetimes, and if that parameter contains exactly one (unique) lifetime, *and if we didn't find a `self` lifetime parameter already*, we'll return this lifetime.

## The new rules

There are no changes to the "regular parameter search rules" or to the overall flow, only to the `self` search rules which are now:

1. Recursively walks the type of the `self` parameter, searching for lifetimes of reference types whose referent **contains** `Self`.[^1]
2. Keep a record of:
   * Whether 0, 1 or n unique lifetimes are found on references encountered during the walk
4. If no lifetime was found, we don't return a lifetime. (This means other parameters' lifetimes may be used for return type lifetime elision).
5. If there's one lifetime found, we return the lifetime.
6. If multiple lifetimes were found, we abort elision entirely (other parameters' lifetimes won't be used).

[^1]: this prevents us from considering lifetimes from inside of the self-type

## Examples that were accepted before and will now be rejected

```rust
fn a(self: &Box<&Self>) -> &u32
fn b(self: &Pin<&mut Self>) -> &String
fn c(self: &mut &Self) -> Option<&Self>
fn d(self: &mut &Box<Self>, arg: &usize) -> &usize // previously used the lt from arg
```

### Examples that change the elided lifetime

```rust
fn e(self: &mut Box<Self>, arg: &usize) -> &usize
//         ^ new                ^ previous
```

## Examples that were rejected before and will now be accepted

```rust
fn f(self: &Box<Self>) -> &u32
```

---

*edit: old PR description:*

```rust
  struct Concrete(u32);

  impl Concrete {
      fn m(self: &Box<Self>) -> &u32 {
          &self.0
      }
  }
```

resulted in a confusing error.

```rust
  impl Concrete {
      fn n(self: &Box<&Self>) -> &u32 {
          &self.0
      }
  }
```

resulted in no error or warning, despite apparent ambiguity over the elided lifetime.

Fixes https://github.com/rust-lang/rust/issues/117715
2024-07-18 13:33:38 +00:00
Matthias Krüger b52883decf
Rollup merge of #127886 - estebank:as-rename-suggestion, r=compiler-errors
Accurate `use` rename suggestion span

When suggesting to rename an import with `as`, use a smaller span to render the suggestion with a better format:

```
error[E0252]: the name `baz` is defined multiple times
  --> $DIR/issue-25396.rs:4:5
   |
LL | use foo::baz;
   |     -------- previous import of the module `baz` here
LL | use bar::baz;
   |     ^^^^^^^^ `baz` reimported here
   |
   = note: `baz` must be defined only once in the type namespace of this module
help: you can use `as` to change the binding name of the import
   |
LL | use bar::baz as other_baz;
   |              ++++++++++++
```
2024-07-18 08:09:01 +02:00
Esteban Küber 8eb51852a8 Accurate use rename suggestion span
When suggesting to rename an import with `as`, use a smaller span to
render the suggestion with a better format:

```
error[E0252]: the name `baz` is defined multiple times
  --> $DIR/issue-25396.rs:4:5
   |
LL | use foo::baz;
   |     -------- previous import of the module `baz` here
LL | use bar::baz;
   |     ^^^^^^^^ `baz` reimported here
   |
   = note: `baz` must be defined only once in the type namespace of this module
help: you can use `as` to change the binding name of the import
   |
LL | use bar::baz as other_baz;
   |              ++++++++++++
```
2024-07-18 00:00:04 +00:00
Noah Lev 37ed7a4438 Add ConstArgKind::Path and make ConstArg its own HIR node
This is a very large commit since a lot needs to be changed in order to
make the tests pass. The salient changes are:

- `ConstArgKind` gets a new `Path` variant, and all const params are now
  represented using it. Non-param paths still use `ConstArgKind::Anon`
  to prevent this change from getting too large, but they will soon use
  the `Path` variant too.

- `ConstArg` gets a distinct `hir_id` field and its own variant in
  `hir::Node`. This affected many parts of the compiler that expected
  the parent of an `AnonConst` to be the containing context (e.g., an
  array repeat expression). They have been changed to check the
  "grandparent" where necessary.

- Some `ast::AnonConst`s now have their `DefId`s created in
  rustc_ast_lowering rather than `DefCollector`. This is because in some
  cases they will end up becoming a `ConstArgKind::Path` instead, which
  has no `DefId`. We have to solve this in a hacky way where we guess
  whether the `AnonConst` could end up as a path const since we can't
  know for sure until after name resolution (`N` could refer to a free
  const or a nullary struct). If it has no chance as being a const
  param, then we create a `DefId` in `DefCollector` -- otherwise we
  decide during ast_lowering. This will have to be updated once all path
  consts use `ConstArgKind::Path`.

- We explicitly use `ConstArgHasType` for array lengths, rather than
  implicitly relying on anon const type feeding -- this is due to the
  addition of `ConstArgKind::Path`.

- Some tests have their outputs changed, but the changes are for the
  most part minor (including removing duplicate or almost-duplicate
  errors). One test now ICEs, but it is for an incomplete, unstable
  feature and is now tracked at #127009.
2024-07-16 19:27:28 -07:00
Oli Scherer 6ce78bea03 Update method name to reflect changes to its internals 2024-07-16 15:34:35 +00:00
Jubilee afb2fbf692
Rollup merge of #127310 - chenyukang:yukang-fix-suggest-import-ice, r=estebank
Fix import suggestion ice

Fixes #127302

#127302 only crash in edition 2015
#120074 can only reproduced in edition 2021
so I added revisions in test file.
2024-07-12 13:47:07 -07:00
Esteban Küber cf09cba20c When finding item gated behind a cfg flat, point at it
Previously we would only mention that the item was gated out, and opportunisitically mention the feature flag name when possible. We now point to the place where the item was gated, which can be behind layers of macro indirection, or in different modules.

```
error[E0433]: failed to resolve: could not find `doesnt_exist` in `inner`
  --> $DIR/diagnostics-cross-crate.rs:18:23
   |
LL |     cfged_out::inner::doesnt_exist::hello();
   |                       ^^^^^^^^^^^^ could not find `doesnt_exist` in `inner`
   |
note: found an item that was configured out
  --> $DIR/auxiliary/cfged_out.rs:6:13
   |
LL |     pub mod doesnt_exist {
   |             ^^^^^^^^^^^^
note: the item is gated here
  --> $DIR/auxiliary/cfged_out.rs:5:5
   |
LL |     #[cfg(FALSE)]
   |     ^^^^^^^^^^^^^
```
2024-07-12 18:52:52 +00:00
bors 4a31a6c32a Auto merge of #127382 - estebank:const-let, r=compiler-errors
Use verbose style when suggesting changing `const` with `let`
2024-07-12 01:18:12 +00:00
Esteban Küber cbe75486f7 Account for let foo = expr; to suggest const foo: Ty = expr; 2024-07-11 20:39:24 +00:00
Esteban Küber b56dc8ee90 Use verbose style when suggesting changing const with let 2024-07-11 20:39:24 +00:00
Michael Goulet 12ae282987 Fix diagnostic and add a test for it 2024-07-10 18:56:06 -04:00
许杰友 Jieyou Xu (Joe) bd4ab30e9c
Rollup merge of #127431 - oli-obk:feed_item_attrs, r=compiler-errors
Use field ident spans directly instead of the full field span in diagnostics on local fields

This improves diagnostics and avoids having to store the `DefId`s of fields
2024-07-08 13:04:32 +08:00
Matthias Krüger 510020ad4c
Rollup merge of #127308 - nnethercote:Attribute-cleanups, r=petrochenkov
Attribute cleanups

More refactoring done while trying to fix the final remaining test failure for #124141.

r? `@petrochenkov`
2024-07-07 14:22:01 +02:00
Nicholas Nethercote b261501b71 Remove HasSpan trait.
The only place it is meaningfully used is in a panic message in
`TokenStream::from_ast`. But `node.span()` doesn't need to be printed
because `node` is also printed and it must contain the span.
2024-07-07 15:58:34 +10:00
Oli Scherer 8c2ea715e9 Use field ident spans directly instead of the full field span in diagnostics on local fields 2024-07-06 19:22:05 +00:00
Vadim Petrochenkov 83cf471361 out_of_scope_macro_calls: Detect calls inside attributes more precisely 2024-07-06 15:36:30 +03:00
yukang fe5581dd31 Fix import suggestion ice 2024-07-04 09:55:00 +00:00
bors 66b4f0021b Auto merge of #127127 - notriddle:notriddle/pulldown-cmark-0.11, r=GuillaumeGomez
rustdoc: update to pulldown-cmark 0.11

r? rustdoc

This pull request updates rustdoc to the latest version of pulldown-cmark. Along with adding new markdown extensions (which this PR doesn't enable), the new pulldown-cmark version also fixes a large number of bugs. Because all text files successfully parse as markdown, these bugfixes change the output, which can break people's existing docs.

A crater run, https://github.com/rust-lang/rust/pull/121659, has already been run for this change.

The first commit upgrades and fixes rustdoc. The second commit adds a lint for the footnote and block quote parser changes, which break the largest numbers of docs in the Crater run. The strikethrough change was mitigated in pulldown-cmark itself.

Unblocks https://github.com/rust-lang/rust-clippy/pull/12876
2024-07-04 01:50:31 +00:00
Matthias Krüger 33e9f25e91
Rollup merge of #127092 - compiler-errors:rtn-dots-redux, r=estebank
Change return-type-notation to use `(..)`

Aligns the syntax with the current wording of [RFC 3654](https://github.com/rust-lang/rfcs/pull/3654). Also implements rustfmt support (along with making a match exhaustive).

Tracking:
* https://github.com/rust-lang/rust/issues/109417
2024-07-03 23:30:07 +02:00
yukang 8cc1ed81df Fix import suggestion error when failed not from starting 2024-07-01 20:07:29 +08:00
Michael Howell 15fbe618a1 rustdoc: update to pulldown-cmark 0.11 2024-06-30 18:33:48 -07:00
Michael Goulet b1a0c0b123 Change RTN to use .. again 2024-06-28 14:20:43 -04:00
Michael Goulet 789ee88bd0 Tighten spans for async blocks 2024-06-27 15:19:08 -04:00
Vadim Petrochenkov b6074fffd1 resolve: Tweak some naming around import ambiguities 2024-06-25 19:52:59 +03:00
bors d929a42a66 Auto merge of #125741 - petrochenkov:atvisord, r=davidtwco
ast: Standardize visiting order for attributes and node IDs

This should only affect `macro_rules` scopes and order of diagnostics.

Also add a deprecation lint for `macro_rules` called outside of their scope, like in https://github.com/rust-lang/rust/issues/124535.
2024-06-25 11:48:14 +00:00
Vadim Petrochenkov c4c7859e40 resolve: Implement a lint for out-of-scope use of macro_rules 2024-06-24 17:12:08 +03:00
Matthias Krüger 9d24ecc37b
Rollup merge of #125241 - Veykril:tool-rust-analyzer, r=davidtwco
Add `rust_analyzer` as a predefined tool

Given all the other rust-lang tools have it, I'd expect r-a to have it too. (we have a few ideas for using this https://github.com/rust-lang/rust-analyzer/issues/11556).
2024-06-24 15:06:21 +02:00
Michael Goulet ffd72b1700 Fix remaining cases 2024-06-21 19:00:18 -04:00
Lukas Wirth 339015920d Add rust_analyzer as a predefined tool 2024-06-21 12:10:18 +02:00
Matthias Krüger f577d808b7
Rollup merge of #126767 - compiler-errors:static-foreign-item, r=spastorino
`StaticForeignItem` and `StaticItem` are the same

The struct `StaticItem` and `StaticForeignItem` are the same, so remove `StaticForeignItem`. Having them be separate is unique to `static` items -- unlike `ForeignItemKind::{Fn,TyAlias}`, which use the normal AST item.

r? ``@spastorino`` or ``@oli-obk``
2024-06-21 09:12:37 +02:00
Michael Goulet 3e59f0c3c5 StaticForeignItem and StaticItem are the same 2024-06-20 19:51:09 -04:00
bohan 1e42bb606d collect attrs in const block expr 2024-06-20 19:59:27 +08:00
许杰友 Jieyou Xu (Joe) f8ce1cfbf5
Rollup merge of #124135 - petrochenkov:deleglob, r=fmease
delegation: Implement glob delegation

Support delegating to all trait methods in one go.
Overriding globs with explicit definitions is also supported.

The implementation is generally based on the design from https://github.com/rust-lang/rfcs/pull/3530#issuecomment-2020869823, but unlike with list delegation in https://github.com/rust-lang/rust/pull/123413 we cannot expand glob delegation eagerly.
We have to enqueue it into the queue of unexpanded macros (most other macros are processed this way too), and then a glob delegation waits in that queue until its trait path is resolved, and enough code expands to generate the identifier list produced from the glob.

Glob delegation is only allowed in impls, and can only point to traits.
Supporting it in other places gives very little practical benefit, but significantly raises the implementation complexity.

Part of https://github.com/rust-lang/rust/issues/118212.
2024-06-19 01:51:36 +01:00
Oli Scherer 3f34196839 Remove redundant argument from subdiagnostic method 2024-06-18 15:42:11 +00:00
Oli Scherer 7ba82d61eb Use a dedicated type instead of a reference for the diagnostic context
This paves the way for tracking more state (e.g. error tainting) in the diagnostic context handle
2024-06-18 15:42:11 +00:00
Michael Goulet b1efe1ab5d Rework precise capturing syntax 2024-06-17 22:35:25 -04:00
Matthias Krüger ba26af3e83
Rollup merge of #126568 - bvanjoi:fix-126376, r=petrochenkov
mark undetermined if target binding in current ns is not got

Fixes #126376
Fixes #126389

Add a branch to handle more cases...

r? `@petrochenkov`
2024-06-17 15:43:32 +02:00
许杰友 Jieyou Xu (Joe) 23b936f981
Rollup merge of #125258 - compiler-errors:static-if-no-lt, r=nnethercote
Resolve elided lifetimes in assoc const to static if no other lifetimes are in scope

Implements the change to elided lifetime resolution in *associated consts* subject to FCP here: https://github.com/rust-lang/rust/issues/125190#issue-2301532282

Specifically, walk the enclosing lifetime ribs in an associated const, and if we find no other lifetimes, then resolve to `'static`.

Also make it work for traits, but don't lint -- just give a hard error in that case.
2024-06-17 04:53:54 +01:00
bohan 2f17535584 mark undetermined if target binding in current ns is not got 2024-06-17 11:29:43 +08:00
Vadim Petrochenkov cbc3bdbe01 delegation: Fix hygiene for self
And fix diagnostics for `self` from a macro.
2024-06-15 00:45:05 +03:00
Vadim Petrochenkov 22d0b1ee18 delegation: Implement glob delegation 2024-06-14 19:27:51 +03:00
Michael Goulet 5f3357c3c6 Resolve const lifetimes to static in trait too 2024-06-14 11:05:35 -04:00
Michael Goulet 4f97ab54c4 Resolve elided lifetimes in assoc const to static if no other lifetimes are in scope 2024-06-14 11:05:35 -04:00
Esteban Küber 5de8e6edfc Tweak output of import suggestions
When both `std::` and `core::` items are available, only suggest the
`std::` ones. We ensure that in `no_std` crates we suggest `core::`
items.

Ensure that the list of items suggested to be imported are always in the
order of local crate items, `std`/`core` items and finally foreign crate
items.

Tweak wording of import suggestion: if there are multiple items but they
are all of the same kind, we use the kind name and not the generic "items".

Fix #83564.
2024-06-13 20:22:21 +00:00
许杰友 Jieyou Xu (Joe) 76acf2617c
Rollup merge of #126234 - Bryanskiy:delegation-no-entry-ice, r=petrochenkov
Delegation: fix ICE on late diagnostics

fixes https://github.com/rust-lang/rust/issues/124342
2024-06-11 09:14:35 +01:00
许杰友 Jieyou Xu (Joe) 81ff9b5770
Rollup merge of #125913 - fmease:early-lints-spruce-up-some-diags, r=Nadrieril
Spruce up the diagnostics of some early lints

Implement the various "*(note to myself) in a follow-up PR we should turn parts of this message into a subdiagnostic (help msg or even struct sugg)*" drive-by comments I left in #124417 during my review.

For context, before #124417, only a few early lints touched/decorated/customized their diagnostic because the former API made it a bit awkward. Likely because of that, things that should've been subdiagnostics were just crammed into the primary message. This PR rectifies this.
2024-06-11 09:14:34 +01:00
Bryanskiy 040791a9c5 Delegation: fix ICE on late diagnostics 2024-06-10 19:25:34 +03:00
Adrian Taylor a22130e1e0 Elision: consider lifetimes from &T iff T has Self
Change the algorithm which determines whether a self lifetime can be
used for return type lifetime elision, such that we consider lifetimes
attached to any reference in the self type, so long as Self can be found
anywhere inside the type of that reference.
2024-06-10 08:44:44 +00:00
bohan 93feaa6685 mark binding undetermined if target name exist and not obtained 2024-06-07 21:23:56 +08:00
Oli Scherer cbee17d502 Revert "Create const block DefIds in typeck instead of ast lowering"
This reverts commit ddc5f9b6c1.
2024-06-07 08:33:58 +00:00
bors 2d28b6384e Auto merge of #124482 - spastorino:unsafe-extern-blocks, r=oli-obk
Unsafe extern blocks

This implements RFC 3484.

Tracking issue #123743 and RFC https://github.com/rust-lang/rfcs/pull/3484

This is better reviewed commit by commit.
2024-06-06 08:14:58 +00:00
bors 72fdf913c5 Auto merge of #126038 - matthiaskrgr:rollup-h4rm3x2, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #124840 (resolve: mark it undetermined if single import is not has any bindings)
 - #125622 (Winnow private method candidates instead of assuming any candidate of the right name will apply)
 - #125648 (Remove unused(?) `~/rustsrc` folder from docker script)
 - #125672 (Add more ABI test cases to miri (RFC 3391))
 - #125800 (Fix `mut` static task queue in SGX target)
 - #125871 (Orphanck[old solver]: Consider opaque types to never cover type parameters)
 - #125893 (Handle all GVN binops in a single place.)
 - #126008 (Port `tests/run-make-fulldeps/issue-19371` to ui-fulldeps)
 - #126032 (Update description of the `IsTerminal` example)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-06-05 20:53:32 +00:00
Matthias Krüger 69a8c139f1
Rollup merge of #124840 - bvanjoi:fix-124490, r=petrochenkov
resolve: mark it undetermined if single import is not has any bindings

- Fixes #124490
- Fixes #125013

This issue arises from incorrect resolution updates, for example:

```rust
mod a {
    pub mod b {
        pub mod c {}
    }
}

use a::*;

use b::c;
use c as b;

fn main() {}
```

1. In the first loop, binding `(root, b)` is refer to `root:🅰️:b` due to `use a::*`.
    1. However, binding `(root, c)` isn't defined by `use b::c` during this stage because `use c as b` falls under the `single_imports` of `(root, b)`, where the `imported_module` hasn't been computed yet. This results in marking the `path_res` for `b` as `Indeterminate`.
    2. Then, the `imported_module` for `use c as b` will be recorded.
2. In the second loop, `use b::c` will be processed again:
    1. Firstly, it attempts to find the `path_res` for `(root, b)`.
    2. It will iterate through the `single_imports` of `use b::c`, encounter `use c as b`, attempt to resolve `c` in `root`, and ultimately return `Err(Undetermined)`, thus passing the iterator.
    3. Use the binding `(root, b)` -> `root:🅰️:b` introduced by `use a::*` and ultimately return `root:🅰️:b` as the `path_res` of `b`.
    4. Then define the binding `(root, c)` -> `root:🅰️🅱️:c`.
3. Then process `use c as b`, update the resolution for `(root, b)` to refer to `root:🅰️🅱️:c`, ultimately causing inconsistency.

In my view, step `2.2` has an issue where it should exit early, similar to the behavior when there's no `imported_module`. Therefore, I've added an attribute called `indeterminate` to `ImportData`. This will help us handle only those single imports that have at least one determined binding.

r? ``@petrochenkov``
2024-06-05 18:21:11 +02:00
Matthias Krüger 49f950434b
Rollup merge of #125407 - pacak:no-lending-iterators, r=pnkfelix
Detect when user is trying to create a lending `Iterator` and give a custom explanation

The scope for this diagnostic is to detect lending iterators specifically and it's main goal is to help beginners to understand that what they are trying to implement might not be possible for `Iterator` trait specifically.

I ended up to changing the wording from originally proposed in the ticket because it might be misleading otherwise: `Data` might have a lifetime parameter but it can be unrelated to items user is planning to return.

Fixes https://github.com/rust-lang/rust/issues/125337
2024-06-05 18:21:08 +02:00
Santiago Pastorino bac72cf7cf
Add safe/unsafe to static inside extern blocks 2024-06-04 14:19:43 -03:00
Santiago Pastorino 2a377122dd
Handle safety keyword for extern block inner items 2024-06-04 14:19:42 -03:00
Michael Goulet 7e5528fa55
Rollup merge of #125795 - lucasscharenbroch:undescore-prefix-suggestion, r=compiler-errors
Improve renaming suggestion for names with leading underscores

Fixes #125650

Before:
```
error[E0425]: cannot find value `p` in this scope
 --> test.rs:2:13
  |
2 |     let _ = p;
  |             ^
  |
help: a local variable with a similar name exists, consider renaming `_p` into `p`
  |
1 | fn a(p: i32) {
  |      ~
```

After:
```
error[E0425]: cannot find value `p` in this scope
 --> test.rs:2:13
  |
1 | fn a(_p: i32) {
  |      -- `_p` defined here
2 |     let _ = p;
  |             ^
  |
help: the leading underscore in `_p` marks it as unused, consider renaming it to `p`
  |
1 | fn a(p: i32) {
  |      ~
```

This change doesn't exactly conform to what was proposed in the issue:

1. I've kept the suggested code instead of solely replacing it with the label
2. I've removed the "...similar name exists..." message instead of relocating to the usage span
3. You could argue that it still isn't completely clear that the change is referring to the definition (not the usage), but I'm not sure how to do this without playing down the fact that the error was caused by the usage of an undefined name.
2024-06-04 08:52:13 -04:00
bohan f67a0eb2b7 resolve: mark it undetermined if single import is not has any bindings 2024-06-04 12:40:41 +08:00
León Orell Valerian Liehr b2949ff911
Spruce up the diagnostics of some early lints 2024-06-03 07:25:32 +02:00
Matthias Krüger 379233242b
Rollup merge of #125635 - fmease:mv-type-binding-assoc-item-constraint, r=compiler-errors
Rename HIR `TypeBinding` to `AssocItemConstraint` and related cleanup

Rename `hir::TypeBinding` and `ast::AssocConstraint` to `AssocItemConstraint` and update all items and locals using the old terminology.

Motivation: The terminology *type binding* is extremely outdated. "Type bindings" not only include constraints on associated *types* but also on associated *constants* (feature `associated_const_equality`) and on RPITITs of associated *functions* (feature `return_type_notation`). Hence the word *item* in the new name. Furthermore, the word *binding* commonly refers to a mapping from a binder/identifier to a "value" for some definition of "value". Its use in "type binding" made sense when equality constraints (e.g., `AssocTy = Ty`) were the only kind of associated item constraint. Nowadays however, we also have *associated type bounds* (e.g., `AssocTy: Bound`) for which the term *binding* doesn't make sense.

---

Old terminology (HIR, rustdoc):

```
`TypeBinding`: (associated) type binding
├── `Constraint`: associated type bound
└── `Equality`: (associated) equality constraint (?)
    ├── `Ty`: (associated) type binding
    └── `Const`: associated const equality (constraint)
```

Old terminology (AST, abbrev.):

```
`AssocConstraint`
├── `Bound`
└── `Equality`
    ├── `Ty`
    └── `Const`
```

New terminology (AST, HIR, rustdoc):

```
`AssocItemConstraint`: associated item constraint
├── `Bound`: associated type bound
└── `Equality`: associated item equality constraint OR associated item binding (for short)
    ├── `Ty`: associated type equality constraint OR associated type binding (for short)
    └── `Const`: associated const equality constraint OR associated const binding (for short)
```

r? compiler-errors
2024-05-31 08:50:22 +02:00
Lucas Scharenbroch 08fe940f0a Improve renaming suggestion for names with leading underscores 2024-05-30 21:39:12 -05:00
León Orell Valerian Liehr 34c56c45cf
Rename HIR TypeBinding to AssocItemConstraint and related cleanup 2024-05-30 22:52:33 +02:00
Matthias Krüger c09b89ea32
Rollup merge of #125705 - oli-obk:const_block_ice, r=compiler-errors
Reintroduce name resolution check for trying to access locals from an inline const

fixes #125676

I removed this without replacement in https://github.com/rust-lang/rust/pull/124650 without considering the consequences
2024-05-29 20:12:34 +02:00
Oli Scherer bcfefe1c7e Reintroduce name resolution check for trying to access locals from an inline const 2024-05-29 08:28:44 +00:00
许杰友 Jieyou Xu (Joe) bc1a069ec5
Rollup merge of #125381 - estebank:issue-96799, r=petrochenkov
Silence some resolve errors when there have been glob import errors

When encountering `use foo::*;` where `foo` fails to be found, and we later encounter resolution errors, we silence those later errors.

A single case of the above, for an *existing* import on a big codebase would otherwise have a huge number of knock-down spurious errors.

Ideally, instead of a global flag to silence all subsequent resolve errors, we'd want to introduce an unnameable binding in the appropriate rib as a sentinel when there's a failed glob import, so when we encounter a resolve error we can search for that sentinel and if found, and only then, silence that error. The current approach is just a quick proof of concept to iterate over.

Partially address #96799.
2024-05-29 03:25:08 +01:00
Esteban Küber 37c54db477 Silence some resolve errors when there have been glob import errors
When encountering `use foo::*;` where `foo` fails to be found, and we later
encounter resolution errors, we silence those later errors.

A single case of the above, for an *existing* import on a big codebase would
otherwise have a huge number of knock-down spurious errors.

Ideally, instead of a global flag to silence all subsequent resolve errors,
we'd want to introduce an unameable binding in the appropriate rib as a
sentinel when there's a failed glob import, so when we encounter a resolve
error we can search for that sentinel and if found, and only then, silence
that error. The current approach is just a quick proof of concept to
iterate over.

Partially address #96799.
2024-05-28 14:45:21 +00:00
Oli Scherer ddc5f9b6c1 Create const block DefIds in typeck instead of ast lowering 2024-05-28 13:38:43 +00:00
Michael Baikov b70fb4159b And more general error 2024-05-24 11:20:33 -04:00
Michael Baikov d6e4fe569c A custom error message for lending iterators 2024-05-24 07:23:30 -04:00
Matthias Krüger 4af1c31fcf
Rollup merge of #125156 - zachs18:for_loops_over_fallibles_behind_refs, r=Nilstrieb
Expand `for_loops_over_fallibles` lint to lint on fallibles behind references.

Extends the scope of the (warn-by-default) lint `for_loops_over_fallibles` from just `for _ in x` where `x: Option<_>/Result<_, _>` to also cover `x: &(mut) Option<_>/Result<_>`

```rs
fn main() {
    // Current lints
    for _ in Some(42) {}
    for _ in Ok::<_, i32>(42) {}

    // New lints
    for _ in &Some(42) {}
    for _ in &mut Some(42) {}
    for _ in &Ok::<_, i32>(42) {}
    for _ in &mut Ok::<_, i32>(42) {}

    // Should not lint
    for _ in Some(42).into_iter() {}
    for _ in Some(42).iter() {}
    for _ in Some(42).iter_mut() {}
    for _ in Ok::<_, i32>(42).into_iter() {}
    for _ in Ok::<_, i32>(42).iter() {}
    for _ in Ok::<_, i32>(42).iter_mut() {}
}
```

<details><summary><code>cargo build</code> diff</summary>

```diff
diff --git a/old.out b/new.out
index 84215aa..ca195a7 100644
--- a/old.out
+++ b/new.out
`@@` -1,33 +1,93 `@@`
 warning: for loop over an `Option`. This is more readably written as an `if let` statement
  --> src/main.rs:3:14
   |
 3 |     for _ in Some(42) {}
   |              ^^^^^^^^
   |
   = note: `#[warn(for_loops_over_fallibles)]` on by default
 help: to check pattern in a loop use `while let`
   |
 3 |     while let Some(_) = Some(42) {}
   |     ~~~~~~~~~~~~~~~ ~~~
 help: consider using `if let` to clear intent
   |
 3 |     if let Some(_) = Some(42) {}
   |     ~~~~~~~~~~~~ ~~~

 warning: for loop over a `Result`. This is more readably written as an `if let` statement
  --> src/main.rs:4:14
   |
 4 |     for _ in Ok::<_, i32>(42) {}
   |              ^^^^^^^^^^^^^^^^
   |
 help: to check pattern in a loop use `while let`
   |
 4 |     while let Ok(_) = Ok::<_, i32>(42) {}
   |     ~~~~~~~~~~~~~ ~~~
 help: consider using `if let` to clear intent
   |
 4 |     if let Ok(_) = Ok::<_, i32>(42) {}
   |     ~~~~~~~~~~ ~~~

-warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 2 warnings
-    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.04s
+warning: for loop over a `&Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:7:14
+  |
+7 |     for _ in &Some(42) {}
+  |              ^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+7 |     while let Some(_) = &Some(42) {}
+  |     ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+7 |     if let Some(_) = &Some(42) {}
+  |     ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Option`. This is more readably written as an `if let` statement
+ --> src/main.rs:8:14
+  |
+8 |     for _ in &mut Some(42) {}
+  |              ^^^^^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+8 |     while let Some(_) = &mut Some(42) {}
+  |     ~~~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+8 |     if let Some(_) = &mut Some(42) {}
+  |     ~~~~~~~~~~~~ ~~~
+
+warning: for loop over a `&Result`. This is more readably written as an `if let` statement
+ --> src/main.rs:9:14
+  |
+9 |     for _ in &Ok::<_, i32>(42) {}
+  |              ^^^^^^^^^^^^^^^^^
+  |
+help: to check pattern in a loop use `while let`
+  |
+9 |     while let Ok(_) = &Ok::<_, i32>(42) {}
+  |     ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+  |
+9 |     if let Ok(_) = &Ok::<_, i32>(42) {}
+  |     ~~~~~~~~~~ ~~~
+
+warning: for loop over a `&mut Result`. This is more readably written as an `if let` statement
+  --> src/main.rs:10:14
+   |
+10 |     for _ in &mut Ok::<_, i32>(42) {}
+   |              ^^^^^^^^^^^^^^^^^^^^^
+   |
+help: to check pattern in a loop use `while let`
+   |
+10 |     while let Ok(_) = &mut Ok::<_, i32>(42) {}
+   |     ~~~~~~~~~~~~~ ~~~
+help: consider using `if let` to clear intent
+   |
+10 |     if let Ok(_) = &mut Ok::<_, i32>(42) {}
+   |     ~~~~~~~~~~ ~~~
+
+warning: `for-loops-over-fallibles` (bin "for-loops-over-fallibles") generated 6 warnings
+    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.02s

```

</details>

-----

Question:

* ~~Currently, the article `an` is used for `&Option`, and `&mut Option` in the lint diagnostic, since that's what `Option` uses. Is this okay or should it be changed? (likewise, `a` is used for `&Result` and `&mut Result`)~~ The article `a` is used for `&Option`, `&mut Option`, `&Result`, `&mut Result` and (as before) `Result`. Only `Option` uses `an` (as before).

`@rustbot` label +A-lint
2024-05-23 07:41:17 +02:00
Adrian Taylor e62599f856 Do not elide if there's ambiguity in self lifetime.
This makes a small change as requested in code review, such that if there's
ambiguity in the self lifetime, we avoid lifetime elision entirely instead of
considering using lifetimes from any of the other parameters.

For example,

impl Something {
  fn method(self: &Box<&Self>, something_else: &u32) -> &u32 { ... }
}

in standard Rust would have assumed the return lifetime was that of &Self;
with this PR prior to this commit would have chosen the lifetime of
'something_else', and after this commit would give an error message explaining
that the lifetime is ambiguous.
2024-05-22 14:22:52 +00:00
Adrian Taylor 8d1958f0d2 Ambiguous Self lifetimes: don't elide.
struct Concrete(u32);

  impl Concrete {
      fn m(self: &Box<Self>) -> &u32 {
          &self.0
      }
  }

resulted in a confusing error.

  impl Concrete {
      fn n(self: &Box<&Self>) -> &u32 {
          &self.0
      }
  }

resulted in no error or warning, despite apparent ambiguity over the elided
lifetime.

This commit changes two aspects of the behavior.

Previously, when examining the self type, we considered lifetimes only if they
were immediately adjacent to Self. We now consider lifetimes anywhere in the
self type.

Secondly, if more than one lifetime is discovered in the self type, we
disregard it as a possible lifetime elision candidate.

This is a compatibility break, and in fact has required some changes to tests
which assumed the earlier behavior.

Fixes https://github.com/rust-lang/rust/issues/117715
2024-05-22 14:22:52 +00:00
bors b54dd08a84 Auto merge of #125326 - weiznich:move/do_not_recommend_to_diganostic_namespace, r=compiler-errors
Move `#[do_not_recommend]` to the `#[diagnostic]` namespace

This commit moves the `#[do_not_recommend]` attribute to the `#[diagnostic]` namespace. It still requires
`#![feature(do_not_recommend)]` to work.

r? `@compiler-errors`
2024-05-22 04:14:08 +00:00
bors 791adf759c Auto merge of #124417 - Xiretza:translate-early-lints, r=fmease
Make early lints translatable

<del>Requires https://github.com/projectfluent/fluent-rs/pull/353.</del> 5134a04eaa

r? diagnostics
2024-05-21 21:36:09 +00:00
Xiretza 98dd6c7e8f Rename buffer_lint_with_diagnostic to buffer_lint 2024-05-21 20:16:39 +00:00
Xiretza 8004e6a379 Make early lints translatable 2024-05-21 20:16:39 +00:00
Xiretza b7abf014ec Convert uses of BuiltinLintDiag::Normal to custom variants
This ensures all diagnostic messages are created at diagnostic emission
time, making them translatable.
2024-05-21 20:16:39 +00:00
Xiretza 41a20b4c56 Port DeprecatedMacro to diag structs 2024-05-21 20:16:39 +00:00
Xiretza c227f35a9c Generate lint diagnostic message from BuiltinLintDiag
Translation of the lint message happens when the actual diagnostic is
created, not when the lint is buffered. Generating the message from
BuiltinLintDiag ensures that all required data to construct the message
is preserved in the LintBuffer, eventually allowing the messages to be
moved to fluent.

Remove the `msg` field from BufferedEarlyLint, it is either generated
from the data in the BuiltinLintDiag or stored inside
BuiltinLintDiag::Normal.
2024-05-21 20:16:39 +00:00
Georg Semmler 2cff3e90bc
Move #[do_not_recommend] to the #[diagnostic] namespace
This commit moves the `#[do_not_recommend]` attribute to the
`#[diagnostic]` namespace. It still requires
`#![feature(do_not_recommend)]` to work.
2024-05-21 13:14:41 +02:00
surechen 4ebbb5f048 Fix incorrect suggestion for undeclared hrtb lifetimes in where clauses.
fixes #122714
2024-05-20 20:28:57 +08:00
Pietro Albini 5d03c3d3a5
fix typo 2024-05-19 10:23:31 +02:00
bors 36c0a6d40f Auto merge of #125105 - nnethercote:rustc_resolve-cleanups, r=estebank
`rustc_resolve` cleanups

Some improvements I found while looking through this code.

r? `@estebank`
2024-05-18 06:36:44 +00:00
Zachary S 7d7eb973d0 Fix new for_loops_over_fallibles hits in compiler. 2024-05-15 11:05:44 -05:00
bors 3cb0030fe9 Auto merge of #123413 - petrochenkov:delegmulti2, r=fmease
delegation: Implement list delegation

```rust
reuse prefix::{a, b, c};
```

Using design described in https://github.com/rust-lang/rfcs/pull/3530#issuecomment-2020869823 (the lists are desugared at macro expansion time).
List delegations are expanded eagerly when encountered, similarly to `#[cfg]`s, and not enqueued for later resolution/expansion like regular macros or glob delegation (https://github.com/rust-lang/rust/pull/124135).

Part of https://github.com/rust-lang/rust/issues/118212.
2024-05-15 10:35:31 +00:00