Commit Graph

946 Commits

Author SHA1 Message Date
Eric Holk 27d6539a46
Plumb awaitness of for loops 2023-12-19 12:26:20 -08:00
Nicholas Nethercote e7724a2e31 Add `level` arg to `into_diagnostic`.
And make all hand-written `IntoDiagnostic` impls generic, by using
`DiagnosticBuilder::new(dcx, level, ...)` instead of e.g.
`dcx.struct_err(...)`.

This means the `create_*` functions are the source of the error level.
This change will let us remove `struct_diagnostic`.

Note: `#[rustc_lint_diagnostics]` is added to `DiagnosticBuilder::new`,
it's necessary to pass diagnostics tests now that it's used in
`into_diagnostic` functions.
2023-12-19 09:19:25 +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 f7125f1f66 Rename `CollectProcMacros::handler` as `CollectProcMacros::dcx`. 2023-12-18 16:06:22 +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
Nicholas Nethercote 7bdb227567 Avoid `struct_diagnostic` where possible.
It's necessary for `derive(Diagnostic)`, but is best avoided elsewhere
because there are clearer alternatives.

This required adding `Handler::struct_almost_fatal`.
2023-12-14 15:53:55 +11:00
bors a9cb8ee821 Auto merge of #114571 - nnethercote:improve-print_tts, r=petrochenkov
Improve `print_tts`

By slightly changing the meaning of `tokenstream::Spacing` we can greatly improve the output of `print_tts`.

r? `@ghost`
2023-12-11 00:03:56 +00:00
Nicholas Nethercote 925f7fad57 Improve `print_tts` by changing `tokenstream::Spacing`.
`tokenstream::Spacing` appears on all `TokenTree::Token` instances,
both punct and non-punct. Its current usage:
- `Joint` means "can join with the next token *and* that token is a
  punct".
- `Alone` means "cannot join with the next token *or* can join with the
  next token but that token is not a punct".

The fact that `Alone` is used for two different cases is awkward.
This commit augments `tokenstream::Spacing` with a new variant
`JointHidden`, resulting in:
- `Joint` means "can join with the next token *and* that token is a
  punct".
- `JointHidden` means "can join with the next token *and* that token is a
  not a punct".
- `Alone` means "cannot join with the next token".

