about summary refs log tree commit diff
path: root/compiler/rustc_lint/src
AgeCommit message (Collapse)AuthorLines
2024-08-07unused_parens: do not lint against parens around &rawRalf Jung-0/+7
2024-08-07Disallow setting built-in cfgs via set the command-lineUrgau-0/+13
2024-08-07Make `Span` optional in `BufferedEarlyLint`Urgau-3/+17
2024-08-07Use more slice patterns inside the compilerLeón Orell Valerian Liehr-14/+9
2024-08-06Rollup merge of #128517 - clubby789:overflowing-lit-span, r=petrochenkovMatthias Krüger-9/+13
Fallback to string formatting if source is not available for lint Fixes #128445
2024-08-06Rollup merge of #128369 - GrigorenkoPV:let-underscore-translatable, r=davidtwcoMatthias Krüger-6/+7
rustc_lint: make `let-underscore-lock` translatable
2024-08-06Add a special case for CStr/CString in the improper_ctypes lintFlying-Toast-15/+39
Instead of saying to "consider adding a `#[repr(C)]` or `#[repr(transparent)]` attribute to this struct", we now tell users to "Use `*const ffi::c_char` instead, and pass the value from `CStr::as_ptr()`" when the type involved is a `CStr` or a `CString`. Co-authored-by: Jieyou Xu <jieyouxu@outlook.com>
2024-08-05Rollup merge of #127907 - RalfJung:byte_slice_in_packed_struct_with_derive, ↵Matthias Krüger-1/+6
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-03Rollup merge of #128368 - nnethercote:rustfmt-tweaks, r=cuviperMatthias Krüger-2/+2
Formatting tweaks Some small post-#125443 formatting tweaks. r? ``@cuviper``
2024-08-01Fallback to string formatting if source is not availableclubby789-9/+13
2024-08-01interpret: simplify pointer arithmetic logicRalf Jung-5/+1
2024-07-31Temporarily switch `ambiguous_negative_literals` lint to allowUrgau-1/+2
2024-07-30rustc_lint: make `let-underscore-lock` translatablePavel Grigorenko-6/+7
2024-07-30Insert some blank lines.Nicholas Nethercote-2/+2
After things that are immediately followed by a `use` declaration and look like they might apply to that `use` item but actually don't.
2024-07-29Reformat `use` declarations.Nicholas Nethercote-272/+265
The previous commit updated `rustfmt.toml` appropriately. This commit is the outcome of running `x fmt --all` with the new formatting options.
2024-07-27built-in derive: remove BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE hack and lintRalf Jung-1/+6
2024-07-26Auto merge of #121676 - Bryanskiy:polarity, r=petrochenkovbors-4/+6
Support ?Trait bounds in supertraits and dyn Trait under a feature gate This patch allows `maybe` polarity bounds under a feature gate. The only language change here is that corresponding hard errors are replaced by feature gates. Example: ```rust #![feature(allow_maybe_polarity)] ... trait Trait1 : ?Trait { ... } // ok fn foo(_: Box<(dyn Trait2 + ?Trait)>) {} // ok fn bar<T: ?Sized + ?Trait>(_: &T) {} // ok ``` Maybe bounds still don't do anything (except for `Sized` trait), however this patch will allow us to [experiment with default auto traits](https://github.com/rust-lang/rust/pull/120706#issuecomment-1934006762). This is a part of the [MCP: Low level components for async drop](https://github.com/rust-lang/compiler-team/issues/727)
2024-07-26Rollup merge of #126575 - fmease:update-lint-type_alias_bounds, ↵Trevor Gross-126/+154
r=compiler-errors Make it crystal clear what lint `type_alias_bounds` actually signifies This is part of my work on https://github.com/rust-lang/rust/labels/F-lazy_type_alias ([tracking issue](#112792)). --- To recap, the lint `type_alias_bounds` detects bounds on generic parameters and where clauses on (eager) type aliases. These bounds should've never been allowed because they are currently neither enforced[^1] at usage sites of type aliases nor thoroughly checked for correctness at definition sites due to the way type aliases are represented in the compiler. Allowing them was an oversight. Explicitly label this as a known limitation of the type checker/system and establish the experimental feature `lazy_type_alias` as its eventual proper solution. Where this becomes a bit tricky (for me as a rustc dev) are the "secondary effects" of these bounds whose existence I sadly can't deny. As a matter of fact, type alias bounds do play some small roles during type checking. However, after a lot of thinking over the last two weeks I've come to the conclusion (not without second-guessing myself though) that these use cases should not trump the fact that these bounds are currently *inherently broken*. Therefore the lint `type_alias_bounds` should and will continue to flag bounds that may have subordinate uses. The two *known* secondary effects are: 1. They may enable the use of "shorthand" associated type paths `T::Assoc` (as opposed to fully qualified paths `<T as Trait>::Assoc`) where `T` is a type param bounded by some trait `Trait` which defines that assoc ty. 2. They may affect the default lifetime of trait object types passed as a type argument to the type alias. That concept is called (trait) object lifetime default. The second one is negligible, no question asked. The first one however is actually "kinda nice" (for writability) and comes up in practice from time to time. So why don't I just special-case trait bounds that "define" shorthand assoc type paths as originally planned in #125709? 1. Starting to permit even a tiny subset of bounds would already be enough to send a signal to users that bounds in type aliases have been legitimized and that they can expect to see type alias bounds in the wild from now on (proliferation). This would be actively misleading and dangerous because those bounds don't behave at all like one would expect, they are *not real*[^2]! 1. Let's take `type A<T: Trait> = T::Proj;` for example. Everywhere else in the language `T: Trait` means `T: Trait + Sized`. For type aliases, that's not the case though: `T: Trait` and `T: Trait + ?Sized` for that matter do neither mean `T: Trait + Sized` nor `T: Trait + ?Sized` (for both!). Instead, whether `T` requires `Sized` or not entirely depends on the definition of `Trait`[^2]. Namely, whether or not it is bounded by `Sized`. 2. Given `type A<T: Trait<AssocA = ()>> = T::AssocB;`, while `X: Trait` gets checked given `A<X>` (by virtue of projection wfchecking post alias expansion[^2]), the associated type constraint `AssocA = ()` gets dropped entirely! While we could choose to warn on such cases, it would inevitably lead to a huge pile of special cases. 3. While it's common knowledge that the body / aliased type / RHS of an (eager) type alias does not get checked for well-formedness, I'm not sure if people would realize that that extends to bounds as well. Namely, `type A<T: Trait<[u8]>> = T::Proj;` compiles even if `Trait`'s generic parameter requires `Sized`. Of course, at usage sites `[u8]: Sized` would still end up getting checked[^2], so it's not a huge problem if you have full control over `A`. However, imagine that `A` was actually part of a public API and was never used inside the defining crate (not unreasonable). In such a scenario, downstream users would be presented with an impossible to use type alias! Remember, bounds may grow arbitrarily complex and nuanced in practice. 4. Even if we allowed trait bounds that "define" shorthand assoc type paths, we would still need to continue to warn in cases where the assoc ty comes from a supertrait despite the fact that the shorthand syntax can be used: `type A<T: Sub> = T::Assoc;` does compile given `trait Sub: Super {}` and `trait Super { type Assoc; }`. However, `A<X>` does not enforce `X: Sub`, only `X: Super`[^2]. All that to say, type alias bounds are simply not real and we shouldn't pretend they are! 5. Summarizing the points above, we would be legitimizing bounds that are completely broken! 2. It's infeasible to implement: Due to the lack of `TypeckResults` in `ItemCtxt` (and a way to propagate it to other parts of the compiler), the resolution of type-dependent paths in non-`Body` items (most notably type aliases) is not recoverable from the HIR alone which would be necessary because the information of whether an associated type path (projection) is a shorthand is only present pre&in-HIR and doesn't survive HIR ty lowering. Of course, I could rerun parts of HIR ty lowering inside the lint `type_alias_bounds` (namely, `probe_single_ty_param_bound_for_assoc_ty` which would need to be exposed or alternatively a stripped-down version of it). This likely has a performance impact and introduces complexity. In short, the "benefits" are not worth the costs. --- * 3rd commit: Update a diagnostic to avoid suggesting type alias bounds * 4th commit: Flag type alias bounds even if the RHS contains inherent associated types. * I started to allow them at some point in the past which was not correct (see commit for details) * 5th commit: Allow type alias bounds if the RHS contains const projections and GCEs are enabled * (and add a `FIXME(generic_const_exprs)` to be revisited before (M)GCE's stabilization) * As a matter of fact type alias bounds are enforced in this case because the contained AnonConsts do get checked for well-formedness and crucially they inherit the generics and predicates of their parent item (here: the type alias) * Remaining commits: Improve the lint `type_alias_bounds` itself --- Fixes #125789 (sugg diag fix). Fixes #125709 (wontfix, acknowledgement, sugg diag applic fix). Fixes #104918 (sugg diag applic fix). Fixes #100270 (wontfix, acknowledgement, sugg diag applic fix). Fixes #94398 (true fix). r? `@compiler-errors` `@oli-obk` [^1]: From the perspective of the trait solver. [^2]: Given `type A<T: Trait> = T::Proj;`, the reason why the trait bound "`T: Trait`" gets *seemingly* enforced at usage sites of the type alias `A` is simply because `A<X>` gets expanded to "`<X as Trait>::Proj`" very early on and it's the *expansion* that gets checked for well-formedness, not the type alias reference.
2024-07-26Rollup merge of #127950 - nnethercote:rustfmt-skip-on-use-decls, r=cuviperMatthias Krüger-0/+1
Use `#[rustfmt::skip]` on some `use` groups to prevent reordering. `use` declarations will be reformatted in #125443. Very rarely, there is a desire to force a group of `use` declarations together in a way that auto-formatting will break up. E.g. when you want a single comment to apply to a group. #126776 dealt with all of these in the codebase, ensuring that no comments intended for multiple `use` declarations would end up in the wrong place. But some people were unhappy with it. This commit uses `#[rustfmt::skip]` to create these custom `use` groups in an idiomatic way for a few of the cases changed in #126776. This works because rustfmt treats any `use` item annotated with `#[rustfmt::skip]` as a barrier and won't reorder other `use` items around it. r? `@cuviper`
2024-07-25Support ?Trait bounds in supertraits and dyn Trait under a feature gateBryanskiy-4/+6
2024-07-25Rollup merge of #121364 - Urgau:unary_precedence, r=compiler-errorsMatthias Krüger-0/+102
Implement lint against ambiguous negative literals This PR implements a lint against ambiguous negative literals with a literal and method calls right after it. ## `ambiguous_negative_literals` (deny-by-default) The `ambiguous_negative_literals` lint checks for cases that are confusing between a negative literal and a negation that's not part of the literal. ### Example ```rust,compile_fail -1i32.abs(); // equals -1, while `(-1i32).abs()` equals 1 ``` ### Explanation Method calls take precedence over unary precedence. Setting the precedence explicitly makes the code clearer and avoid potential bugs. <details> <summary>Old proposed lint</summary> ## `ambiguous_unary_precedence` (deny-by-default) The `ambiguous_unary_precedence` lint checks for use the negative unary operator with a literal and method calls. ### Example ```rust -1i32.abs(); // equals -1, while `(-1i32).abs()` equals 1 ``` ### Explanation Unary operations take precedence on binary operations and method calls take precedence over unary precedence. Setting the precedence explicitly makes the code clearer and avoid potential bugs. </details> ----- Note: This is a strip down version of https://github.com/rust-lang/rust/pull/117161, without the binary op precedence. Fixes https://github.com/rust-lang/rust/issues/117155 `@rustbot` labels +I-lang-nominated cc `@scottmcm` r? compiler
2024-07-23Update the description of lint type_alias_boundsLeón Orell Valerian Liehr-9/+21
2024-07-23Make lint type_alias_bounds's removal sugg maybe-incorrect if the RHS ↵León Orell Valerian Liehr-129/+109
contains shorthand assoc tys
2024-07-23Improve the impl and diag output of lint type_alias_boundsLeón Orell Valerian Liehr-104/+136
2024-07-23Suppress lint type_alias_bounds for ty aliases containing const projections ↵León Orell Valerian Liehr-0/+10
under GCE
2024-07-23Don't suppress lint type_alias_bounds for ty aliases containing inherent ↵León Orell Valerian Liehr-17/+11
assoc tys
2024-07-22Rollup merge of #125990 - tbu-:pr_unsafe_env_lint_name, r=ehussTrevor Gross-0/+2
Rename `deprecated_safe` lint to `deprecated_safe_2024` Create a lint group `deprecated_safe` that includes `deprecated_safe_2024`. Addresses https://github.com/rust-lang/rust/issues/124866#issuecomment-2142814375. r? `@ehuss`
2024-07-19Auto merge of #127956 - tgross35:rollup-8ten7pk, r=tgross35bors-19/+42
Rollup of 7 pull requests Successful merges: - #121533 (Handle .init_array link_section specially on wasm) - #127825 (Migrate `macos-fat-archive`, `manual-link` and `archive-duplicate-names` `run-make` tests to rmake) - #127891 (Tweak suggestions when using incorrect type of enum literal) - #127902 (`collect_tokens_trailing_token` cleanups) - #127928 (Migrate `lto-smoke-c` and `link-path-order` `run-make` tests to rmake) - #127935 (Change `binary_asm_labels` to only fire on x86 and x86_64) - #127953 ([compiletest] Search *.a when getting dynamic libraries on AIX) r? `@ghost` `@rustbot` modify labels: rollup
2024-07-19Auto merge of #125915 - camelid:const-arg-refactor, r=BoxyUwUbors-1/+1
Represent type-level consts with new-and-improved `hir::ConstArg` ### Summary This is a step toward `min_generic_const_exprs`. We now represent all const generic arguments using an enum that differentiates between const *paths* (temporarily just bare const params) and arbitrary anon consts that may perform computations. This will enable us to cleanly implement the `min_generic_const_args` plan of allowing the use of generics in paths used as const args, while disallowing their use in arbitrary anon consts. Here is a summary of the salient aspects of this change: - Add `current_def_id_parent` to `LoweringContext` This is needed to track anon const parents properly once we implement `ConstArgKind::Path` (which requires moving anon const def-creation outside of `DefCollector`). - Create `hir::ConstArgKind` enum with `Path` and `Anon` variants. Use it in the existing `hir::ConstArg` struct, replacing the previous `hir::AnonConst` field. - Use `ConstArg` for all instances of const args. Specifically, use it instead of `AnonConst` for assoc item constraints, array lengths, and const param defaults. - Some `ast::AnonConst`s now have their `DefId`s created in rustc_ast_lowering rather than `DefCollector`. This is because in some cases they will end up becoming a `ConstArgKind::Path` instead, which has no `DefId`. We have to solve this in a hacky way where we guess whether the `AnonConst` could end up as a path const since we can't know for sure until after name resolution (`N` could refer to a free const or a nullary struct). If it has no chance as being a const param, then we create a `DefId` in `DefCollector` -- otherwise we decide during ast_lowering. This will have to be updated once all path consts use `ConstArgKind::Path`. - We explicitly use `ConstArgHasType` for array lengths, rather than implicitly relying on anon const type feeding -- this is due to the addition of `ConstArgKind::Path`. - Some tests have their outputs changed, but the changes are for the most part minor (including removing duplicate or almost-duplicate errors). One test now ICEs, but it is for an incomplete, unstable feature and is now tracked at https://github.com/rust-lang/rust/issues/127009. ### Followup items post-merge - Use `ConstArgKind::Path` for all const paths, not just const params. - Fix (no github dont close this issue) #127009 - If a path in generic args doesn't resolve as a type, try to resolve as a const instead (do this in rustc_resolve). Then remove the special-casing from `rustc_ast_lowering`, so that all params will automatically be lowered as `ConstArgKind::Path`. - (?) Consider making `const_evaluatable_unchecked` a hard error, or at least trying it in crater r? `@BoxyUwU`
2024-07-19Rollup merge of #127935 - tgross35:binary_asm_labels-x86-only, r=estebank,UrgauTrevor Gross-19/+42
Change `binary_asm_labels` to only fire on x86 and x86_64 In <https://github.com/rust-lang/rust/pull/126922>, the `binary_asm_labels` lint was added which flags labels such as `0:` and `1:`. Before that change, LLVM was giving a confusing error on x86/x86_64 because of an incorrect interpretation. However, targets other than x86 and x86_64 never had the error message and have not been a problem. This means that the lint was causing code that previously worked to start failing (e.g. `compiler_builtins`), rather than only providing a more clear messages where there has always been an error. Adjust the lint to only fire on x86 and x86_64 assembly to avoid this regression. Also update the help message. Fixes: https://github.com/rust-lang/rust/issues/127821
2024-07-19Update the `binary_asm_label` documentationTrevor Gross-9/+23
Disable a test that now only passes on x86 and make the link point to the new (open) LLVM bug.
2024-07-19Use `#[rustfmt::skip]` on some `use` groups to prevent reordering.Nicholas Nethercote-0/+1
`use` declarations will be reformatted in #125443. Very rarely, there is a desire to force a group of `use` declarations together in a way that auto-formatting will break up. E.g. when you want a single comment to apply to a group. #126776 dealt with all of these in the codebase, ensuring that no comments intended for multiple `use` declarations would end up in the wrong place. But some people were unhappy with it. This commit uses `#[rustfmt::skip]` to create these custom `use` groups in an idiomatic way for a few of the cases changed in #126776. This works because rustfmt treats any `use` item annotated with `#[rustfmt::skip]` as a barrier and won't reorder other `use` items around it.
2024-07-18Update the `binary_asm_label` messageTrevor Gross-1/+3
The link pointed to a closed issue. Create a new one and point the link to it. Also add a help message to hint what change the user could make. Fixes: https://github.com/rust-lang/rust/issues/127821
2024-07-18Change `binary_asm_labels` to only fire on x86 and x86_64Trevor Gross-9/+16
In <https://github.com/rust-lang/rust/pull/126922>, the `binary_asm_labels` lint was added which flags labels such as `0:` and `1:`. Before that change, LLVM was giving a confusing error on x86/x86_64 because of an incorrect interpretation. However, targets other than x86 and x86_64 never had the error message and have not been a problem. This means that the lint was causing code that previously worked to start failing (e.g. `compiler_builtins`), rather than only providing a more clear messages where there has always been an error. Adjust the lint to only fire on x86 and x86_64 assembly to avoid this regression.
2024-07-18Rollup merge of #127854 - fmease:glob-import-type_ir_inherent-lint, ↵Matthias Krüger-1/+56
r=compiler-errors Add internal lint for detecting non-glob imports of `rustc_type_ir::inherent` https://github.com/rust-lang/rust/pull/127627#issuecomment-2225295951 r? compiler-errors
2024-07-18Add internal lint for detecting non-glob imports of `rustc_type_ir::inherent`León Orell Valerian Liehr-1/+56
2024-07-17Rename `deprecated_safe` lint to `deprecated_safe_2024`Tobias Bucher-0/+2
Create a lint group `deprecated_safe` that includes `deprecated_safe_2024`. Addresses https://github.com/rust-lang/rust/issues/124866#issuecomment-2142814375.
2024-07-16hir: Create `hir::ConstArgKind` enumNoah Lev-1/+1
This will allow lowering const params to a dedicated enum variant, rather than to an `AnonConst` that is later examined during `ty` lowering.
2024-07-17Avoid comments that describe multiple `use` items.Nicholas Nethercote-1/+0
There are some comments describing multiple subsequent `use` items. When the big `use` reformatting happens some of these `use` items will be reordered, possibly moving them away from the comment. With this additional level of formatting it's not really feasible to have comments of this type. This commit removes them in various ways: - merging separate `use` items when appropriate; - inserting blank lines between the comment and the first `use` item; - outright deletion (for comments that are relatively low-value); - adding a separate "top-level" comment. We also entirely skip formatting for four library files that contain nothing but `pub use` re-exports, where reordering would be painful.
2024-07-12Rollup merge of #127631 - compiler-errors:yeet-fully-norm, r=lcnrJubilee-13/+14
Remove `fully_normalize` Yeet this function and replace it w/ some `ObligationCtxt` instead. It wasn't called very often anyways. r? lcnr
2024-07-12Rollup merge of #127535 - spastorino:unsafe_code-unsafe_extern_blocks, r=oli-obkJubilee-0/+8
Fire unsafe_code lint on unsafe extern blocks Fixes #126738
2024-07-12Rollup merge of #126922 - asquared31415:asm_binary_label, r=estebankJubilee-34/+129
add lint for inline asm labels that look like binary fixes #94426 Due to a bug/feature in LLVM, labels composed of only the digits `0` and `1` can sometimes be confused with binary literals, even if a binary literal would not be valid in that position. This PR adds detection for such labels and also as a drive-by change, adds a note to cases such as `asm!(include_str!("file"))` that the label that it found came from an expansion of a macro, it wasn't found in the source code. I expect this PR to upset some people that were using labels `0:` or `1:` without issue because they never hit the case where LLVM got it wrong, but adding a heuristic to the lint to prevent this is not feasible - it would involve writing a whole assembly parser for every target that we have assembly support for. [zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/238009-t-compiler.2Fmeetings/topic/.5Bweekly.5D.202024-06-20/near/445870628) r? ``@estebank``
2024-07-11Remove fully_normalizeMichael Goulet-13/+14
2024-07-11Auto merge of #127097 - compiler-errors:async-closure-lint, r=oli-obkbors-5/+136
Implement simple, unstable lint to suggest turning closure-of-async-block into async-closure We want to eventually suggest people to turn `|| async {}` to `async || {}`. This begins doing that. It's a pretty rudimentary lint, but I wanted to get something down so I wouldn't lose the code. Tracking: * #62290
2024-07-11Implement `ambiguous_negative_literals` lintUrgau-0/+102
2024-07-10Auto merge of #127549 - jhpratt:rollup-o1mbmhr, r=jhprattbors-0/+165
Rollup of 8 pull requests Successful merges: - #124211 (Bump `elided_lifetimes_in_associated_constant` to deny) - #125627 (migration lint for `expr2024` for the edition 2024) - #127091 (impl FusedIterator and a size hint for the error sources iter) - #127461 (Fixup failing fuchsia tests) - #127484 (`#[doc(alias)]`'s doc: say that ASCII spaces are allowed) - #127508 (small search graph refactor) - #127521 (Remove spastorino from SMIR) - #127532 (documentation: update cmake version) r? `@ghost` `@rustbot` modify labels: rollup
2024-07-10Rollup merge of #125627 - vincenzopalazzo:macros/cargo-fix-expr2024, ↵Jacob Pratt-0/+165
r=compiler-errors,eholk migration lint for `expr2024` for the edition 2024 This is adding a migration lint for the current (in the 2021 edition and previous) to move expr to expr_2021 from expr Issue https://github.com/rust-lang/rust/issues/123742 I created also a repository to test out the migration https://github.com/vincenzopalazzo/expr2024-cargo-fix-migration Co-Developed-by: ``@eholk``
2024-07-10Auto merge of #127496 - tgross35:f16-f128-pattern-fixme, r=Nadrierilbors-1/+2
Update `f16`/`f128` FIXMEs that needed `(NEG_)INFINITY` Just a small fix to the pattern matching tests now that we can. Also contains a small unrelated comment tweak.
2024-07-09Fire unsafe_code lint on unsafe extern blocksSantiago Pastorino-0/+8
2024-07-09Adds expr_2024 migration litVincenzo Palazzo-0/+165
This is adding a migration lint for the current (in the 2021 edition and previous) to move expr to expr_2021 from expr Co-Developed-by: Eric Holk Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>