Commit Graph

988 Commits

Author SHA1 Message Date
bors
33855f80d4 Auto merge of #130025 - Urgau:missing_docs-expect, r=petrochenkov
Also emit `missing_docs` lint with `--test` to fulfil expectations

This PR removes the "test harness" suppression of the `missing_docs` lint to be able to fulfil `#[expect]` (expectations) as it is now "relevant".

I think the goal was to maybe avoid false-positive while linting on public items under `#[cfg(test)]` but with effective visibility we should no longer have any false-positive.

Another possibility would be to query the lint level and only emit the lint if it's of expect level, but that is even more hacky.

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

try-job: x86_64-gnu-aux
2024-09-10 14:54:09 +00:00
Folkert de Vries
6ca5ec7b4e disallow naked_asm! outside of #[naked] functions 2024-09-10 15:19:14 +02:00
Urgau
a1a8627dd7 Allow missing_docs lint on the generated test harness 2024-09-09 14:51:39 +02:00
Folkert de Vries
02378997ea bootstrap naked_asm! for compiler-builtins
in this commit, `naked_asm!` is an alias for `asm!` with one difference: `options(noreturn)` is always enabled by `naked_asm!`. That makes it future-compatible for when `naked_asm!` starts disallowing `options(noreturn)` later.
2024-09-09 12:47:40 +02:00
Guillaume Gomez
015e9371e0
Rollup merge of #123940 - kornelski:remove-derived-debug, r=Urgau
debug-fmt-detail option

I'd like to propose a new option that makes `#[derive(Debug)]` generate no-op implementations that don't print anything, and makes `{:?}` in format strings a no-op.

There are a couple of motivations for this:

1. A more thorough stripping of debug symbols. Binaries stripped of debug symbols still retain some of them through `Debug` implementations. It's hard to avoid that without compiler's help, because debug formatting can be used in many places, including dependencies, and their loggers, asserts, panics, etc.
   * In my testing it gives about 2% binary size reduction on top of all other binary-minimizing best practices (including `panic_immediate_abort`). There are targets like Web WASM or embedded where users pay attention to binary sizes.
   * Users distributing closed-source binaries may not want to "leak" any symbol names as a matter of principle.
