Commit Graph

1083 Commits

Author SHA1 Message Date
Matthias Krüger d30af5e168
Rollup merge of #123344 - pietroalbini:pa-unused-imports, r=Nilstrieb
Remove braces when fixing a nested use tree into a single item

[Back in 2019](https://github.com/rust-lang/rust/pull/56645) I added rustfix support for the `unused_imports` lint, to automatically remove them when running `cargo fix`. For the most part this worked great, but when removing all but one childs of a nested use tree it turned `use foo::{Unused, Used}` into `use foo::{Used}`. This is slightly annoying, because it then requires you to run `rustfmt` to get `use foo::Used`.

This PR automatically removes braces and the surrouding whitespace when all but one child of a nested use tree are unused. To get it done I had to add the span of the nested use tree to the AST, and refactor a bit the code I wrote back then.

A thing I noticed is, there doesn't seem to be any `//@ run-rustfix` test for fixing the `unused_imports` lint. I created a test in `tests/suggestions` (is that the right directory?) that for now tests just what I added in the PR. I can followup in a separate PR to add more tests for fixing `unused_lints`.

This PR is best reviewed commit-by-commit.
2024-05-08 23:33:24 +02:00
Nicholas Nethercote 2acbe9c743 Move some tests from `rustc_expand` to `rustc_parse`.
There are some test cases involving `parse` and `tokenstream` and
`mut_visit` that are located in `rustc_expand`. Because it used to be
the case that constructing a `ParseSess` required the involvement of
`rustc_expand`. However, since #64197 merged (a long time ago)
`rust_expand` no longer needs to be involved.

This commit moves the tests into `rustc_parse`. This is the optimal
place for the `parse` tests. It's not ideal for the `tokenstream` and
`mut_visit` tests -- they would be better in `rustc_ast` -- but they
still rely on parsing, which is not available in `rustc_ast`. But
`rustc_parse` is lower down in the crate graph and closer to `rustc_ast`
than `rust_expand`, so it's still an improvement for them.

The exact renaming is as follows:

- rustc_expand/src/mut_visit/tests.rs -> rustc_parse/src/parser/mut_visit/tests.rs
- rustc_expand/src/tokenstream/tests.rs -> rustc_parse/src/parser/tokenstream/tests.rs
- rustc_expand/src/tests.rs + rustc_expand/src/parse/tests.rs ->
  compiler/rustc_parse/src/parser/tests.rs

The latter two test files are combined because there's no need for them
to be separate, and having a `rustc_parse::parser::parse` module would
be weird. This also means some `pub(crate)`s can be removed.
2024-05-06 09:06:02 +10:00
Nicholas Nethercote 3a3a15d753 Refactor `Frame`.
It is currently an enum and the `tts` and `idx` fields are repeated
across the two variants.

This commit splits it into a struct `Frame` and an enum `FrameKind`, to
factor out the duplication. The commit also renames `Frame::new` as
`Frame::new_delimited` and adds `Frame::new_sequence`. I.e. both
variants now have a constructor.
2024-05-03 09:06:26 +10:00
Nicholas Nethercote 5ac017e772 Type annotate `repeats`.
Because the type is not obvious, and this clarifies things.
2024-05-03 09:06:26 +10:00
Nicholas Nethercote ae7e32880a Introduce `Invocation::span_mut`.
Alongside the existing `Invocation::span`.
2024-05-03 09:06:26 +10:00
Nicholas Nethercote 1c15b6ae9c Replace a hard-to-read line.
Too clever by half, IMO.
2024-05-03 09:06:26 +10:00
Nicholas Nethercote 3b6978196d Tweak `fully_expand_fragment` loop.
Control flow never gets past the end of the `ExpandResult::Retry` match
arm, due to the `span_bug` and the `continue`. Therefore, the code after
the match can only be reached from the `ExpandResult::Ready` arm.

This commit moves that code after the match into the
`ExpandResult::Ready` arm, avoiding the need for the `continue` in the
`ExpandResult::Retry` arm.
2024-05-03 09:06:26 +10:00
Nicholas Nethercote 79c4d0202f Remove unnecessary `pub`s. 2024-05-03 09:06:26 +10:00
Nicholas Nethercote c9c964fc37 Fix some comment formatting. 2024-05-03 09:06:26 +10:00
Nicholas Nethercote d7f5319b6d Inline and remove three `DummyResult` methods.
They each have a single call site.
2024-05-03 09:06:26 +10:00
Nicholas Nethercote e809df6ed4 Remove unnecessary re-export of `MacroKind`. 2024-05-03 09:06:25 +10:00
Nicholas Nethercote 189a8a6925 De-`pub` some `rustc_expand` modules. 2024-05-03 09:06:25 +10:00
Nicholas Nethercote 3f055893b4 Remove unused `ExpCtxt` methods. 2024-05-03 09:06:25 +10:00
Nicholas Nethercote 7c6d36345f Remove an unnecessary `#[macro_use]`. 2024-05-03 09:06:25 +10:00
Nicholas Nethercote d817856978 Remove an unnecessary re-export of `rustc_span::hygiene`. 2024-05-03 09:06:25 +10:00
Nicholas Nethercote aabb90d254 rustc_expand: clean up attributes.
Sort them, and remove the unused ones (`lint_reasons` and
`proc_macro_span`).
2024-05-03 09:06:23 +10:00
Mark Rousskov a64f941611 Step bootstrap cfgs 2024-05-01 22:19:11 -04:00
Nicholas Nethercote 6341935a13 Remove `extern crate tracing` from numerous crates. 2024-04-30 16:47:49 +10:00
Nicholas Nethercote 4814fd0a4b Remove `extern crate rustc_macros` from numerous crates. 2024-04-29 10:21:54 +10:00
Matthias Krüger cf07246ae9
Rollup merge of #124382 - petrochenkov:itemvisit, r=lcnr
ast: Generalize item kind visiting

And avoid duplicating logic for visiting `Item`s with different kinds (regular, associated, foreign).

The diff is better viewed with whitespace ignored.
2024-04-27 07:55:37 +02:00
Jacob Pratt 608f71ec66
Rollup merge of #124391 - nnethercote:builtin_macros-cleanups, r=fee1-dead
`rustc_builtin_macros` cleanups

Some improvements I found while looking over this code.

r? ``@fee1-dead``
2024-04-26 19:25:55 -04:00
Nicholas Nethercote 8dc84fa7d1 Move some functions from `rustc_expand` to `rustc_builtin_macros`.
These functions are only used in `rustc_builtin_macros`, so it makes
sense for them to live there. This allows them to be changed from `pub`
to `pub(crate)`.
2024-04-26 09:24:33 +10:00
Nicholas Nethercote e2d2b1c698 Introduce `DeriveResolution`.
Making this a proper struct, and giving its fields names, makes things
easier to understand.
2024-04-26 07:55:21 +10:00
Vadim Petrochenkov 5be9fdd636 ast: Generalize item kind visiting
And avoid duplicating logic for visiting `Item`s with different kinds (regular, associated, foreign).
2024-04-25 22:49:58 +03:00
Vadim Petrochenkov 98804c1786 debuginfo: Stabilize `-Z debug-macros`, `-Z collapse-macro-debuginfo` and `#[collapse_debuginfo]`
`-Z debug-macros` is "stabilized" by enabling it by default and removing.

`-Z collapse-macro-debuginfo` is stabilized as `-C collapse-macro-debuginfo`.
It now supports all typical boolean values (`parse_opt_bool`) in addition to just yes/no.

Default value of `collapse_debuginfo` was changed from `false` to `external` (i.e. collapsed if external, not collapsed if local).
`#[collapse_debuginfo]` attribute without a value is no longer supported to avoid guessing the default.
2024-04-25 22:14:47 +03:00
Xiretza 3289a9a60d rustc_expand: make diagnostic translatable 2024-04-22 16:29:54 +00:00
Xiretza bfacfe2510 expand: fix minor diagnostics bug
The error mentions `///`, when it's actually `//!`:

error[E0658]: attributes on expressions are experimental
 --> test.rs:4:9
  |
4 |         //! wah
  |         ^^^^^^^
  |
  = note: see issue #15701 <https://github.com/rust-lang/rust/issues/15701> for more information
  = help: add `#![feature(stmt_expr_attributes)]` to the crate attributes to enable
  = help: `///` is for documentation comments. For a plain comment, use `//`.
2024-04-22 16:28:20 +00:00
bors c25473ff62 Auto merge of #124008 - nnethercote:simpler-static_assert_size, r=Nilstrieb
Simplify `static_assert_size`s.

We want to run them on all 64-bit platforms.

r? `@ghost`
2024-04-18 09:47:45 +00:00
Nicholas Nethercote 0d97669a17 Simplify `static_assert_size`s.
We want to run them on all 64-bit platforms.
2024-04-18 15:36:25 +10:00
Jules Bertholet 2a4624ddd1
Rename `BindingAnnotation` to `BindingMode` 2024-04-17 09:34:39 -04:00
León Orell Valerian Liehr c5665990c5
Rollup merge of #123462 - fmease:rn-mod-sep-to-path-sep, r=nnethercote
Cleanup: Rename `ModSep` to `PathSep`

`::` is usually referred to as the *path separator* (citation needed).

The existing name `ModSep` for *module separator* is a bit misleading since it in fact separates the segments of arbitrary path segments, not only ones resolving to modules. Let me just give a shout-out to associated items (`T::Assoc`, `<Ty as Trait>::function`) and enum variants (`Option::None`).

Motivation: Reduce friction for new contributors, prevent potential confusion.

cc `@petrochenkov`
r? nnethercote or compiler
2024-04-16 01:12:37 +02:00
Pietro Albini 13f76235b3
store the span of the nested part of the use tree in the ast 2024-04-14 18:45:28 +02:00
León Orell Valerian Liehr 3cbc9e9560
Rename ModSep to PathSep 2024-04-04 19:44:04 +02:00
Zalathar 2d47cd77ac Check `x86_64` size assertions on `aarch64`, too
This makes it easier for contributors on aarch64 workstations (e.g. Macs) to
notice when these assertions have been violated.
2024-04-03 16:53:03 +11:00
Jacob Pratt e41d7e7aaf
Rollup merge of #123182 - jhpratt:fix-decodable-derive, r=davidtwco
Avoid expanding to unstable internal method

Fixes #123156

Rather than expanding to `std::rt::begin_panic`, the expansion is now to `unreachable!()`. The resulting behavior is identical. A test that previously triggered the same error as #123156 has been added to ensure it does not regress.

r? compiler
2024-04-02 20:37:40 -04:00
Jacob Pratt 0fcdf34861
Avoid expanding to unstable internal method 2024-04-02 22:21:16 +00:00
klensy aa35530319 compiler: fix few needless_pass_by_ref_mut clippy lints
warning: this argument is a mutable reference, but not used mutably
    --> compiler\rustc_session\src\config.rs:2013:16
     |
2013 |     early_dcx: &mut EarlyDiagCtxt,
     |                ^^^^^^^^^^^^^^^^^^ help: consider changing to: `&EarlyDiagCtxt`
     |
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut

warning: this argument is a mutable reference, but not used mutably
    --> compiler\rustc_ast_passes\src\ast_validation.rs:1555:11
     |
1555 |     this: &mut AstValidator<'_>,
     |           ^^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&AstValidator<'_>`
     |
     = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut

warning: this argument is a mutable reference, but not used mutably
  --> compiler\rustc_infer\src\infer\snapshot\fudge.rs:16:12
   |
16 |     table: &mut UnificationTable<'_, 'tcx, T>,
   |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: consider changing to: `&UnificationTable<'_, 'tcx, T>`
   |
   = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut

warning: this argument is a mutable reference, but not used mutably
   --> compiler\rustc_expand\src\expand.rs:961:13
    |
961 |     parser: &mut Parser<'a>,
    |             ^^^^^^^^^^^^^^^ help: consider changing to: `&Parser<'a>`
    |
    = warning: changing this function will impact semver compatibility
    = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#needless_pass_by_ref_mut
2024-03-28 11:37:52 +03:00
Kornel 826ddb3018 Suggest correct path in include_bytes! 2024-03-27 15:16:25 +00:00
Kornel 89ceced6f6 Helper function for resolve_path 2024-03-27 14:57:37 +00:00
Matthias Krüger 783778c631
Rollup merge of #121619 - RossSmyth:pfix_match, r=petrochenkov
Experimental feature postfix match

This has a basic experimental implementation for the RFC postfix match (rust-lang/rfcs#3295, #121618). [Liaison is](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Postfix.20Match.20Liaison/near/423301844) ```@scottmcm``` with the lang team's [experimental feature gate process](https://github.com/rust-lang/lang-team/blob/master/src/how_to/experiment.md).

This feature has had an RFC for a while, and there has been discussion on it for a while. It would probably be valuable to see it out in the field rather than continue discussing it. This feature also allows to see how popular postfix expressions like this are for the postfix macros RFC, as those will take more time to implement.

It is entirely implemented in the parser, so it should be relatively easy to remove if needed.

This PR is split in to 5 commits to ease review.

1. The implementation of the feature & gating.
2. Add a MatchKind field, fix uses, fix pretty.
3. Basic rustfmt impl, as rustfmt crashes upon seeing this syntax without a fix.
4. Add new MatchSource to HIR for Clippy & other HIR consumers
2024-03-22 11:36:58 +01:00
Matthias Krüger 8b132109c4
Rollup merge of #122752 - nnethercote:Interpolated-cleanups, r=petrochenkov
Interpolated cleanups

Various cleanups I made while working on attempts to remove `Interpolated`, that are worth merging now. Best reviewed one commit at a time.

r? `@petrochenkov`
2024-03-21 17:46:49 +01:00
Matthias Krüger 8106b54290
Rollup merge of #122773 - tshepang:make-expand-translatable, r=fee1-dead
make "expected paren or brace" error translatable
2024-03-21 12:05:07 +01:00
Nicholas Nethercote a94bb2a013 Streamline `NamedMatch`.
This commit combines `MatchedTokenTree` and `MatchedNonterminal`, which
are often considered together, into a single `MatchedSingle`. It shares
a representation with the newly-parameterized `ParseNtResult`.

This will also make things much simpler if/when variants from
`Interpolated` start being moved to `ParseNtResult`.
2024-03-21 10:18:34 +11:00
Nicholas Nethercote 099e716502 Factor out `tt` pushes. 2024-03-21 09:00:25 +11:00
Tshepang Mbambo 3e8ff90935 make "expected paren or brace" error translatable 2024-03-20 14:31:05 +02:00
Matthias Krüger 9fb40efa6d
Rollup merge of #122540 - WaffleLapkin:ununexpected, r=estebank
Do not use `?`-induced skewing of type inference in the compiler

This prevents breakage from #122412 and is generally a good idea.

r? `@estebank`
2024-03-20 05:51:22 +01:00
bors bd459c2877 Auto merge of #122029 - estebank:drive-by-ui-test, r=oli-obk
When displaying multispans, ignore empty lines adjacent to `...`

```
error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:98:18
    |
6   |       let _ = match true {
    |               ---------- `match` arms have incompatible types
7   |           true => (
    |  _________________-
8   | |             // last line shown in multispan header
...   |
96  | |
97  | |         ),
    | |_________- this is found to be of type `()`
98  |           false => "
    |  __________________^
...   |
119 | |
120 | |         ",
    | |_________^ expected `()`, found `&str`

error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:215:18
    |
122 |       let _ = match true {
    |               ---------- `match` arms have incompatible types
123 |           true => (
    |  _________________-
124 | |
125 | |         1 // last line shown in multispan header
...   |
213 | |
214 | |         ),
    | |_________- this is found to be of type `{integer}`
215 |           false => "
    |  __________________^
216 | |
217 | |
218 | |         1 last line shown in multispan
...   |
237 | |
238 | |         ",
    | |_________^ expected integer, found `&str`
```
2024-03-19 22:11:59 +00:00
bors 21d94a3d2c Auto merge of #122055 - compiler-errors:stabilize-atb, r=oli-obk
Stabilize associated type bounds (RFC 2289)

This PR stabilizes associated type bounds, which were laid out in [RFC 2289]. This gives us a shorthand to express nested type bounds that would otherwise need to be expressed with nested `impl Trait` or broken into several `where` clauses.

### What are we stabilizing?

We're stabilizing the associated item bounds syntax, which allows us to put bounds in associated type position within other bounds, i.e. `T: Trait<Assoc: Bounds...>`. See [RFC 2289] for motivation.

In all position, the associated type bound syntax expands into a set of two (or more) bounds, and never anything else (see "How does this differ[...]" section for more info).

Associated type bounds are stabilized in four positions:
* **`where` clauses (and APIT)** - This is equivalent to breaking up the bound into two (or more) `where` clauses. For example, `where T: Trait<Assoc: Bound>` is equivalent to `where T: Trait, <T as Trait>::Assoc: Bound`.
* **Supertraits** - Similar to above, `trait CopyIterator: Iterator<Item: Copy> {}`. This is almost equivalent to breaking up the bound into two (or more) `where` clauses; however, the bound on the associated item is implied whenever the trait is used. See #112573/#112629.
* **Associated type item bounds** - This allows constraining the *nested* rigid projections that are associated with a trait's associated types. e.g. `trait Trait { type Assoc: Trait2<Assoc2: Copy>; }`.
* **opaque item bounds (RPIT, TAIT)** - This allows constraining associated types that are associated with the opaque without having to *name* the opaque. For example, `impl Iterator<Item: Copy>` defines an iterator whose item is `Copy` without having to actually name that item bound.

The latter three are not expressible in surface Rust (though for associated type item bounds, this will change in #120752, which I don't believe should block this PR), so this does represent a slight expansion of what can be expressed in trait bounds.

### How does this differ from the RFC?

Compared to the RFC, the current implementation *always* desugars associated type bounds to sets of `ty::Clause`s internally. Specifically, it does *not* introduce a position-dependent desugaring as laid out in [RFC 2289], and in particular:
* It does *not* desugar to anonymous associated items in associated type item bounds.
* It does *not* desugar to nested RPITs in RPIT bounds, nor nested TAITs in TAIT bounds.

This position-dependent desugaring laid out in the RFC existed simply to side-step limitations of the trait solver, which have mostly been fixed in #120584. The desugaring laid out in the RFC also added unnecessary complication to the design of the feature, and introduces its own limitations to, for example:
* Conditionally lowering to nested `impl Trait` in certain positions such as RPIT and TAIT means that we inherit the limitations of RPIT/TAIT, namely lack of support for higher-ranked opaque inference. See this code example: https://github.com/rust-lang/rust/pull/120752#issuecomment-1979412531.
* Introducing anonymous associated types makes traits no longer object safe, since anonymous associated types are not nameable, and all associated types must be named in `dyn` types.

This last point motivates why this PR is *not* stabilizing support for associated type bounds in `dyn` types, e.g, `dyn Assoc<Item: Bound>`. Why? Because `dyn` types need to have *concrete* types for all associated items, this would necessitate a distinct lowering for associated type bounds, which seems both complicated and unnecessary compared to just requiring the user to write `impl Trait` themselves. See #120719.

### Implementation history:

Limited to the significant behavioral changes and fixes and relevant PRs, ping me if I left something out--
* #57428
* #108063
* #110512
* #112629
* #120719
* #120584

Closes #52662

[RFC 2289]: https://rust-lang.github.io/rfcs/2289-associated-type-bounds.html
2024-03-19 00:04:09 +00:00
Esteban Küber cc9631a371 When displaying multispans, ignore empty lines adjacent to `...`
```
error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:98:18
    |
6   |       let _ = match true {
    |               ---------- `match` arms have incompatible types
7   |           true => (
    |  _________________-
8   | |             // last line shown in multispan header
...   |
96  | |
97  | |         ),
    | |_________- this is found to be of type `()`
98  |           false => "
    |  __________________^
...   |
119 | |
120 | |         ",
    | |_________^ expected `()`, found `&str`

error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:215:18
    |
122 |       let _ = match true {
    |               ---------- `match` arms have incompatible types
123 |           true => (
    |  _________________-
124 | |
125 | |         1 // last line shown in multispan header
...   |
213 | |
214 | |         ),
    | |_________- this is found to be of type `{integer}`
215 |           false => "
    |  __________________^
216 | |
217 | |
218 | |         1 last line shown in multispan
...   |
237 | |
238 | |         ",
    | |_________^ expected integer, found `&str`
```
2024-03-18 16:25:36 +00:00
Maybe Waffle 75d940f637 Use `do yeet ()` and `do yeet _` instead of `None?` and `Err(_)?` in compiler
This prevents breakage when `?` no longer skews inference.
2024-03-15 11:37:42 +00:00
Guillaume Gomez ca9f0630a9 Rename `ast::StmtKind::Local` into `ast::StmtKind::Let` 2024-03-14 12:42:04 +01:00
bohan 8fcdf54a6b delay expand macro bang when there has indeterminate path 2024-03-13 16:11:16 +08:00
Michael Goulet c63f3feb0f Stabilize associated type bounds 2024-03-08 20:56:25 +00:00
Matthias Krüger efe9deace8
Rollup merge of #121382 - nnethercote:rework-untranslatable_diagnostic-lint, r=davidtwco
Rework `untranslatable_diagnostic` lint

Currently it only checks calls to functions marked with `#[rustc_lint_diagnostics]`. This PR changes it to check calls to any function with an `impl Into<{D,Subd}iagnosticMessage>` parameter. This greatly improves its coverage and doesn't rely on people remembering to add `#[rustc_lint_diagnostics]`. It also lets us add `#[rustc_lint_diagnostics]` to a number of functions that don't have an `impl Into<{D,Subd}iagnosticMessage>`, such as `Diag::span`.

r? ``@davidtwco``
2024-03-06 22:02:46 +01:00
Ross Smyth 78b3bf98c3 Add MatchKind member to the Match expr for pretty printing & fmt 2024-03-06 00:35:19 -05:00
Nicholas Nethercote b7d58eef4b Rewrite the `untranslatable_diagnostic` lint.
Currently it only checks calls to functions marked with
`#[rustc_lint_diagnostics]`. This commit changes it to check calls to
any function with an `impl Into<{D,Subd}iagMessage>` parameter. This
greatly improves its coverage and doesn't rely on people remembering to
add `#[rustc_lint_diagnostics]`.

The commit also adds `#[allow(rustc::untranslatable_diagnostic)`]
attributes to places that need it that are caught by the improved lint.
These places that might be easy to convert to translatable diagnostics.

Finally, it also:
- Expands and corrects some comments.
- Does some minor formatting improvements.
- Adds missing `DecorateLint` cases to
  `tests/ui-fulldeps/internal-lints/diagnostics.rs`.
2024-03-06 14:19:01 +11:00
bors b77e0184a9 Auto merge of #122045 - matthiaskrgr:rollup-5l3vpn7, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #121065 (Add basic i18n guidance for `Display`)
 - #121744 (Stop using Bubble in coherence and instead emulate it with an intercrate check)
 - #121829 (Dummy tweaks (attempt 2))
 - #121857 (Implement async closure signature deduction)
 - #121894 (const_eval_select: make it safe but be careful with what we expose on stable for now)
 - #122014 (Change some attributes to only_local.)
 - #122016 (will_wake tests fail on Miri and that is expected)
 - #122018 (only set noalias on Box with the global allocator)
 - #122028 (Remove some dead code)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-06 02:18:22 +00:00
Matthias Krüger 0783a63d34
Rollup merge of #121829 - nnethercote:dummy-tweaks-2, r=petrochenkov
Dummy tweaks (attempt 2)

r? `````@petrochenkov`````
2024-03-05 22:10:00 +01:00
Jason Newcomb 5abfb3775d Move visitor utils to `rustc_ast_ir` 2024-03-05 12:38:03 -05: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 18715c98c6 Rename `DiagnosticMessage` as `DiagMessage`. 2024-03-05 12:14:49 +11:00
Nicholas Nethercote b5d7da878f Decouple `DummyAstNode` and `DummyResult`.
They are two different ways of creating dummy results, with two
different purposes. Their implementations are separate except for
crates, where `DummyResult` depends on `DummyAstNode`.

This commit removes that dependency, so they are now fully separate. It
also expands the comment on `DummyAstNode`.
2024-03-05 12:05:04 +11: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
Nicholas Nethercote 4260f7ec67 Rename a misnamed `Session` parameter. 2024-03-04 16:32:37 +11:00
Nicholas Nethercote 0d4ebe1c1b Move `sess` function and use it more. 2024-03-04 16:26:51 +11:00
Nicholas Nethercote 3996447b37 Remove `file_path_mapping` param from `ParseSess::new`.
It's always empty.
2024-03-04 16:22:06 +11:00
bors 4cdd20584c Auto merge of #121657 - estebank:issue-119665, r=davidtwco
Detect more cases of `=` to `:` typo

When a `Local` is fully parsed, but not followed by a `;`, keep the `:` span arround and mention it. If the type could continue being parsed as an expression, suggest replacing the `:` with a `=`.

```
error: expected one of `!`, `+`, `->`, `::`, `;`, or `=`, found `.`
 --> file.rs:2:32
  |
2 |     let _: std::env::temp_dir().join("foo");
  |          -                     ^ expected one of `!`, `+`, `->`, `::`, `;`, or `=`
  |          |
  |          while parsing the type for `_`
  |          help: use `=` if you meant to assign
```

Fix #119665.
2024-03-02 05:03:46 +00:00
Esteban Küber bde2dfb127 Detect more cases of `=` to `:` typo
When a `Local` is fully parsed, but not followed by a `;`, keep the `:` span
arround and mention it. If the type could continue being parsed as an
expression, suggest replacing the `:` with a `=`.

```
error: expected one of `!`, `+`, `->`, `::`, `;`, or `=`, found `.`
 --> file.rs:2:32
  |
2 |     let _: std::env::temp_dir().join("foo");
  |          -                     ^ expected one of `!`, `+`, `->`, `::`, `;`, or `=`
  |          |
  |          while parsing the type for `_`
  |          help: use `=` if you meant to assign
```

Fix #119665.
2024-03-01 02:03:00 +00:00
Nicholas Nethercote 880c1c585f Rename `DiagCtxt::with_emitter` as `DiagCtxt::new`.
Because it's now the only constructor.
2024-02-29 16:30:12 +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
Lieselotte c440a5b814
Add `ErrorGuaranteed` to `ast::ExprKind::Err` 2024-02-25 22:24:31 +01:00
Lieselotte a3fce72a27
Add `ast::ExprKind::Dummy` 2024-02-25 22:22:09 +01: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
Matthias Krüger 86a7fc840f compiler: clippy::complexity fixes 2024-02-23 19:56:35 +01:00
Nicholas Nethercote 326b44e4d3 Fix panic when compiling `Rocket`.
`Rustc::emit_diagnostic` reconstructs a diagnostic passed in from the
macro machinery. Currently it uses the type `DiagnosticBuilder<'_,
ErrorGuaranteed>`, which is incorrect, because the diagnostic might be a
warning. And if it is a warning, because of the `ErrorGuaranteed` we end
up calling into `emit_producing_error_guaranteed` and the assertion
within that function (correctly) fails because the level is not an error
level.

The fix is simple: change the type to `DiagnosticBuilder<'_, ()>`. Using
`()` works no matter what the diagnostic level is, and we don't need an
`ErrorGuaranteed` here.

The panic was reported in #120576.
2024-02-22 13:46:33 +11:00
Dylan DPC 4840785cf8
Rollup merge of #121288 - tshepang:make-expand-translatable, r=michaelwoerister
make rustc_expand translatable

these are the last of the easy ones
2024-02-21 08:55:56 +00:00
clubby789 06d6c62f80 Add newtype for raw idents 2024-02-20 13:13:29 +00:00
bors 29f87ade9d Auto merge of #120576 - nnethercote:merge-Diagnostic-DiagnosticBuilder, r=davidtwco
Overhaul `Diagnostic` and `DiagnosticBuilder`

Implements the first part of https://github.com/rust-lang/compiler-team/issues/722, which moves functionality and use away from `Diagnostic`, onto `DiagnosticBuilder`.

Likely follow-ups:
- Move things around, because this PR was written to minimize diff size, so some things end up in sub-optimal places. E.g. `DiagnosticBuilder` has impls in both `diagnostic.rs` and `diagnostic_builder.rs`.
- Rename `Diagnostic` as `DiagInner` and `DiagnosticBuilder` as `Diag`.

r? `@davidtwco`
2024-02-20 12:05:09 +00:00
Nilstrieb 46cab11ed1
Rollup merge of #121256 - Jarcho:visitor2, r=oli-obk
Allow AST and HIR visitors to return `ControlFlow`

Alternative to #108598.

Since rust-lang/libs-team#187 was rejected, this implements our own version of the `Try` trait (`VisitorResult`) and the `try` macro (`try_visit`). Since this change still allows visitors to return `()`, no changes have been made to the existing ones. They can be done in a separate PR.
2024-02-20 07:35:47 +01:00
Tshepang Mbambo f68682fd48 make "proc-macro derive panicked" translatable 2024-02-20 08:31:13 +02:00
Nicholas Nethercote f6f8779843 Reduce capabilities of `Diagnostic`.
Currently many diagnostic modifier methods are available on both
`Diagnostic` and `DiagnosticBuilder`. This commit removes most of them
from `Diagnostic`. To minimize the diff size, it keeps them within
`diagnostic.rs` but changes the surrounding `impl Diagnostic` block to
`impl DiagnosticBuilder`. (I intend to move things around later, to give
a more sensible code layout.)

`Diagnostic` keeps a few methods that it still needs, like `sub`,
`arg`, and `replace_args`.

The `forward!` macro, which defined two additional methods per call
(e.g. `note` and `with_note`), is replaced by the `with_fn!` macro,
which defines one additional method per call (e.g. `with_note`). It's
now also only used when necessary -- not all modifier methods currently
need a `with_*` form. (New ones can be easily added as necessary.)

All this also requires changing `trait AddToDiagnostic` so its methods
take `DiagnosticBuilder` instead of `Diagnostic`, which leads to many
mechanical changes. `SubdiagnosticMessageOp` gains a type parameter `G`.

There are three subdiagnostics -- `DelayedAtWithoutNewline`,
`DelayedAtWithNewline`, and `InvalidFlushedDelayedDiagnosticLevel` --
that are created within the diagnostics machinery and appended to
external diagnostics. These are handled at the `Diagnostic` level, which
means it's now hard to construct them via `derive(Diagnostic)`, so
instead we construct them by hand. This has no effect on what they look
like when printed.

There are lots of new `allow` markers for `untranslatable_diagnostics`
and `diagnostics_outside_of_impl`. This is because
`#[rustc_lint_diagnostics]` annotations were present on the `Diagnostic`
modifier methods, but missing from the `DiagnosticBuilder` modifier
methods. They're now present.
2024-02-20 13:22:17 +11: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
Tshepang Mbambo 61509914a3 make "custom attribute panicked" translatable 2024-02-19 09:23:26 +02:00
bors 2bf78d12d3 Auto merge of #119673 - petrochenkov:dialoc5, r=compiler-errors,cjgillot
macro_rules: Preserve all metavariable spans in a global side table

This PR preserves spans of `tt` metavariables used to pass tokens to declarative macros.
Such metavariable spans can then be used in span combination operations like `Span::to` to improve all kinds of diagnostics.

Spans of non-`tt` metavariables are currently kept in nonterminal tokens, but the long term plan is remove all nonterminal tokens from rustc parser and rely on the proc macro model with invisible delimiters (#114647, #67062).
In particular, `NtIdent` nonterminal (corresponding to `ident` metavariables) becomes easy to remove when this PR lands (#119412 does it).

The metavariable spans are kept in a global side table keyed by `Span`s of original tokens.
The alternative to the side table is keeping them in `SpanData` instead, but the performance regressions would be large because any spans from tokens passed to declarative macros would stop being inline and would work through span interner instead, and the penalty would be paid even if we never use the metavar span for the given original span.
(But also see the comment on `fn maybe_use_metavar_location` describing the map collision issues with the side table approach.)

There are also other alternatives - keeping the metavar span in `Token` or `TokenTree`, but associating it with `Span` itsel is the most natural choice because metavar spans are used in span combining operations, and those operations are not necessarily tied to tokens.
2024-02-18 20:51:16 +00:00
Matthias Krüger ddf6c6dbc6
Rollup merge of #121067 - tshepang:make-expand-translatable, r=fmease
make "invalid fragment specifier" translatable
2024-02-18 18:54:32 +01:00
Jason Newcomb 864cee3ea3 Allow AST and HIR visitors to return `ControlFlow` 2024-02-18 03:49:28 -05:00
Vadim Petrochenkov 9f8d05f29f macro_rules: Preserve all metavariable spans in a global side table 2024-02-18 11:19:24 +03: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
Tshepang Mbambo 3a917cdfcb make "invalid fragment specifier" translatable 2024-02-16 20:15:07 +02:00
Guillaume Gomez c73aa787f6
Rollup merge of #121109 - nnethercote:TyKind-Err-guar-2, r=oli-obk
Add an ErrorGuaranteed to ast::TyKind::Err (attempt 2)

This makes it more like `hir::TyKind::Err`, and avoids a `has_errors` assertion in `LoweringContext::lower_ty_direct`.

r? ```@oli-obk```
2024-02-16 00:27:32 +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
Nicholas Nethercote 25ed6e43b0 Add `ErrorGuaranteed` to `ast::LitKind::Err`, `token::LitKind::Err`.
This mostly works well, and eliminates a couple of delayed bugs.

One annoying thing is that we should really also add an
`ErrorGuaranteed` to `proc_macro::bridge::LitKind::Err`. But that's
difficult because `proc_macro` doesn't have access to `ErrorGuaranteed`,
so we have to fake it.
2024-02-15 14:46:08 +11:00
Nicholas Nethercote 5233bc91da Add an `ErrorGuaranteed` to `ast::TyKind::Err`.
This makes it more like `hir::TyKind::Err`, and avoids a
`span_delayed_bug` call in `LoweringContext::lower_ty_direct`.

It also requires adding `ast::TyKind::Dummy`, now that
`ast::TyKind::Err` can't be used for that purpose in the absence of an
error emission.

There are a couple of cases that aren't as neat as I would have liked,
marked with `FIXME` comments.
2024-02-15 09:35:11 +11:00
Nicholas Nethercote 05849e8c2f Use fewer delayed bugs.
For some cases where it's clear that an error has already occurred,
e.g.:
- there's a comment stating exactly that, or
- things like HIR lowering, where we are lowering an error kind

The commit also tweaks some comments around delayed bug sites.
2024-02-14 20:30:37 +11: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
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
Michael Goulet 0eb2adb7e8 Add async bound modifier to enable async Fn bounds 2024-01-31 16:59:19 +00:00
Guillaume Gomez b28e6f143e
Rollup merge of #120342 - oli-obk:track_errors6, r=nnethercote
Remove various `has_errors` or `err_count` uses

follow up to https://github.com/rust-lang/rust/pull/119895

r? `@nnethercote` since you recently did something similar.

There are so many more of these, but I wanted to get a PR out instead of growing the commit list indefinitely. The commits all work on their own and can be reviewed commit by commit.
2024-01-30 16:57:49 +01: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
Matthias Krüger 4808aa8872
Rollup merge of #117420 - Jules-Bertholet:internal-unstable-stmt-expr-attributes, r=petrochenkov
Make `#![allow_internal_unstable(..)]` work with `stmt_expr_attributes`

This is a necessary first step to fixing #117304, as explained in https://github.com/rust-lang/rust/issues/117304#issuecomment-1784414453.

`@rustbot` label T-compiler
2024-01-26 14:43:29 +01:00
Matthias Krüger 626797b61d
Rollup merge of #120204 - azhogin:azhogin/collapse_debuginfo_for_builtin, r=petrochenkov
Builtin macros effectively have implicit #[collapse_debuginfo(yes)]

If collapse_debuginfo attribute for builtin macro is not specified explicitly, it will be effectively set to `#[collapse_debuginfo(yes)]`.
2024-01-26 06:36:38 +01:00
Andrew Zhogin 27717dbd4d Builtin macros effectively have implicit #[collapse_debuginfo(yes)] attribute 2024-01-26 01:45:50 +07:00
clubby789 fd29f74ff8 Remove unused features 2024-01-25 14:01:33 +00:00
Oli Scherer f68741b637 Stop checking `err_count` in macro_rules validity checking
All errors are local anyway, so we can track them directly
2024-01-25 11:57:01 +00:00
Josh Stone 33e0422826 Pack the u128 in LitKind::Int 2024-01-19 20:10:39 -08:00
bors 32ec40c685 Auto merge of #120121 - matthiaskrgr:rollup-razammh, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #118665 (Consolidate all associated items on the NonZero integer types into a single impl block per type)
 - #118798 (Use AtomicU8 instead of AtomicUsize in backtrace.rs)
 - #119062 (Deny braced macro invocations in let-else)
 - #119138 (Docs: Use non-SeqCst in module example of atomics)
 - #119907 (Update `fn()` trait implementation docs)
 - #120083 (Warn when not having a profiler runtime means that coverage tests won't be run/blessed)
 - #120107 (dead_code treats #[repr(transparent)] the same as #[repr(C)])
 - #120110 (Update documentation for Vec::into_boxed_slice to be more clear about excess capacity)
 - #120113 (Remove myself from review rotation)
 - #120118 (Fix typo in documentation in base.rs)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-19 16:26:37 +00:00
kapilsinha 1a343424f3
Fix typo in documentation in base.rs 2024-01-18 17:49:06 -08:00
Andrew Zhogin 8507f5105b Improved collapse_debuginfo attribute, added command-line flag (no|external|yes) 2024-01-17 23:18:14 +07:00
George-lewis 36a69e9d39 Add check for ui_testing via promoting parameters from `ParseSess` to `Session` 2024-01-13 12:11:13 -05:00
Nicholas Nethercote 0e388f2192 Change how `force-warn` lint diagnostics are recorded.
`is_force_warn` is only possible for diagnostics with `Level::Warning`,
but it is currently stored in `Diagnostic::code`, which every diagnostic
has.

This commit:
- removes the boolean `DiagnosticId::Lint::is_force_warn` field;
- adds a `ForceWarning` variant to `Level`.

Benefits:
- The common `Level::Warning` case now has no arguments, replacing
  lots of `Warning(None)` occurrences.
- `rustc_session::lint::Level` and `rustc_errors::Level` are more
  similar, both having `ForceWarning` and `Warning`.
2024-01-11 07:56:17 +11: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
Matthias Krüger 1c9e862a3e
Rollup merge of #119740 - Mark-Simulacrum:drop-crossbeam, r=davidtwco
Remove crossbeam-channel

The standard library's std::sync::mpsc basically is a crossbeam channel, and for the use case here will definitely suffice. This drops this dependency from librustc_driver.
2024-01-09 00:19:36 +01:00
bors ca663b06c5 Auto merge of #119606 - nnethercote:consuming-emit, r=oli-obk
Consuming `emit`

This PR makes `DiagnosticBuilder::emit` consuming, i.e. take `self` instead of `&mut self`. This is good because it doesn't make sense to emit a diagnostic twice.

This requires some changes to `DiagnosticBuilder` method changing -- every existing non-consuming chaining method gets a new consuming partner with a `_mv` suffix -- but permits a host of beneficial follow-up changes: more concise code through more chaining, removal of redundant diagnostic construction API methods, and removal of machinery to track the possibility of a diagnostic being emitted multiple times.

r? `@compiler-errors`
2024-01-08 16:06:28 +00: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
Mark Rousskov be0293f468 Remove crossbeam-channel
The standard library's std::sync::mpsc basically is a crossbeam channel,
and for the use case here will definitely suffice. This drops this
dependency from librustc_driver.
2024-01-07 19:16:13 -05:00
Vadim Petrochenkov edec91d624 macro_rules: Add an expansion-local cache to span marker 2024-01-08 03:06:37 +03:00
Vadim Petrochenkov 90d11d6448 rustc_span: Optimize syntax context comparisons
Including comparisons with root context
2024-01-06 01:25:20 +03:00
Michael Goulet da700b39df
Rollup merge of #119601 - nnethercote:Emitter-cleanups, r=oli-obk
`Emitter` cleanups

Some improvements I found while looking at this code.

r? `@oli-obk`
2024-01-05 10:57:24 -05: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
Nicholas Nethercote cb9abcae79 Rename `EmitterWriter` as `HumanEmitter`.
For consistency with other `Emitter` impls, such as `JsonEmitter`,
`SilentEmitter`, `SharedEmitter`, etc.
2024-01-05 10:02:40 +11:00
Nicholas Nethercote 8388112970 Remove `is_lint` field from `Level::Error`.
Because it's redundant w.r.t. `Diagnostic::is_lint`, which is present
for every diagnostic level.

`struct_lint_level_impl` was the only place that set the `Error` field
to `true`, and it's also the only place that calls
`Diagnostic::is_lint()` to set the `is_lint` field.
2024-01-04 16:09:31 +11:00
Vadim Petrochenkov e1d12c8caf macro_rules: Less hacky heuristic for using `tt` metavariable spans 2024-01-04 03:53:56 +03: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
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 d51db05d7e Remove `ParseSess` methods that duplicate `DiagCtxt` methods.
Also add missing `#[track_caller]` attributes to `DiagCtxt` methods as
necessary to keep tests working.
2023-12-24 07:59:21 +11:00
Nicholas Nethercote d86a48278f Remove `ExtCtxt` methods that duplicate `DiagCtxt` methods. 2023-12-24 07:24:52 +11:00
Matthias Krüger bdc4480914
Rollup merge of #119231 - aDotInTheVoid:PatKind-struct-bool-docs, r=compiler-errors
Clairify `ast::PatKind::Struct` presese of `..` by using an enum instead of a bool

The bool is mainly used for when a `..` is present, but it is also set on recovery to avoid errors. The doc comment not describes both of these cases.

See cee794ee98/compiler/rustc_parse/src/parser/pat.rs (L890-L897) for the only place this is constructed.

r? ``@compiler-errors``
2023-12-23 16:23:54 +01:00
Alona Enraght-Moony 1349d86c72 bool->enum for ast::PatKind::Struct presence of `..`
See cee794ee98/compiler/rustc_parse/src/parser/pat.rs (L890-L897) for the only place this is constructed.
2023-12-23 02:50:31 +00:00
Michael Goulet e0d7a72c46
Rollup merge of #119171 - nnethercote:cleanup-errors-4, r=compiler-errors
Cleanup error handlers: round 4

More `rustc_errors` cleanups. A sequel to #118933.

r? `@compiler-errors`
2023-12-22 21:41:03 -05:00
Nicholas Nethercote 125337bd68 Remove `render_span` args from `Diagnostic::{sub,sub_with_highlight}`.
They're always `None`.
2023-12-23 13:23: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
Pietro Albini f9f5840eb4
update cfg(bootstrap)s 2023-12-22 11:14:11 +01: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
bors cee794ee98 Auto merge of #119097 - nnethercote:fix-EmissionGuarantee, r=compiler-errors
Fix `EmissionGuarantee`

There are some problems with the `DiagCtxt` API related to `EmissionGuarantee`. This PR fixes them.

r? `@compiler-errors`
2023-12-22 00:03:57 +00:00
León Orell Valerian Liehr 5e4f12b41a
Refactor AST trait bound modifiers 2023-12-20 19:39:46 +01:00
Alona Enraght-Moony 11337805fb Give `VariantData::Struct` named fields, to clairfy `recovered`. 2023-12-20 00:07:34 +00:00
Nicholas Nethercote 072c157d68 Introduce `DiagCtxt::struct_bug`.
This makes `DiagCtxt::bug` look like the other similar functions.
2023-12-19 09:52:19 +11:00
Nicholas Nethercote cea683c08f Use `.into_diagnostic()` less.
This commit replaces this pattern:
```
err.into_diagnostic(dcx)
```
with this pattern:
```
dcx.create_err(err)
```
in a lot of places.

It's a little shorter, makes the error level explicit, avoids some
`IntoDiagnostic` imports, and is a necessary prerequisite for the next
commit which will add a `level` arg to `into_diagnostic`.

This requires adding `track_caller` on `create_err` to avoid mucking up
the output of `tests/ui/track-diagnostics/track4.rs`. It probably should
have been there already.
2023-12-18 20:46:13 +11:00
Nicholas Nethercote f6aa418c9f Rename many `DiagCtxt` and `EarlyDiagCtxt` locals. 2023-12-18 16:06:22 +11:00
Nicholas Nethercote f422dca3ae Rename many `DiagCtxt` arguments. 2023-12-18 16:06:22 +11:00
Nicholas Nethercote d1d0896c40 Rename `ParseSess::with_span_handler` as `ParseSess::with_dcx`. 2023-12-18 16:06:21 +11:00
Nicholas Nethercote 09af8a667c Rename `Session::span_diagnostic` as `Session::dcx`. 2023-12-18 16:06:21 +11:00
Nicholas Nethercote 9df1576e1d Rename `ParseSess::span_diagnostic` as `ParseSess::dcx`. 2023-12-18 16:06:21 +11:00
Nicholas Nethercote cde19c016e Rename `Handler` as `DiagCtxt`. 2023-12-18 16:06:19 +11:00
Matthias Krüger 93d3a4231e
Rollup merge of #118928 - EliseZeroTwo:EliseZeroTwo/fix-issue-118786, r=cjgillot
fix: Overlapping spans in delimited meta-vars

Closes #118786

Delimited meta-vars inside of MBE's spans were set to have the same opening and closing position resulting in an ICE when debug assertions were enabled and an error was present in the templated code.

This ensures that the spans do not overlap, whilst still having the spans point at the usage of the meta-var inside the macro definition.

It includes a regression test.

🖤
2023-12-17 21:29:59 +01:00
bors 5e7025419d Auto merge of #118830 - GuillaumeGomez:env-tracked_env, r=Nilstrieb
Add support for `--env` on `tracked_env::var`

Follow-up of https://github.com/rust-lang/rust/pull/118368.
Part of Part of https://github.com/rust-lang/rust/issues/80792.

It adds support of the `--env` option for proc-macros through `tracked_env::var`.

r? `@Nilstrieb`
2023-12-17 04:23:08 +00:00
Jubilee 9e872b7cd8
Rollup merge of #118933 - nnethercote:cleanup-errors-even-more, r=compiler-errors
Cleanup errors handlers even more

A sequel to #118587.

r? `@compiler-errors`
2023-12-14 16:07:48 -08:00
Nicholas Nethercote 9a78412511 Split `Handler::emit_diagnostic` in two.
Currently, `emit_diagnostic` takes `&mut self`.

This commit changes it so `emit_diagnostic` takes `self` and the new
`emit_diagnostic_without_consuming` function takes `&mut self`.

I find the distinction useful. The former case is much more common, and
avoids a bunch of `mut` and `&mut` occurrences. We can also restrict the
latter with `pub(crate)` which is nice.
2023-12-15 10:13:12 +11:00