This *drastically* improves the output of `print_tts`. For example,
this:
```
stringify!(let a: Vec<u32> = vec![];)
```
currently produces this string:
```
let a : Vec < u32 > = vec! [] ;
```
With this PR, it now produces this string:
```
let a: Vec<u32> = vec![] ;
```
(The space after the `]` is because `TokenTree::Delimited` currently
doesn't have spacing information. The subsequent commit fixes this.)

The new `print_tts` doesn't replicate original code perfectly. E.g.
multiple space characters will be condensed into a single space
character. But it's much improved.

`print_tts` still produces the old, uglier output for code produced by
proc macros. Because we have to translate the generated code from
`proc_macro::Spacing` to the more expressive `token::Spacing`, which
results in too much `proc_macro::Along` usage and no
`proc_macro::JointHidden` usage. So `space_between` still exists and
is used by `print_tts` in conjunction with the `Spacing` field.

This change will also help with the removal of `Token::Interpolated`.
Currently interpolated tokens are pretty-printed nicely via AST pretty
printing. `Token::Interpolated` removal will mean they get printed with
`print_tts`. Without this change, that would result in much uglier
output for code produced by decl macro expansions. With this change, AST
pretty printing and `print_tts` produce similar results.

The commit also tweaks the comments on `proc_macro::Spacing`. In
particular, it refers to "compound tokens" rather than "multi-char
operators" because lifetimes aren't operators.
2023-12-11 09:19:09 +11:00
bors d86d65bbc1 Auto merge of #118368 - GuillaumeGomez:env-flag, r=Nilstrieb
Implement `--env` compiler flag (without `tracked_env` support)

Part of https://github.com/rust-lang/rust/issues/80792.
Implementation of https://github.com/rust-lang/compiler-team/issues/653.
Not an implementation of https://github.com/rust-lang/rfcs/pull/2794.

It adds the `--env` compiler flag option which allows to set environment values used by `env!` and `option_env!`.

Important to note: When trying to retrieve an environment variable value, it will first look into the ones defined with `--env`, and if there isn't one, then only it will look into the environment variables. So if you use `--env PATH=a`, then `env!("PATH")` will return `"a"` and not the actual `PATH` value.

As mentioned in the title, `tracked_env` support is not added here. I'll do it in a follow-up PR.

r? rust-lang/compiler
2023-12-10 21:48:53 +00:00
Guillaume Gomez 486e55e547 Implement `--env` compiler flag 2023-12-10 14:25:57 +01:00
surechen 40ae34194c remove redundant imports
detects redundant imports that can be eliminated.

for #117772 :

In order to facilitate review and modification, split the checking code and
removing redundant imports code into two PR.
2023-12-10 10:56:22 +08:00
Michael Goulet 384a49edd0 Rename some more coro_kind -> coroutine_kind 2023-12-08 21:46:40 +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 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 1dd4db5062 Auto merge of #118655 - compiler-errors:rollup-vrngyzn, r=compiler-errors
Rollup of 9 pull requests

Successful merges:

 - #117793 (Update variable name to fix `unused_variables` warning)
 - #118123 (Add support for making lib features internal)
 - #118268 (Pretty print `Fn<(..., ...)>` trait refs with parentheses (almost) always)
 - #118346 (Add `deeply_normalize_for_diagnostics`, use it in coherence)
 - #118350 (Simplify Default for tuples)
 - #118450 (Use OnceCell in cell module documentation)
 - #118585 (Fix parser ICE when recovering `dyn`/`impl` after `for<...>`)
 - #118587 (Cleanup error handlers some more)
 - #118642 (bootstrap(builder.rs): Don't explicitly warn against `semicolon_in_expressions_from_macros`)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-12-06 04:20:51 +00:00
Eric Holk 50ef8006eb
Address code review feedback 2023-12-04 14:33:46 -08: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
Nicholas Nethercote b7e18cabd2 De-genericize some `IntoDiagnostic` impls.
These impls are all needed for just a single `IntoDiagnostic` type, not
a family of them.

Note that `ErrorGuaranteed` is the default type parameter for
`IntoDiagnostic`.
2023-12-04 18:57:42 +11: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 a179a53565 Use `Session::diagnostic` in more places. 2023-12-02 09:01:35 +11:00
bors 63d16b5a98 Auto merge of #117472 - jmillikin:stable-c-str-literals, r=Nilstrieb
Stabilize C string literals

RFC: https://rust-lang.github.io/rfcs/3348-c-str-literal.html

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

Documentation PR (reference manual): https://github.com/rust-lang/reference/pull/1423

# Stabilization report

Stabilizes C string and raw C string literals (`c"..."` and `cr#"..."#`), which are expressions of type [`&CStr`](https://doc.rust-lang.org/stable/core/ffi/struct.CStr.html). Both new literals require Rust edition 2021 or later.

```rust
const HELLO: &core::ffi::CStr = c"Hello, world!";
```

C strings may contain any byte other than `NUL` (`b'\x00'`), and their in-memory representation is guaranteed to end with `NUL`.

## Implementation

Originally implemented by PR https://github.com/rust-lang/rust/pull/108801, which was reverted due to unintentional changes to lexer behavior in Rust editions < 2021.

The current implementation landed in PR https://github.com/rust-lang/rust/pull/113476, which restricts C string literals to Rust edition >= 2021.

## Resolutions to open questions from the RFC

* Adding C character literals (`c'.'`) of type `c_char` is not part of this feature.
  * Support for `c"..."` literals does not prevent `c'.'` literals from being added in the future.
* C string literals should not be blocked on making `&CStr` a thin pointer.
  * It's possible to declare constant expressions of type `&'static CStr` in stable Rust (as of v1.59), so C string literals are not adding additional coupling on the internal representation of `CStr`.
* The unstable `concat_bytes!` macro should not accept `c"..."` literals.
  * C strings have two equally valid `&[u8]` representations (with or without terminal `NUL`), so allowing them to be used in `concat_bytes!` would be ambiguous.
* Adding a type to represent C strings containing valid UTF-8 is not part of this feature.
  * Support for a hypothetical `&Utf8CStr` may be explored in the future, should such a type be added to Rust.
2023-12-01 13:33:55 +00:00
klensy de13a3871d unwrap return Option value, as it always returns Some for some fns 2023-11-28 14:52:21 +03: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
Matthias Krüger 82538b72c0
Rollup merge of #118131 - lukas-code:multi-default, r=wesleywiser
improve tool-only help for multiple `#[default]` variants

When defining an enum with multiple `#[default]` variants, we emit a tool-only suggestion for every `#[default]`ed variant to remove all other `#[default]`s. This PR improves the suggestion to correctly handle the cases where one variant has multiple `#[default]`s and where different `#[default]`s have the same span due to macro expansions.

fixes https://github.com/rust-lang/rust/issues/118119
2023-11-23 07:06:30 +01: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
Lukas Markeffsky f697a00f76 improve help for multiple `#[default]` variants 2023-11-21 12:20:54 +00:00
Mark Rousskov 917f6540ed Re-format code with new rustfmt 2023-11-15 21:45:48 -05:00
Mark Rousskov db3e2bacb6 Bump cfg(bootstrap)s 2023-11-15 19:41:28 -05:00
Ben Kimock d32d9238cf Emit #[inline] on derive(Debug) 2023-11-09 10:40:55 -05:00
Thom Chiovoloni 86fca873ba
Use the correct span when emitting the `env!` result 2023-11-04 14:04:01 -07:00
Nicholas Nethercote f405ce86c2 Minimize `pub` usage in `source_map.rs`.
Most notably, this commit changes the `pub use crate::*;` in that file
to `use crate::*;`. This requires a lot of `use` items in other crates
to be adjusted, because everything defined within `rustc_span::*` was
also available via `rustc_span::source_map::*`, which is bizarre.

The commit also removes `SourceMap::span_to_relative_line_string`, which
is unused.
2023-11-02 19:35:00 +11:00
John Millikin 0f41bc21b9 Stabilize C string literals 2023-11-01 09:16:34 +09: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
Oli Scherer 621494382d Add gen blocks to ast and do some broken ast lowering 2023-10-27 13:05:48 +00:00
bors c716f180e8 Auto merge of #116236 - dtolnay:builtinmacrocomment, r=cjgillot
Modernize rustc_builtin_macros generics helpers

- Rustfmt-compatible formatting for the code snippets in comments
- Eliminate an _"Extra scope required"_ obsoleted by NLL
2023-10-25 06:57:37 +00:00
bors 111adde7ed Auto merge of #115324 - francorbacho:master, r=davidtwco
Suggest removing redundant arguments in format!()

Closes #105225. This is also a follow-up to #105635, which seems to have become stale.

r? `@estebank`
2023-10-23 00:51:35 +00:00
David Tolnay 45363f11ef
Directly collect into ty_param_names instead of peeking to see if empty 2023-10-22 12:13:12 -07:00
David Tolnay bd2b53ba6d
Eliminate an "Extra scope required" obsoleted by NLL 2023-10-22 12:05:45 -07:00
David Tolnay d03b3db95b
Rustfmt-compatible formatting for code snippets in rustc_builtin_macros 2023-10-22 12:04:50 -07:00
Oli Scherer e96ce20b34 s/generator/coroutine/ 2023-10-20 21:14:01 +00:00
Urgau eccc9e6628 [RFC 3127 - Trim Paths]: Condition remapped filepath on remap scopes 2023-10-17 10:11:30 +02:00
Michael Howell 2ff2624722 docs: add Rust logo to more compiler crates
c6e6ecb1af added it to some of the
compiler's crates, but avoided adding it to all of them to reduce
bit-rot. This commit adds to more.
2023-10-16 15:38:08 -07:00
bors a48396984a Auto merge of #116688 - compiler-errors:rustfmt-up, r=WaffleLapkin,Nilstrieb
Format all the let-chains in compiler crates

Since rust-lang/rustfmt#5910 has landed, soon we will have support for formatting let-chains (as soon as rustfmt syncs and beta gets bumped).

This PR applies the changes [from master rustfmt to rust-lang/rust eagerly](https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/out.20formatting.20of.20prs/near/374997516), so that the next beta bump does not have to deal with a 200+ file diff and can remain concerned with other things like `cfg(bootstrap)` -- #113637 was a pain to land, for example, because of let-else.

I will also add this commit to the ignore list after it has landed.

The commands that were run -- I'm not great at bash-foo, but this applies rustfmt to every compiler crate, and then reverts the two crates that should probably be formatted out-of-tree.
```
~/rustfmt $ ls -1d ~/rust/compiler/* | xargs -I@ cargo run --bin rustfmt -- `@/src/lib.rs` --config-path ~/rust --edition=2021 # format all of the compiler crates
~/rust $ git checkout HEAD -- compiler/rustc_codegen_{gcc,cranelift} # revert changes to cg-gcc and cg-clif
```

cc `@rust-lang/rustfmt`
r? `@WaffleLapkin` or `@Nilstrieb` who said they may be able to review this purely mechanical PR :>

cc `@Mark-Simulacrum` and `@petrochenkov,` who had some thoughts on the order of operations with big formatting changes in https://github.com/rust-lang/rust/pull/95262#issue-1178993801. I think the situation has changed since then, given that let-chains support exists on master rustfmt now, and I'm fairly confident that this formatting PR should land even if *bootstrap* rustfmt doesn't yet format let-chains in order to lessen the burden of the next beta bump.
2023-10-15 13:23:55 +00:00
Matthias Krüger 6fef4f089f
Rollup merge of #116696 - c410-f3r:in-doc, r=petrochenkov
Misc improvements

cc https://github.com/rust-lang/rust/pull/116323#discussion_r1355282195

r? `@petrochenkov`
2023-10-14 13:36:28 +02:00
Caio 6b59f6fbea Misc improvements 2023-10-13 10:22:33 -03:00
Michael Goulet b2d2184ede Format all the let chains in compiler 2023-10-13 08:59:36 +00:00
Nicholas Nethercote 7528fdc4c4 Don't `escape_debug` the condition of `assert!`.
The assertion in `assert-long-condition.rs` used to be fail like this, all on
one line:
```
thread 'main' panicked at 'assertion failed: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18\n                                + 19 + 20 + 21 + 22 + 23 + 24 + 25 == 0', tests/ui/macros/assert-long-condition.rs:7:5
```
The `\n` and subsequent indent is because the condition is pretty-printed, and
the pretty-printer inserts a newline. Printing the newline in this way is
arguably reasonable given that the message appears within single quotes, which
is very similar to a string literal.

However, after the assertion printing improvements that were released in 1.73,
the assertion now fails like this:
```
thread 'main' panicked at tests/ui/macros/assert-long-condition.rs:7:5:
assertion failed: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18\n                                + 19 + 20 + 21 + 22 + 23 + 24 + 25 == 0
```
Now that there are no single quotes around the pretty-printed condition, the
`\n` is quite strange.

This commit gets rid of the `\n`, by removing the `escape_debug` done on the
pretty-printed message. This results in the following:
```
thread 'main' panicked at tests/ui/macros/assert-long-condition.rs:7:5:
assertion failed: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18
                                + 19 + 20 + 21 + 22 + 23 + 24 + 25 == 0
```
The overly-large indent is still strange, but that's a separate pretty-printing issue.

This change helps with #108341.
2023-10-10 09:08:11 +11:00
francorbacho cbc6b65d9a Keep fluent slugs in alphabetical order 2023-10-05 16:17:32 +02:00
francorbacho c8ee7db6ea Only give autofix suggestion when no named args are present 2023-10-05 16:11:31 +02:00
francorbacho 905bace904 Highlight redundant arguments instead of the whole format string 2023-10-05 16:11:31 +02:00
francorbacho fcdd5c0b2d Plurals in format redundant arguments suggestion 2023-10-05 16:11:31 +02:00
francorbacho 4a7a98cf30 Fix diagnostics being cancelled even with unused arguments 2023-10-05 16:09:57 +02:00
francorbacho dc75c99226 Remove unused variable 2023-10-05 16:09:57 +02:00
francorbacho e1c18f4d9d Document report_redundant_format_arguments() 2023-10-05 16:09:57 +02:00
francorbacho 9c921f843c Rename report_redundant_placeholders() to report_redundant_format_arguments() 2023-10-05 16:09:57 +02:00
francorbacho 04fc051a34 Use diagnostic impls and add suggestions in redundant format!() args 2023-10-05 16:09:57 +02:00
francorbacho 4cc2d0bd65 Separate report_redundant_placeholders() into its own function 2023-10-05 16:05:42 +02:00
francorbacho 93df9e6d7d Suggest removing redundant arguments in format!() 2023-10-05 16:05:42 +02:00
Nicholas Nethercote 7326cd98b9 Factor out the two `entry_point_type` functions.
They are very similar, and each one has a comment about the importance
of being kept in sync with the other. This commit removes the
duplication.
2023-10-01 20:45:09 +11:00
Nicholas Nethercote 373cc2160a Change `depth` arg to `at_root`.
This will facilitate a subsequent refactoring.
2023-09-29 17:49:16 +10:00
Ralf Jung ad509633a2 ConstParamTy: require Eq 2023-09-24 23:38:07 +02:00
Matthias Krüger 864f7aafe4
Rollup merge of #115891 - RalfJung:structural-trait-derive, r=nnethercote
simplify inject_impl_of_structural_trait

There's a comment at `inject_impl_of_structural_trait` saying we cannot use `TraitDef`, but that comment is outdated -- we *can* use `TraitDef` nowadays since it has the `skip_path_as_bound` flag. (The flag needed some fixing, though.)
2023-09-18 18:27:20 +02:00
Ralf Jung 0522bde4bc simplify inject_impl_of_structural_trait 2023-09-18 07:45:46 +02:00
Dylan DPC 0900712fe0
Rollup merge of #115611 - lukas-code:format!("{r#ident}"), r=compiler-errors
add diagnostic for raw identifiers in format string

Format strings don't support raw identifiers (e.g. `format!("{r#type}")`), but they do support keywords in the format string directly (e.g. `format!("{type}")`). This PR improves the error output when attempting to use a raw identifier in a format string and adds a machine-applicable suggestion to remove the `r#`.

fixes https://github.com/rust-lang/rust/issues/115466
2023-09-17 11:23:25 +00:00
Guillaume Gomez e39c39346b Fix invalid markdown codeblock label 2023-09-16 11:37:41 +02:00
bors dac91a82e1 Auto merge of #115677 - matthewjasper:let-expr-recovery, r=b-naber
Improve invalid let expression handling

- Move all of the checks for valid let expression positions to parsing.
- Add a field to ExprKind::Let in AST/HIR to mark whether it's in a valid location.
- Suppress some later errors and MIR construction for invalid let expressions.
- Fix a (drop) scope issue that was also responsible for #104172.

Fixes #104172
Fixes #104868
2023-09-14 19:56:55 +00:00
Matthew Jasper 333388fd3c Move let expression checking to parsing
There was an incomplete version of the check in parsing and a second
version in AST validation. This meant that some, but not all, invalid
uses were allowed inside macros/disabled cfgs. It also means that later
passes have a hard time knowing when the let expression is in a valid
location, sometimes causing ICEs.

- Add a field to ExprKind::Let in AST/HIR to mark whether it's in a
  valid location.
- Suppress later errors and MIR construction for invalid let
  expressions.
2023-09-11 15:51:18 +00:00
Andy Caldwell 679267f2ac
Rename the feature, but not the attribute, to `coverage_attribute` 2023-09-08 12:46:09 +01:00
Andy Caldwell 8e03371fc3
Rework no_coverage to coverage(off) 2023-09-08 12:46:06 +01:00
Lukas Markeffsky d990eee0c8 add diagnostic for raw identifiers in format string 2023-09-06 18:55:45 +02:00
Ben Kimock f26293dca4 Load include_bytes! directly into an Lrc 2023-08-27 20:16:19 -04:00
Vadim Petrochenkov 7353c96be8 rustc: Move `features` from `Session` to `GlobalCtxt`
Removes two pieces of mutable state.
Follow up to #114622.
2023-08-11 16:51:50 +08:00
bors e286f25ec0 Auto merge of #114507 - sebastiantoh:issue-114235, r=jackh726
Add suggestion to quote inlined format argument as string literal

Fixes #114235
2023-08-11 01:41:30 +00:00
David Tolnay 704aa56ba0
Generate better function argument names in global_allocator expansion 2023-08-06 07:36:05 -07:00
David Tolnay e57a89174c
Delete some useless casts from global_allocator expansion 2023-08-05 23:10:38 -07:00
Sebastian Toh d003fd9859 Add suggestion to quote inlined format argument as string literal 2023-08-05 17:29:06 +08:00
Matthias Krüger 99e4127d85
Rollup merge of #114434 - Nilstrieb:indexing-spans, r=est31
Improve spans for indexing expressions

fixes #114388

Indexing is similar to method calls in having an arbitrary left-hand-side and then something on the right, which is the main part of the expression. Method calls already have a span for that right part, but indexing does not. This means that long method chains that use indexing have really bad spans, especially when the indexing panics and that span in coverted into a panic location.

This does the same thing as method calls for the AST and HIR, storing an extra span which is then put into the `fn_span` field in THIR.

r? compiler-errors
2023-08-04 21:31:57 +02:00
bors ec5b882c2f Auto merge of #114414 - cjgillot:early-unnameable-test, r=petrochenkov
Make test harness lint about unnnameable tests.

Implementation of https://github.com/rust-lang/rust/pull/113734#discussion_r1283073418

About the options suggested in https://github.com/rust-lang/rust/issues/36629#issuecomment-404753945: adding this case to unused_attribute was just more complicated. I'll try to understand a bit more what you had in mind in https://github.com/rust-lang/rfcs/pull/2471#issuecomment-397241123

This was just simpler to do in a standalone PR. I'll remove the corresponding changes from https://github.com/rust-lang/rust/pull/113734 later.

r? `@petrochenkov`
2023-08-04 14:13:11 +00:00
Nilstrieb 5706be1854 Improve spans for indexing expressions
Indexing is similar to method calls in having an arbitrary
left-hand-side and then something on the right, which is the main part
of the expression. Method calls already have a span for that right part,
but indexing does not. This means that long method chains that use
indexing have really bad spans, especially when the indexing panics and
that span in coverted into a panic location.

This does the same thing as method calls for the AST and HIR, storing an
extra span which is then put into the `fn_span` field in THIR.
2023-08-04 13:17:39 +02:00
Camille GILLOT 2a0a1f918d Make test harness lint about unnnameable tests. 2023-08-03 13:07:30 +00:00
Nicholas Nethercote d75ee2a6bc Remove `MacDelimiter`.
It's the same as `Delimiter`, minus the `Invisible` variant. I'm
generally in favour of using types to make impossible states
unrepresentable, but this one feels very low-value, and the conversions
between the two types are annoying and confusing.

Look at the change in `src/tools/rustfmt/src/expr.rs` for an example:
the old code converted from `MacDelimiter` to `Delimiter` and back
again, for no good reason. This suggests the author was confused about
the types.
2023-08-03 09:03:30 +10:00
Matthias Krüger 23815467a2 inline format!() args up to and including rustc_middle 2023-07-30 13:18:33 +02:00
León Orell Valerian Liehr afd009a8d8
Parse generic const items 2023-07-28 22:21:33 +02:00
David Wood 75df62d4a2
builtin_macros: raw str in diagnostic output
If a raw string was used in the `env!` invocation, then it should also
be shown in the diagnostic messages as a raw string.

Signed-off-by: David Wood <david@davidtw.co>
2023-07-25 11:12:52 +01:00
David Wood c06a7eb2a6
builtin_macros: expect raw strings too
`expr_to_string` allows raw strings through so this code should be
expected to handle those.

Signed-off-by: David Wood <david@davidtw.co>
2023-07-24 15:06:50 +01:00
Matthias Krüger adf759bf6a fix couple of clippy findings:
filter_map_identity
iter_kv_map
needless_question_mark
redundant_at_rest_pattern
filter_next
derivable_impls
2023-07-23 10:50:14 +02:00
David Tolnay 56633b3f51
Add a comparison between match *self and intrinsics::unreachable() 2023-07-16 15:33:29 -07:00
David Tolnay f441adc89a
Generate safe stable code for derives on empty enums
Generate `match *self {}` instead of `unsafe { core::intrinsics::unreachable() }`.

This is:

    1. safe
    2. stable

for the benefit of everyone looking at these derived impls through `cargo expand`.

Both expansions compile to the same code at all optimization levels (including `0`).
2023-07-16 15:02:08 -07:00
bors 4a07b2baf5 Auto merge of #113557 - Amanieu:no-builtins-prelude, r=petrochenkov
Hide `compiler_builtins` in the prelude

This crate is a private implementation detail. We only need to insert it into the crate graph for linking and should not expose any of its public API.

Fixes #113533
2023-07-16 13:19:14 +00:00
Amanieu d'Antras 07f855d781 Hide `compiler_builtins` in the prelude
This crate is a private implementation detail. We only need to insert it
into the crate graph for linking and should not expose any of its public
API.

Fixes #113533
2023-07-14 16:53:36 +01:00
Mark Rousskov cc907f80b9 Re-format let-else per rustfmt update 2023-07-12 21:49:27 -04:00
He1pa 453603a4b5 fix typo 2023-06-28 10:52:48 +08:00
He1pa 8af8a95a64 Migrate some rustc_builtin_macros to SessionDiagnostic 2023-06-25 01:32:30 +08:00
bors ed1ce580ec Auto merge of #112802 - lukas-code:fancy-bool, r=Nilstrieb
use ErrorGuaranteed instead of booleans in rustc_builtin_macros

implements https://github.com/rust-lang/rust/pull/112366#discussion_r1233821873

No functional changes.

Best reviewed with whitespace diff disabled.

r? `@Nilstrieb`
2023-06-24 11:43:41 +00:00
Nilstrieb c6710d15f1
Rollup merge of #112790 - WaffleLapkin:syntactically, r=Nilstrieb
Syntactically accept `become` expressions (explicit tail calls experiment)

This adds `ast::ExprKind::Become`, implements parsing and properly gates the feature.

cc `@scottmcm`
2023-06-21 07:37:02 +02:00
Lukas Markeffsky d50875e24a use `ErrorGuaranteed` instead of booleans 2023-06-19 21:34:59 +02:00
bors 689511047a Auto merge of #112366 - lukas-code:test, r=Nilstrieb
`#[test]` function signature verification improvements

This PR contains two improvements to the expansion of the `#[test]` macro.

The first one fixes https://github.com/rust-lang/rust/issues/112360 by correctly recovering item statements if the signature verification fails.

The second one forbids non-lifetime generics on `#[test]` functions. These were previously allowed if the function returned `()`, but always caused an inference error:

before:
```text
error[E0282]: type annotations needed
 --> src/lib.rs:2:1
  |
1 | #[test]
  | ------- in this procedural macro expansion
2 | fn foo<T>() {}
  | ^^^^^^^^^^^^^^ cannot infer type
```

after:
```text
error: functions used as tests can not have any non-lifetime generic parameters
 --> src/lib.rs:2:1
  |
2 | fn foo<T>() {}
  | ^^^^^^^^^^^^^^
```

Also includes some basic tests for test function signature verification, because I couldn't find any (???) in the test suite.
2023-06-19 13:39:46 +00:00
Maybe Waffle d7713feb99 Syntatically accept `become` expressions 2023-06-19 12:54:34 +00:00
asquared31415 3dc793e625 fix ICE on specific malformed asm clobber_abi 2023-06-16 19:51:01 -04:00
clubby789 053e6b80c7 Remove accidental comment 2023-06-07 17:16:34 +00:00
Lukas Markeffsky 774f7825cb Deny non-lifetime generics for test functions.
Previously, these were allowed if the function returned `()`, but always led to an ambiguity error.
2023-06-07 00:04:04 +02:00
Lukas Markeffsky 4bf00613ee Fix ICE for nested test function with arguments. 2023-06-06 23:28:15 +02:00
bors 70e04bd88d Auto merge of #111748 - nnethercote:Cow-DiagnosticMessage, r=WaffleLapkin
Use `Cow` in `{D,Subd}iagnosticMessage`.

Each of `{D,Subd}iagnosticMessage::{Str,Eager}` has a comment:
```
// FIXME(davidtwco): can a `Cow<'static, str>` be used here?
```
This commit answers that question in the affirmative. It's not the most compelling change ever, but it might be worth merging.

This requires changing the `impl<'a> From<&'a str>` impls to `impl From<&'static str>`, which involves a bunch of knock-on changes that require/result in call sites being a little more precise about exactly what kind of string they use to create errors, and not just `&str`. This will result in fewer unnecessary allocations, though this will not have any notable perf effects given that these are error paths.

Note that I was lazy within Clippy, using `to_string` in a few places to preserve the existing string imprecision. I could have used `impl Into<{D,Subd}iagnosticMessage>` in various places as is done in the compiler, but that would have required changes to *many* call sites (mostly changing `&format("...")` to `format!("...")`) which didn't seem worthwhile.

r? `@WaffleLapkin`
2023-05-29 07:10:44 +00:00
bors f8447b9638 Auto merge of #111963 - nnethercote:inline-derived-hash, r=lqd
Inline derived `hash`

Because most of the other derived functions are inlined: `clone`, `default`, `eq`, `partial_cmp`, `cmp`. The exception is `fmt`, but it tends to not be on hot paths as much.

r? `@ghost`
2023-05-29 00:25:54 +00:00
Nicholas Nethercote 781111ef35 Use `Cow` in `{D,Subd}iagnosticMessage`.
Each of `{D,Subd}iagnosticMessage::{Str,Eager}` has a comment:
```
// FIXME(davidtwco): can a `Cow<'static, str>` be used here?
```
This commit answers that question in the affirmative. It's not the most
compelling change ever, but it might be worth merging.

This requires changing the `impl<'a> From<&'a str>` impls to `impl
From<&'static str>`, which involves a bunch of knock-on changes that
require/result in call sites being a little more precise about exactly
what kind of string they use to create errors, and not just `&str`. This
will result in fewer unnecessary allocations, though this will not have
any notable perf effects given that these are error paths.

Note that I was lazy within Clippy, using `to_string` in a few places to
preserve the existing string imprecision. I could have used `impl
Into<{D,Subd}iagnosticMessage>` in various places as is done in the
compiler, but that would have required changes to *many* call sites
(mostly changing `&format("...")` to `format!("...")`) which didn't seem
worthwhile.
2023-05-29 09:23:43 +10:00
bors a525c7ddba Auto merge of #111928 - c410-f3r:dqewdas, r=eholk
[RFC-2011] Expand more expressions

cc #44838

Expands `if`, `let`, `match` and also makes `generic_assert_internals` an allowed feature when using `assert!`. `#![feature(generic_assert)]` is still needed to activate everything.

```rust
#![feature(generic_assert)]

fn fun(a: Option<i32>, b: Option<i32>, c: Option<i32>) {
  assert!(
    if a.is_some() { 1 } else { 2 } == 3
      && if let Some(elem) = b { elem == 4 } else { false }
      && match c { Some(_) => true, None => false }
  );
}

fn main() {
  fun(Some(1), None, Some(2));
}

// Assertion failed: assert!(
//   if a.is_some() { 1 } else { 2 } == 3
//     && if let Some(elem) = b { elem == 4 } else { false }
//     && match c { Some(_) => true, None => false }
// );
//
// With captures:
//   a = Some(1)
//   b = None
//   c = Some(2)
```
2023-05-27 07:02:48 +00:00
clubby789 f97fddab91 Ensure Fluent messages are in alphabetical order 2023-05-25 23:49:35 +00:00
Nicholas Nethercote ee013d83c3 Avoid some unnecessary local `attr` variables. 2023-05-26 07:00:26 +10:00
Nicholas Nethercote 5b0324fce0 Inline derived `hash` function.
Because most of the other derived functions are inlined: `clone`,
`default`, `eq`, `partial_cmp`, `cmp`. The exception is `fmt`, but it
tends to not be on hot paths as much.
2023-05-26 06:55:06 +10:00
bors a2b1646c59 Auto merge of #86844 - bjorn3:global_alloc_improvements, r=pnkfelix
Support #[global_allocator] without the allocator shim

This makes it possible to use liballoc/libstd in combination with `--emit obj` if you use `#[global_allocator]`. This is what rust-for-linux uses right now and systemd may use in the future. Currently they have to depend on the exact implementation of the allocator shim to create one themself as `--emit obj` doesn't create an allocator shim.

Note that currently the allocator shim also defines the oom error handler, which is normally required too. Once `#![feature(default_alloc_error_handler)]` becomes the only option, this can be avoided. In addition when using only fallible allocator methods and either `--cfg no_global_oom_handling` for liballoc (like rust-for-linux) or `--gc-sections` no references to the oom error handler will exist.

To avoid this feature being insta-stable, you will have to define `__rust_no_alloc_shim_is_unstable` to avoid linker errors.

(Labeling this with both T-compiler and T-lang as it originally involved both an implementation detail and had an insta-stable user facing change. As noted above, the `__rust_no_alloc_shim_is_unstable` symbol requirement should prevent unintended dependence on this unstable feature.)
2023-05-25 16:59:57 +00:00
Caio 462a96c9e9 [RFC-2011] Expand more expressions 2023-05-24 21:15:50 -03:00
Maybe Waffle fb0f74a8c9 Use `Option::is_some_and` and `Result::is_ok_and` in the compiler 2023-05-24 14:20:41 +00:00
Dylan DPC ee26abdafb
Rollup merge of #111054 - cjgillot:cfg-eval-recover, r=b-naber
Do not recover when parsing stmt in cfg-eval.

`parse_stmt` does recovery on its own. When parsing the statement fails, we always get `Ok(None)` instead of an `Err` variant with the diagnostic that we can emit.

To avoid this behaviour, we need to opt-out of recovery for cfg_eval.

Fixes https://github.com/rust-lang/rust/issues/105228
2023-05-18 17:37:08 +05:30
Dylan DPC 08efb9d652
Rollup merge of #111633 - nnethercote:avoid-ref-format, r=WaffleLapkin
Avoid `&format("...")` calls in error message code.

Some error message cleanups. Best reviewed one commit at a time.

r? `@davidtwco`
2023-05-18 10:52:35 +05:30
Dylan DPC bc3b94a486
Rollup merge of #111649 - Nilstrieb:derive-const-param-ty, r=BoxyUwU
Add derive for `core::marker::ConstParamTy`

This makes it easier to implement it for a type, just like `Copy`.

`@BoxyUwU` half asked me to add it
2023-05-17 11:13:57 +05:30
Nilstrieb 0336dd132b Add derive for `core::marker::ConstParamTy`
This makes it easier to implement it for a type, just like `Copy`.
2023-05-16 20:09:25 +02:00
Nicholas Nethercote 01e33a3600 Avoid `&format("...")` calls in error message code.
Error message all end up passing into a function as an `impl
Into<{D,Subd}iagnosticMessage>`. If an error message is creatd as
`&format("...")` that means we allocate a string (in the `format!`
call), then take a reference, and then clone (allocating again) the
reference to produce the `{D,Subd}iagnosticMessage`, which is silly.

This commit removes the leading `&` from a lot of these cases. This
means the original `String` is moved into the
`{D,Subd}iagnosticMessage`, avoiding the double allocations. This
requires changing some function argument types from `&str` to `String`
(when all arguments are `String`) or `impl
Into<{D,Subd}iagnosticMessage>` (when some arguments are `String` and
some are `&str`).
2023-05-16 17:59:56 +10:00
Matthias Krüger 0b8f2bfe5f
Rollup merge of #111463 - clubby789:env-escaped-var, r=cjgillot
Better diagnostics for `env!` where variable contains escape

Fixes #110559
2023-05-14 08:21:39 +02:00
bors 077fc26f0a Auto merge of #109732 - Urgau:uplift_drop_forget_ref_lints, r=davidtwco
Uplift `clippy::{drop,forget}_{ref,copy}` lints

This PR aims at uplifting the `clippy::drop_ref`, `clippy::drop_copy`, `clippy::forget_ref` and `clippy::forget_copy` lints.

Those lints are/were declared in the correctness category of clippy because they lint on useless and most probably is not what the developer wanted.

## `drop_ref` and `forget_ref`

The `drop_ref` and `forget_ref` lint checks for calls to `std::mem::drop` or `std::mem::forget` with a reference instead of an owned value.

### Example

```rust
let mut lock_guard = mutex.lock();
std::mem::drop(&lock_guard) // Should have been drop(lock_guard), mutex
// still locked
operation_that_requires_mutex_to_be_unlocked();
```

### Explanation

Calling `drop` or `forget` on a reference will only drop the reference itself, which is a no-op. It will not call the `drop` or `forget` method on the underlying referenced value, which is likely what was intended.

## `drop_copy` and `forget_copy`

The `drop_copy` and `forget_copy` lint checks for calls to `std::mem::forget` or `std::mem::drop` with a value that derives the Copy trait.

### Example

```rust
let x: i32 = 42; // i32 implements Copy
std::mem::forget(x) // A copy of x is passed to the function, leaving the
                    // original unaffected
```

### Explanation

Calling `std::mem::forget` [does nothing for types that implement Copy](https://doc.rust-lang.org/std/mem/fn.drop.html) since the value will be copied and moved into the function on invocation.

-----

Followed the instructions for uplift a clippy describe here: https://github.com/rust-lang/rust/pull/99696#pullrequestreview-1134072751

cc `@m-ou-se` (as T-libs-api leader because the uplifting was discussed in a recent meeting)
2023-05-12 12:04:32 +00:00
Caleb Cartwright 05c5df5682 refactor: use by-ref TokenTree iterator to avoid a few clones 2023-05-11 21:59:38 -05:00
clubby789 2555f3bbcf Better diagnostics for `env!` where variable contains escape 2023-05-11 21:41:07 +01:00
bjorn3 6ba7c5db07 Split AllocatorKind::fn_name in global_fn_name and default_fn_name 2023-05-11 14:35:08 +00:00
bjorn3 79fa6ce7a1 Inline AllocFnFactory kind field 2023-05-11 14:23:31 +00:00
Urgau 7dab6094bb Remove useless drop of copy type 2023-05-10 19:36:01 +02:00
Dylan DPC dbd090c655
Rollup merge of #110694 - est31:builtin, r=petrochenkov
Implement builtin # syntax and use it for offset_of!(...)

Add `builtin #` syntax to the parser, as well as a generic infrastructure to support both item and expression position builtin syntaxes. The PR also uses this infrastructure for the implementation of the `offset_of!` macro, added by #106934.

cc `@petrochenkov` `@DrMeepster`

cc #110680 `builtin #` tracking issue
cc #106655 `offset_of!` tracking issue
2023-05-09 12:33:45 +05:30
bors ea0c22ea4f Auto merge of #106621 - ozkanonur:enable-elided-lifetimes-for-doctests, r=Mark-Simulacrum
enable `rust_2018_idioms` lint group for doctests

With this change, `rust_2018_idioms` lint group will be enabled for compiler/libstd doctests.

Resolves #106086
Resolves #99144

Signed-off-by: ozkanonur <work@onurozkan.dev>
2023-05-08 04:50:28 +00:00
ozkanonur 4e7c14fe9f enable `rust_2018_idioms` for doctests
Signed-off-by: ozkanonur <work@onurozkan.dev>
2023-05-07 00:12:29 +03:00
est31 5eb29c7f49 Migrate offset_of from a macro to builtin # syntax 2023-05-05 21:44:13 +02:00
Dylan DPC 4891f02cff
Rollup merge of #108801 - fee1-dead-contrib:c-str, r=compiler-errors
Implement RFC 3348, `c"foo"` literals

RFC: https://github.com/rust-lang/rfcs/pull/3348
Tracking issue: #105723
2023-05-05 18:40:33 +05:30
Matthias Krüger 6387eda3ba
Rollup merge of #111027 - clubby789:query-instability-builtin-macros, r=petrochenkov
Remove `allow(rustc::potential_query_instability)` for `builtin_macros`

cc #84447
2023-05-04 08:09:05 +02:00
Nicholas Nethercote 6b62f37402 Restrict `From<S>` for `{D,Subd}iagnosticMessage`.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.

This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.

As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-05-03 08:44:39 +10:00
clubby789 e3e93f2867 Use `GrowableBitSet` to store positional indexes in `asm!` 2023-05-02 16:42:36 +01:00
clubby789 1590350836 Remove `allow(rustc::potential_query_instability)` for `builtin_macros` 2023-05-02 16:33:00 +01:00
Deadbeef a49570fd20 fix TODO comments 2023-05-02 10:32:07 +00:00
Deadbeef 8ff3903643 initial step towards implementing C string literals 2023-05-02 10:30:09 +00:00
bors 98c33e47a4 Auto merge of #109128 - chenyukang:yukang/remove-type-ascription, r=estebank
Remove type ascription from parser and diagnostics

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

Part of #101728

r? `@estebank`
2023-05-02 09:41:35 +00:00
Matthias Krüger 0a2562bf4d
Rollup merge of #111042 - Zalathar:no-coverage, r=wesleywiser
Add `#[no_coverage]` to the test harness's `fn main`

There are two main motivations for adding `#[no_coverage]` to the test harness's entry point:

- The entry point is trivial compiler-generated code that doesn't correspond to user source, and it always runs, so there's no value in instrumenting it for coverage.
- Because it has dummy spans, it causes the instrumentor implementation to emit invalid coverage mappings that confuse `llvm-cov` and result in strange coverage reports.

Fixes #110749.
2023-05-01 17:10:24 +02:00
Camille GILLOT d56ce8e199 Do not recover when parsing stmt in cfg-eval. 2023-05-01 08:51:47 +00:00
yukang 5d1796a608 soften the wording for removing type ascription 2023-05-01 16:37:00 +08:00
Nilstrieb c63b6a437e Rip it out
My type ascription
Oh rip it out
Ah
If you think we live too much then
You can sacrifice diagnostics
Don't mix your garbage
Into my syntax
So many weird hacks keep diagnostics alive
Yet I don't even step outside
So many bad diagnostics keep tyasc alive
Yet tyasc doesn't even bother to survive!
2023-05-01 16:15:13 +08:00
Zalathar 77af67ab64 Add `#[no_coverage]` to the test harness's `fn main` 2023-05-01 11:01:12 +10:00
Matthias Krüger 124aad337f
Rollup merge of #111032 - clubby789:migrate-asm-diagnostics, r=compiler-errors
Migrate `builtin_macros::asm` diagnostics to translatable diagnostics

cc #100717

Planning on working through the remaining diagnostics in this crate
2023-05-01 01:09:49 +02:00
clubby789 3738a18df7 Migrate `builtin_macros::asm` diagnostics to translatable diagnostics 2023-04-30 21:45:46 +01:00
Michael Goulet f0fc4f9acf Tweak await span 2023-04-27 17:18:11 +00:00
clubby789 0138513635 Fix static string lints 2023-04-25 18:59:55 +01:00
Matthias Krüger f54dbe6e31 Revert "Remove #[alloc_error_handler] from the compiler and library"
This reverts commit abc0660118.
2023-04-25 00:08:35 +02:00
bors 39cf520299 Auto merge of #109507 - Amanieu:panic-oom-payload, r=davidtwco
Report allocation errors as panics

OOM is now reported as a panic but with a custom payload type (`AllocErrorPanicPayload`) which holds the layout that was passed to `handle_alloc_error`.

This should be review one commit at a time:
- The first commit adds `AllocErrorPanicPayload` and changes allocation errors to always be reported as panics.
- The second commit removes `#[alloc_error_handler]` and the `alloc_error_hook` API.

ACP: https://github.com/rust-lang/libs-team/issues/192

Closes #51540
Closes #51245
2023-04-22 12:27:45 +00:00
DrMeepster 631ea7cc15 use P<[Ident]> instead of Vec<Ident> 2023-04-21 02:14:03 -07:00
DrMeepster 511e457c4b offset_of 2023-04-21 02:14:02 -07:00
Nilstrieb b5d3d970fa Add `rustc_fluent_macro` to decouple fluent from `rustc_macros`
Fluent, with all the icu4x it brings in, takes quite some time to
compile. `fluent_messages!` is only needed in further downstream rustc
crates, but is blocking more upstream crates like `rustc_index`. By
splitting it out, we allow `rustc_macros` to be compiled earlier, which
speeds up `x check compiler` by about 5 seconds (and even more after the
needless dependency on `serde_json` is removed from
`rustc_data_structures`).
2023-04-18 18:56:22 +00:00
Amanieu d'Antras abc0660118 Remove #[alloc_error_handler] from the compiler and library 2023-04-16 08:35:50 -07:00
Matthias Krüger 543f8bc38c fix clippy::toplevel_ref_arg and ::manual_map 2023-04-16 13:28:13 +02:00
bors 9693b178fc Auto merge of #110252 - matthiaskrgr:rollup-ovaixra, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #109810 (Replace rustdoc-ui/{c,z}-help tests with a stable run-make test )
 - #110035 (fix: ensure bad `#[test]` invocs retain correct AST)
 - #110089 (sync::mpsc: synchronize receiver disconnect with initialization)
 - #110103 (Report overflows gracefully with new solver)
 - #110122 (Fix x check --stage 1 when download-ci-llvm=false)
 - #110133 (Do not use ImplDerivedObligationCause for inherent impl method error reporting)
 - #110135 (Revert "Don't recover lifetimes/labels containing emojis as character literals")
 - #110235 (Fix `--extend-css` option)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-04-12 22:19:29 +00:00
Matthias Krüger d40c827e9a
Rollup merge of #110035 - Ezrashaw:improve-test-attr-expansion-code, r=davidtwco
fix: ensure bad `#[test]` invocs retain correct AST

Fixes #109816

Ensures that a `StmtKind::Item` doesn't get converted into a plain `Item` (causing the ICE from the linked issue) Also unifies the error path a bit.
2023-04-12 22:04:32 +02:00
Matthias Krüger 331e7c3659
Rollup merge of #110153 - DaniPopes:compiler-typos, r=Nilstrieb
Fix typos in compiler

I ran [`typos -w compiler`](https://github.com/crate-ci/typos) to fix typos in the `compiler` directory.

Refs #110150
2023-04-12 20:56:21 +02:00
bors 45749b21b7 Auto merge of #110092 - clubby789:builtin-macros-translatable, r=compiler-errors
Migrate most of `rustc_builtin_macros` to diagnostic impls

cc #100717

This is a couple of days work, but I decided to stop for now before the PR becomes too big. There's around 50 unresolved failures when `rustc::untranslatable_diagnostic` is denied, which I'll finish addressing once this PR goes thtough

A couple of outputs have changed, but in all instances I think the changes are an improvement/are more consistent with other diagnostics (although I'm happy to revert any which seem worse)
2023-04-11 14:40:54 +00:00
Ezra Shaw 9e70541eac
refactor: extract `not_testable_error` into function 2023-04-11 21:07:02 +12:00
clubby789 64f7597776 Migrate most of `rustc_builtin_macros` to diagnostic impls
Co-authored-by: Joe ST <joe@fbstj.net>
Co-authored-by: Michael Goulet <michael@errs.io>
2023-04-10 21:16:53 +01:00
DaniPopes 677357d32b
Fix typos in compiler 2023-04-10 22:02:52 +02:00
blyxyas 2c976765b8
Migrate `sess.opts.tests` uses to `sess.is_test_crate()` 2023-04-09 21:37:31 +02:00
Ezra Shaw f4e7a99662
fix: ensure bad `#[test]` invocs retain correct AST 2023-04-07 14:32:55 +12:00
Jonas Platte 443928f7e3
Stabilize is_some_and 2023-04-06 23:14:23 +02:00
Oli Scherer 373807a95c Rename `ast::Static` to `ast::StaticItem` to match `ast::ConstItem` 2023-04-04 15:34:40 +00:00
Oli Scherer 4bebdd7104 box a bunch of large types 2023-04-04 13:58:50 +00:00
Oli Scherer ec74653652 Split out ast::ItemKind::Const into its own struct 2023-04-04 09:44:50 +00:00
Oli Scherer e3828777a6 rust-analyzer guided tuple field to named field 2023-04-04 09:44:50 +00:00
Oli Scherer b08a557f80 rust-analyzer guided enum variant structification 2023-04-04 09:44:45 +00:00
Guillaume Gomez b1e8be783f
Rollup merge of #109354 - Swatinem:rm-closureid, r=compiler-errors
Remove the `NodeId` of `ast::ExprKind::Async`

This is a followup to https://github.com/rust-lang/rust/pull/104833#pullrequestreview-1314537416.

In my original attempt, I was using `LoweringContext::expr`, which was not correct as it creates a fresh `DefId`.
It now uses the correct `DefId` for the wrapping `Expr`, and also makes forwarding `#[track_caller]` attributes more explicit.
2023-03-27 18:56:19 +02:00
Vadim Petrochenkov aca1b1e0b3 rustc_interface: Add a new query `pre_configure`
It partially expands crate attributes before the main expansion pass (without modifying the crate), and the produced preliminary crate attribute list is used for querying a few attributes that are required very early.

Crate-level cfg attributes are then expanded normally during the main expansion pass, like attributes on any other nodes.
2023-03-23 14:22:48 +04:00
Vadim Petrochenkov 6cc33b7691 expand: Pass `ast::Crate` by reference to AST transforming passes
Also some more attributes are passed by reference.
2023-03-23 14:20:55 +04:00
Vadim Petrochenkov 67a2c5bec8 rustc: Remove unused `Session` argument from some attribute functions 2023-03-22 13:55:55 +04:00
Matthias Krüger 5d3f460708
Rollup merge of #109301 - Ezrashaw:fix-ctf-ice, r=Nilstrieb
fix: fix ICE in `custom-test-frameworks` feature

Fixes #107454

Simple fix to emit error instead of ICEing. At some point, all the code in `tests.rs` should be refactored, there is a bit of duplication (this PR's code is repeated five times over lol).

r? `@Nilstrieb` (active on the linked issue?)
2023-03-20 07:10:31 +01:00
Arpad Borsos c8ead2e693
Remove the `NodeId` of `ast::ExprKind::Async` 2023-03-19 19:01:31 +01:00
Ezra Shaw c05bebcd67
fix: fix ICE in `custom-test-frameworks` feature 2023-03-19 22:11:17 +13:00
Partha P. Das 3720753632
Implementing "<test_binary> --list --format json" #107307 #49359 2023-03-15 14:20:20 -04:00
Nilstrieb 729185338f Properly allow macro expanded `format_args` invocations to uses captures
Originally, this was kinda half-allowed. There were some primitive
checks in place that looked at the span to see whether the input was
likely a literal. These "source literal" checks are needed because the
spans created during `format_args` parsing only make sense when it is
indeed a literal that was written in the source code directly.

This is orthogonal to the restriction that the first argument must be a
"direct literal", not being exanpanded from macros. This restriction was
imposed by [RFC 2795] on the basis of being too confusing. But this was
only concerned with the argument of the invocation being a literal, not
whether it was a source literal (maybe in spirit it meant it being a
source literal, this is not clear to me).

Since the original check only really cared about source literals (which
is good enough to deny the `format_args!(concat!())` example), macros
expanding to `format_args` invocations were able to use implicit
captures if they spanned the string in a way that lead back to a source
string.

The "source literal" checks were not strict enough and caused ICEs in
certain cases (see # 106191 (the space is intended to avoid spammy
backreferences)). So I tightened it up in # 106195 to really only work
if it's a direct source literal.

This caused the `indoc` crate to break. `indoc` transformed the source
literal by removing whitespace, which made it not a "source literal"
anymore (which is required to fix the ICE). But since `indoc` spanned
the literal in ways that made the old check think that it's a literal,
it was able to use implicit captures (which is useful and nice for the
users of `indoc`).

This commit properly seperates the previously introduced concepts of
"source literal" and "direct literal" and therefore allows `indoc`
invocations, which don't create "source literals" to use implicit
captures again.

[RFC 2795]: https://rust-lang.github.io/rfcs/2795-format-args-implicit-identifiers.html#macro-hygiene
2023-03-14 13:16:52 +00:00
clubby789 0932452fa4 Remove `box_syntax` from AST and use in tools 2023-03-12 13:19:46 +00:00
Matthias Krüger 9668ae5eb8
Rollup merge of #108726 - est31:backticks_matchmaking_tidy, r=Nilstrieb
tidy: enforce comment blocks to have an even number of backticks

After PR #108694, most unmatched backticks in `compiler/` comments have been eliminated. This PR adds a tidy lint to ensure no new unmatched backticks are added, and either addresses the lint in the remaining instances it found, or allows it.

Very often, backtick containing sections wrap around lines, for example:

```Rust
// This function takes a tuple `(Vec<String>,
// Box<[u8]>)` and transforms it into `Vec<u8>`.
```

The lint is implemented to work on top of blocks, counting each line with a `//` into a block, and counting if there are an odd or even number of backticks in the entire block, instead of looking at just a single line.
2023-03-12 08:13:25 +01:00
est31 7e2ecb3cd8 Simplify message paths
This makes it easier to open the messages file while developing on features.

The commit was the result of automatted changes:

for p in compiler/rustc_*; do mv $p/locales/en-US.ftl $p/messages.ftl; rmdir $p/locales; done

for p in compiler/rustc_*; do sed -i "s#\.\./locales/en-US.ftl#../messages.ftl#" $p/src/lib.rs; done
2023-03-11 22:51:57 +01:00
est31 7f4cc178f0 Address the new odd backticks tidy lint in compiler/ 2023-03-11 20:40:18 +01:00
Matthias Krüger d47d4ad4b2
Rollup merge of #106844 - Ezrashaw:concat-negative-int-lit, r=dtolnay
allow negative numeric literals in `concat!`

Fixes #106837

While *technically* negative numeric literals are implemented as unary operations, users can reasonably expect that negative literals are treated the same as positive literals.
2023-03-11 15:43:12 +01:00
Matthias Krüger cb0fb246d5
Rollup merge of #105798 - Amanieu:relax-asm, r=joshtriplett
Relax ordering rules for `asm!` operands

The `asm!` and `global_asm!` macros require their operands to appear strictly in the following order:
- Template strings
- Positional operands
- Named operands
- Explicit register operands
- `clobber_abi`
- `options`

This is overly strict and can be inconvienent when building complex `asm!` statements with macros. This PR relaxes the ordering requirements as follows:
- Template strings must still come before all other operands.
- Positional operands must still come before named and explicit register operands.
- Named and explicit register operands can be freely mixed.
- `options` and `clobber_abi` can appear in any position after the template strings.

r? ```````@joshtriplett```````
2023-03-10 21:15:42 +01:00
Kornel 2407b0c578 Explain compile-time vs run-time difference in env!() error message 2023-02-28 16:44:59 +00:00
est31 2850116636 Replace parse_[sth]_expr with parse_expr_[sth] function names
This resolves an inconsistency in naming style for functions
on the parser, between functions parsing specific kinds of items
and those for expressions, favoring the parse_item_[sth] style
used by functions for items. There are multiple advantages
of that style:

* functions of both categories are collected in the same place
  in the rustdoc output.
* it helps with autocompletion, as you can narrow down your
  search for a function to those about expressions.
* it mirrors rust's path syntax where less specific things
  come first, then it gets more specific, i.e.
  std::collections::hash_map::Entry

The disadvantage is that it doesn't "read like a sentence"
any more, but I think the advantages weigh more greatly.

This change was mostly application of this command:

sed -i -E 's/(fn |\.)parse_([[:alnum:]_]+)_expr/\1parse_expr_\2/' compiler/rustc_parse/src/parser/*.rs

Plus very minor fixes outside of rustc_parse, and an invocation
of x fmt.
2023-02-24 05:12:03 +01:00
David Wood d1fcf61117 errors: generate typed identifiers in each crate
Instead of loading the Fluent resources for every crate in
`rustc_error_messages`, each crate generates typed identifiers for its
own diagnostics and creates a static which are pulled together in the
`rustc_driver` crate and provided to the diagnostic emitter.

Signed-off-by: David Wood <david.wood@huawei.com>
2023-02-22 09:15:53 +00:00
Nicholas Nethercote 7e855d5f31 Use `ThinVec` in a few more AST types. 2023-02-21 11:51:56 +11:00
Nicholas Nethercote 549f1c60af Use `ThinVec` in `ast::ExprKind::Match`. 2023-02-21 11:51:56 +11:00
Nicholas Nethercote 912b825002 Use `ThinVec` in `ast::PatKind::Struct`. 2023-02-21 11:51:56 +11:00
Nicholas Nethercote b14b7ba5dd Use `ThinVec` in `ast::Block`. 2023-02-21 11:51:56 +11:00
Nicholas Nethercote 4143b101f9 Use `ThinVec` in various AST types.
This commit changes the sequence parsers to produce `ThinVec`, which
triggers numerous conversions.
2023-02-21 11:51:56 +11:00
Nicholas Nethercote 6a56c3a930 Use `ThinVec` in `ast::Impl` and related types. 2023-02-21 11:51:55 +11:00
Nicholas Nethercote 068db466e8 Use `ThinVec` in `ast::WhereClause`. 2023-02-21 11:51:55 +11:00
Nicholas Nethercote dd7aff5cc5 Use `ThinVec` in `ast::Generics` and related types. 2023-02-21 11:51:55 +11:00
Nicholas Nethercote 06228d6e93 Upgrade `thin-vec` from 0.2.9 to 0.2.12.
Because 0.2.10 added supports for `ThinVec::splice`, and 0.2.12 is the
latest release.
2023-02-21 11:51:55 +11:00
bors 21e5b941e0 Auto merge of #108128 - clubby789:builtin-derived-attr, r=jackh726
Properly check for builtin derived code

Fixes #108122
2023-02-19 21:18:07 +00:00
clubby789 90f642bb3d Properly check for builtin derives 2023-02-16 19:44:03 +00:00
Maybe Waffle 5bf6a46032 Replace some `then`s with some `then_some`s 2023-02-16 15:26:03 +00:00
Maybe Waffle 8751fa1a9a `if $c:expr { Some($r:expr) } else { None }` =>> `$c.then(|| $r)` 2023-02-16 15:26:00 +00:00
Nicholas Nethercote a70d03b624 Extend `BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE`.
To temporarily allow a `str` field in a packed struct using `derive`,
along with `[u8]`.
2023-02-09 11:47:12 +11:00
Michael Goulet 7a4505900d Add ~const bounds trait bounds when using derive_const 2023-02-07 21:00:12 +00:00
clubby789 d8651aae22 Don't generate unecessary `&&self.field` in deriving Debug 2023-02-02 22:06:23 +00:00
Nicholas Nethercote 75e87d1f81 Fix syntax in `-Zunpretty-expanded` output for derived `PartialEq`.
If you do `derive(PartialEq)` on a packed struct, the output shown by
`-Zunpretty=expanded` includes expressions like this:
```
{ self.x } == { other.x }
```
This is invalid syntax. This doesn't break compilation, because the AST
nodes are constructed within the compiler. But it does mean anyone using
`-Zunpretty=expanded` output as a guide for hand-written impls could get
a nasty surprise.

This commit fixes things by instead using this form:
```
({ self.x }) == ({ other.x })
```
2023-02-01 15:14:05 +11:00
Nicholas Nethercote 2e93f2c92f Allow more deriving on packed structs.
Currently, deriving on packed structs has some non-trivial limitations,
related to the fact that taking references on unaligned fields is UB.

The current approach to field accesses in derived code:
- Normal case: `&self.0`
- In a packed struct that derives `Copy`: `&{self.0}`
- In a packed struct that doesn't derive `Copy`: `&self.0`

Plus, we disallow deriving any builtin traits other than `Default` for any
packed generic type, because it's possible that there might be
misaligned fields. This is a fairly broad restriction.

Plus, we disallow deriving any builtin traits other than `Default` for most
packed types that don't derive `Copy`. (The exceptions are those where the
alignments inherently satisfy the packing, e.g. in a type with
`repr(packed(N))` where all the fields have alignments of `N` or less
anyway. Such types are pretty strange, because the `packed` attribute is
not having any effect.)

This commit introduces a new, simpler approach to field accesses:
- Normal case: `&self.0`
- In a packed struct: `&{self.0}`

In the latter case, this requires that all fields impl `Copy`, which is
a new restriction. This means that the following example compiles under
the old approach and doesn't compile under the new approach.
```
 #[derive(Debug)]
 struct NonCopy(u8);

 #[derive(Debug)
 #[repr(packed)]
 struct MyType(NonCopy);
```
(Note that the old approach's support for cases like this was brittle.
Changing the `u8` to a `u16` would be enough to stop it working. So not
much capability is lost here.)

However, the other constraints from the old rules are removed. We can now
derive builtin traits for packed generic structs like this:
```
 trait Trait { type A; }

 #[derive(Hash)]
 #[repr(packed)]
 pub struct Foo<T: Trait>(T, T::A);
```
To allow this, we add a `T: Copy` bound in the derived impl and a `T::A:
Copy` bound in where clauses. So `T` and `T::A` must impl `Copy`.

We can now also derive builtin traits for packed structs that don't derive
`Copy`, so long as the fields impl `Copy`:
```
 #[derive(Hash)]
 #[repr(packed)]
 pub struct Foo(u32);
```
This includes types that hand-impl `Copy` rather than deriving it, such as the
following, that show up in winapi-0.2:
```
 #[derive(Clone)]
 #[repr(packed)]
 struct MyType(i32);

 impl Copy for MyType {}
```
The new approach is simpler to understand and implement, and it avoids
the need for the `unsafe_derive_on_repr_packed` check.

One exception is required for backwards-compatibility: we allow `[u8]`
fields for now. There is a new lint for this,
`byte_slice_in_packed_struct_with_derive`.
2023-01-30 12:00:42 +11:00
bors 9f82651a5f Auto merge of #103659 - clubby789:improve-partialord-derive, r=nagisa
Special-case deriving `PartialOrd` for enums with dataless variants

I was able to get slightly better codegen by flipping the derived `PartialOrd` logic for two-variant enums.  I also tried to document the implementation of the derive macro to make the special-case logic a little clearer.
```rs
#[derive(PartialEq, PartialOrd)]
pub enum A<T> {
    A,
    B(T)
}
```
```diff
impl<T: ::core::cmp::PartialOrd> ::core::cmp::PartialOrd for A<T> {
   #[inline]
   fn partial_cmp(
       &self,
       other: &A<T>,
   ) -> ::core::option::Option<::core::cmp::Ordering> {
       let __self_tag = ::core::intrinsics::discriminant_value(self);
       let __arg1_tag = ::core::intrinsics::discriminant_value(other);
-      match ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag) {
-          ::core::option::Option::Some(::core::cmp::Ordering::Equal) => {
-              match (self, other) {
-                  (A::B(__self_0), A::B(__arg1_0)) => {
-                      ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0)
-                  }
-                  _ => ::core::option::Option::Some(::core::cmp::Ordering::Equal),
-              }
+      match (self, other) {
+          (A::B(__self_0), A::B(__arg1_0)) => {
+              ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0)
           }
-          cmp => cmp,
+          _ => ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag),
       }
   }
}
```
Godbolt: [Current](https://godbolt.org/z/GYjEzG1T8), [New](https://godbolt.org/z/GoK78qx15)
I'm not sure how common a case comparing two enums like this (such as `Option`) is, and if it's worth the slowdown of adding a special case to the derive. If it causes overall regressions it might be worth just manually implementing this for `Option`.
2023-01-28 22:11:11 +00:00
Amanieu d'Antras 52f7a218fb Relax ordering rules for `asm!` operands
The `asm!` and `global_asm!` macros require their operands to appear
strictly in the following order:
- Template strings
- Positional operands
- Named operands
- Explicit register operands
- `clobber_abi`
- `options`

This is overly strict and can be inconvienent when building complex
`asm!` statements with macros. This PR relaxes the ordering requirements
as follows:
- Template strings must still come before all other operands.
- Positional operands must still come before named and explicit register
operands.
- Named and explicit register operands can be freely mixed.
- `options` and `clobber_abi` can appear in any position.
2023-01-27 08:15:38 +00:00
Mara Bos 0abf8a0617 Replace format flags u32 by enums and bools. 2023-01-27 08:53:39 +01:00
bors 3e97763872 Auto merge of #106745 - m-ou-se:format-args-ast, r=oli-obk
Move format_args!() into AST (and expand it during AST lowering)

Implements https://github.com/rust-lang/compiler-team/issues/541

This moves FormatArgs from rustc_builtin_macros to rustc_ast_lowering. For now, the end result is the same. But this allows for future changes to do smarter things with format_args!(). It also allows Clippy to directly access the ast::FormatArgs, making things a lot easier.

This change turns the format args types into lang items. The builtin macro used to refer to them by their path. After this change, the path is no longer relevant, making it easier to make changes in `core`.

This updates clippy to use the new language items, but this doesn't yet make clippy use the ast::FormatArgs structure that's now available. That should be done after this is merged.
2023-01-26 12:44:47 +00:00
bors b22aa57fd5 Auto merge of #106884 - clubby789:fieldless-enum-debug, r=michaelwoerister
Simplify `derive(Debug)` output for fieldless enums

Fixes #106875
2023-01-21 07:49:09 +00:00
clubby789 95a824c02c Special case `derive(Debug)` for fieldless enums 2023-01-19 15:53:31 +00:00
clubby789 97cf1713d1 Add enum for fieldless unification 2023-01-19 15:41:11 +00:00
Maybe Waffle 6a28fb42a8 Remove double spaces after dots in comments 2023-01-17 08:09:33 +00:00
clubby789 2883148e60 Special case deriving `PartialOrd` for certain enum layouts 2023-01-15 01:35:48 +00:00
Ezra Shaw 41856b0a0f
allow negative numeric literals in `concat!` 2023-01-15 12:48:53 +13:00
Mara Bos 56593104ac Update comment explaining format_args!() expansion. 2023-01-12 00:45:29 +01:00
Mara Bos a4dbcb525b Expand format_args!() in rust_ast_lowering. 2023-01-12 00:25:45 +01:00
Gimbles 32ab2d95f1
Update format.rs 2023-01-02 15:51:54 +05:30
Nilstrieb 9067e4417e Rename `Rptr` to `Ref` in AST and HIR
The name makes a lot more sense, and `ty::TyKind` calls it `Ref` already
as well.
2022-12-28 18:52:36 +01:00
Matthias Krüger d23cb738d2
Rollup merge of #105975 - jeremystucki:rustc-remove-needless-lifetimes, r=eholk
rustc: Remove needless lifetimes
2022-12-24 00:31:41 +01:00
Matthias Krüger 3e58de240c
Rollup merge of #105978 - jyn514:unused_proc_macro_decl, r=tmiasko
Mark `proc_macro_decls_static` as always used

This would have avoided a bug in https://github.com/rust-lang/rust/pull/104860.

In practice this shouldn't matter since nothing uses the query other than the `dead_code` lint, but this isn't documented as an internal-only query so it seems nice for it to be accurate. I think for `dead_code` it doesn't matter because the relevant code is generated by `rustc_builtin_macros` and isn't linted.

I think `@tmiasko` or `@bjorn3` would be a good reviewer?

r? `@tmiasko`
2022-12-23 01:17:50 +01:00
Joshua Nelson 164e22109b Mark `proc_macro_decls_static` as always used
This would have avoided a bug in https://github.com/rust-lang/rust/pull/104860.

In practice this shouldn't matter since nothing uses the query other than the `dead_code` lint,
but this isn't documented as an internal-only query so it seems nice for it to be accurate.
I think for `dead_code` it doesn't matter because the relevant code is generated by `rustc_builtin_macros` and isn't linted.
2022-12-22 12:02:53 -06:00
Jeremy Stucki 3dde32ca97
rustc: Remove needless lifetimes 2022-12-20 22:10:40 +01:00
Matthias Krüger 8892698903
Rollup merge of #105870 - matthiaskrgr:useless_conv, r=oli-obk
avoid .into() conversion to identical types
2022-12-18 18:57:05 +01:00
Matthias Krüger 0aa4cde747 avoid .into() conversion to identical types 2022-12-18 16:20:32 +01:00
Matthias Krüger 1ade25491e remove redundant clone 2022-12-18 00:29:25 +01:00
Matthias Krüger 4069792d73
Rollup merge of #105620 - TaKO8Ki:remove-unnecessary-uses-of-clone, r=compiler-errors
Remove unnecessary uses of `clone`
2022-12-13 01:17:10 +01:00
Takayuki Maeda ee40a67cd9 remove unnecessary uses of `clone` 2022-12-13 02:06:24 +09:00
bors 2cd2070af7 Auto merge of #105160 - nnethercote:rm-Lit-token_lit, r=petrochenkov
Remove `token::Lit` from `ast::MetaItemLit`.

Currently `ast::MetaItemLit` represents the literal kind twice. This PR removes that redundancy. Best reviewed one commit at a time.

r? `@petrochenkov`
2022-12-12 05:16:50 +00:00
Matthias Krüger 2daa3bcbc2
Rollup merge of #105537 - kadiwa4:remove_some_imports, r=fee1-dead
compiler: remove unnecessary imports and qualified paths

Some of these imports were necessary before Edition 2021, others were already in the prelude.

I hope it's fine that this PR is so spread-out across files :/
2022-12-11 09:51:57 +01:00
KaDiWa 9bc69925cb
compiler: remove unnecessary imports and qualified paths 2022-12-10 18:45:34 +01:00
nils 2f9f097cb8 Migrate parts of `rustc_expand` to session diagnostics
This migrates everything but the `mbe` and `proc_macro` modules. It also
contains a few cleanups and drive-by/accidental diagnostic improvements
which can be seen in the diff for the UI tests.
2022-12-10 11:02:41 +01:00
bors 0d5573e6da Auto merge of #105363 - WaffleLapkin:thin2win_box_next_argument, r=nnethercote
Shrink `rustc_parse_format::Piece`

This makes both variants closer together in size (previously they were different by 208 bytes -- 16 vs 224). This may make things worse, but it's worth a try.

r? `@nnethercote`
2022-12-09 21:27:35 +00:00
Maybe Waffle 700c095306 `rustc_builtin_macros`: remove `ref` patterns
... and other pattern matching improvements
2022-12-06 14:45:58 +00:00
Maybe Waffle 78060cb6de Box `rustc_parse_format::Piece::NextArgument`
This makes both variants closer together in size (previously they were
different by 208 bytes -- 16 vs 224). This may make things worse, but
it's worth a try.
2022-12-06 12:02:56 +00:00
Matthias Krüger 4fdc3eb176
Rollup merge of #104614 - Nilstrieb:type-ascribe!, r=TaKO8Ki
Add `type_ascribe!` macro as placeholder syntax for type ascription

This makes it still possible to test the internal semantics of type ascription even once the `:`-syntax is removed from the parser. The macro now gets used in a bunch of UI tests that test the semantics and not syntax of type ascription.

I might have forgotten a few tests but this should hopefully be most of them. The remaining ones will certainly be found once type ascription is removed from the parser altogether.

Part of #101728
2022-12-02 08:28:08 +01:00
bors 11663b1b48 Auto merge of #104963 - petrochenkov:noaddids2, r=cjgillot
rustc_ast_lowering: Stop lowering imports into multiple items

Lower them into a single item with multiple resolutions instead.
This also allows to remove additional `NodId`s and `DefId`s related to those additional items.
2022-12-02 04:24:57 +00:00
Nicholas Nethercote 2fd364acff Remove `token::Lit` from `ast::MetaItemLit`.
`token::Lit` contains a `kind` field that indicates what kind of literal
it is. `ast::MetaItemLit` currently wraps a `token::Lit` but also has
its own `kind` field. This means that `ast::MetaItemLit` encodes the
literal kind in two different ways.

This commit changes `ast::MetaItemLit` so it no longer wraps
`token::Lit`. It now contains the `symbol` and `suffix` fields from
`token::Lit`, but not the `kind` field, eliminating the redundancy.
2022-12-02 13:49:19 +11:00
Nicholas Nethercote a7f35c42d4 Add `StrStyle` to `ast::LitKind::ByteStr`.
This is required to distinguish between cooked and raw byte string
literals in an `ast::LitKind`, without referring to an adjacent
`token::Lit`. It's a prerequisite for the next commit.
2022-12-02 10:38:58 +11:00
Vadim Petrochenkov b32a4edb20 rustc_ast_lowering: Stop lowering imports into multiple items
Lower them into a single item with multiple resolutions instead.
This also allows to remove additional `NodId`s and `DefId`s related to those additional items.
2022-12-01 18:51:20 +03:00
Matthias Krüger ee9eaa695c
Rollup merge of #105106 - jhpratt:issue-105101, r=TaKO8Ki
Fix ICE from #105101

Fixes #105101

Rather than comparing idents, compare spans, which should be unique to each variant.
2022-12-01 11:59:01 +01:00
bors d6c4de0fb2 Auto merge of #104861 - nnethercote:attr-cleanups, r=petrochenkov
Attribute cleanups

Best reviewed one commit at a time.

r? `@petrochenkov`
2022-12-01 07:13:45 +00:00
Jacob Pratt ab264ae612
Fix ICE from #105101 2022-11-30 21:18:31 +00:00
Nicholas Nethercote bf4a62c381 Fix an ICE parsing a malformed literal in `concat_bytes!`.
Fixes #104769.
2022-11-30 12:19:07 +11:00