2. Adds ability to test whether code depends on specifics of the `Debug` format implementation in unwise ways (e.g. trying to get data unavailable via public interface, or using it as a serialization format). Because current Rust's debug implementation doesn't change, there's a risk of it becoming a fragile de-facto API that [won't be possible to change in the future](https://www.hyrumslaw.com/). An option that "breaks" it can act as a [grease](https://www.rfc-editor.org/rfc/rfc8701.html).

This implementation is a `-Z fmt-debug=opt` flag that takes:

* `full` — the default, current state.
* `none` — makes derived `Debug` and `{:?}` no-ops. Explicit `impl Debug for T` implementations are left unharmed, but `{:?}` format won't use them, so they may get dead-code eliminated if they aren't invoked directly.
* `shallow` — makes derived `Debug` print only the type's name, without recursing into fields. Fieldless enums print their variant names. `{:?}` works.

The `shallow` option is a compromise between minimizing the `Debug` code, and compatibility. There are popular proc-macro crates that use `Debug::fmt` as a way to convert enum values into their Rust source code.

There's a corresponding `cfg` flag: `#[cfg(fmt_debug = "none")]` that can be used in user code to react to this setting to minimize custom `Debug` implementations or remove unnecessary formatting helper functions.
2024-08-29 16:21:46 +02:00
Jubilee
d2418cb888
Rollup merge of #129467 - dingxiangfei2009:smart-pointer-relax-pointee, r=compiler-errors
derive(SmartPointer): assume pointee from the single generic and better error messages

Fix #129465

Actually RFC says that `#[pointee]` can be inferred when there is no ambiguity, or there is only one generic type parameter so to say.

cc ```@Darksonn```

r? ```@compiler-errors```
2024-08-28 19:12:52 -07:00
Kornel
88b9edc9db
fmt-debug option
Allows disabling `fmt::Debug` derive and debug formatting.
2024-08-28 23:32:40 +01:00
Ding Xiang Fei
39148351bd
derive(SmartPointer): assume pointee from the single generic and better error messages 2024-08-29 01:39:52 +08:00
Matthias Krüger
110c3df7fd
Rollup merge of #126013 - nnethercote:unreachable_pub, r=Urgau
Add `#[warn(unreachable_pub)]` to a bunch of compiler crates

By default `unreachable_pub` identifies things that need not be `pub` and tells you to make them `pub(crate)`. But sometimes those things don't need any kind of visibility. So they way I did these was to remove the visibility entirely for each thing the lint identifies, and then add `pub(crate)` back in everywhere the compiler said it was necessary. (Or occasionally `pub(super)` when context suggested that was appropriate.) Tedious, but results in more `pub` removal.

There are plenty more crates to do but this seems like enough for a first PR.

r? `@compiler-errors`
2024-08-27 00:41:57 +02:00
bors
37d56daac6 Auto merge of #128771 - carbotaniuman:stabilize_unsafe_attr, r=nnethercote
Stabilize `unsafe_attributes`

# Stabilization report

## Summary

This is a tracking issue for the RFC 3325: unsafe attributes

We are stabilizing `#![feature(unsafe_attributes)]`,  which makes certain attributes considered 'unsafe', meaning that they must be surrounded by an `unsafe(...)`, as in `#[unsafe(no_mangle)]`.

RFC: rust-lang/rfcs#3325
Tracking issue: #123757

## What is stabilized

### Summary of stabilization

Certain attributes will now be designated as unsafe attributes, namely, `no_mangle`, `export_name`, and `link_section` (stable only), and these attributes will need to be called by surrounding them in `unsafe(...)` syntax. On editions prior to 2024, this is simply an edition lint, but it will become a hard error in 2024. This also works in `cfg_attr`, but `unsafe` is not allowed for any other attributes, including proc-macros ones.

```rust
#[unsafe(no_mangle)]
fn a() {}

#[cfg_attr(any(), unsafe(export_name = "c"))]
fn b() {}
```

For a table showing the attributes that were considered to be included in the list to require unsafe, and subsequent reasoning about why each such attribute was or was not included, see [this comment here](https://github.com/rust-lang/rust/pull/124214#issuecomment-2124753464)

## Tests

The relevant tests are in `tests/ui/rust-2024/unsafe-attributes` and `tests/ui/attributes/unsafe`.
2024-08-17 22:48:42 +00:00
Nicholas Nethercote
0544d3a952 Add warn(unreachable_pub) to rustc_builtin_macros. 2024-08-16 08:46:57 +10:00
Nicholas Nethercote
7923b20dd9 Use impl PartialEq<TokenKind> for Token more.
This lets us compare a `Token` with a `TokenKind`. It's used a lot, but
can be used even more, avoiding the need for some `.kind` uses.
2024-08-14 16:37:09 +10:00
Matthias Krüger
32e0fe129d
Rollup merge of #128762 - fmease:use-more-slice-pats, r=compiler-errors
Use more slice patterns inside the compiler

Nothing super noteworthy. Just replacing the common 'fragile' pattern of "length check followed by indexing or unwrap" with slice patterns for legibility and 'robustness'.

r? ghost
2024-08-11 07:51:51 +02:00
Urgau
eedb32dd12 Make Span optional in BufferedEarlyLint 2024-08-07 14:08:34 +02:00
León Orell Valerian Liehr
c4c518d2d4
Use more slice patterns inside the compiler 2024-08-07 13:37:52 +02:00
carbotaniuman
de9b5c3ea2 Stabilize unsafe_attributes 2024-08-07 03:12:13 -05:00
Matthias Krüger
d10f2b32f0
Rollup merge of #127907 - RalfJung:byte_slice_in_packed_struct_with_derive, r=nnethercote
built-in derive: remove BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE hack and lint

Fixes https://github.com/rust-lang/rust/issues/107457 by turning the lint into a hard error. The lint has been shown in future breakage reports since Rust 1.69 (released in April 2023).

Let's see (via crater) if enough time has passed since https://github.com/rust-lang/rust/pull/104429, and https://github.com/unicode-org/icu4x/pull/2834 has propagated far enough to let us make this a hard error.

Cc ``@nnethercote`` ``@Manishearth``
2024-08-05 05:40:19 +02:00
Matthias Krüger
b6b8330b9d
Rollup merge of #128305 - folkertdev:asm-parser-unsupported-operand, r=Amanieu
improve error message when `global_asm!` uses `asm!` operands

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

what was

```
error: expected expression, found keyword `in`
 --> src/lib.rs:1:31
  |
1 | core::arch::global_asm!("{}", in(reg));
  |                               ^^ expected expression
```

becomes

```
error: the `in` operand cannot be used with `global_asm!`
  --> $DIR/parse-error.rs:150:19
   |
LL | global_asm!("{}", in(reg));
   |                   ^^ the `in` operand is not meaningful for global-scoped inline assembly, remove it
```

the span of the error is just the keyword, which means that we can't create a machine-applicable suggestion here. The alternative would be to attempt to parse the full operand, but then if there are syntax errors in the operand those would  be presented to the user, even though the parser already knows that the output won't be valid. Also that would require more complexity in the parser.

So I think this is a nice improvement at very low cost.
2024-08-04 11:32:33 +02:00
Matthias Krüger
9b69042d5b
Rollup merge of #128557 - nyurik:dup-init, r=compiler-errors
chore: use shorthand initializer

Tiny readability improvement - don't use redundant initializer vars
2024-08-03 11:17:45 +02:00
Matthias Krüger
dee57ce043
Rollup merge of #128483 - nnethercote:still-more-cfg-cleanups, r=petrochenkov
Still more `cfg` cleanups

Found while looking closely at `cfg`/`cfg_attr` processing code.

r? `````````@petrochenkov`````````
2024-08-03 11:17:44 +02:00
Yuri Astrakhan
84e261e5cb chore: use shorthand initializer 2024-08-02 13:22:28 -04:00
bors
c0e32983f5 Auto merge of #127543 - carbotaniuman:more_unsafe_attr_verification, r=estebank,traviscross
More unsafe attr verification

This code denies unsafe on attributes such as `#[test]` and `#[ignore]`, while also changing the `MetaItem` parsing so `unsafe` in args like `#[allow(unsafe(dead_code))]` is not accidentally allowed.

Tracking:

- https://github.com/rust-lang/rust/issues/123757
2024-08-01 10:40:45 +00:00
Nicholas Nethercote
d1f05fd184 Distinguish the two kinds of token range.
When collecting tokens there are two kinds of range:
- a range relative to the parser's full token stream (which we get when
  we are parsing);
- a range relative to a single AST node's token stream (which we use
  within `LazyAttrTokenStreamImpl` when replacing tokens).

