Commit graph

1965 commits

Author SHA1 Message Date
Bryanskiy 17c6101864 Delegation: fix ICE on wrong self resolution 2024-03-26 14:00:51 +03:00
Michael Goulet a4db3ffdcb Don't suggest deref macro since it's unstable 2024-03-21 11:42:49 -04:00
bors 6e1f7b538a Auto merge of #121587 - ShoyuVanilla:fix-issue-121267, r=TaKO8Ki
Fix bad span for explicit lifetime suggestions

Fixes #121267

Current explicit lifetime suggestions are not showing correct spans for some lifetimes - e.g. elided lifetime generic parameters;

This should be done correctly regarding elided lifetime kind like the following code

43fdd4916d/compiler/rustc_resolve/src/late/diagnostics.rs (L3015-L3044)
2024-03-21 04:11:09 +00:00
Shoyu Vanilla c270a42fea Fix bad span for explicit lifetime suggestion
Move verbose logic to a function

Minor renaming
2024-03-21 10:31:04 +09:00
Alex Macleod a8452461dc Ignore paths from expansion in unused_qualifications 2024-03-20 16:30:26 +00:00
bohan 7f45f53204 store segment and module in UnresolvedImportError 2024-03-20 18:04:47 +08:00
Matthias Krüger 489c2e9918
Rollup merge of #122435 - jieyouxu:unused_qualifications_global_paths, r=petrochenkov
Don't trigger `unused_qualifications` on global paths

Fixes #122374.
2024-03-19 18:03:49 +01:00
bors c03ea3dfd9 Auto merge of #121926 - tgross35:f16-f128-step3-feature-gate, r=compiler-errors,petrochenkov
`f16` and `f128` step 3: compiler support & feature gate

Continuation of https://github.com/rust-lang/rust/pull/121841, another portion of https://github.com/rust-lang/rust/pull/114607

