Handle field projections like slice indexing in invalid_reference_casting
r? `@Urgau`
I saw the implementation in https://github.com/rust-lang/rust/pull/124761, and I was wondering if we also need to handle field access. We do. Without this PR, we get this errant diagnostic:
```
error: casting references to a bigger memory layout than the backing allocation is undefined behavior, even if the reference is unused
--> /home/ben/rust/tests/ui/lint/reference_casting.rs:262:18
|
LL | let r = &mut v.0;
| --- backing allocation comes from here
LL | let ptr = r as *mut i32 as *mut Vec3<i32>;
| ------------------------------- casting happend here
LL | unsafe { *ptr = Vec3(0, 0, 0) }
| ^^^^^^^^^^^^^^^^^^^^
|
= note: casting from `i32` (4 bytes) to `Vec3<i32>` (12 bytes)
```
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.
Fix insufficient logic when searching for the underlying allocation
This PR fixes the logic inside the `invalid_reference_casting` lint, when trying to lint on bigger memory layout casts.
More specifically when looking for the "underlying allocation" we were wrongly assuming that when we got `&mut slice[index]` that `slice[index]` was the allocation, but it's not.
Fixes https://github.com/rust-lang/rust/issues/124685
Some hir cleanups
It seemed odd to not put `AnonConst` in the arena, compared with the other types that we did put into an arena. This way we can also give it a `Span` without growing a lot of other HIR data structures because of the extra field.
r? compiler
Use `tcx.types.unit` instead of `Ty::new_unit(tcx)`
I don't think there is any need for the function, given that we can just access the `.types`, similarly to all other primitives?
Adjust `#[macro_export]`/doctest help suggestion for non_local_defs lint
This PR adjust the help suggestion of the `non_local_definitions` lint when encountering a `#[macro_export]` at top-level doctest.
So instead of a non-sentential help suggestion to move the `macro_rules!` up above the `rustdoc`-generated function. We now suggest users to declare their own function.
Fixes *(partially, needs backport)* #124534
Remove many `#[macro_use] extern crate foo` items
This requires the addition of more `use` items, which often make the code more verbose. But they also make the code easier to read, because `#[macro_use]` obscures where macros are defined.
r? `@fee1-dead`
[Refactor] Rename `Lint` and `LintGroup`'s `is_loaded` to `is_externally_loaded`
The field being named `is_loaded` was very confusing. Turns out it's true for lints that are registered by external tools like Clippy (I had to look at https://github.com/rust-lang/rust/pull/116412 to know what the variable meant). So I renamed `is_loaded` to `is_externally_loaded` and added some docs.
Couldn't find documentation supporting that single-variant
`#[repr(Rust)]` enums with RHS assigned work as expected with this
change.
```rust
enum Variants {
A = 17,
} // Would this be zero sized optimized guaranteed?
```
panic_str only exists for the migration to 2021 panic macros
The only caller is `expect_failed`, which is already a cold inline(never) function, so inlining into that function should be fine. (And indeed `panic_str` was `#[inline]` anyway.)
The existence of panic_str risks someone calling it when they should call `panic` instead, and I can't see a reason why this footgun should exist.
I also extended the comment in `panic` to explain why it needs a `'static` string -- I know I've wondered about this in the past and it took me quite a while to understand.
Rollup of 7 pull requests
Successful merges:
- #123680 (Deny gen keyword in `edition_2024_compat` lints)
- #124057 (Fix ICE when ADT tail has type error)
- #124168 (Use `DefiningOpaqueTypes::Yes` in rustdoc, where the `InferCtxt` is guaranteed to have no opaque types it can define)
- #124197 (Move duplicated code in functions in `tests/rustdoc-gui/notable-trait.goml`)
- #124200 (Improve handling of expr->field errors)
- #124220 (Miri: detect wrong vtables in wide pointers)
- #124266 (remove an unused type from the reentrant lock tests)
r? `@ghost`
`@rustbot` modify labels: rollup
Deny gen keyword in `edition_2024_compat` lints
Splits the `keyword_idents` lint into two -- `keyword_idents_2018` and `keyword_idents_2024` -- since each corresponds to a future-compat warning in a different edition. Group these together into a new `keyword_idents` lint group, and add the latter to the `rust_2024_compatibility` so that `gen` is ready for the 2024 edition.
cc `@traviscross` `@ehuss`
Fix trait solver overflow with `non_local_definitions` lint
This PR fixes the trait solver overflow with the `non_local_definitions` lint reported in https://github.com/rust-lang/rust/issues/123573 using the suggestion from `@lcnr:` https://github.com/rust-lang/rust/issues/123573#issuecomment-2041348320 to use the next trait solver.
~~I have not (yet) tried to create a minimized repro~~ ``@compiler-errors`` did the minimization (thanks you) but I have manually tested on the `starlark-rust` project that it fixes the issue.
Fixes#123573
r? `@lcnr`
Stabilize checking of cfgs at compile-time: `--check-cfg` option
This PR stabilize the `--check-cfg` CLI option of `rustc` (and `rustdoc`) 🎉.
In particular this PR does two things:
1. it makes the `--check-cfg` option stable
2. and it moves the documentation to the stable books
FCP: https://github.com/rust-lang/rust/issues/82450#issuecomment-1965328542Resolves#82450
``@rustbot`` labels +S-blocked +F-check-cfg
r? ``@petrochenkov``
Implement syntax for `impl Trait` to specify its captures explicitly (`feature(precise_capturing)`)
Implements `impl use<'a, 'b, T, U> Sized` syntax that allows users to explicitly list the captured parameters for an opaque, rather than inferring it from the opaque's bounds (or capturing *all* lifetimes under 2024-edition capture rules). This allows us to exclude some implicit captures, so this syntax may be used as a migration strategy for changes due to #117587.
We represent this list of captured params as `PreciseCapturingArg` in AST and HIR, resolving them between `rustc_resolve` and `resolve_bound_vars`. Later on, we validate that the opaques only capture the parameters in this list.
We artificially limit the feature to *require* mentioning all type and const parameters, since we don't currently have support for non-lifetime bivariant generics. This can be relaxed in the future.
We also may need to limit this to require naming *all* lifetime parameters for RPITIT, since GATs have no variance. I have to investigate this. This can also be relaxed in the future.
r? `@oli-obk`
Tracking issue:
- https://github.com/rust-lang/rust/issues/123432
Skip `unused_parens` report for `Paren(Path(..))` in macro.
fixes#120642
In following code, `unused_parens` suggest change `<($($rest),*)>::bar()` to `<$rest>::bar()` which will cause another err: `error: variable 'rest' is still repeating at this depth`:
```rust
trait Foo {
fn bar();
}
macro_rules! problem {
($ty:ident) => {
impl<$ty: Foo> Foo for ($ty,) {
fn bar() { <$ty>::bar() }
}
};
($ty:ident $(, $rest:ident)*) => {
impl<$ty: Foo, $($rest: Foo),*> Foo for ($ty, $($rest),*) {
fn bar() {
<$ty>::bar();
<($($rest),*)>::bar()
}
}
problem!($($rest),*);
}
}
```
I think maybe we can handle this by avoid warning for `Paren(Path(..))` in the macro. Is this reasonable approach?
Implement minimal, internal-only pattern types in the type system
rebase of https://github.com/rust-lang/rust/pull/107606
You can create pattern types with `std::pat::pattern_type!(ty is pat)`. The feature is incomplete and will panic on you if you use any pattern other than integral range patterns. The only way to create or deconstruct a pattern type is via `transmute`.
This PR's implementation differs from the MCP's text. Specifically
> This means you could implement different traits for different pattern types with the same base type. Thus, we just forbid implementing any traits for pattern types.
is violated in this PR. The reason is that we do need impls after all in order to make them usable as fields. constants of type `std::time::Nanoseconds` struct are used in patterns, so the type must be structural-eq, which it only can be if you derive several traits on it. It doesn't need to be structural-eq recursively, so we can just manually implement the relevant traits on the pattern type and use the pattern type as a private field.
Waiting on:
* [x] move all unrelated commits into their own PRs.
* [x] fix niche computation (see 2db07f94f44f078daffe5823680d07d4fded883f)
* [x] add lots more tests
* [x] T-types MCP https://github.com/rust-lang/types-team/issues/126 to finish
* [x] some commit cleanup
* [x] full self-review
* [x] remove 61bd325da19a918cc3e02bbbdce97281a389c648, it's not necessary anymore I think.
* [ ] ~~make sure we never accidentally leak pattern types to user code (add stability checks or feature gate checks and appopriate tests)~~ we don't even do this for the new float primitives
* [x] get approval that [the scope expansion to trait impls](https://rust-lang.zulipchat.com/#narrow/stream/326866-t-types.2Fnominated/topic/Pattern.20types.20types-team.23126/near/427670099) is ok
r? `@BoxyUwU`
Add consistency with phrases "meantime" and "mean time"
"mean time" is used in a few places while "meantime" is used everywhere else; this would make usage consistent throughout the codebase.
Add detection of [Partial]Ord methods in the `ambiguous_wide_pointer_comparisons` lint
Partially addresses https://github.com/rust-lang/rust/issues/121264 by adding diagnostics items for PartialOrd and Ord methods, detecting such diagnostics items as "binary operation" and suggesting the correct replacement.
I also took the opportunity to change the suggestion to use new methods `.cast()` on `*mut T` an d `*const T`.
Rename `hir::Local` into `hir::LetStmt`
Follow-up of #122776.
As discussed on [zulip](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Improve.20naming.20of.20.60ExprKind.3A.3ALet.60.3F).
I made this change into a separate PR because I'm less sure about this change as is. For example, we have `visit_local` and `LocalSource` items. Is it fine to keep these two as is (I supposed it is but I prefer to ask) or not? Having `Node::Local(LetStmt)` makes things more explicit but is it going too far?
r? ```@oli-obk```
Rollup of 8 pull requests
Successful merges:
- #114009 (compiler: allow transmute of ZST arrays with generics)
- #122195 (Note that the caller chooses a type for type param)
- #122651 (Suggest `_` for missing generic arguments in turbofish)
- #122784 (Add `tag_for_variant` query)
- #122839 (Split out `PredicatePolarity` from `ImplPolarity`)
- #122873 (Merge my contributor emails into one using mailmap)
- #122885 (Adjust better spastorino membership to triagebot's adhoc_groups)
- #122888 (add a couple more tests)
r? `@ghost`
`@rustbot` modify labels: rollup
Experimental feature postfix match
This has a basic experimental implementation for the RFC postfix match (rust-lang/rfcs#3295, #121618). [Liaison is](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Postfix.20Match.20Liaison/near/423301844) ```@scottmcm``` with the lang team's [experimental feature gate process](https://github.com/rust-lang/lang-team/blob/master/src/how_to/experiment.md).
This feature has had an RFC for a while, and there has been discussion on it for a while. It would probably be valuable to see it out in the field rather than continue discussing it. This feature also allows to see how popular postfix expressions like this are for the postfix macros RFC, as those will take more time to implement.
It is entirely implemented in the parser, so it should be relatively easy to remove if needed.
This PR is split in to 5 commits to ease review.
1. The implementation of the feature & gating.
2. Add a MatchKind field, fix uses, fix pretty.
3. Basic rustfmt impl, as rustfmt crashes upon seeing this syntax without a fix.
4. Add new MatchSource to HIR for Clippy & other HIR consumers
Provide structured suggestion for `#![feature(foo)]`
```
error: `S2<'_>` is forbidden as the type of a const generic parameter
--> $DIR/lifetime-in-const-param.rs:5:23
|
LL | struct S<'a, const N: S2>(&'a ());
| ^^
|
= note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
|
LL + #![feature(adt_const_params)]
|
```
Fix#55941.
```
error: `S2<'_>` is forbidden as the type of a const generic parameter
--> $DIR/lifetime-in-const-param.rs:5:23
|
LL | struct S<'a, const N: S2>(&'a ());
| ^^
|
= note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
|
LL + #![feature(adt_const_params)]
|
```
Fix#55941.
Move check-cfg diagnostic logic into a separate file
as well as adding some triagebot mentions (for me) for check-cfg related files.
``@rustbot`` label +F-check-cfg
Split refining_impl_trait lint into _reachable, _internal variants
As discussed in https://github.com/rust-lang/rust/issues/119535#issuecomment-1909352040:
> We discussed this today in triage and developed a consensus to:
>
> * Add a separate lint against impls that refine a return type defined with RPITIT even when the trait is not crate public.
> * Place that in a lint group along with the analogous crate public lint.
> * Create an issue to solicit feedback on these lints (or perhaps two separate ones).
> * Have the warnings displayed with each lint reference this issue in a similar manner to how we do that today with the required `Self: '0'` bound on GATs.
> * Make a note to review this feedback on 2-3 release cycles.
This points users to https://github.com/rust-lang/rust/issues/121718 to leave feedback.
`f16` and `f128` step 3: compiler support & feature gate
Continuation of https://github.com/rust-lang/rust/pull/121841, another portion of https://github.com/rust-lang/rust/pull/114607
This PR exposes the new types to the world and adds a feature gate. Marking this as a draft because I need some feedback on where I did the feature gate check. It also does not yet catch type via suffixed literals (so the feature gate test will fail, probably some others too because I haven't belssed).
If there is a better place to check all types after resolution, I can do that. If not, I figure maybe I can add a second gate location in AST when it checks numeric suffixes.
Unfortunately I still don't think there is much testing to be done for correctness (codegen tests or parsed value checks) until we have basic library support. I think that will be the next step.
Tracking issue: https://github.com/rust-lang/rust/issues/116909
r? `@compiler-errors`
cc `@Nilstrieb`
`@rustbot` label +F-f16_and_f128
Create some minimal HIR for associated opaque types
`LocalDefId`s for opaque types in traits and impls are created after AST -> HIR lowering, so they don't have corresponding HIR and return their various properties through fed queries.
In this PR I also feed some core HIR-related queries for these `LocalDefId`s (which happen to be HIR owners).
As a result all `LocalDefId`s now have corresponding `HirId`s and HIR nodes, and "optional" methods like `opt_local_def_id_to_hir_id` and `opt_hir_node_by_def_id` can be removed.
Follow up to https://github.com/rust-lang/rust/pull/120206.
- Replace some nested if-let with let-chains
- Tweak a match pattern to allow shorthand struct syntax
- Fuse an `is_empty` check with getting the last element
- Merge some common code that emits `MalformedAttribute` and continues
- Format `"{tool}::{name}"` in a way that's consistent with other match arms
- Replace if-let-else-panic with let-else
- Use early-exit to flatten a method body
The internal diagnostic lint currently only allows one, because that was
all that occurred in practice. But rust-lang/rust-clippy/pull/12453
wants to introduce functions with more than one, and this limitation is
getting in the way.
Add a tidy check that checks whether the fluent slugs only appear once
As ``````@Nilstrieb`````` said in https://github.com/rust-lang/rust/pull/121828#issuecomment-1972622855:
> Might make sense to have a tidy check that checks whether the fluent slugs only appear once in the source code and lint for that
there's a tidy check already for sorting
We can get the tidy check error:
```
tidy check
tidy error: /path/to/rust/compiler/rustc_const_eval/messages.ftl: message `const_eval_invalid_align` is not used
tidy error: /path/to/rust/compiler/rustc_lint/messages.ftl: message `lint_trivial_untranslatable_diag` is not used
tidy error: /path/to/rust/compiler/rustc_parse/messages.ftl: message `parse_invalid_literal_suffix` is not used
tidy error: /path/to/rust/compiler/rustc_infer/messages.ftl: message `infer_need_type_info_in_coroutine` is not used
tidy error: /path/to/rust/compiler/rustc_passes/messages.ftl: message `passes_expr_not_allowed_in_context` is not used
tidy error: /path/to/rust/compiler/rustc_passes/messages.ftl: message `passes_layout` is not used
tidy error: /path/to/rust/compiler/rustc_parse/messages.ftl: message `parse_not_supported` is not used
```
r? ``````@Nilstrieb``````
Misc improvements to non local defs lint implementation
This PR is a collection of small improvements I found when I [needlessly tried](https://www.github.com/rust-lang/rust/pull/120393#issuecomment-1971787475) to fix a "perf-regression" in the lint implementation.
I recommend looking at each commit individually.
Use `ControlFlow` in visitors.
Follow up to #121256
This does have a few small behaviour changes in some diagnostic output where the visitor will now find the first match rather than the last match. The change in `find_anon_types.rs` has the only affected test. I don't see this being an issue as the last occurrence isn't any better of a choice than the first.
Rollup of 9 pull requests
Successful merges:
- #121958 (Fix redundant import errors for preload extern crate)
- #121976 (Add an option to have an external download/bootstrap cache)
- #122022 (loongarch: add frecipe and relax target feature)
- #122026 (Do not try to format removed files)
- #122027 (Uplift some feeding out of `associated_type_for_impl_trait_in_impl` and into queries)
- #122063 (Make the lowering of `thir::ExprKind::If` easier to follow)
- #122074 (Add missing PartialOrd trait implementation doc for array)
- #122082 (remove outdated fixme comment)
- #122091 (Note why we're using a new thread in `test_get_os_named_thread`)
r? `@ghost`
`@rustbot` modify labels: rollup
Rework `untranslatable_diagnostic` lint
Currently it only checks calls to functions marked with `#[rustc_lint_diagnostics]`. This PR changes it to check calls to any function with an `impl Into<{D,Subd}iagnosticMessage>` parameter. This greatly improves its coverage and doesn't rely on people remembering to add `#[rustc_lint_diagnostics]`. It also lets us add `#[rustc_lint_diagnostics]` to a number of functions that don't have an `impl Into<{D,Subd}iagnosticMessage>`, such as `Diag::span`.
r? ``@davidtwco``
Currently it only checks calls to functions marked with
`#[rustc_lint_diagnostics]`. This commit changes it to check calls to
any function with an `impl Into<{D,Subd}iagMessage>` parameter. This
greatly improves its coverage and doesn't rely on people remembering to
add `#[rustc_lint_diagnostics]`.
The commit also adds `#[allow(rustc::untranslatable_diagnostic)`]
attributes to places that need it that are caught by the improved lint.
These places that might be easy to convert to translatable diagnostics.
Finally, it also:
- Expands and corrects some comments.
- Does some minor formatting improvements.
- Adds missing `DecorateLint` cases to
`tests/ui-fulldeps/internal-lints/diagnostics.rs`.
Rollup of 8 pull requests
Successful merges:
- #121202 (Limit the number of names and values in check-cfg diagnostics)
- #121301 (errors: share `SilentEmitter` between rustc and rustfmt)
- #121658 (Hint user to update nightly on ICEs produced from outdated nightly)
- #121846 (only compare ambiguity item that have hard error)
- #121961 (add test for #78894#71450)
- #121975 (hir_analysis: enums return `None` in `find_field`)
- #121978 (Fix duplicated path in the "not found dylib" error)
- #121991 (Merge impl_trait_in_assoc_types_defined_by query back into `opaque_types_defined_by`)
r? `@ghost`
`@rustbot` modify labels: rollup
Add a scheme for moving away from `extern "rust-intrinsic"` entirely
All `rust-intrinsic`s can become free functions now, either with a fallback body, or with a dummy body and an attribute, requiring backends to actually implement the intrinsic.
This PR demonstrates the dummy-body scheme with the `vtable_size` intrinsic.
cc https://github.com/rust-lang/rust/issues/63585
follow-up to #120500
MCP at https://github.com/rust-lang/compiler-team/issues/720
Existing names for values of this type are `sess`, `parse_sess`,
`parse_session`, and `ps`. `sess` is particularly annoying because
that's also used for `Session` values, which are often co-located, and
it can be difficult to know which type a value named `sess` refers to.
(That annoyance is the main motivation for this change.) `psess` is nice
and short, which is good for a name used this much.
The commit also renames some `parse_sess_created` values as
`psess_created`.
make unused_imports less assertive in test modules
closes#121502
This is a fairly small change and I used the fix suggested in the example expected error message.
Not sure if I should've rather used the alternatives but this one seems the most descriptive.
Some alternatives:
- if this is meant to be a test module, add `#[cfg(test)]` to the containing module
- try adding #[cfg(test)] to this test module
- consider adding #[allow(unused_imports)] if you want to silent the lint on the unused import
- consider removing the unused import
Add stubs in IR and ABI for `f16` and `f128`
This is the very first step toward the changes in https://github.com/rust-lang/rust/pull/114607 and the [`f16` and `f128` RFC](https://rust-lang.github.io/rfcs/3453-f16-and-f128.html). It adds the types to `rustc_type_ir::FloatTy` and `rustc_abi::Primitive`, and just propagates those out as `unimplemented!` stubs where necessary.
These types do not parse yet so there is no feature gate, and it should be okay to use `unimplemented!`.
The next steps will probably be AST support with parsing and the feature gate.
r? `@compiler-errors`
cc `@Nilstrieb` suggested breaking the PR up in https://github.com/rust-lang/rust/pull/120645#issuecomment-1925900572
Detect empty leading where clauses on type aliases
1. commit: refactor the AST of type alias where clauses
* I could no longer bear the look of `.0.1` and `.1.0`
* Arguably moving `split` out of `TyAlias` into a substruct might not make that much sense from a semantic standpoint since it reprs an index into `TyAlias.predicates` but it's alright and it cleans up the usage sites of `TyAlias`
2. commit: fix an oversight: An empty leading where clause is still a leading where clause
* semantically reject empty leading where clauses on lazy type aliases
* e.g., on `#![feature(lazy_type_alias)] type X where = ();`
* make empty leading where clauses on assoc types trigger lint `deprecated_where_clause_location`
* e.g., `impl Trait for () { type X where = (); }`
Diagnostic renaming
Renaming various diagnostic types from `Diagnostic*` to `Diag*`. Part of https://github.com/rust-lang/compiler-team/issues/722. There are more to do but this is enough for one PR.
r? `@davidtwco`
It's a specialized form of the `UntranslatableDiagnostic` lint that is
deny-by-default.
Now that `UntranslatableDiagnostic` has been changed from
allow-by-default to deny-by-default, the trivial variant is no longer
needed.
Split Diagnostics for Uncommon Codepoints: Add Individual Identifier Types
This pull request further modifies the `uncommon_codepoints` lint, adding the individual identifier types of `Technical`, `Not_NFKC`, `Exclusion` and `Limited_Use` to the diagnostic message.
Example rendered diagnostic:
```
error: identifier contains a Unicode codepoint that is not used in normalized strings: 'ij'
--> $DIR/lint-uncommon-codepoints.rs:6:4
|
LL | fn dijkstra() {}
| ^^^^^^^
= note: this character is included in the Not_NFKC Unicode general security profile
```
Second step of #120228.
Add newtypes for bool fields/params/return types
Fixed all the cases of this found with some simple searches for `*/ bool` and `bool /*`; probably many more
When encountering `<&T as Clone>::clone(x)` because `T: Clone`, suggest `#[derive(Clone)]`
CC #40699.
```
warning: call to `.clone()` on a reference in this situation does nothing
--> $DIR/noop-method-call.rs:23:71
|
LL | let non_clone_type_ref_clone: &PlainType<u32> = non_clone_type_ref.clone();
| ^^^^^^^^
|
= note: the type `PlainType<u32>` does not implement `Clone`, so calling `clone` on `&PlainType<u32>` copies the reference, which does not do anything and can be removed
help: remove this redundant call
|
LL - let non_clone_type_ref_clone: &PlainType<u32> = non_clone_type_ref.clone();
LL + let non_clone_type_ref_clone: &PlainType<u32> = non_clone_type_ref;
|
help: if you meant to clone `PlainType<u32>`, implement `Clone` for it
|
LL + #[derive(Clone)]
LL | struct PlainType<T>(T);
|
```
Downgrade ambiguous_wide_pointer_comparisons suggestions to MaybeIncorrect
In certain cases like #121330, it is possible to have more than one suggestion from the `ambiguous_wide_pointer_comparisons` lint (which before this PR are `MachineApplicable`). When this gets passed to rustfix, rustfix makes *multiple* changes according to the suggestions which result in incorrect code.
This is a temporary workaround. The real long term solution to problems like these is to address <https://github.com/rust-lang/rust/issues/53934>.
This PR also includes a drive-by edit to the panic message emitted by compiletest because "ui" test suite now uses `//`@`` directives.
Fixes#121330.
It is possible to have more than one valid suggestion, which when
applied together via rustfix causes the code to no longer compile.
This is a temporary workaround; the real long term solution to these
issues is to solve <https://github.com/rust-lang/rust/issues/53934>.
Trigger `unsafe_code` lint on invocations of `global_asm`
`unsafe_code` already warns about things that don't involve the `unsafe` keyword, e.g. `#[no_mangle]`. This makes it warn on `core::arch::global_asm` too.
Fixes#103078
Overhaul `Diagnostic` and `DiagnosticBuilder`
Implements the first part of https://github.com/rust-lang/compiler-team/issues/722, which moves functionality and use away from `Diagnostic`, onto `DiagnosticBuilder`.
Likely follow-ups:
- Move things around, because this PR was written to minimize diff size, so some things end up in sub-optimal places. E.g. `DiagnosticBuilder` has impls in both `diagnostic.rs` and `diagnostic_builder.rs`.
- Rename `Diagnostic` as `DiagInner` and `DiagnosticBuilder` as `Diag`.
r? `@davidtwco`
Always evaluate free constants and statics, even if previous errors occurred
work towards https://github.com/rust-lang/rust/issues/79738
We will need to evaluate static items before the `definitions.freeze()` below, as we will start creating new `DefId`s (for nested allocations) within the `eval_static_initializer` query.
But even without that motivation, this is a good change. Hard errors should always be reported and not silenced if other errors happened earlier.
Currently many diagnostic modifier methods are available on both
`Diagnostic` and `DiagnosticBuilder`. This commit removes most of them
from `Diagnostic`. To minimize the diff size, it keeps them within
`diagnostic.rs` but changes the surrounding `impl Diagnostic` block to
`impl DiagnosticBuilder`. (I intend to move things around later, to give
a more sensible code layout.)
`Diagnostic` keeps a few methods that it still needs, like `sub`,
`arg`, and `replace_args`.
The `forward!` macro, which defined two additional methods per call
(e.g. `note` and `with_note`), is replaced by the `with_fn!` macro,
which defines one additional method per call (e.g. `with_note`). It's
now also only used when necessary -- not all modifier methods currently
need a `with_*` form. (New ones can be easily added as necessary.)
All this also requires changing `trait AddToDiagnostic` so its methods
take `DiagnosticBuilder` instead of `Diagnostic`, which leads to many
mechanical changes. `SubdiagnosticMessageOp` gains a type parameter `G`.
There are three subdiagnostics -- `DelayedAtWithoutNewline`,
`DelayedAtWithNewline`, and `InvalidFlushedDelayedDiagnosticLevel` --
that are created within the diagnostics machinery and appended to
external diagnostics. These are handled at the `Diagnostic` level, which
means it's now hard to construct them via `derive(Diagnostic)`, so
instead we construct them by hand. This has no effect on what they look
like when printed.
There are lots of new `allow` markers for `untranslatable_diagnostics`
and `diagnostics_outside_of_impl`. This is because
`#[rustc_lint_diagnostics]` annotations were present on the `Diagnostic`
modifier methods, but missing from the `DiagnosticBuilder` modifier
methods. They're now present.
errors: only eagerly translate subdiagnostics
Subdiagnostics don't need to be lazily translated, they can always be eagerly translated. Eager translation is slightly more complex as we need to have a `DiagCtxt` available to perform the translation, which involves slightly more threading of that context.
This slight increase in complexity should enable later simplifications - like passing `DiagCtxt` into `AddToDiagnostic` and moving Fluent messages into the diagnostic structs rather than having them in separate files (working on that was what led to this change).
r? ```@nnethercote```
Implement intrinsics with fallback bodies
fixes#93145 (though we can port many more intrinsics)
cc #63585
The way this works is that the backend logic for generating custom code for intrinsics has been made fallible. The only failure path is "this intrinsic is unknown". The `Instance` (that was `InstanceDef::Intrinsic`) then gets converted to `InstanceDef::Item`, which represents the fallback body. A regular function call to that body is then codegenned. This is currently implemented for
* codegen_ssa (so llvm and gcc)
* codegen_cranelift
other backends will need to adjust, but they can just keep doing what they were doing if they prefer (though adding new intrinsics to the compiler will then require them to implement them, instead of getting the fallback body).
cc `@scottmcm` `@WaffleLapkin`
### todo
* [ ] miri support
* [x] default intrinsic name to name of function instead of requiring it to be specified in attribute
* [x] make sure that the bodies are always available (must be collected for metadata)
Subdiagnostics don't need to be lazily translated, they can always be
eagerly translated. Eager translation is slightly more complex as we need
to have a `DiagCtxt` available to perform the translation, which involves
slightly more threading of that context.
This slight increase in complexity should enable later simplifications -
like passing `DiagCtxt` into `AddToDiagnostic` and moving Fluent messages
into the diagnostic structs rather than having them in separate files
(working on that was what led to this change).
Signed-off-by: David Wood <david@davidtw.co>
For some cases where it's clear that an error has already occurred,
e.g.:
- there's a comment stating exactly that, or
- things like HIR lowering, where we are lowering an error kind
The commit also tweaks some comments around delayed bug sites.
Remove unnecessary `#![feature(min_specialization)]`
As of #119963 and #120676, we can now rely on `newtype_index!` having `#[allow_internal_unstable(min_specialization)]`, so there are a few compiler crates that no longer need to include min-spec in their own crate features.
---
Some of the expansions of `newtype_index!` still appear to require min-spec in the crate features. I think this is because `#[orderable]` causes the expansion to include an implementation of `TrustedStep`, which is flagged with `#[rustc_specialization_trait]`, and for whatever reason that isn't permitted by allow-internal-unstable. So this PR only touches the crates where that isn't the case.
Avoid a collection and iteration on empty passes
Just some mini optimization I saw in the wild. This way, we avoid a `collect` and `map` on an empty `passes`. Honestly, I don't even think this is big enough of a change to make a benchmark, but I'd still like to see results.
Based on [this book](https://nnethercote.github.io/perf-book/iterators.html#collect-and-extend)
Invert diagnostic lints.
That is, change `diagnostic_outside_of_impl` and `untranslatable_diagnostic` from `allow` to `deny`, because more than half of the compiler has been converted to use translated diagnostics.
This commit removes more `deny` attributes than it adds `allow` attributes, which proves that this change is warranted.
r? ````@davidtwco````
Introduce `enter_forall` to supercede `instantiate_binder_with_placeholders`
r? `@lcnr`
Long term we'd like to experiment with decrementing the universe count after "exiting" binders so that we do not end up creating infer vars in non-root universes even when they logically reside in the root universe. The fact that we dont do this currently results in a number of issues in the new trait solver where we consider goals to be ambiguous because otherwise it would require lowering the universe of an infer var. i.e. the goal `?x.0 eq <T as Trait<?y.1>>::Assoc` where the alias is rigid would not be able to instantiate `?x` with the alias as there would be a universe error.
This PR is the first-ish sort of step towards being able to implement this as eventually we would want to decrement the universe in `enter_forall`. Unfortunately its Difficult to actually implement decrementing universes nicely so this is a separate step which moves us closer to the long term goal ✨
update indirect structural match lints to match RFC and to show up for dependencies
This is a large step towards implementing https://github.com/rust-lang/rfcs/pull/3535.
We currently have five lints related to "the structural match situation":
- nontrivial_structural_match
- indirect_structural_match
- pointer_structural_match
- const_patterns_without_partial_eq
- illegal_floating_point_literal_pattern
This PR concerns the first 3 of them. (The 4th already is set up to show for dependencies, and the 5th is removed by https://github.com/rust-lang/rust/pull/116284.) nontrivial_structural_match is being removed as per the RFC; the other two are enabled to show up in dependencies.
Fixes https://github.com/rust-lang/rust/issues/73448 by removing the affected analysis.
That is, change `diagnostic_outside_of_impl` and
`untranslatable_diagnostic` from `allow` to `deny`, because more than
half of the compiler has be converted to use translated diagnostics.
This commit removes more `deny` attributes than it adds `allow`
attributes, which proves that this change is warranted.
make matching on NaN a hard error, and remove the rest of illegal_floating_point_literal_pattern
These arms would never be hit anyway, so the pattern makes little sense. We have had a future-compat lint against float matches in general for a *long* time, so I hope we can get away with immediately making this a hard error.
This is part of implementing https://github.com/rust-lang/rfcs/pull/3535.
Closes https://github.com/rust-lang/rust/issues/41620 by removing the lint.
https://github.com/rust-lang/reference/pull/1456 updates the reference to match.
Error codes are integers, but `String` is used everywhere to represent
them. Gross!
This commit introduces `ErrCode`, an integral newtype for error codes,
replacing `String`. It also introduces a constant for every error code,
e.g. `E0123`, and removes the `error_code!` macro. The constants are
imported wherever used with `use rustc_errors::codes::*`.
With the old code, we have three different ways to specify an error code
at a use point:
```
error_code!(E0123) // macro call
struct_span_code_err!(dcx, span, E0123, "msg"); // bare ident arg to macro call
\#[diag(name, code = "E0123")] // string
struct Diag;
```
With the new code, they all use the `E0123` constant.
```
E0123 // constant
struct_span_code_err!(dcx, span, E0123, "msg"); // constant
\#[diag(name, code = E0123)] // constant
struct Diag;
```
The commit also changes the structure of the error code definitions:
- `rustc_error_codes` now just defines a higher-order macro listing the
used error codes and nothing else.
- Because that's now the only thing in the `rustc_error_codes` crate, I
moved it into the `lib.rs` file and removed the `error_codes.rs` file.
- `rustc_errors` uses that macro to define everything, e.g. the error
code constants and the `DIAGNOSTIC_TABLES`. This is in its new
`codes.rs` file.
Don't fire `OPAQUE_HIDDEN_INFERRED_BOUND` on sized return of AFIT
Conceptually, we should probably not fire `OPAQUE_HIDDEN_INFERRED_BOUND` for methods like:
```
trait Foo { async fn bar() -> Self; }
```
Even though we technically cannot prove that `Self: Sized`, which is one of the item bounds of the `Output` type in the `-> impl Future<Output = Sized>` from the async desugaring.
This is somewhat justifiable along the same lines as how we allow regular methods to return `-> Self` even though `Self` isn't sized.
Fixes#113538
(side-note: some days i wonder if we should just remove the `OPAQUE_HIDDEN_INFERRED_BOUND` lint... it does make me sad that we have non-well-formed types in signatures, though.)
Revert stabilization of trait_upcasting feature
Reverts #118133
This reverts commit 6d2b84b3ed, reversing changes made to 73bc12199e.
The feature has a soundness bug:
* #120222
It is unclear to me whether we'll actually want to destabilize, but I thought it was still prudent to open the PR for easy destabilization once we get there.
Pack u128 in the compiler to mitigate new alignment
This is based on #116672, adding a new `#[repr(packed(8))]` wrapper on `u128` to avoid changing any of the compiler's size assertions. This is needed in two places:
* `SwitchTargets`, otherwise its `SmallVec<[u128; 1]>` gets padded up to 32 bytes.
* `LitKind::Int`, so that entire `enum` can stay 24 bytes.
* This change definitely has far-reaching effects though, since it's public.