These are currently both represented with `Range<u32>` and it's easy to
mix them up -- until now I hadn't properly understood the difference.

This commit introduces `ParserRange` and `NodeRange` to distinguish
them. This also requires splitting `ReplaceRange` in two, giving the new
types `ParserReplacement` and `NodeReplacement`. (These latter two names
reduce the overloading of the word "range".)

The commit also rewrites some comments to be clearer.

The end result is a little more verbose, but much clearer.
2024-08-01 19:30:40 +10:00
Ding Xiang Fei
14a0963f96
reject pointee without ?Sized 2024-08-01 02:00:05 +08:00
Matthias Krüger
563f938ab3
Rollup merge of #127681 - dingxiangfei2009:smart-ptr-bounds, r=compiler-errors
derive(SmartPointer): rewrite bounds in where and generic bounds

Fix #127647

Due to the `Unsize` bounds, we need to commute the bounds on the pointee type to the new self type.

cc ```@Darksonn```
2024-07-31 15:36:29 +02:00
carbotaniuman
49db8a5a99 Add toggle for parse_meta_item unsafe parsing
This makes it possible for the `unsafe(...)` syntax to only be
valid at the top level, and the `NestedMetaItem`s will automatically
reject `unsafe(...)`.
2024-07-30 18:28:43 -05:00
Matthias Krüger
6f0b237c72
Rollup merge of #128376 - compiler-errors:finish-ur-vegetables, r=jieyouxu
Mark `Parser::eat`/`check` methods as `#[must_use]`

These methods return a `bool`, but we probably should either use these values or explicitly throw them away (e.g. when we just want to unconditionally eat a token if it exists).

I changed a few places from `eat` to `expect`, but otherwise I tried to leave a comment explaining why the `eat` was okay.

This also adds a test for the `pattern_type!` macro, which used to silently accept a missing `is` token.
2024-07-30 22:51:38 +02:00
Ding Xiang Fei
e7f89a7eea
derive(SmartPointer): rewrite bounds in where and generic bounds 2024-07-30 21:14:10 +02:00
bors
f8060d282d Auto merge of #128083 - Mark-Simulacrum:bump-bootstrap, r=albertlarsan68
Bump bootstrap compiler to new beta

https://forge.rust-lang.org/release/process.html#master-bootstrap-update-t-2-day-tuesday
2024-07-30 17:49:08 +00:00
carbotaniuman
d8bc8761a5 Deny unsafe on more builtin attributes 2024-07-29 21:00:09 -05:00
Michael Goulet
e4076e34f8 Mark Parser::eat/check methods as must_use 2024-07-29 21:29:08 -04:00
Nicholas Nethercote
84ac80f192 Reformat use declarations.
The previous commit updated `rustfmt.toml` appropriately. This commit is
the outcome of running `x fmt --all` with the new formatting options.
2024-07-29 08:26:52 +10:00
Mark Rousskov
5eca36d27a step cfg(bootstrap) 2024-07-28 14:46:29 -04:00
Folkert
571f7b6589
improve error message when global asm uses inline asm operands 2024-07-28 15:11:32 +02:00
Matthias Krüger
a13f40dae6
Rollup merge of #127853 - folkertdev:naked-function-error-messages, r=bjorn3
`#[naked]`: report incompatible attributes