This PR exposes the new types to the world and adds a feature gate. Marking this as a draft because I need some feedback on where I did the feature gate check. It also does not yet catch type via suffixed literals (so the feature gate test will fail, probably some others too because I haven't belssed).

If there is a better place to check all types after resolution, I can do that. If not, I figure maybe I can add a second gate location in AST when it checks numeric suffixes.

Unfortunately I still don't think there is much testing to be done for correctness (codegen tests or parsed value checks) until we have basic library support. I think that will be the next step.

Tracking issue: https://github.com/rust-lang/rust/issues/116909

r? `@compiler-errors`
cc `@Nilstrieb`
`@rustbot` label +F-f16_and_f128
2024-03-16 02:02:00 +00:00
Guillaume Gomez 6ec4092eaf
Rollup merge of #122530 - klensy:as_str, r=fee1-dead
less symbol interner locks

This reduces instructions under 1% (in rustdoc run), but essentially free.
2024-03-15 17:24:10 +01:00
许杰友 Jieyou Xu (Joe) 85bad8d1bf
Don't trigger unused_qualifications on global paths
# Conflicts:
#	tests/ui/lint/lint-qualification.stderr
2024-03-15 14:59:05 +00:00
klensy 7ea4f35766 less symbols interner locks 2024-03-15 10:54:40 +03:00
Matthias Krüger b200108bc5
Rollup merge of #122373 - surechen:fix_121331, r=petrochenkov
Fix the conflict problem between the diagnostics fixes of lint `unnecessary_qualification`  and  `unused_imports`

fixes #121331

For an `item` that triggers lint unnecessary_qualification, if the `use item` which imports this item is also trigger unused import, fixing the two lints at the same time may lead to the problem that the `item` cannot be found.
This PR will avoid reporting lint unnecessary_qualification when conflict occurs.

r? ``@petrochenkov``
2024-03-14 20:00:20 +01:00
Trevor Gross e782d27ec6 Add feature gates for f16 and f128
Includes related tests and documentation pages.

Michael Goulet: Don't issue feature error in resolver for f16/f128
unless finalize

Co-authored-by: Michael Goulet <michael@errs.io>
2024-03-14 13:32:54 -04:00
surechen 1a81a941ad fixes #121331 2024-03-14 09:54:42 +08:00
bohan 8fcdf54a6b delay expand macro bang when there has indeterminate path 2024-03-13 16:11:16 +08:00
Oli Scherer bbbf06d5e9 Manual rustfmt 2024-03-12 05:53:46 +00:00
Oli Scherer 926bfe5078 s/mt/mutability/ 2024-03-12 05:53:46 +00:00
Oli Scherer 0b4cbee660 Add nested bool to DefKind::Static.
Will be used in the next commit
2024-03-12 05:53:46 +00:00
Oli Scherer 9816915954 Change DefKind::Static to a struct variant 2024-03-12 05:53:46 +00:00
Nicholas Nethercote a09b1d33a7 Rename IntoDiagnosticArg as IntoDiagArg.
Also rename `into_diagnostic_arg` as `into_diag_arg`, and
`NotIntoDiagnosticArg` as `NotInotDiagArg`.
2024-03-11 09:12:19 +11:00
Nicholas Nethercote 567744c10e Remove Default derive from MacroExpectedFound.
It's the only diagnostic in the entire project that impls `Default`, and
the code is clearer without it.
2024-03-11 08:52:50 +11:00
Matthias Krüger d774fbea7c
Rollup merge of #119365 - nbdd0121:asm-goto, r=Amanieu
Add asm goto support to `asm!`

Tracking issue: #119364

This PR implements asm-goto support, using the syntax described in "future possibilities" section of [RFC2873](https://rust-lang.github.io/rfcs/2873-inline-asm.html#asm-goto).

Currently I have only implemented the `label` part, not the `fallthrough` part (i.e. fallthrough is implicit). This doesn't reduce the expressive though, since you can use label-break to get arbitrary control flow or simply set a value and rely on jump threading optimisation to get the desired control flow. I can add that later if deemed necessary.

r? ``@Amanieu``
cc ``@ojeda``
2024-03-08 08:19:17 +01:00
Guillaume Gomez 4de78d2a8d
Rollup merge of #121089 - oli-obk:create_def_feed, r=petrochenkov
Remove `feed_local_def_id`

best reviewed commit by commit

Basically I returned `TyCtxtFeed` from `create_def` and then preserved that in the local caches

based on https://github.com/rust-lang/rust/pull/121084

r? ````@petrochenkov````
2024-03-07 18:32:47 +01:00
Oli Scherer 8206cffc48 Merge check_mod_impl_wf and check_mod_type_wf 2024-03-07 06:27:09 +00:00
bors aa029ce4d8 Auto merge of #122113 - matthiaskrgr:rollup-5d1jnwi, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #121958 (Fix redundant import errors for preload extern crate)
 - #121976 (Add an option to have an external download/bootstrap cache)
 - #122022 (loongarch: add frecipe and relax target feature)
 - #122026 (Do not try to format removed files)
 - #122027 (Uplift some feeding out of `associated_type_for_impl_trait_in_impl` and into queries)
 - #122063 (Make the lowering of `thir::ExprKind::If` easier to follow)
 - #122074 (Add missing PartialOrd trait implementation doc for array)
 - #122082 (remove outdated fixme comment)
 - #122091 (Note why we're using a new thread in `test_get_os_named_thread`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-07 02:30:40 +00:00
Matthias Krüger e93a3d1d93
Rollup merge of #122038 - Alexendoo:unused-qualifications, r=petrochenkov
Fix linting paths with qself in `unused_qualifications`

Fixes #121999

`resolve_qpath` ends up being called again with `qself` set to `None` to check trait items from fully qualified paths. To avoid this the lint is moved to a place that accounts for this already

96561a8fd1/compiler/rustc_resolve/src/late.rs (L4074-L4088)

r? `````@petrochenkov`````
2024-03-06 22:02:47 +01:00
yukang 5a4ff2779e Fix redundant import errors for preload extern crate 2024-03-06 21:29:33 +08:00
bohan 7303014381 avoid overlapping privacy suggestion for single nested imports 2024-03-06 21:17:12 +08:00
bors 62415e2a95 Auto merge of #122041 - matthiaskrgr:rollup-imsmdke, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #121202 (Limit the number of names and values in check-cfg diagnostics)
 - #121301 (errors: share `SilentEmitter` between rustc and rustfmt)
 - #121658 (Hint user to update nightly on ICEs produced from outdated nightly)
 - #121846 (only compare ambiguity item that have hard error)
 - #121961 (add test for #78894 #71450)
 - #121975 (hir_analysis: enums return `None` in `find_field`)
 - #121978 (Fix duplicated path in the "not found dylib" error)
 - #121991 (Merge impl_trait_in_assoc_types_defined_by query back into `opaque_types_defined_by`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-06 00:03:50 +00:00
Matthias Krüger 152b69054c
Rollup merge of #121846 - bvanjoi:fix-121760, r=petrochenkov
only compare ambiguity item that have hard error

Fixes #121760

An easy fix, r? ``@petrochenkov``
2024-03-05 19:53:20 +01:00
Alex Macleod 6120de99f7 Fix linting paths with qself in unused_qualifications 2024-03-05 18:31:32 +00:00
Jason Newcomb 5abfb3775d Move visitor utils to rustc_ast_ir 2024-03-05 12:38:03 -05:00
Oli Scherer c696d4c323 Remove a use of feed_local_crate and make it fail if used within queries 2024-03-05 08:53:14 +00:00
Oli Scherer 3845be6b37 Prevent feeding CRATE_DEF_ID queries outside the resolver 2024-03-05 05:53:33 +00:00
Oli Scherer 5a0c46a22c Get rid of feed_local_def_id 2024-03-05 05:52:00 +00:00
Oli Scherer 30f2ec2895 Eliminate all non-CRATE_DEF_ID uses of feed_def_id 2024-03-05 05:51:44 +00:00
Oli Scherer 3b9dfd3f09 Preserve the Feed in local tables 2024-03-05 05:49:52 +00:00
Oli Scherer 2149c45e03 Bubble up the TyCtxtFeed 2024-03-05 05:45:03 +00:00
Nicholas Nethercote 5cce28725f Rename DiagnosticMetadata as DiagMetadata. 2024-03-05 12:15:13 +11:00
Nicholas Nethercote 7aa0eea19c Rename BuiltinLintDiagnostics as BuiltinLintDiag.
Not the dropping of the trailing `s` -- this type describes a single
diagnostic and its name should be singular.
2024-03-05 12:15:10 +11:00
Nicholas Nethercote d0e9bab51b Rename DiagnosticMode as DiagMode. 2024-03-05 12:14:49 +11:00
Matthias Krüger 13b971209a
Rollup merge of #121969 - nnethercote:ParseSess-cleanups, r=wesleywiser
`ParseSess` cleanups

The main change here is to rename all `ParseSess` values as `psess`. Plus a few other small cleanups.

r? `@wesleywiser`
2024-03-04 22:16:33 +01:00
Nicholas Nethercote 80d2bdb619 Rename all ParseSess variables/fields/lifetimes as psess.
Existing names for values of this type are `sess`, `parse_sess`,
`parse_session`, and `ps`. `sess` is particularly annoying because
that's also used for `Session` values, which are often co-located, and
it can be difficult to know which type a value named `sess` refers to.
(That annoyance is the main motivation for this change.) `psess` is nice
and short, which is good for a name used this much.

The commit also renames some `parse_sess_created` values as
`psess_created`.
2024-03-05 08:11:45 +11:00
Matthias Krüger c620ae5be9
Rollup merge of #121130 - chenyukang:yukang-fix-121061-macro-later, r=matthiaskrgr
Suggest moving definition if non-found macro_rules! is defined later

Fixes #121061
2024-03-04 07:57:56 +01:00
Matthias Krüger ed6d17523a
Rollup merge of #121528 - Alexendoo:unused_qualifications, r=petrochenkov
Consider middle segments of paths in `unused_qualifications`

Currently `unused_qualifications` looks at the last segment of a path to see if it can be trimmed, this PR extends the check to the middle segments also

```rust
// currently linted
use std::env::args();
std::env::args(); // Removes `std::env::`
```
```rust
// newly linted
use std::env;
std::env::args(); // Removes `std::`
```

Paths with generics in them are now linted as long as the part being trimmed is before any generic args, e.g. it will now suggest trimming `std::vec::` from `std::vec::Vec<usize>`

Paths with any segments that are from an expansion are no longer linted

Fixes #100979
Fixes #96698
2024-03-03 22:56:13 +01:00
Alex Macleod 4ea9f72c72 Consider middle segments of paths in unused_qualifications 2024-03-03 19:14:28 +00:00
Matthias Krüger 7a48987006 avoid collecting into vecs in some places 2024-03-02 14:18:47 +01:00
bohan 89954e55e1 only compare ambiguity item that have hard error 2024-03-01 19:41:46 +08:00
r0cky 2064c19886 Remove unused fluent messages 2024-03-01 09:59:44 +08:00
Guillaume Gomez 8a74df9c22
Rollup merge of #121792 - GuillaumeGomez:improve-suggestion, r=michaelwoerister
Improve renaming suggestion when item starts with underscore

Fixes https://github.com/rust-lang/rust/issues/121776.

It goes from:

```terminal
error[E0433]: failed to resolve: use of undeclared type `Foo`
 --> src/foo.rs:6:13
  |
6 |     let _ = Foo::Bar;
  |             ^^^ use of undeclared type `Foo`
  |
help: an enum with a similar name exists, consider changing it
  |
1 | enum Foo {
  |      ~~~
```

to:

```terminal
error[E0433]: failed to resolve: use of undeclared type `Foo`
 --> foo.rs:6:13
  |
6 |     let _ = Foo::Bar;
  |             ^^^ use of undeclared type `Foo`
  |
help: an enum with a similar name exists, consider renaming `_Foo` into `Foo`
  |
1 | enum Foo {
  |      ~~~

error: aborting due to 1 previous error
```
2024-02-29 14:33:53 +01:00
Guillaume Gomez 3770cf7abf Improve suggestion to rename type starting with underscore to make it more obvious what is actually suggested 2024-02-29 12:07:41 +01:00
yukang 97feb71254 Suggest moving if non-found macro_rules! is defined later 2024-02-29 19:01:45 +08:00
r0cky 1850ba7f54 Remove unused diagnostic struct 2024-02-29 14:14:21 +08:00
bors c475e2303b Auto merge of #121489 - nnethercote:diag-renaming, r=davidtwco
Diagnostic renaming

Renaming various diagnostic types from `Diagnostic*` to `Diag*`. Part of https://github.com/rust-lang/compiler-team/issues/722. There are more to do but this is enough for one PR.

r? `@davidtwco`
2024-02-28 20:39:38 +00:00
Guillaume Gomez c5dafe66ba
Rollup merge of #121226 - chenyukang:yukang-fix-import-alias, r=davidtwco
Fix issues in suggesting importing extern crate paths

Fixes #121168

r? ``@petrochenkov``
2024-02-28 16:04:49 +01:00
Nicholas Nethercote 8199632aa8 Rename DiagnosticArg{,Map,Name,Value} as DiagArg{,Map,Name,Value}. 2024-02-28 08:55:37 +11:00
Nicholas Nethercote 899cb40809 Rename DiagnosticBuilder as Diag.
Much better!

Note that this involves renaming (and updating the value of)
`DIAGNOSTIC_BUILDER` in clippy.
2024-02-28 08:55:35 +11:00
Nicholas Nethercote d0267cb26b Remove an unnecessary span_delayed_bug in Resolver::valid_res_from_ribs.
`Resolver::report_error` always emits (this commit makes that clearer),
so the `span_delayed_bug` is unnecessary.
2024-02-27 16:31:40 +11:00
Matthias Krüger 7c88ea2842
Rollup merge of #121060 - clubby789:bool-newtypes, r=cjgillot
Add newtypes for bool fields/params/return types

Fixed all the cases of this found with some simple searches for `*/ bool` and `bool /*`; probably many more
2024-02-25 17:05:20 +01:00
yukang 3bcef2dc1b Fix issues in suggesting importing extern crate paths 2024-02-25 11:29:13 +08:00
Gary Guo 93fa8579c6 Add asm label support to AST and HIR 2024-02-24 18:49:39 +00:00
Matthias Krüger 86a7fc840f compiler: clippy::complexity fixes 2024-02-23 19:56:35 +01:00
Nicholas Nethercote 2903bbbc15 Convert bugs back to delayed_bugs.
This commit undoes some of the previous commit's mechanical changes,
based on human judgment.
2024-02-21 10:35:54 +11:00
Nicholas Nethercote 010f3944e0 Convert delayed_bugs to bugs.
I have a suspicion that quite a few delayed bug paths are impossible to
reach, so I did an experiment.

I converted every `delayed_bug` to a `bug`, ran the full test suite,
then converted back every `bug` that was hit. A surprising number were
never hit.

The next commit will convert some more back, based on human judgment.
2024-02-21 10:20:05 +11:00
Nilstrieb 073d2983a4
Rollup merge of #121167 - petrochenkov:unload2, r=wesleywiser
resolve: Scale back unloading of speculatively loaded crates

Fixes https://github.com/rust-lang/rust/issues/120830 and fixes https://github.com/rust-lang/rust/issues/120909 while still unblocking https://github.com/rust-lang/rust/pull/117772.

I cannot reproduce https://github.com/parasyte/crash-rustc as an UI test for some reason, but I tested all the cases linked above manually.
2024-02-20 15:13:50 +01:00
clubby789 06e77397e1 Add newtype for using the prelude in resolution 2024-02-20 13:32:58 +00:00
Nicholas Nethercote b18f3e11fa Prefer DiagnosticBuilder over Diagnostic in diagnostic modifiers.
There are lots of functions that modify a diagnostic. This can be via a
`&mut Diagnostic` or a `&mut DiagnosticBuilder`, because the latter type
wraps the former and impls `DerefMut`.

This commit converts all the `&mut Diagnostic` occurrences to `&mut
DiagnosticBuilder`. This is a step towards greatly simplifying
`Diagnostic`. Some of the relevant function are made generic, because
they deal with both errors and warnings. No function bodies are changed,
because all the modifier methods are available on both `Diagnostic` and
`DiagnosticBuilder`.
2024-02-19 20:23:20 +11:00
Vadim Petrochenkov 24cffbf703 resolve: Scale back unloading of speculatively loaded crates 2024-02-18 20:59:19 +03:00
surechen a61126cef6 By tracking import use types to check whether it is scope uses or the other situations like module-relative uses, we can do more accurate redundant import checking.
fixes #117448

For example unnecessary imports in std::prelude that can be eliminated:

```rust
use std::option::Option::Some;//~ WARNING the item `Some` is imported redundantly
use std::option::Option::None; //~ WARNING the item `None` is imported redundantly
```
2024-02-18 16:38:11 +08:00
Matthias Krüger 45d5773704
Rollup merge of #121085 - davidtwco:always-eager-diagnostics, r=nnethercote
errors: only eagerly translate subdiagnostics

Subdiagnostics don't need to be lazily translated, they can always be eagerly translated. Eager translation is slightly more complex as we need to have a `DiagCtxt` available to perform the translation, which involves slightly more threading of that context.

This slight increase in complexity should enable later simplifications - like passing `DiagCtxt` into `AddToDiagnostic` and moving Fluent messages into the diagnostic structs rather than having them in separate files (working on that was what led to this change).

r? ```@nnethercote```
2024-02-17 18:47:40 +01:00
Guillaume Gomez 670bdbf808
Rollup merge of #121111 - trevyn:associated-type-suggestion, r=davidtwco
For E0038, suggest associated type if available

Closes #116434
2024-02-16 17:08:12 +01:00
David Wood b80fc5d4e8
errors: only eagerly translate subdiagnostics
Subdiagnostics don't need to be lazily translated, they can always be
eagerly translated. Eager translation is slightly more complex as we need
to have a `DiagCtxt` available to perform the translation, which involves
slightly more threading of that context.

This slight increase in complexity should enable later simplifications -
like passing `DiagCtxt` into `AddToDiagnostic` and moving Fluent messages
into the diagnostic structs rather than having them in separate files
(working on that was what led to this change).

Signed-off-by: David Wood <david@davidtw.co>
2024-02-15 10:34:41 +00:00
Matthias Krüger f62d981a18
Rollup merge of #121084 - oli-obk:create_def_forever_red2, r=WaffleLapkin
Make sure `tcx.create_def` also depends on the forever red node, instead of just `tcx.at(span).create_def`

oversight from https://github.com/rust-lang/rust/pull/119136

Not actually an issue, because all uses of `tcx.create_def` were in the resolver, which is `eval_always`, but still good to harden against future uses of `create_def`

cc `@petrochenkov` `@WaffleLapkin`
2024-02-15 09:20:20 +01:00
trevyn 220e8a7484 For E0038, suggest associated type if available 2024-02-14 12:42:32 -08:00
Oli Scherer 55f9aed9c7 Move all the heavy lifting from TyCtxtAt::create_def into TyCtxt::create_def 2024-02-14 16:03:49 +00:00
Guillaume Gomez 8e690fdd6a
Rollup merge of #120966 - chenyukang:yukang-fix-120599-resolve, r=pnkfelix
Remove importing suggestions when there is a shadowed typo candidate

Fixes #120559
2024-02-14 15:41:27 +01:00
yukang 2a229c96e8 remove importing suggestions when there is a shadowed typo canddiate 2024-02-14 14:08:51 +08:00
clubby789 4de3a3af4a Bump indexmap
`swap` has been deprecated in favour of `swap_remove` - the behaviour
is the same though.
2024-02-13 21:03:34 +00:00
Frank King 0dbd6e9572 Improve some codes according to the reviews
- improve diagnostics of field uniqueness check and representation check
- simplify the implementation of field uniqueness check
- remove some useless codes and improvement neatness
2024-02-12 12:47:32 +08:00
Frank King 7660d6bf2c Check representation of unnamed fields 2024-02-12 12:47:31 +08:00
Frank King 0c0df4efe0 Lowering field access for anonymous adts 2024-02-12 12:47:30 +08:00
Matthias Krüger 46a0448405
Rollup merge of #120693 - nnethercote:invert-diagnostic-lints, r=davidtwco
Invert diagnostic lints.

That is, change `diagnostic_outside_of_impl` and `untranslatable_diagnostic` from `allow` to `deny`, because more than half of the compiler has been converted to use translated diagnostics.

This commit removes more `deny` attributes than it adds `allow` attributes, which proves that this change is warranted.

r? ````@davidtwco````
2024-02-09 14:41:50 +01:00
Matthias Krüger 4ffb1a7f3d
Rollup merge of #120590 - compiler-errors:dead, r=Nilstrieb
Remove unused args from functions

`#[instrument]` suppresses the unused arguments from a function, *and* suppresses unused methods too! This PR removes things which are only used via `#[instrument]` calls, and fixes some other errors (privacy?) that I will comment inline.

It's possible that some of these arguments were being passed in for the purposes of being instrumented, but I am unconvinced by most of them.
2024-02-08 20:34:57 +01:00
Matthias Krüger 4e11d03d0e
Rollup merge of #119592 - petrochenkov:unload, r=compiler-errors
resolve: Unload speculatively resolved crates before freezing cstore

Name resolution sometimes loads additional crates to improve diagnostics (e.g. suggest imports).
Not all of these diagnostics result in errors, sometimes they are just warnings, like in #117772.

If additional crates loaded speculatively stay and gets listed by things like `query crates` then they may produce further errors like duplicated lang items, because lang items from speculatively loaded crates are as good as from non-speculatively loaded crates.
They can probably do things like adding unintended impls from speculatively loaded crates to method resolution as well.
The extra crates will also get into the crate's metadata as legitimate dependencies.

In this PR I remove the speculative crates from cstore when name resolution is finished and cstore is frozen.
This is better than e.g. filtering away speculative crates in `query crates` because things like `DefId`s referring to these crates and leaking to later compilation stages can produce ICEs much easier, allowing to detect them.

The unloading could potentially be skipped if any errors were reported (to allow using `DefId`s from speculatively loaded crates for recovery), but I didn't do it in this PR because I haven't seen such cases of recovery. We can reconsider later if any relevant ICEs are reported.

Unblocks https://github.com/rust-lang/rust/pull/117772.
2024-02-08 09:06:31 +01:00
Matthias Krüger 3c52832375
Rollup merge of #119939 - clubby789:static-const-generic-note, r=compiler-errors
Improve 'generic param from outer item' error for `Self` and inside `static`/`const` items

Fixes #109596
Fixes #119936
2024-02-06 22:45:39 +01:00
Vadim Petrochenkov a2ab48c21b resolve: Unload speculatively resolved crates before freezing cstore 2024-02-06 17:44:53 +03:00
Nicholas Nethercote 0ac1195ee0 Invert diagnostic lints.
That is, change `diagnostic_outside_of_impl` and
`untranslatable_diagnostic` from `allow` to `deny`, because more than
half of the compiler has be converted to use translated diagnostics.

This commit removes more `deny` attributes than it adds `allow`
attributes, which proves that this change is warranted.
2024-02-06 13:12:33 +11:00
León Orell Valerian Liehr 285d8c225d
Suggest [tail @ ..] on [..tail] and [...tail] where tail is unresolved 2024-02-04 22:16:21 +01:00
Matthias Krüger 968cff7cf3
Rollup merge of #120592 - trevyn:cleanup-to-string, r=Nilstrieb
Remove unnecessary `.to_string()`/`.as_str()`s
2024-02-03 21:29:43 +01:00
trevyn ef37dcb7db Remove unnecessary .to_string()/.as_str()s 2024-02-02 15:16:05 -08:00
Michael Goulet 6b2a8249c1 Remove dead args from functions 2024-02-02 22:47:26 +00:00
León Orell Valerian Liehr 5906237b32
Suggest changing ty to const params if appropriate 2024-02-02 03:25:04 +01:00
León Orell Valerian Liehr 3f7b1a5f49
Clean up some things in the name resolver
* Get rid of a typo in a function name
* Rename `currently_processing_generics`: The old name confused me at first since
  I assumed it referred to generic *parameters* when it was in fact referring to
  generic *arguments*. Generics are typically short for generic params.
* Get rid of a few unwraps by properly leveraging slice patterns
2024-02-02 02:51:48 +01:00
Guillaume Gomez ee2e9e1eda
Rollup merge of #118533 - chenyukang:yukang-fix-118455, r=petrochenkov
Suppress unhelpful diagnostics for unresolved top level attributes

Fixes #118455, unresolved top level attribute error didn't imported prelude and already have emitted an error, report builtin macro and attributes error by the way, so `check_invalid_crate_level_attr` in can ignore them.

Also fixes #89566, fixes #67107.

r? `@petrochenkov`
2024-01-30 16:57:46 +01:00
Guillaume Gomez f99b510429
Rollup merge of #120488 - nnethercote:diag-lifetimes, r=oli-obk
Diagnostic lifetimes cleanups

Some diagnostic simplifications.

r? `@oli-obk`
2024-01-30 11:19:20 +01:00
Guillaume Gomez f35504dbf2
Rollup merge of #120443 - GuillaumeGomez:footnote-def-improvement, r=fmease
Fixes footnote handling in rustdoc

Fixes #100638.

You can now declare footnotes like this:

```rust
//! Reference to footnotes A[^1], B[^2] and C[^3].
//!
//! [^1]: Footnote A.
//! [^2]: Footnote B.
//! [^3]: Footnote C.
```

r? `@notriddle`
2024-01-30 11:19:18 +01:00
Guillaume Gomez a44b134770
Rollup merge of #120402 - compiler-errors:async-closure-def-tree, r=cjgillot
Make the coroutine def id of an async closure the child of the closure def id

Adjust def collection to make the (inner) coroutine returned by an async closure be a def id child of the (outer) closure. This makes it easy to map from coroutine -> closure by using `tcx.parent`, since currently it's not trivial to do this.
2024-01-30 11:19:15 +01:00
Nicholas Nethercote 5350edb9e8 Remove the lifetime from DiagnosticArgValue.
Because it's almost always static.

This makes `impl IntoDiagnosticArg for DiagnosticArgValue` trivial,
which is nice.

There are a few diagnostics constructed in
`compiler/rustc_mir_build/src/check_unsafety.rs` and
`compiler/rustc_mir_transform/src/errors.rs` that now need symbols
converted to `String` with `to_string` instead of `&str` with `as_str`,
but that' no big deal, and worth it for the simplifications elsewhere.
2024-01-30 18:46:06 +11:00
Guillaume Gomez 1bdeeef0d5 Update pulldown-cmark version to 0.9.5 2024-01-29 14:14:03 +01:00
yukang 492df34eea Supress unhelpful diagnostics for unresolved top level attributes 2024-01-29 17:43:07 +08:00
Nicholas Nethercote 5d9dfbd08f Stop using String for error codes.
Error codes are integers, but `String` is used everywhere to represent
them. Gross!

This commit introduces `ErrCode`, an integral newtype for error codes,
replacing `String`. It also introduces a constant for every error code,
e.g. `E0123`, and removes the `error_code!` macro. The constants are
imported wherever used with `use rustc_errors::codes::*`.

With the old code, we have three different ways to specify an error code
at a use point:
```
error_code!(E0123)  // macro call

struct_span_code_err!(dcx, span, E0123, "msg");  // bare ident arg to macro call

\#[diag(name, code = "E0123")]  // string
struct Diag;
```

With the new code, they all use the `E0123` constant.
```
E0123  // constant

struct_span_code_err!(dcx, span, E0123, "msg");  // constant

\#[diag(name, code = E0123)]  // constant
struct Diag;
```

The commit also changes the structure of the error code definitions:
- `rustc_error_codes` now just defines a higher-order macro listing the
  used error codes and nothing else.
- Because that's now the only thing in the `rustc_error_codes` crate, I
  moved it into the `lib.rs` file and removed the `error_codes.rs` file.
- `rustc_errors` uses that macro to define everything, e.g. the error
  code constants and the `DIAGNOSTIC_TABLES`. This is in its new
  `codes.rs` file.
2024-01-29 07:41:41 +11:00
Nicholas Nethercote 0321de2778 Remove bogus {code} attributes on TraitImplMismatch.
This makes no sense, and has no effect. I suspect it's been confused
with a `code = "{code}"` attribute on a subdiagnostic suggestion, where
it is valid (but the "code" there is suggested source code, rather than
an error code.)
2024-01-29 07:40:10 +11:00
Michael Goulet 5d8c1780fa Make the coroutine def id of an async closure the child of the closure def id 2024-01-27 19:39:02 +00:00
Matthias Krüger e400311486
Rollup merge of #120322 - compiler-errors:higher-ranked-async-closures, r=oli-obk
Don't manually resolve async closures in `rustc_resolve`

There's a comment here that talks about doing this "[so] closure [args] are detected as upvars rather than normal closure arg usages", but we do upvar analysis on the HIR now:

cd6d8f2a04/compiler/rustc_passes/src/upvars.rs (L21-L29)

Removing this ad-hoc logic makes it so that `async |x: &str|` now introduces an implicit binder, like regular closures.

r? ```@oli-obk```
2024-01-26 06:36:39 +01:00
clubby789 fd29f74ff8 Remove unused features 2024-01-25 14:01:33 +00:00
Michael Goulet 8c2ae804e3 Don't manually resolve async closures in rustc_resolve 2024-01-24 20:48:07 +00:00
Matthias Krüger c5984caa44
Rollup merge of #119369 - bvanjoi:fix-119301, r=petrochenkov
exclude unexported macro bindings from extern crate

Fixes #119301

Macros that aren't exported from an external crate should not be defined.

r? ``@petrochenkov``
2024-01-22 16:13:25 +01:00
bors 3066253050 Auto merge of #120080 - cuviper:128-align-packed, r=nikic
Pack u128 in the compiler to mitigate new alignment

This is based on #116672, adding a new `#[repr(packed(8))]` wrapper on `u128` to avoid changing any of the compiler's size assertions. This is needed in two places:

* `SwitchTargets`, otherwise its `SmallVec<[u128; 1]>` gets padded up to 32 bytes.
* `LitKind::Int`, so that entire `enum` can stay 24 bytes.
  * This change definitely has far-reaching effects though, since it's public.
2024-01-22 13:08:19 +00:00
bohan 9c3091e9cf exclude unexported macro bindings from extern crate 2024-01-21 20:24:40 +08:00
Josh Stone 33e0422826 Pack the u128 in LitKind::Int 2024-01-19 20:10:39 -08:00
trevyn de2575f35d Don't delete any lifetimes with bounds 2024-01-20 02:30:58 +04:00
Oli Scherer 557b111870 Make crate_inherent_impls fallible and stop using track_errors for it 2024-01-17 10:02:29 +00:00
bors 16f4b02dd8 Auto merge of #119922 - nnethercote:fix-Diag-code-is_lint, r=oli-obk
Rework how diagnostic lints are stored.

`Diagnostic::code` has the type `DiagnosticId`, which has `Error` and
`Lint` variants. Plus `Diagnostic::is_lint` is a bool, which should be
redundant w.r.t. `Diagnostic::code`.

Seems simple. Except it's possible for a lint to have an error code, in
which case its `code` field is recorded as `Error`, and `is_lint` is
required to indicate that it's a lint. This is what happens with
`derive(LintDiagnostic)` lints. Which means those lints don't have a
lint name or a `has_future_breakage` field because those are stored in
the `DiagnosticId::Lint`.

It's all a bit messy and confused and seems unintentional.

This commit:
- removes `DiagnosticId`;
- changes `Diagnostic::code` to `Option<String>`, which means both
  errors and lints can straightforwardly have an error code;
- changes `Diagnostic::is_lint` to `Option<IsLint>`, where `IsLint` is a
  new type containing a lint name and a `has_future_breakage` bool, so
  all lints can have those, error code or not.

r? `@oli-obk`
2024-01-17 07:33:52 +00:00
bors 714b29a17f Auto merge of #119610 - Nadrieril:never_pattern_bindings, r=compiler-errors
never patterns: Check bindings wrt never patterns

Never patterns:
- Shouldn't contain bindings since they never match anything;
- Don't count when checking that or-patterns have consistent bindings.

r? `@compiler-errors`
2024-01-15 21:24:13 +00:00
clubby789 2cfc81766c Special case 'generic param from outer item' message for Self 2024-01-14 12:31:34 +00:00
clubby789 511bf6e1c7 Add note to resolve error about generics from inside static/const 2024-01-14 12:31:28 +00:00
Nicholas Nethercote d71f535a6f Rework how diagnostic lints are stored.
`Diagnostic::code` has the type `DiagnosticId`, which has `Error` and
`Lint` variants. Plus `Diagnostic::is_lint` is a bool, which should be
redundant w.r.t. `Diagnostic::code`.

Seems simple. Except it's possible for a lint to have an error code, in
which case its `code` field is recorded as `Error`, and `is_lint` is
required to indicate that it's a lint. This is what happens with
`derive(LintDiagnostic)` lints. Which means those lints don't have a
lint name or a `has_future_breakage` field because those are stored in
the `DiagnosticId::Lint`.

It's all a bit messy and confused and seems unintentional.

This commit:
- removes `DiagnosticId`;
- changes `Diagnostic::code` to `Option<String>`, which means both
  errors and lints can straightforwardly have an error code;
- changes `Diagnostic::is_lint` to `Option<IsLint>`, where `IsLint` is a
  new type containing a lint name and a `has_future_breakage` bool, so
  all lints can have those, error code or not.
2024-01-14 14:04:25 +11:00
bors 3deb9bbf84 Auto merge of #119945 - matthiaskrgr:rollup-oy3e1j2, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #119189 (Move section "Installing from Source" to seperate file)
 - #119925 (store the segment name when resolution fails)
 - #119935 (Move personality implementation out of PAL)
 - #119937 (Improve UEFI target docs)
 - #119938 (Allow unauthorized users to user the has-merge-commits label)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-13 22:05:46 +00:00
George-lewis 36a69e9d39 Add check for ui_testing via promoting parameters from ParseSess to Session 2024-01-13 12:11:13 -05:00
bohan c288cb1f74 store the segment name when resolution fails 2024-01-13 21:06:38 +08:00
Bryanskiy d69cd6473c Delegation implementation: step 1 2024-01-12 14:11:16 +03:00
Matthias Krüger 6238698ab5
Rollup merge of #119788 - mj10021:issue-119787-fix, r=oli-obk
change function name in comments

fixes #119787 where I believe an incorrect function name is used in the comments
2024-01-11 03:02:42 +01:00
Nadrieril 68a13bf7fd Explain never patterns in resolve 2024-01-10 22:10:08 +01:00
mj10021 894d1d4a25
change function name in comments 2024-01-09 18:39:53 -05:00
Nicholas Nethercote ed76b0b882 Rename consuming chaining methods on DiagnosticBuilder.
In #119606 I added them and used a `_mv` suffix, but that wasn't great.

A `with_` prefix has three different existing uses.
- Constructors, e.g. `Vec::with_capacity`.
- Wrappers that provide an environment to execute some code, e.g.
  `with_session_globals`.
- Consuming chaining methods, e.g. `Span::with_{lo,hi,ctxt}`.

The third case is exactly what we want, so this commit changes
`DiagnosticBuilder::foo_mv` to `DiagnosticBuilder::with_foo`.

Thanks to @compiler-errors for the suggestion.
2024-01-10 07:40:00 +11:00
Nicholas Nethercote ff40ad4107 Shorten some error invocations.
- `struct_foo` + `emit` -> `foo`
- `create_foo` + `emit` -> `emit_foo`

I have made recent commits in other PRs that have removed some of these
shortcuts for combinations with few uses, e.g.
`struct_span_err_with_code`. But for the remaining combinations that
have high levels of use, we might as well use them wherever possible.
2024-01-10 07:33:06 +11:00
Nicholas Nethercote 4864cb8aef Rename struct_span_err! as struct_span_code_err!.
Because it takes an error code after the span. This avoids the confusing
overlap with the `DiagCtxt::struct_span_err` method, which doesn't take
an error code.
2024-01-10 07:33:04 +11:00
Nadrieril 223cda4107 Use Result<_, IsNeverPattern> consistently 2024-01-09 17:06:14 +01:00
Nadrieril 807d618676 Only check bindings if the pattern is an or- or never- pattern 2024-01-09 17:05:55 +01:00
Nadrieril 560beb1ad4 Check bindings around never patterns 2024-01-09 17:00:24 +01:00
Nadrieril b31735a401 Tweak binding map computation 2024-01-09 16:49:12 +01:00
Nicholas Nethercote 6682f243dc Remove all eight DiagnosticBuilder::*_with_code methods.
These all have relatively low use, and can be perfectly emulated with
a simpler construction method combined with `code` or `code_mv`.
2024-01-08 16:00:34 +11:00
Nicholas Nethercote bd4e623485 Use chaining for DiagnosticBuilder construction and emit.
To avoid the use of a mutable local variable, and because it reads more
nicely.
2024-01-08 15:45:29 +11:00
Nicholas Nethercote 589591efde Use chaining in DiagnosticBuilder construction.
To avoid the use of a mutable local variable, and because it reads more
nicely.
2024-01-08 15:43:07 +11:00
Nicholas Nethercote b1b9278851 Make DiagnosticBuilder::emit consuming.
This works for most of its call sites. This is nice, because `emit` very
much makes sense as a consuming operation -- indeed,
`DiagnosticBuilderState` exists to ensure no diagnostic is emitted
twice, but it uses runtime checks.

For the small number of call sites where a consuming emit doesn't work,
the commit adds `DiagnosticBuilder::emit_without_consuming`. (This will
be removed in subsequent commits.)

Likewise, `emit_unless` becomes consuming. And `delay_as_bug` becomes
consuming, while `delay_as_bug_without_consuming` is added (which will
also be removed in subsequent commits.)

All this requires significant changes to `DiagnosticBuilder`'s chaining
methods. Currently `DiagnosticBuilder` method chaining uses a
non-consuming `&mut self -> &mut Self` style, which allows chaining to
be used when the chain ends in `emit()`, like so:
```
    struct_err(msg).span(span).emit();
```
But it doesn't work when producing a `DiagnosticBuilder` value,
requiring this:
```
    let mut err = self.struct_err(msg);
    err.span(span);
    err
```
This style of chaining won't work with consuming `emit` though. For
that, we need to use to a `self -> Self` style. That also would allow
`DiagnosticBuilder` production to be chained, e.g.:
```
    self.struct_err(msg).span(span)
```
However, removing the `&mut self -> &mut Self` style would require that
individual modifications of a `DiagnosticBuilder` go from this:
```
    err.span(span);
```
to this:
```
    err = err.span(span);
```
There are *many* such places. I have a high tolerance for tedious
refactorings, but even I gave up after a long time trying to convert
them all.

Instead, this commit has it both ways: the existing `&mut self -> Self`
chaining methods are kept, and new `self -> Self` chaining methods are
added, all of which have a `_mv` suffix (short for "move"). Changes to
the existing `forward!` macro lets this happen with very little
additional boilerplate code. I chose to add the suffix to the new
chaining methods rather than the existing ones, because the number of
changes required is much smaller that way.

This doubled chainging is a bit clumsy, but I think it is worthwhile
because it allows a *lot* of good things to subsequently happen. In this
commit, there are many `mut` qualifiers removed in places where
diagnostics are emitted without being modified. In subsequent commits:
- chaining can be used more, making the code more concise;
- more use of chaining also permits the removal of redundant diagnostic
  APIs like `struct_err_with_code`, which can be replaced easily with
  `struct_err` + `code_mv`;
- `emit_without_diagnostic` can be removed, which simplifies a lot of
  machinery, removing the need for `DiagnosticBuilderState`.
2024-01-08 15:24:49 +11:00
Michael Goulet 61c776ae0a
Rollup merge of #119638 - lukas-code:suggest-constructor-cycle-error, r=cjgillot
fix cyle error when suggesting to use associated function instead of constructor

Fixes https://github.com/rust-lang/rust/issues/119625.

The first commit fixes the infinite recursion and makes the cycle error actually show up. We do this by making the `Display` for `ty::Instance` impl  respect `with_no_queries` so that it can be used in query descriptions.

The second commit fixes the cycle error `resolver_for_lowering` -> `normalize` -> `resolve_instance` (for evaluating const) -> `lang_items` (for `drop_in_place`) -> `resolver_for_lowering` (for collecting lang items). We do this by simply skipping the suggestion when encountering an unnormalized type.
2024-01-05 23:41:43 -05:00
Lukas Markeffsky 339fa311ad fix cycle error for "use constructor" suggestion 2024-01-05 21:56:32 +01:00
Matthias Krüger 3a0536ab51
Rollup merge of #119151 - Jules-Bertholet:no-foreign-doc-hidden-suggest, r=davidtwco
Hide foreign `#[doc(hidden)]` paths in import suggestions

Stops the compiler from suggesting to import foreign `#[doc(hidden)]` paths.

```@rustbot``` label A-suggestion-diagnostics
2024-01-05 20:39:50 +01:00
Michael Goulet f361b591ef
Rollup merge of #119538 - nnethercote:cleanup-errors-5, r=compiler-errors
Cleanup error handlers: round 5

More rustc_errors cleanups. A sequel to https://github.com/rust-lang/rust/pull/119171.

r? ````@compiler-errors````
2024-01-05 10:57:21 -05:00
bohan 862368db9f fallback visibility for unexpected trait item 2024-01-04 02:02:57 +08:00
Nicholas Nethercote 505c1371d0 Rename some Diagnostic setters.
`Diagnostic` has 40 methods that return `&mut Self` and could be
considered setters. Four of them have a `set_` prefix. This doesn't seem
necessary for a type that implements the builder pattern. This commit
removes the `set_` prefixes on those four methods.
2024-01-03 19:40:20 +11:00
Nilstrieb ffafcd8819 Update to bitflags 2 in the compiler
This involves lots of breaking changes. There are two big changes that
force changes. The first is that the bitflag types now don't
automatically implement normal derive traits, so we need to derive them
manually.

Additionally, bitflags now have a hidden inner type by default, which
breaks our custom derives. The bitflags docs recommend using the impl
form in these cases, which I did.
2023-12-30 18:17:28 +01:00
Nicholas Nethercote 99472c7049 Remove Session methods that duplicate DiagCtxt methods.
Also add some `dcx` methods to types that wrap `TyCtxt`, for easier
access.
2023-12-24 08:05:28 +11:00
Nicholas Nethercote 824667f753 Improve some names.
Lots of vectors of messages called `message` or `msg`. This commit
pluralizes them.

Note that `emit_message_default` and `emit_messages_default` both
already existed, and both process a vector, so I renamed the former
`emit_messages_default_inner` because it's called by the latter.
2023-12-23 13:23:28 +11:00
Nicholas Nethercote 757d6f6ef8 Give DiagnosticBuilder a default type.
`IntoDiagnostic` defaults to `ErrorGuaranteed`, because errors are the
most common diagnostic level. It makes sense to do likewise for the
closely-related (and much more widely used) `DiagnosticBuilder` type,
letting us write `DiagnosticBuilder<'a, ErrorGuaranteed>` as just
`DiagnosticBuilder<'a>`. This cuts over 200 lines of code due to many
multi-line things becoming single line things.
2023-12-23 13:23:10 +11:00
bors 208dd2032b Auto merge of #118847 - eholk:for-await, r=compiler-errors
Add support for `for await` loops

This adds support for `for await` loops. This includes parsing, desugaring in AST->HIR lowering, and adding some support functions to the library.

Given a loop like:
```rust
for await i in iter {
    ...
}
```
this is desugared to something like:
```rust
let mut iter = iter.into_async_iter();
while let Some(i) = loop {
    match core::pin::Pin::new(&mut iter).poll_next(cx) {
        Poll::Ready(i) => break i,
        Poll::Pending => yield,
    }
} {
    ...
}
```

This PR also adds a basic `IntoAsyncIterator` trait. This is partly for symmetry with the way `Iterator` and `IntoIterator` work. The other reason is that for async iterators it's helpful to have a place apart from the data structure being iterated over to store state. `IntoAsyncIterator` gives us a good place to do this.

I've gated this feature behind `async_for_loop` and opened #118898 as the feature tracking issue.

r? `@compiler-errors`
2023-12-22 14:17:10 +00:00
bors aaef5fe497 Auto merge of #119163 - fmease:refactor-ast-trait-bound-modifiers, r=compiler-errors
Refactor AST trait bound modifiers

Instead of having two types to represent trait bound modifiers in the parser / the AST (`parser::ty::BoundModifiers` & `ast::TraitBoundModifier`), only to map one to the other later, just use `parser::ty::BoundModifiers` (moved & renamed to `ast::TraitBoundModifiers`).

The struct type is more extensible and easier to deal with (see [here](https://github.com/rust-lang/rust/pull/119099/files#r1430749981) and [here](https://github.com/rust-lang/rust/pull/119099/files#r1430752116) for context) since it more closely models what it represents: A compound of two kinds of modifiers, constness and polarity. Modeling this as an enum (the now removed `ast::TraitBoundModifier`) meant one had to add a new variant per *combination* of modifier kind, which simply isn't scalable and which lead to a lot of explicit non-DRY matches.

NB: `hir::TraitBoundModifier` being an enum is fine since HIR doesn't need to worry representing invalid modifier kind combinations as those get rejected during AST validation thereby immensely cutting down the number of possibilities.
2023-12-22 02:00:55 +00:00
León Orell Valerian Liehr 5e4f12b41a
Refactor AST trait bound modifiers 2023-12-20 19:39:46 +01:00
Vadim Petrochenkov 006e0ef18d resolve: Stop feeding visibilities for import list stems 2023-12-20 20:27:10 +03:00
bors 8fca8295cb Auto merge of #119136 - petrochenkov:feedvis3, r=WaffleLapkin
resolve: Eagerly feed closure visibilities

Also factor out all tcx-dependent operations performed for every created definition into `TyCtxt::create_def`.

Addresses https://github.com/rust-lang/rust/pull/118657#discussion_r1421424277
2023-12-20 14:03:00 +00:00
Vadim Petrochenkov 5e5d82e803 resolve: Eagerly feed closure visibilities
Also factor out all tcx-dependent operations performed for every created definition into `TyCtxt::create_def`
2023-12-20 13:42:58 +03:00
Jules Bertholet 5c0e62cd3e
Hide foreign #[doc(hidden)] paths in import suggestions 2023-12-20 00:19:45 -05:00
Eric Holk 27d6539a46
Plumb awaitness of for loops 2023-12-19 12:26:20 -08:00
Vadim Petrochenkov 7571f6f685 resolve: Feed visibilities for unresolved trait impl items 2023-12-19 22:33:26 +03:00
Michael Woerister 115885ba7e Replace some instances of FxHashMap/FxHashSet with stable alternatives (mostly in rustc_hir and rustc_ast_lowering)
Part of https://github.com/rust-lang/compiler-team/issues/533
2023-12-18 21:03:32 +01:00
Nicholas Nethercote 09af8a667c Rename Session::span_diagnostic as Session::dcx. 2023-12-18 16:06:21 +11:00
Vadim Petrochenkov be321aa473 resolve: Replace visibility table in resolver outputs with query feeding
Also feed missing visibilities for import stems and trait impl items, which were previously evaluated lazily.
2023-12-18 02:26:55 +03:00
Matthias Krüger 8479945c08 NFC don't convert types to identical types 2023-12-15 23:56:24 +01:00
Jubilee 4583a0134f
Rollup merge of #118889 - matthiaskrgr:compl_2023_2, r=WaffleLapkin
more clippy::complexity fixes

      redundant_guards
      redundant_slicing
      filter_next
      needless_borrowed_reference
      useless_format
2023-12-12 18:48:54 -08:00
Jubilee 89d4a9bee9
Rollup merge of #118884 - matthiaskrgr:auszweimacheins, r=Nadrieril
NFC: simplify merging of two vecs
2023-12-12 18:48:52 -08:00
Matthias Krüger 3795cc8eb0 more clippy::complexity fixes
redundant_guards
      redundant_slicing
      filter_next
      needless_borrowed_reference
      useless_format
2023-12-12 20:41:51 +01:00
Matthias Krüger 6892fcd690 simplify merging of two vecs 2023-12-12 18:42:37 +01:00
Matthias Krüger ffdb471872
Rollup merge of #117914 - estebank:issue-85843, r=wesleywiser
On borrow return type, suggest borrowing from arg or owned return type

When we encounter a function with a return type that has an anonymous lifetime with no argument to borrow from, besides suggesting the `'static` lifetime we now also suggest changing the arguments to be borrows or changing the return type to be an owned type.

```
error[E0106]: missing lifetime specifier
  --> $DIR/variadic-ffi-6.rs:7:6
   |
LL | ) -> &usize {
   |      ^ expected named lifetime parameter
   |
   = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
   |
LL | ) -> &'static usize {
   |       +++++++
help: instead, you are more likely to want to change one of the arguments to be borrowed...
   |
LL |     x: &usize,
   |        +
help: ...or alternatively, to want to return an owned value
   |
LL - ) -> &usize {
LL + ) -> usize {
   |
```

Fix #85843.
2023-12-12 17:40:53 +01:00
Matthias Krüger fefa8fc6c4
Rollup merge of #118840 - matthiaskrgr:cloooooone, r=compiler-errors
remove some redundant clones
2023-12-12 06:52:50 +01:00
Matthias Krüger 0564de10b1 remove some redundant clones 2023-12-11 21:54:36 +01:00
Matthias Krüger 670ba478de
Rollup merge of #118620 - petrochenkov:defeed2, r=compiler-errors
resolve: Use `def_kind` query to cleanup some code

Follow up to https://github.com/rust-lang/rust/pull/118188.

Similar attempts to use queries in resolver resulted in perf regressions in the past, so this needs a perf run first.
2023-12-11 20:46:48 +01:00
Michael Goulet 8361a7288e Introduce closure_id method on CoroutineKind 2023-12-08 21:46:39 +00:00
bors f967532a47 Auto merge of #118420 - compiler-errors:async-gen, r=eholk
Introduce support for `async gen` blocks

I'm delighted to demonstrate that `async gen` block are not very difficult to support. They're simply coroutines that yield `Poll<Option<T>>` and return `()`.

**This PR is WIP and in draft mode for now** -- I'm mostly putting it up to show folks that it's possible. This PR needs a lang-team experiment associated with it or possible an RFC, since I don't think it falls under the jurisdiction of the `gen` RFC that was recently authored by oli (https://github.com/rust-lang/rfcs/pull/3513, https://github.com/rust-lang/rust/issues/117078).

### Technical note on the pre-generator-transform yield type:

The reason that the underlying coroutines yield `Poll<Option<T>>` and not `Poll<T>` (which would make more sense, IMO, for the pre-transformed coroutine), is because the `TransformVisitor` that is used to turn coroutines into built-in state machine functions would have to destructure and reconstruct the latter into the former, which requires at least inserting a new basic block (for a `switchInt` terminator, to match on the `Poll` discriminant).

This does mean that the desugaring (at the `rustc_ast_lowering` level) of `async gen` blocks is a bit more involved. However, since we already need to intercept both `.await` and `yield` operators, I don't consider it much of a technical burden.

r? `@ghost`
2023-12-08 19:13:57 +00:00
Michael Goulet 44911b7c67 Make some matches exhaustive to avoid bugs, fix tools 2023-12-08 17:23:26 +00:00
Michael Goulet a208bae00e Support async gen fn 2023-12-08 17:23:26 +00:00
Michael Goulet 2806c2df7b coro_kind -> coroutine_kind 2023-12-08 17:23:25 +00:00
bors 2b399b5275 Auto merge of #118527 - Nadrieril:never_patterns_parse, r=compiler-errors
never_patterns: Parse match arms with no body

Never patterns are meant to signal unreachable cases, and thus don't take bodies:
```rust
let ptr: *const Option<!> = ...;
match *ptr {
    None => { foo(); }
    Some(!),
}
```
This PR makes rustc accept the above, and enforces that an arm has a body xor is a never pattern. This affects parsing of match arms even with the feature off, so this is delicate. (Plus this is my first non-trivial change to the parser).

~~The last commit is optional; it introduces a bit of churn to allow the new suggestions to be machine-applicable. There may be a better solution? I'm not sure.~~ EDIT: I removed that commit

r? `@compiler-errors`
2023-12-08 17:08:52 +00:00
bors 8235469e48 Auto merge of #118687 - matthiaskrgr:rollup-317ztgu, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #117981 (Remove deprecated `--check-cfg` syntax)
 - #118177 (Suppress warnings in LLVM wrapper when targeting MSVC)
 - #118317 (tip for define macro name after `macro_rules!`)
 - #118504 (Enforce `must_use` on associated types and RPITITs that have a must-use trait in bounds)
 - #118660 (rustc_arena: add `alloc_str`)
 - #118681 (Fix is_foreign_item for StableMIR instance )

r? `@ghost`
`@rustbot` modify labels: rollup
2023-12-06 22:23:25 +00:00
bohan 0f14e8ea74 tip for define macro name after macro_rules! 2023-12-06 23:19:39 +08:00
r0cky 940473adb4 Use the glob binding in resolve_rustdoc_path process 2023-12-06 21:48:19 +08:00
bors 56278a6e28 Auto merge of #118457 - eholk:genfn, r=compiler-errors
Add support for `gen fn`

This builds on #116447 to add support for `gen fn` functions. For the most part we follow the same approach as desugaring `async fn`, but replacing `Future` with `Iterator` and `async {}` with `gen {}` for the body.

The version implemented here uses the return type of a `gen fn` as the yield type. For example:

```rust
gen fn count_to_three() -> i32 {
    yield 1;
    yield 2;
    yield 3;
}
```

In the future, I think we should experiment with a syntax like `gen fn count_to_three() yield i32 { ... }`, but that can go in another PR.

cc `@oli-obk` `@compiler-errors`
2023-12-05 18:37:15 +00:00
Vadim Petrochenkov fb9ca0ffe5 resolve: Use def_kind query to cleanup some code 2023-12-05 20:56:38 +03:00
Eric Holk 50ef8006eb
Address code review feedback 2023-12-04 14:33:46 -08:00
Esteban Küber beaf31581a Structured use suggestion on privacy error
When encoutering a privacy error on an item through a re-export that is
accessible in an alternative path, provide a structured suggestion with
that path.

```
error[E0603]: module import `mem` is private
  --> $DIR/private-std-reexport-suggest-public.rs:4:14
   |
LL |     use foo::mem;
   |              ^^^ private module import
   |
note: the module import `mem` is defined here...
  --> $DIR/private-std-reexport-suggest-public.rs:8:9
   |
LL |     use std::mem;
   |         ^^^^^^^^
note: ...and refers to the module `mem` which is defined here
  --> $SRC_DIR/std/src/lib.rs:LL:COL
   |
   = note: you could import this
help: import `mem` through the re-export
   |
LL |     use std::mem;
   |         ~~~~~~~~
```

Fix #42909.
2023-12-04 22:26:08 +00:00
Eric Holk f9d1f922dc
Option<CoroutineKind> 2023-12-04 13:03:37 -08:00
Eric Holk 48d5f1f0f2
Merge Async and Gen into CoroutineKind 2023-12-04 12:48:01 -08:00
Eric Holk c104f3b629
Lower return types for gen fn to impl Iterator 2023-12-04 11:23:05 -08:00
Vadim Petrochenkov 17e799c270 rustc: Harmonize DefKind and DefPathData
`DefPathData::(ClosureExpr,ImplTrait)` are renamed to match `DefKind::(Closure,OpaqueTy)`.

`DefPathData::ImplTraitAssocTy` is replaced with `DefPathData::TypeNS(kw::Empty)` because both correspond to `DefKind::AssocTy`.
It's possible that introducing `(DefKind,DefPathData)::AssocOpaqueTy` could be a better solution, but that would be a much more invasive change.

Const generic parameters introduced for effects are moved from `DefPathData::TypeNS` to `DefPathData::ValueNS`, because constants are values.

`DefPathData` is no longer passed to `create_def` functions to avoid redundancy.
2023-12-03 16:24:56 +03:00
Nadrieril 80bdcbf50a Parse a pattern with no arm 2023-12-03 12:25:46 +01:00
bors 2da59b8676 Auto merge of #118470 - nnethercote:cleanup-error-handlers, r=compiler-errors
Cleanup error handlers

Mostly by making function naming more consistent. More to do after this, but this is enough for one PR.

r? compiler-errors
2023-12-02 02:48:34 +00:00
Nicholas Nethercote 5d1d384443 Rename HandlerInner::delay_span_bug as HandlerInner::span_delayed_bug.
Because the corresponding `Level` is `DelayedBug` and `span_delayed_bug`
follows the pattern used everywhere else: `span_err`, `span_warning`,
etc.
2023-12-02 09:01:19 +11:00
bors 64d7e0d0b6 Auto merge of #115993 - bvanjoi:fix-115966, r=petrochenkov
vis note for no pub reexports glob import

Fixes #115966

Only trigger the `unused_import` lint when it's not being used.

r? `@petrochenkov`
2023-12-01 15:46:04 +00:00
bohan d0941f92d7 vis note for no pub reexports glob import 2023-12-01 12:10:07 +08:00
Ralf Jung 1dbfe17f12 generic_const_exprs: suggest to add the feature, not use it 2023-11-30 20:59:51 +01:00
Matthias Krüger 5e7f770a0d
Rollup merge of #118342 - compiler-errors:macro-generic-bang, r=estebank
Dont suggest `!` for path in function call if it has generic args

Fixes #118335
2023-11-29 04:23:28 +01:00
Vadim Petrochenkov 84de641484 def collector: Set correct namespace in DefPathData for foreign types 2023-11-28 16:17:52 +03:00
Vadim Petrochenkov f0dc906319 resolve: Feed the def_kind query immediately on DefId creation 2023-11-28 15:39:31 +03:00
Jake Goulding 87380cbc0c Address unused tuple struct fields in the compiler 2023-11-27 13:54:50 -05:00
Michael Goulet 8490b8ec63 Dont suggest ! for path in function call if it has generic args 2023-11-27 01:02:37 +00:00
bohan f23befe6c1 merge DefKind::Coroutine into DefKind::Closure 2023-11-26 21:05:08 +08:00
Michael Goulet 8dd8db5073
Rollup merge of #118288 - compiler-errors:is_some_and, r=lqd,dtolnay
Use `is_{some,ok}_and` more in the compiler

slightly more fluent-reading code
2023-11-25 17:23:34 -05:00
Michael Goulet 3b2f33ee28
Rollup merge of #118158 - nnethercote:reduce-fluent-boilerplate, r=compiler-errors
Reduce fluent boilerplate

Best reviewed one commit at a time.

r? `@davidtwco`
2023-11-25 17:23:33 -05:00
Nicholas Nethercote 57cd5e6551 Use rustc_fluent_macro::fluent_messages! directly.
Currently we always do this:
```
use rustc_fluent_macro::fluent_messages;
...
fluent_messages! { "./example.ftl" }
```
But there is no need, we can just do this everywhere:
```
rustc_fluent_macro::fluent_messages! { "./example.ftl" }
```
which is shorter.
2023-11-26 08:38:40 +11:00
Nicholas Nethercote a733082be9 Avoid need for {D,Subd}iagnosticMessage imports.
The `fluent_messages!` macro produces uses of
`crate::{D,Subd}iagnosticMessage`, which means that every crate using
the macro must have this import:
```
use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage};
```

This commit changes the macro to instead use
`rustc_errors::{D,Subd}iagnosticMessage`, which avoids the need for the
imports.
2023-11-26 08:38:00 +11:00
Michael Goulet 079a2e865f is_{some,ok}_and 2023-11-25 18:47:16 +00:00
Vadim Petrochenkov ad0770eeee resolve: Avoid clones of MacroData
And move declarative macro compilation to an earlier point in def collector, which is required for #118188.
2023-11-25 02:32:33 +03:00
bors 4fd68eb47b Auto merge of #117934 - Young-Flash:dev, r=petrochenkov
feat: make `let_binding_suggestion` more reasonable

This is my first PR for rustc, which trying to fix https://github.com/rust-lang/rust/issues/117894, I am not familiar with some internal api so maybe some modification here isn't the way to go, appreciated for any review suggestion.
2023-11-24 15:26:04 +00:00
Young-Flash c710db8ea7 feat: make let_binding_suggestion more reasonable 2023-11-23 20:22:17 +08:00
bors 360bafad68 Auto merge of #118065 - estebank:core-not-found-404, r=TaKO8Ki
When failing to import `core`, suggest `std`
2023-11-23 02:26:52 +00:00
Esteban Küber ec50f1c90b When failing to import core, suggest std 2023-11-22 19:30:47 +00:00
Nilstrieb 21a870515b Fix clippy::needless_borrow in the compiler
`x clippy compiler -Aclippy::all -Wclippy::needless_borrow --fix`.

Then I had to remove a few unnecessary parens and muts that were exposed
now.
2023-11-21 20:13:40 +01:00
Esteban Küber eee4cc6616 let-chain fmt 2023-11-20 23:44:37 +00:00
Esteban Küber 02bea16c08 Rely in resolve and not on path name for &str -> String suggestion 2023-11-20 23:44:37 +00:00
Esteban Küber bb9d720a16 Do not consider traits as ownable in suggestion 2023-11-20 23:44:37 +00:00
Esteban Küber 85f26ade8d Account for '_ in lifetime suggestion 2023-11-20 23:44:37 +00:00
Esteban Küber 2a92d820c7 Suggest 'a when trait object assoc type has '_ 2023-11-20 23:44:37 +00:00
Esteban Küber dec7f00e15 Fix incorrect lifetime suggestion 2023-11-20 23:44:37 +00:00
Esteban Küber d30252e359 Tweak wording 2023-11-20 23:44:37 +00:00
Esteban Küber 5fce361d58 Account for impl Trait in lifetime suggestion
When encountering
```rust
fn g(mut x: impl Iterator<Item = &()>) -> Option<&()> { /* */ }
```
Suggest
```rust
fn g<'a>(mut x: impl Iterator<Item = &'a ()>) -> Option<&'a ()> { /* */ }
```
2023-11-20 23:44:37 +00:00
Esteban Küber b7a23bc08b On borrow return type, suggest borrowing from arg or owned return type
When we encounter a function with a return type that has an anonymous
lifetime with no argument to borrow from, besides suggesting the
`'static` lifetime we now also suggest changing the arguments to be
borrows or changing the return type to be an owned type.

```
error[E0106]: missing lifetime specifier
  --> $DIR/variadic-ffi-6.rs:7:6
   |
LL | ) -> &usize {
   |      ^ expected named lifetime parameter
   |
   = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
   |
LL | ) -> &'static usize {
   |       +++++++
help: instead, you are more likely to want to change one of the arguments to be borrowed...
   |
LL |     x: &usize,
   |        +
help: ...or alternatively, to want to return an owned value
   |
LL - ) -> &usize {
LL + ) -> usize {
   |
```

Fix #85843.
2023-11-20 23:44:36 +00:00
Esteban Küber ac56b06b44 fix rebase 2023-11-19 18:07:22 +00:00
Esteban Küber a519c9b6b7 review comments 2023-11-19 17:50:47 +00:00
Esteban Küber 4d16171f56 Account for number of arguments in suggestion 2023-11-19 17:50:47 +00:00
Esteban Küber 00265f0cc0 fix tidy 2023-11-19 17:50:47 +00:00
Esteban Küber 987155f35d Suggest using builder on curly brace struct called as fn 2023-11-19 17:50:46 +00:00
Esteban Küber 12a8bb8d9b Do not suggest struct literal when fields are private 2023-11-19 17:50:46 +00:00
Esteban Küber a4f47de7ff On private tuple struct, suggest Default::default when possible 2023-11-19 17:50:46 +00:00
Esteban Küber f1ae02f4bd Don't sort span_suggestions, leave that to caller 2023-11-19 17:50:45 +00:00
Esteban Küber 42aa1273b0 When encountering struct fn call literal with private fields, suggest all builders
When encountering code like `Box(42)`, suggest `Box::new(42)` and *all*
other associated functions that return `-> Box<T>`.
2023-11-19 17:47:41 +00:00
Matthias Krüger 8792e81f29
Rollup merge of #117964 - estebank:issue-81232, r=petrochenkov
When using existing fn as module, don't claim it doesn't exist

Tweak wording of module not found in resolve, when the name exists but belongs to a non-`mod` item.

Fix #81232.
2023-11-17 23:04:23 +01:00
Esteban Küber 5c3e01a340 On resolve error of [rest..], suggest [rest @ ..]
When writing a pattern to collect multiple entries of a slice in a
single binding, it is easy to misremember or typo the appropriate syntax
to do so, instead writing the experimental `X..` pattern syntax. When we
encounter a resolve error because `X` isn't available, we suggest
`X @ ..` as an alternative.

```
error[E0425]: cannot find value `rest` in this scope
  --> $DIR/range-pattern-meant-to-be-slice-rest-pattern.rs:3:13
   |
LL |         [1, rest..] => println!("{rest:?}"),
   |             ^^^^ not found in this scope
   |
help: if you meant to collect the rest of the slice in `rest`, use the at operator
   |
LL |         [1, rest @ ..] => println!("{rest:?}"),
   |                  +
```

Fix #88404.
2023-11-17 00:55:55 +00:00
Esteban Küber 890ce26213 When using existing fn as module, don't claim it doesn't exist
Tweak wording of module not found in resolve, when the name exists but
belongs to a non-`mod` item.

Fix #81232.
2023-11-16 06:07:33 +00:00
Mark Rousskov db3e2bacb6 Bump cfg(bootstrap)s 2023-11-15 19:41:28 -05:00
Nicholas Nethercote 1b3733e5a4 rustc: minor changes suggested by clippy perf lints. 2023-11-08 08:57:57 +11:00
Nicholas Nethercote 8ff624a9f2 Clean up rustc_*/Cargo.toml.
- Sort dependencies and features sections.
- Add `tidy` markers to the sorted sections so they stay sorted.
- Remove empty `[lib`] sections.
- Remove "See more keys..." comments.

Excluded files:
- rustc_codegen_{cranelift,gcc}, because they're external.
- rustc_lexer, because it has external use.
- stable_mir, because it has external use.
2023-10-30 08:46:02 +11:00
bors 2cad938a81 Auto merge of #116447 - oli-obk:gen_fn, r=compiler-errors
Implement `gen` blocks in the 2024 edition

Coroutines tracking issue https://github.com/rust-lang/rust/issues/43122
`gen` block tracking issue https://github.com/rust-lang/rust/issues/117078

This PR implements `gen` blocks that implement `Iterator`. Most of the logic with `async` blocks is shared, and thus I renamed various types that were referring to `async` specifically.

An example usage of `gen` blocks is

```rust
fn foo() -> impl Iterator<Item = i32> {
    gen {
        yield 42;
        for i in 5..18 {
            if i.is_even() { continue }
            yield i * 2;
        }
    }
}
```

The limitations (to be resolved) of the implementation are listed in the tracking issue
2023-10-29 00:03:52 +00:00
Oli Scherer b8bfd08999 Rename RibKind::ClosureOrAsync to reflect how it is actually used 2023-10-27 13:05:49 +00:00
Oli Scherer 621494382d Add gen blocks to ast and do some broken ast lowering 2023-10-27 13:05:48 +00:00
bors 688892938e Auto merge of #116858 - estebank:issue-22488, r=petrochenkov
Suggest assoc fn `new` when trying to build tuple struct with private fields

Fix #22488.
2023-10-27 12:16:01 +00:00
Esteban Küber 87dc85d322 Suggest assoc fn new when trying to build tuple struct with private fields
Fix #22488.
2023-10-26 22:21:05 +00:00
Matthias Krüger 17fb2f4b31
Rollup merge of #116905 - Fenex:refactor/compiler/resolve, r=petrochenkov
refactor(compiler/resolve): simplify some code

Removes unnecessary allocate and double-sorting the same vector, makes the code a little nicer.
2023-10-26 17:45:43 +02:00
Matthias Krüger 2a027faf68
Rollup merge of #117009 - fmease:diag-disambig-sugg-crate, r=b-naber
On unresolved imports, suggest a disambiguated path if necessary to avoid collision with local items

Fixes #116970.
2023-10-25 23:37:10 +02:00
bohan 482275b194 use visibility to check unused imports and delete some stmts 2023-10-22 21:27:46 +08:00
León Orell Valerian Liehr 4aaf8e03e1
on unresolved import disambiguate suggested path if it would collide 2023-10-21 15:40:32 +02:00
Matthias Krüger c5dd84d493
Rollup merge of #116961 - estebank:issue-60164, r=oli-obk
Typo suggestion to change bindings with leading underscore

When encountering a binding that isn't found but has a typo suggestion for a binding with a leading underscore, suggest changing the binding definition instead of the use place.

Fix #60164.
2023-10-21 10:08:16 +02:00
Oli Scherer 60956837cf s/Generator/Coroutine/ 2023-10-20 21:10:38 +00:00
Esteban Küber b0d17f35d9 Typo suggestion to change bindings with leading underscore
When encountering a binding that isn't found but has a typo suggestion
for a binding with a leading underscore, suggest changing the binding
definition instead of the use place.

Fix #60164.
2023-10-20 15:58:25 +00:00
Vitaliy Busko e68edb89ad
refactor(compiler/resolve): simplify some code
Removes unnecessary allocates and double-sorting the same vector,
makes the code a little nicer.
2023-10-19 04:45:06 +07:00
Michael Goulet b2d2184ede Format all the let chains in compiler 2023-10-13 08:59:36 +00:00
Michael Howell c6e6ecb1af rustdoc: remove rust logo from non-Rust crates 2023-10-08 20:17:53 -07:00
Nicholas Nethercote eb209057b1 Rename Resolver::active_features.
For the reasons described in the previous commit.
2023-10-05 18:01:11 +11:00
Matthias Krüger 144862ede8
Rollup merge of #115863 - chenyukang:yukang-add-message-tidy-check, r=davidtwco
Add check_unused_messages in tidy

From https://github.com/rust-lang/rust/pull/115728#issuecomment-1715490553
The check is not 100% accurate, I guess it's enough for now.
2023-10-03 12:24:11 +02:00
Tyler Mandry af77806bee
Rollup merge of #114454 - Nilstrieb:no-evil-sorting, r=cjgillot
Replace `HashMap` with `IndexMap` in pattern binding resolve

fixes https://github.com/rust-lang/rust/pull/114332#discussion_r1284189179
2023-10-02 16:09:42 -04:00
Nilstrieb 6ca07235a6 Replace HashMap with IndexMap in pattern binding resolve
It will be iterated over, so we should avoid using `HashMap`.
2023-10-02 19:12:42 +02:00
bors 16b7b39fdd Auto merge of #116228 - bvanjoi:fix-116164, r=cjgillot
resolve: skip underscore character during candidate lookup

Fixes #116164

In use statement, an underscore is merely a placeholder symbol and does not bind to any name. Therefore, it can be safely ignored.
2023-10-01 16:41:03 +00:00