about summary refs log tree commit diff
path: root/tests
AgeCommit message (Collapse)AuthorLines
2024-07-28Rollup merge of #128279 - slanterns:is_sorted, r=dtolnayMatthias Krüger-58/+0
Stabilize `is_sorted` Closes: https://github.com/rust-lang/rust/issues/53485. ~~Question: does~~ https://github.com/rust-lang/rust/blob/8fe0c753f23e7050b87a444b6622caf4d2272d5d/compiler/rustc_lint_defs/src/builtin.rs#L1986-L1994 ~~need a new example?~~ edit: It causes a test failure and needs to be changed anyway. ``@rustbot`` label: +T-libs-api r? libs-api
2024-07-28Rollup merge of #127853 - folkertdev:naked-function-error-messages, r=bjorn3Matthias Krüger-79/+258
`#[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-28Auto merge of #128079 - Oneirical:testiges-of-civilization, r=jieyouxubors-69/+94
Migrate `static-dylib-by-default`, `sanitizer-dylib-link`, `sanitizer-cdylib-link` and `sanitizer-staticlib-link` `run-make` tests to rmake Part of #121876 and the associated [Google Summer of Code project](https://blog.rust-lang.org/2024/05/01/gsoc-2024-selected-projects.html). Please try: try-job: x86_64-msvc try-job: armhf-gnu try-job: test-various try-job: i686-msvc try-job: x86_64-mingw try-job: x86_64-gnu-llvm-18
2024-07-28stabilize `is_sorted`Slanterns-58/+0
2024-07-27Rollup merge of #128271 - ↵Trevor Gross-0/+130
Nilstrieb:jump-into-a-can-of-worms-called-float-equality, r=compiler-errors Disable jump threading of float equality Jump threading stores values as `u128` (`ScalarInt`) and does its comparisons for equality as integer comparisons. This works great for integers. Sadly, not everything is an integer. Floats famously have wonky equality semantcs, with `NaN!=NaN` and `0.0 == -0.0`. This does not match our beautiful integer bitpattern equality and therefore causes things to go horribly wrong. While jump threading could be extended to support floats by remembering that they're floats in the value state and handling them properly, it's signficantly easier to just disable it for now. fixes #128243
2024-07-27Rollup merge of #128267 - GuillaumeGomez:gui-test-title, r=notriddleTrevor Gross-0/+24
Add rustdoc GUI test to check title with and without search Follow-up of https://github.com/rust-lang/rust/pull/128210. r? `@notriddle`
2024-07-27Rollup merge of #128262 - DianQK:remove-unused-tests, r=saethlinTrevor Gross-436/+0
Delete `SimplifyArmIdentity` and `SimplifyBranchSame` tests These two passes have already been deleted in #107256. I'm not sure why tidy didn't catch it. As regression tests, I didn't delete `tests/ui/mir/issue-66851.rs` and `tests/ui/mir/simplify-branch-same.rs`. r? compiler
2024-07-27Rollup merge of #128241 - compiler-errors:clone-sugg, r=jieyouxuTrevor Gross-6/+14
Remove logic to suggest clone of function output I can't exactly tell, but I believe that this suggestion is operating off of a heuristic that the lifetime of a function's input is correlated with the lifetime of a function's output in such a way that cloning would fix an error. I don't think that actually manages to hit the bar of "actually provides useful suggestions" most of the time. Specifically, I've hit false-positives due to this suggestion *twice* when fixing ICEs in the compiler, so I don't think it's worthwhile having this logic around. Neither of the two affected UI tests are actually fixed by the suggestion.
2024-07-27Rollup merge of #128207 - folkertdev:asm-parser-generalize, r=AmanieuTrevor Gross-77/+155
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-27add `needs-asm-support` to `tests/ui/asm/unsupported-option.rs`Folkert-3/+5
2024-07-27fix `tests/ui/asm/naked-functions.rs` for aarch64Folkert-6/+7
2024-07-27update aarch64 asm testsFolkert-47/+61
2024-07-27Disable jump threading of float equalityNilstrieb-0/+130
Jump threading stores values as `u128` (`ScalarInt`) and does its comparisons for equality as integer comparisons. This works great for integers. Sadly, not everything is an integer. Floats famously have wonky equality semantcs, with `NaN!=NaN` and `0.0 == -0.0`. This does not match our beautiful integer bitpattern equality and therefore causes things to go horribly wrong. While jump threading could be extended to support floats by remembering that they're floats in the value state and handling them properly, it's signficantly easier to just disable it for now.
2024-07-27Auto merge of #128006 - tgross35:missing-fragment-specifier-e2024, ↵bors-18/+74
r=petrochenkov Make `missing_fragment_specifier` an error in edition 2024 `missing_fragment_specifier` has been a future compatibility warning since 2017. Uplifting it to an unconditional hard error was attempted in 2020, but eventually reverted due to fallout. Make it an error only in edition >= 2024, leaving the lint for older editions. This change will make it easier to support more macro syntax that relies on usage of `$`. Fixes <https://github.com/rust-lang/rust/issues/40107> --- It is rather late for the edition but since this change is relatively small, it seems worth at least bringing up. This follows a brief [Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/268952-edition/topic/.60.20DBD.20-.3E.20hard.20error) (cc `@tmandry).` Making this an edition-dependent lint has come up before but there was not a strong motivation. I am proposing it at this time because this would simplify the [named macro capture groups](https://github.com/rust-lang/rfcs/pull/3649) RFC, which has had mildly positive response, and makes use of new `$` syntax in the matcher. The proposed syntax currently parses as metavariables without a fragment specifier; this warning is raised, but there are no errors. It is obviously not known that this specific RFC will eventually be accepted, but forbidding `missing_fragment_specifier` should make it easier to support any new syntax in the future that makes use of `$` in different ways. The syntax conflict is also not impossible to overcome, but making it clear that unnamed metavariables are rejected makes things more straightforward and should allow for better diagnostics. `@Mark-Simulacrum` suggested making this forbid-by-default instead of an error at https://github.com/rust-lang/rust/issues/40107#issuecomment-761727885, but I don't think this would allow the same level of syntax flexibility. It is also possible to reconsider making this an unconditional error since four years have elapsed since the previous attempt, but this seems likely to hit the same pitfalls. (Possibly worth a crater run?) Tracking: - https://github.com/rust-lang/rust/issues/128143
2024-07-27allow `#[target_feature]` on `#[naked]` functionsFolkert-25/+6
2024-07-27switch to an allowlist approachFolkert-31/+132
- 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-27Add rustdoc GUI test to check title with and without searchGuillaume Gomez-0/+24
2024-07-27Auto merge of #124905 - reitermarkus:u32-from-char-opt, r=scottmcmbors-0/+35
Allow optimizing `u32::from::<char>`. Extracted from https://github.com/rust-lang/rust/pull/124307. This allows optimizing the panicking branch in the `escape_unicode` function, see https://rust.godbolt.org/z/61YhKrhvP.
2024-07-27Make `missing_fragment_specifier` an error in edition 2024Trevor Gross-18/+74
`missing_fragment_specifier` has been a future compatibility warning since 2017. Uplifting it to an unconditional hard error was attempted in 2020, but eventually reverted due to fallout. Make it an error only in edition >= 2024, leaving the lint for older editions. This change will make it easier to support more macro syntax that relies on usage of `$`. Fixes <https://github.com/rust-lang/rust/issues/40107>
2024-07-27Delete `SimplifyArmIdentity` and `SimplifyBranchSame` testsDianQK-436/+0
2024-07-26Rollup merge of #128229 - tdittr:unsafe-extern-abi-error, r=compiler-errorsTrevor Gross-8/+41
Improve `extern "<abi>" unsafe fn()` error message These errors were already reported in #87217, and fixed by #87235 but missed the case of an explicit ABI. This PR does not cover multiple keywords like `extern "C" pub const unsafe fn()`, but I don't know what a good way to cover this would be. It also seems rarer than `extern "C" unsafe` which I saw happen a few times in workshops.
2024-07-26Rollup merge of #128201 - compiler-errors:closure-clone, r=oli-obkTrevor Gross-18/+93
Implement `Copy`/`Clone` for async closures We can do so in the same cases that regular closures do. For the purposes of cloning, coroutine-closures are actually precisely the same as regular closures, specifically in the aspect that `Clone` impls care about which is the upvars. The only difference b/w coroutine-closures and regular closures is the type that they *return*, but this type has not been *created* yet, so we don't really have a problem. IDK why I didn't add this impl initially -- I went back and forth a bit on the internal representation for coroutine-closures before settling on a design which largely models regular closures. Previous (not published) iterations of coroutine-closures used to be represented as a special (read: cursed) kind of coroutine, which would probably suffer from the pitfalls that coroutines have that oli mentioned below in https://github.com/rust-lang/rust/pull/128201#issuecomment-2251230274. r? oli-obk
2024-07-26Rollup merge of #124941 - Skgland:stabilize-const-int-from-str, r=dtolnayTrevor Gross-4/+2
Stabilize const `{integer}::from_str_radix` i.e. `const_int_from_str` This PR stabilizes the feature `const_int_from_str`. - ACP Issue: rust-lang/libs-team#74 - Implementation PR: rust-lang/rust#99322 - Part of Tracking Issue: rust-lang/rust#59133 API Change Diff: ```diff impl {integer} { - pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>; + pub const fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>; } impl ParseIntError { - pub fn kind(&self) -> &IntErrorKind; + pub const fn kind(&self) -> &IntErrorKind; } ``` This makes it easier to parse integers at compile-time, e.g. the example from the Tracking Issue: ```rust env!("SOMETHING").parse::<usize>().unwrap() ``` could now be achived with ```rust match usize::from_str_radix(env!("SOMETHING"), 10) { Ok(val) => val, Err(err) => panic!("Invalid value for SOMETHING environment variable."), } ``` rather than having to depend on a library that implements or manually implement the parsing at compile-time. --- Checklist based on [Libs Stabilization Guide - When there's const involved](https://std-dev-guide.rust-lang.org/development/stabilization.html#when-theres-const-involved) I am treating this as a [partial stabilization](https://std-dev-guide.rust-lang.org/development/stabilization.html#partial-stabilizations) as it shares a tracking issue (and is rather small), so directly opening the partial stabilization PR for the subset (feature `const_int_from_str`) being stabilized. - [x] ping Constant Evaluation WG - [x] no unsafe involved - [x] no `#[allow_internal_unstable]` - [ ] usage of `intrinsic::const_eval_select` rust-lang/rust#124625 in `from_str_radix_assert` to change the error message between compile-time and run-time - [ ] [rust-labg/libs-api FCP](https://github.com/rust-lang/rust/pull/124941#issuecomment-2207021921)
2024-07-26Auto merge of #121676 - Bryanskiy:polarity, r=petrochenkovbors-20/+250
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-26Remove logic to suggest clone of function outputMichael Goulet-6/+14
2024-07-26Suppress useless clone suggestionMichael Goulet-5/+0
2024-07-26Make coroutine-closures possible to be clonedMichael Goulet-18/+98
2024-07-26Auto merge of #128065 - Oneirical:great-testilence, r=jieyouxubors-59/+84
Migrate `c-unwind-abi-catch-lib-panic`, `foreign-rust-exceptions` and `export-executable-symbols` `run-make` tests to rmake Part of #121876 and the associated [Google Summer of Code project](https://blog.rust-lang.org/2024/05/01/gsoc-2024-selected-projects.html). Please try: try-job: aarch64-apple try-job: i686-mingw
2024-07-26rewrite sanitizer-staticlib-link to rmakeOneirical-23/+39
2024-07-26rewrite export-executable-symbols to rmakeOneirical-16/+30
2024-07-26rewrite foreign-rust-exceptions to rmakeOneirical-13/+23
2024-07-26rewrite c-unwind-abi-catch-lib-panic to rmakeOneirical-35/+36
2024-07-26Forbid `?Trait` bounds repetitionsBryanskiy-1/+56
2024-07-26Improve error message for `extern "C" unsafe fn()`Tamme Dittrich-11/+24
This was handled correctly already for `extern unsafe fn()`. Co-authored-by: Folkert <folkert@folkertdev.nl>
2024-07-26Auto merge of #128165 - saethlin:optimize-clone-shims, r=compiler-errorsbors-41/+22
Let InstCombine remove Clone shims inside Clone shims The Clone shims that we generate tend to recurse into other Clone shims, which gets very silly very quickly. Here's our current state: https://godbolt.org/z/E69YeY8eq So I've added InstSimplify to the shims optimization passes, and improved `is_trivially_pure_clone_copy` so that it can delete those calls inside the shim. This makes the shim way smaller because most of its size is the required ceremony for unwinding. This change also completely breaks the UI test added for https://github.com/rust-lang/rust/issues/104870. With this PR, that program ICEs in MIR type checking because `is_trivially_pure_clone_copy` and the trait solver disagree on whether `*mut u8` is `Copy`. And adding the requisite `Copy` impl to make them agree makes the test not generate any diagnostics. Considering that I spent most of my time on this PR fixing `#![no_core]` tests, I would prefer to just delete this one. The maintenance burden of `#![no_core]` is uniquely high because when they break they tend to break in very confusing ways. try-job: x86_64-mingw
2024-07-26Add a test case for `extern "C" unsafe` to the ui testsTamme Dittrich-0/+20
2024-07-26Auto merge of #128034 - Nadrieril:explain-unreachable, r=compiler-errorsbors-192/+1173
exhaustiveness: Explain why a given pattern is considered unreachable This PR tells the user why a given pattern is considered unreachable. I reused the intersection information we were already computing; even though it's incomplete I convinced myself that it is sufficient to always get a set of patterns that cover the unreachable one. I'm not a fan of the diagnostic messages I came up with, I'm open to suggestions. Fixes https://github.com/rust-lang/rust/issues/127870. This is also the other one of the two diagnostic improvements I wanted to do before https://github.com/rust-lang/rust/pull/122792. Note: the first commit is an unrelated drive-by tweak. r? `@compiler-errors`
2024-07-26Rollup merge of #128099 - lolbinarycat:extern-flag-disambiguates-rmake, r=KobzolTrevor Gross-26/+35
migrate tests/run-make/extern-flag-disambiguates to rmake
2024-07-26Rollup merge of #127989 - Oneirical:testricted-area, r=jieyouxuTrevor Gross-45/+61
Migrate `interdependent-c-libraries`, `compiler-rt-works-on-mingw` and `incr-foreign-head-span` `run-make` tests to rmake Part of #121876 and the associated [Google Summer of Code project](https://blog.rust-lang.org/2024/05/01/gsoc-2024-selected-projects.html). try-job: aarch64-apple try-job: armhf-gnu try-job: test-various try-job: x86_64-mingw try-job: x86_64-msvc try-job: x86_64-gnu-llvm-18
2024-07-26Rollup merge of #127557 - linyihai:issue-126694, r=compiler-errorsTrevor Gross-6/+25
Add a label to point to the lacking macro name definition Fixes https://github.com/rust-lang/rust/issues/126694, but adopts the suggestion from https://github.com/rust-lang/rust/issues/118295 ``` --> src/main.rs:1:14 | 1 | macro_rules! { | ^ put a macro name here ```
2024-07-26Rollup merge of #127523 - Oneirical:treasure-test, r=jieyouxuTrevor Gross-84/+105
Migrate `dump-ice-to-disk` and `panic-abort-eh_frame` `run-make` tests to rmake Part of #121876 and the associated [Google Summer of Code project](https://blog.rust-lang.org/2024/05/01/gsoc-2024-selected-projects.html). Please try: try-job: x86_64-msvc try-job: i686-mingw
2024-07-26Rollup merge of #127017 - mu001999-contrib:dead/enhance, r=pnkfelixTrevor Gross-0/+65
Extend rules of dead code analysis for impls for adts to impls for types refer to adts The rules of dead code analysis for impl blocks can be extended to self types which refer to adts. So that we can lint the following unused struct and trait: ```rust struct Foo; //~ ERROR struct `Foo` is never constructed trait Trait { //~ ERROR trait `Trait` is never used fn foo(&self) {} } impl Trait for &Foo {} ``` r? `@pnkfelix`
2024-07-26Rollup merge of #126575 - fmease:update-lint-type_alias_bounds, ↵Trevor Gross-237/+526
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-26Add a label to point to the lacking macro name definitionLin Yihai-6/+25
2024-07-26Auto merge of #128213 - matthiaskrgr:rollup-v40q1j3, r=matthiaskrgrbors-141/+459
Rollup of 7 pull requests Successful merges: - #126090 (Fix supertrait associated type unsoundness) - #127220 (Graciously handle `Drop` impls introducing more generic parameters than the ADT) - #127950 (Use `#[rustfmt::skip]` on some `use` groups to prevent reordering.) - #128085 (Various notes on match lowering) - #128150 (Stop using `unsized_const_parameters` in core/std) - #128194 (LLVM: LLVM-20.0 removes MMX types) - #128211 (fix: compilation issue w/ refactored type) r? `@ghost` `@rustbot` modify labels: rollup
2024-07-26Rollup merge of #127220 - BoxyUwU:dropck_handle_extra_impl_params, ↵Matthias Krüger-141/+333
r=compiler-errors Graciously handle `Drop` impls introducing more generic parameters than the ADT Follow up to #110577 Fixes #126378 Fixes #126889 ## Motivation A current issue with the way we check drop impls do not specialize any of their generic parameters is that when the `Drop` impl introduces *more* generic parameters than are present on the ADT, we fail to prove any bounds involving those parameters. This can be demonstrated with the following [code on stable](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=139b65e4294634d7286a3282bc61e628) which fails due to the fact that `<T as Trait>::Assoc == U` is not present in `Foo`s `ParamEnv` even though arguably there is no reason it cannot compiler: ```rust struct Foo<T: Trait>(T); trait Trait { type Assoc; } impl<T: Trait<Assoc = U>, U: ?Sized> Drop for Foo<T> { //~^ ERROR: `Drop` impl requires `<T as Trait>::Assoc == U` but the struct ... fn drop(&mut self) {} } fn main() {} ``` I think the motivation for supporting this code is somewhat lacking, it might be useful in practice for deeply nested associated types where you might want to be able to write: `where T: Trait<Assoc: Other<AnotherAssoc: MoreTrait<YetAnotherAssoc: InnerTrait<Final = U>>>>` in order to be able to just use `U` in the function body instead of writing out the whole nested associated type. Regardless I don't think there is really any reason to *not* support this code and it is relatively easy to support it. What I find slightly more compelling is the fact that when defining a const parameter `const N: u8` we desugar that to having a where clause requiring the constant `N` is typed as `u8` (`ClauseKind::ConstArgHasType`). As we *always* desugar const parameters to have these bounds, if we attempt to prove that some const parameter `N` is of type `u8` and there is no bound on `N` in the enviroment that generally indicates usage of an incorrect `ParamEnv` (this has caught a bug already). Given that, if we write the following code: ```rust #![feature(associated_const_equality)] struct Foo<T: Trait>(T); trait Trait { const ASSOC: usize; } impl<T: Trait<ASSOC = N>, const N: usize> Drop for Foo<T> { fn drop(&mut self) {} } fn main() {} ``` The `Drop` impl would have this desugared where clause about `N` being of type `usize`, and if we were to try to prove that where clause in `Foo`'s `ParamEnv` we would ICE as there would not be any `ConstArgHasType` in the environment (which generally indicates improper `ParamEnv` usage. As this is otherwise well formed code (the `T: Trait<ASSOC = N>` causes `N` to be constrained) we have to handle this *somehow* and I believe the only principled way to support this is the changes I have made to `dropck.rs` that would cause these code examples to compiler (Perhaps we could just throw out all `ConstArgHasType` where clauses from the predicates we prove but that makes me nervous even if it might actually be okay). ## The changes Currently the way `dropck.rs` works is that take the `ParamEnv` of the ADT and instantiate it with the generic arguments used on the self ty of the `impl`. We then instantiate the predicates of the drop impl with the identity params to the impl, e.g. in the original example `<T as Trait>::Assoc == U` stays as `<T as Trait>::Assoc == U`. We then attempt to prove all the where clauses in the instantiated env of the self type ADT. This PR changes us to first instantiate the impl with infer vars, then we equate the self type (with infer vars as its generic arguments) with the self type as written by the user. This causes all generic parameters on the impl that are constrained via associated type/const equality bounds to be left as inference variables while all other parameters are still `Ty`/`Const`/`Region` Finally when instantiating the predicates on the impl, instead of using the identity arguments, we use the list of inference variables of which some have been inferred to the impl parameters. In practice this means that we wind up proving `<T as Trait>::Assoc == ?x` which can succeed just fine. In the const generics example we would wind up trying to prove `ConstArgHasType(?x: usize)` instead of `ConstArgHasType(N: usize)` which avoids the ICE as it is expected to encounter goals of the form `?x: usize`. At a higher level the way I justify/think about this is that as we are proving goals in the environment of the ADT (`Foo` in the above examples), we do not expect to encounter generic parameters from a different environment so we must "deal with them" somehow. In this PR we handle them by replacing them with inference variables as they should either *actually* be unconstrained (and we will error later) or they are constrained to be equal to some associated type/const. To go along with this it would be nice if we were not instantiating the adt's env with the generic arguments to the ADT in the `Drop` impl as it would make it clearer we are proving bounds in the adt's env instead of the `Drop` impl's. Instead we would map the predicates on the drop impl to be valid in the environment of the adt. In practice this causes diagnostic regressions as all of the generic parameters in errors refer to the ones defined on the adt; attempting to map these back to the ones on the impl, while possible, is involved as writing a `TypeFolder` over `FulfillmentError` is non trivial. ## Edge cases There are some subtle interactions here: One is that we should not allow `<T as Trait>::Assoc == U` to be present on the `Drop` if `U` is constrained by the self type of the impl and the bound is not present in the ADT's environment. demonstrated with the [following code](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=af839e2c3e43e03a624825c58af84dff): ```rust trait Trait { type Assoc; } struct Foo<T: Trait, U: ?Sized>(T, U); impl<T: Trait<Assoc = U>, U: ?Sized> Drop for Foo<T, U> { //~^ ERROR: `Drop` impl requires `<T as Trait>::Assoc == U` fn drop(&mut self) {} } fn main() {} ``` This is tested at `tests/ui/dropck/constrained_by_assoc_type_equality_and_self_ty.rs`. Another weirdness is that we permit the following code to compile now: ```rust struct Foo<T>(T); impl<'a, T: 'a> Drop for Foo<T> { fn drop(&mut self) {} } ``` This is caused by the fact that we permit unconstrained lifetime parameters in trait implementations as long as they are not used in associated types (so we do not wind up erroring on this code like we perhaps ought to), combined with the fact that as we are now proving `T: '?x` instead of `T: 'a` which allows proving the bound via `'?x= 'empty` wheras previously it would have failed. This is tested as part of `tests/ui/dropck/reject-specialized-drops-8142.rs`. --- r? `@compiler-errors`
2024-07-26Rollup merge of #126090 - compiler-errors:supertrait-assoc-ty-unsoundness, ↵Matthias Krüger-0/+126
r=lcnr Fix supertrait associated type unsoundness ### What? Object safety allows us to name `Self::Assoc` associated types in certain positions if they come from our trait or one of our supertraits. When this check was implemented, I think it failed to consider that supertraits can have different args, and it was only checking def-id equality. This is problematic, since we can sneak different implementations in by implementing `Supertrait<NotActuallyTheSupertraitSubsts>` for a `dyn` type. This can be used to implement an unsound transmute function. See the committed test. ### How do we fix it? We consider the whole trait ref when checking for supertraits. Right now, this is implemented using equality *without* normalization. We erase regions since those don't affect trait selection. This is a limitation that could theoretically affect code that should be accepted, but doesn't matter in practice -- there are 0 crater regression. We could make this check stronger, but I would be worried about cycle issues. I assume that most people are writing `Self::Assoc` so they don't really care about the trait ref being normalized. --- ### What is up w the stacked commit This is built on top of https://github.com/rust-lang/rust/pull/122804 though that's really not related, it's just easier to make this modification with the changes to the object safety code that I did in that PR. The only thing is that PR may make this unsoundness slightly easier to abuse, since there are more positions that allow self-associated-types -- I am happy to stall that change until this PR merges. --- Fixes #126079 r? lcnr
2024-07-25Auto merge of #127042 - GrigorenkoPV:derivative, r=compiler-errorsbors-19/+19
Switch from `derivative` to `derive-where` This is a part of the effort to get rid of `syn 1.*` in compiler's dependencies: #109302 Derivative has not been maintained in nearly 3 years[^1]. It also depends on `syn 1.*`. This PR replaces `derivative` with `derive-where`[^2], a not dead alternative, which uses `syn 2.*`. A couple of `Debug` formats have changed around the skipped fields[^3], but I doubt this is an issue. [^1]: https://github.com/mcarton/rust-derivative/issues/117 [^2]: https://lib.rs/crates/derive-where [^3]: See the changes in `tests/ui`
2024-07-26add `run-rustfix` test for machine-applicable suggestionFolkert-0/+40
2024-07-25improve error message when `global_asm!` uses `asm!` optionsFolkert-41/+63