tracking issue: https://github.com/rust-lang/rust/issues/90957

this is a re-implementation of https://github.com/rust-lang/rust/pull/93809 by ``@bstrie`` which was closed 2 years ago due to inactivity.

This PR takes some of the final comments into account, specifically providing a little more context in error messages, and using an allow list to determine which attributes are compatible with `#[naked]`.

Notable attributes that are incompatible with `#[naked]` are:

  * `#[inline]`
  * `#[track_caller]`
  * ~~`#[target_feature]`~~ (this is now allowed, see PR discussion)
  * `#[test]`, `#[ignore]`, `#[should_panic]`

These attributes just directly conflict with what `#[naked]` should do.

Naked functions are still important for systems programming, embedded, and operating systems, so I'd like to move them forward.
2024-07-28 08:57:16 +02:00
Trevor Gross
9164dbd48c
Rollup merge of #128207 - folkertdev:asm-parser-generalize, r=Amanieu
improve error message when `global_asm!` uses `asm!` options

specifically, what was

    error: expected one of `)`, `att_syntax`, or `raw`, found `preserves_flags`
      --> $DIR/bad-options.rs:45:25
       |
    LL | global_asm!("", options(preserves_flags));
       |                         ^^^^^^^^^^^^^^^ expected one of `)`, `att_syntax`, or `raw`

is now

    error: the `preserves_flags` option cannot be used with `global_asm!`
      --> $DIR/bad-options.rs:45:25
       |
    LL | global_asm!("", options(preserves_flags));
       |                         ^^^^^^^^^^^^^^^ the `preserves_flags` option is not meaningful for global-scoped inline assembly

mirroring the phrasing of the [reference](https://doc.rust-lang.org/reference/inline-assembly.html#options).

This is also a bit of a refactor for a future `naked_asm!` macro (for use in `#[naked]` functions). Currently this sort of error can come up when switching from inline to global asm, or when a user just isn't that experienced with assembly. With  `naked_asm!` added to the mix hitting this error is more likely.
2024-07-27 13:32:56 -04:00
Ralf Jung
bda31d14f4 built-in derive: remove BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE hack and lint 2024-07-27 18:18:41 +02:00
Folkert
c6a166bac2
switch to an allowlist approach
- merge error codes
- use attribute name that is incompatible in error message
- add test for conditional incompatible attribute
- add `linkage` to the allowlist
2024-07-27 12:55:39 +02:00
Folkert
73fde17017
refactor the if if 2024-07-26 00:08:22 +02:00
Folkert
d3858f7465
improve error message when global_asm! uses asm! options 2024-07-25 22:33:52 +02:00
GnomedDev
db8cdc5d37
Use Cow<'static, str> for InlineAsmTemplatePiece::String 2024-07-24 21:11:55 +01:00
Oli Scherer
e9f32d0ca6 Avoid passing state that will not be visited 2024-07-22 14:34:45 +00:00
Oli Scherer
8d290058c9 Always pass the visitor as the first argument to walk* functions 2024-07-22 14:01:24 +00:00
Oli Scherer
754bdef793 Sync mut_visit function names with immut visit ones (s/noop_visit/walk/) 2024-07-22 14:01:24 +00:00
Oli Scherer
6f85f20520 Add Ident to FnKind::Fn, just like with the immutable visitor 2024-07-22 14:01:23 +00:00
Oli Scherer
545553ca4f Pass id and span to visit_fn, just like for the immutable visitor 2024-07-22 14:01:23 +00:00
Oli Scherer
1b9ac0011f Make function items in mut visitors all go through the same visit_fn function, just like with immutable visitors 2024-07-22 14:01:23 +00:00
Oli Scherer
5241d8bb19 Merge impl and trait item mut visitor methods to mirror immut visitor 2024-07-22 14:01:23 +00:00
bors
9629b90b3f Auto merge of #127722 - BoxyUwU:new_adt_const_params_limitations, r=compiler-errors
Forbid borrows and unsized types from being used as the type of a const generic under `adt_const_params`

Fixes #112219
Fixes #112124
Fixes #112125

### Motivation

Currently the `adt_const_params` feature allows writing `Foo<const N: [u8]>` this is entirely useless as it is not possible to write an expression which evaluates to a type that is not `Sized`. In order to actually use unsized types in const generics they are typically written as `const N: &[u8]` which *is* possible to provide a value of.

Unfortunately allowing the types of const parameters to contain references is non trivial (#120961) as it introduces a number of difficult questions about how equality of references in the type system should behave. References in the types of const generics is largely only useful for using unsized types in const generics.

This PR introduces a new feature gate `unsized_const_parameters` and moves support for `const N: [u8]` and `const N: &...` from `adt_const_params` into it. The goal here hopefully is to experiment with allowing `const N: [u8]` to work without references and then eventually completely forbid references in const generics.

Splitting this out into a new feature gate means that stabilization of `adt_const_params` does not have to resolve #120961 which is the only remaining "big" blocker for the feature. Remaining issues after this are a few ICEs and naming bikeshed for `ConstParamTy`.

### Implementation

The implementation is slightly subtle here as we would like to ensure that a stabilization of `adt_const_params` is forwards compatible with any outcome of `unsized_const_parameters`. This is inherently tricky as we do not support unstable trait implementations and we determine whether a type is valid as the type of a const parameter via a trait bound.

There are a few constraints here:
- We would like to *allow for the possibility* of adding a `Sized` supertrait to `ConstParamTy` in the event that we wind up opting to not support unsized types and instead requiring people to write the 'sized version', e.g. `const N: [u8; M]` instead of `const N: [u8]`.
- Crates should be able to enable `unsized_const_parameters` and write trait implementations of `ConstParamTy` for `!Sized` types without downstream crates that only enable `adt_const_params` being able to observe this (required for std to be able to `impl<T> ConstParamTy for [T]`

Ultimately the way this is accomplished is via having two traits (sad), `ConstParamTy` and `UnsizedConstParamTy`. Depending on whether `unsized_const_parameters` is enabled or not we change which trait is used to check whether a type is allowed to be a const parameter.

Long term (when stabilizing `UnsizedConstParamTy`) it should be possible to completely merge these traits (and derive macros), only having a single `trait ConstParamTy` and `macro ConstParamTy`.

Under `adt_const_params` it is now illegal to directly refer to `ConstParamTy` it is only used as an internal impl detail by `derive(ConstParamTy)` and checking const parameters are well formed. This is necessary in order to ensure forwards compatibility with all possible future directions for `feature(unsized_const_parameters)`.

Generally the intuition here should be that `ConstParamTy` is the stable trait that everything uses, and `UnsizedConstParamTy` is that plus unstable implementations (well, I suppose `ConstParamTy` isn't stable yet :P).
2024-07-21 05:36:21 +00:00
Nicholas Nethercote
9d908a2877 Use ForceCollect in parse_attr_item.
Instead of a `bool`. Because `ForceCollect` is used in this way
everywhere else.
2024-07-19 08:24:54 +10:00
Boxy
d0c11bf6e3 Split part of adt_const_params into unsized_const_params 2024-07-17 11:01:29 +01:00
Folkert
4d082b77af
add error message when #[naked] is used with #[test] 2024-07-17 00:04:00 +02:00
Matthias Krüger
510020ad4c
Rollup merge of #127308 - nnethercote:Attribute-cleanups, r=petrochenkov
Attribute cleanups

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

r? `@petrochenkov`
2024-07-07 14:22:01 +02:00
Nicholas Nethercote
3a5c4b6e4e Rename some attribute types for consistency.
- `AttributesData` -> `AttrsTarget`
- `AttrTokenTree::Attributes` -> `AttrTokenTree::AttrsTarget`
- `FlatToken::AttrTarget` -> `FlatToken::AttrsTarget`
2024-07-07 16:14:30 +10:00
Oli Scherer
7dca61b68b Use ControlFlow results for visitors that are only looking for a single value 2024-07-05 15:00:40 +00:00
Matthias Krüger
d27136fb29
Rollup merge of #127283 - dingxiangfei2009:check-repr-transparent, r=davidtwco
Reject SmartPointer constructions not serving the purpose

Tracking issue: #123430

With this PR we will reject a row of malformed `SmartPointer` implementor candidates.

cc `@Darksonn` `@davidtwco` for context.
2024-07-04 18:16:23 +02:00
Matthias Krüger
b16a711191
Rollup merge of #126405 - He1pa:translate_builtin_macro_diag, r=davidtwco
Migrate some rustc_builtin_macros to SessionDiagnostic

<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.

This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using

    r​? <reviewer name>
-->

Part of https://github.com/rust-lang/rust/issues/100717.
pick up abandoned pr: #101935
`@rustbot` label +A-translation
2024-07-04 18:16:22 +02:00
Ding Xiang Fei
0b4edb2487
reject SmartPointer constructions not serving the purpose 2024-07-04 16:41:23 +08:00
Nicholas Nethercote
1680b791d5 Simplify CfgEval.
It can contain an owned value instead of a reference.
2024-07-02 10:46:43 +10:00
Michael Goulet
789ee88bd0 Tighten spans for async blocks 2024-06-27 15:19:08 -04:00
xFrednet
b124b3666e
sudo CI=green && Review changes <3 2024-06-25 18:06:22 +02:00
xFrednet
8b14e23dce
RFC 2383: Stabilize lint_reasons 🎉 2024-06-25 17:22:22 +02:00
he1pa
a82f70eeee Migrate some rustc_builtin_macros to SessionDiagnostic
Signed-off-by: he1pa <18012015693@163.com>
2024-06-25 18:04:21 +08:00
Xiangfei Ding
f1be59fa72
SmartPointer derive-macro
Co-authored-by: Wedson Almeida Filho <walmeida@microsoft.com>
2024-06-24 03:03:34 +08:00
Nicholas Nethercote
09006d6a88 Convert some module-level // and /// comments to //!.
This makes their intent and expected location clearer. We see some
examples where these comments were not clearly separate from `use`
declarations, which made it hard to understand what the comment is
describing.
2024-06-20 09:23:18 +10:00
Oli Scherer
7ba82d61eb Use a dedicated type instead of a reference for the diagnostic context
This paves the way for tracking more state (e.g. error tainting) in the diagnostic context handle
2024-06-18 15:42:11 +00:00
Oli Scherer
c91edc3888 Prefer dcx methods over fields or fields' methods 2024-06-18 13:45:08 +00:00
Nicholas Nethercote
75b164d836 Use tidy to sort crate attributes for all compiler crates.
We already do this for a number of crates, e.g. `rustc_middle`,
`rustc_span`, `rustc_metadata`, `rustc_span`, `rustc_errors`.

For the ones we don't, in many cases the attributes are a mess.
- There is no consistency about order of attribute kinds (e.g.
  `allow`/`deny`/`feature`).
- Within attribute kind groups (e.g. the `feature` attributes),
  sometimes the order is alphabetical, and sometimes there is no
  particular order.
- Sometimes the attributes of a particular kind aren't even grouped
  all together, e.g. there might be a `feature`, then an `allow`, then
  another `feature`.

This commit extends the existing sorting to all compiler crates,
increasing consistency. If any new attribute line is added there is now
only one place it can go -- no need for arbitrary decisions.

Exceptions:
- `rustc_log`, `rustc_next_trait_solver` and `rustc_type_ir_macros`,
  because they have no crate attributes.
- `rustc_codegen_gcc`, because it's quasi-external to rustc (e.g. it's
  ignored in `rustfmt.toml`).
2024-06-12 15:49:10 +10:00
carbotaniuman
f9104f0dfb Handle safe case 2024-06-06 20:54:51 -05:00
carbotaniuman
15f8ffe371 Fix formatting 2024-06-06 20:27:25 -05:00
carbotaniuman
87be1bae73 Fix build 2024-06-06 20:27:25 -05:00
carbotaniuman
c4de986afa Disallow unsafe in derive 2024-06-06 20:26:27 -05:00
carbotaniuman
67f5dd1ef1 Parse unsafe attributes 2024-06-06 20:26:27 -05:00
Jubilee
efd8959ab1
Rollup merge of #126096 - c410-f3r:tests-tests-tests, r=jhpratt
[RFC-2011] Allow `core_intrinsics` when activated

Fix #120612
2024-06-06 14:46:25 -07:00
Caio
a8084dcec1 [RFC-2011] Allow core_intrinsics when activated 2024-06-06 16:30:05 -03:00
Matthias Krüger
55b76f4720
Rollup merge of #125987 - estebank:issue-122622, r=Nadrieril
When `derive`ing, account for HRTB on `BareFn` fields

When given

```rust
trait SomeTrait {
    type SomeType<'a>;
}

#[derive(Clone)]
struct Foo<T: SomeTrait> {
    x: for<'a> fn(T::SomeType<'a>)
}
```

expand to

```rust
impl<T: ::core::clone::Clone + SomeTrait> ::core::clone::Clone for Foo<T>
    where for<'a> T::SomeType<'a>: ::core::clone::Clone {
    #[inline]
    fn clone(&self) -> Foo<T> {
        Foo { x: ::core::clone::Clone::clone(&self.x) }
    }
}
```

instead of the previous invalid

```
impl<T: ::core::clone::Clone + SomeTrait> ::core::clone::Clone for Foo<T>
    where T::SomeType<'a>: ::core::clone::Clone {
    #[inline]
    fn clone(&self) -> Foo<T> {
        Foo { x: ::core::clone::Clone::clone(&self.x) }
    }
}
```

Fix #122622.

<!--
If this PR is related to an unstable feature or an otherwise tracked effort,
please link to the relevant tracking issue here. If you don't know of a related
tracking issue or there are none, feel free to ignore this.

This PR will get automatically assigned to a reviewer. In case you would like
a specific user to review your work, you can assign it to them by using

    r​? <reviewer name>
-->
2024-06-06 04:17:26 +02:00
Nicholas Nethercote
b9037339cb Make top-level rustc_parse functions fallible.
Currently we have an awkward mix of fallible and infallible functions:
```
       new_parser_from_source_str
 maybe_new_parser_from_source_str
       new_parser_from_file
(maybe_new_parser_from_file)        // missing
      (new_parser_from_source_file) // missing
 maybe_new_parser_from_source_file
       source_str_to_stream
 maybe_source_file_to_stream
```
We could add the two missing functions, but instead this commit removes
of all the infallible ones and renames the fallible ones leaving us with
these which are all fallible:
```
new_parser_from_source_str
new_parser_from_file
new_parser_from_source_file
source_str_to_stream
source_file_to_stream
```
This requires making `unwrap_or_emit_fatal` public so callers of
formerly infallible functions can still work.

This does make some of the call sites slightly more verbose, but I think
it's worth it for the simpler API. Also, there are two `catch_unwind`
calls and one `catch_fatal_errors` call in this diff that become
removable thanks this change. (I will do that in a follow-up PR.)
2024-06-05 10:38:03 +10:00
Nicholas Nethercote
3c321b9ea8 Remove stream_to_parser.
It's a zero-value wrapper of `Parser::new`.
2024-06-05 10:37:59 +10:00
Esteban Küber
e7ad2da7f1 When deriveing, account for HRTB on BareFn fields
When given

```rust
trait SomeTrait {
    type SomeType<'a>;
}

struct Foo<T: SomeTrait> {
    x: for<'a> fn(T::SomeType<'a>)
}
```

expand to

```rust
impl<T: ::core::clone::Clone + SomeTrait> ::core::clone::Clone for Foo<T>
    where for<'a> T::SomeType<'a>: ::core::clone::Clone {
    #[inline]
    fn clone(&self) -> Foo<T> {
        Foo { x: ::core::clone::Clone::clone(&self.x) }
    }
}
```

instead of the previous invalid

```
impl<T: ::core::clone::Clone + SomeTrait> ::core::clone::Clone for Foo<T>
    where T::SomeType<'a>: ::core::clone::Clone {
    #[inline]
    fn clone(&self) -> Foo<T> {
        Foo { x: ::core::clone::Clone::clone(&self.x) }
    }
}
```

Fix #122622.
2024-06-04 20:46:03 +00:00
Matthias Krüger
3c79f0cd69
Rollup merge of #125316 - nnethercote:tweak-Spacing, r=petrochenkov
Tweak `Spacing` use

Some clean-up precursors to #125174.

r? ``@petrochenkov``
2024-05-23 07:41:18 +02:00
Matthias Krüger
4af1c31fcf
Rollup merge of #125156 - zachs18:for_loops_over_fallibles_behind_refs, r=Nilstrieb
Expand `for_loops_over_fallibles` lint to lint on fallibles behind references.

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

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

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

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

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

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

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

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

```

</details>

-----

Question:

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

`@rustbot` label +A-lint
2024-05-23 07:41:17 +02:00
Nicholas Nethercote
c679a55102 Convert some token_joint_hidden calls to token_joint.
This has no noticeable effect, but it makes these cases follow the
guidelines in the comments on `Spacing`, which say that `Joint` should
be used "for each token that (a) should be pretty-printed without a
space after it, and (b) is followed by a punctuation token".

These two tokens are both followed by a comma, which is a punctuation
token.
2024-05-23 06:03:17 +10:00
Xiretza
98dd6c7e8f Rename buffer_lint_with_diagnostic to buffer_lint 2024-05-21 20:16:39 +00:00
Xiretza
b7abf014ec Convert uses of BuiltinLintDiag::Normal to custom variants
This ensures all diagnostic messages are created at diagnostic emission
time, making them translatable.
2024-05-21 20:16:39 +00:00
Xiretza
c227f35a9c Generate lint diagnostic message from BuiltinLintDiag
Translation of the lint message happens when the actual diagnostic is
created, not when the lint is buffered. Generating the message from
BuiltinLintDiag ensures that all required data to construct the message
is preserved in the LintBuffer, eventually allowing the messages to be
moved to fluent.

Remove the `msg` field from BufferedEarlyLint, it is either generated
from the data in the BuiltinLintDiag or stored inside
BuiltinLintDiag::Normal.
2024-05-21 20:16:39 +00:00
bors
eb1a5c9bb3 Auto merge of #125077 - spastorino:add-new-fnsafety-enum2, r=jackh726
Rename Unsafe to Safety

Alternative to #124455, which is to just have one Safety enum to use everywhere, this opens the posibility of adding `ast::Safety::Safe` that's useful for unsafe extern blocks.

This leaves us today with:

```rust
enum ast::Safety {
    Unsafe(Span),
    Default,
    // Safe (going to be added for unsafe extern blocks)
}

enum hir::Safety {
    Unsafe,
    Safe,
}
```

We would convert from `ast::Safety::Default` into the right Safety level according the context.
2024-05-18 19:35:24 +00:00
wuaoxiang
582fd1fb53 Fix println! ICE when parsing percent prefix number 2024-05-18 01:05:56 +00:00
Santiago Pastorino
6b46a919e1
Rename Unsafe to Safety 2024-05-17 18:33:37 -03:00
Zachary S
7d7eb973d0 Fix new for_loops_over_fallibles hits in compiler. 2024-05-15 11:05:44 -05:00
Matthias Krüger
0a917f89f3
Rollup merge of #124919 - nnethercote:Recovered-Yes-ErrorGuaranteed, r=compiler-errors
Add `ErrorGuaranteed` to `Recovered::Yes` and use it more.

The starting point for this was identical comments on two different fields, in `ast::VariantData::Struct` and `hir::VariantData::Struct`:
```
    // FIXME: investigate making this a `Option<ErrorGuaranteed>`
    recovered: bool
```
I tried that, and then found that I needed to add an `ErrorGuaranteed` to `Recovered::Yes`. Then I ended up using `Recovered` instead of `Option<ErrorGuaranteed>` for these two places and elsewhere, which required moving `ErrorGuaranteed` from `rustc_parse` to `rustc_ast`.

This makes things more consistent, because `Recovered` is used in more places, and there are fewer uses of `bool` and
`Option<ErrorGuaranteed>`. And safer, because it's difficult/impossible to set `recovered` to `Recovered::Yes` without having emitted an error.

r? `@oli-obk`
2024-05-09 19:09:30 +02:00
Nicholas Nethercote
fd91925bce Add ErrorGuaranteed to Recovered::Yes and use it more.
The starting point for this was identical comments on two different
fields, in `ast::VariantData::Struct` and `hir::VariantData::Struct`:
```
    // FIXME: investigate making this a `Option<ErrorGuaranteed>`
    recovered: bool
```
I tried that, and then found that I needed to add an `ErrorGuaranteed`
to `Recovered::Yes`. Then I ended up using `Recovered` instead of
`Option<ErrorGuaranteed>` for these two places and elsewhere, which
required moving `ErrorGuaranteed` from `rustc_parse` to `rustc_ast`.

This makes things more consistent, because `Recovered` is used in more
places, and there are fewer uses of `bool` and
`Option<ErrorGuaranteed>`. And safer, because it's difficult/impossible
to set `recovered` to `Recovered::Yes` without having emitted an error.
2024-05-09 20:12:07 +10:00
bors
cb93c24bf3 Auto merge of #124157 - wutchzone:partial_eq, r=estebank
Do not add leading asterisk in the `PartialEq`

I think we should address this issue, however I am not exactly sure, if this is the right way to do it. It is related to the #123056.

Imagine the simplified code:

```rust
trait MyTrait {}

impl PartialEq for dyn MyTrait {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

#[derive(PartialEq)]
enum Bar {
    Foo(Box<dyn MyTrait>),
}
```

On the nightly compiler, the `derive` produces invalid code with the weird error message:
```
error[E0507]: cannot move out of `*__arg1_0` which is behind a shared reference
  --> src/main.rs:11:9
   |
9  | #[derive(PartialEq)]
   |          --------- in this derive macro expansion
10 | enum Things {
11 |     Foo(Box<dyn MyTrait>),
   |         ^^^^^^^^^^^^^^^^ move occurs because `*__arg1_0` has type `Box<dyn MyTrait>`, which does not implement the `Copy` trait
   |
   = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info)
```

It may be related to the perfect derive problem, although requiring the _type_ to be `Copy` seems unfortunate because it is not necessary. Besides, we are adding the extra dereference only for the diagnostics?
2024-05-09 08:34:14 +00:00
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
Nilstrieb
1572c0dcd7 Various improvements to entrypoint code
This moves some code around and adds some documentation comments to make
it easier to understand what's going on with the entrypoint logic, which
is a bit complicated.

The only change in behavior is consolidating the error messages for
unix_sigpipe to make the code slightly simpler.
2024-05-04 14:48:42 +02:00
Nicholas Nethercote
a74a272a5b Use parse renaming of rustc_parse_format.
This is a case where `rustc_parse_format` is renamed as `parse` but a
couple of places don't take advantage.
2024-05-03 16:03:15 +10:00
Nicholas Nethercote
6341935a13 Remove extern crate tracing from numerous crates. 2024-04-30 16:47:49 +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
30d6f63b4e Adjust some pubs. 2024-04-26 13:29:20 +10: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