Commit Graph

5749 Commits

Author SHA1 Message Date
bors
77be7a3e0d Auto merge of #121810 - matthiaskrgr:rollup-mawij2g, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #121326 (Detect empty leading where clauses on type aliases)
 - #121464 (rustc: Fix wasm64 metadata object files)
 - #121681 (Safe Transmute: Revise safety analysis)
 - #121753 (Add proper cfg to keep only one AlignmentEnum definition for different target_pointer_widths)
 - #121782 (allow statics pointing to mutable statics)
 - #121798 (Fix links in rustc doc)
 - #121806 (add const test for ptr::metadata)
 - #121809 (Remove doc aliases to PATH)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-29 21:47:54 +00:00
Ramon de C Valle
6d75f54310 Move sanitizer ui tests to sanitizer directory
Moves the sanitizer ui tests to the sanitizer directory and removes the
sanitizer prefix from tests file names similarly to how the sanitizer
codegen tests are organized.
2024-02-29 12:22:34 -08:00
许杰友 Jieyou Xu (Joe)
19ee457ea3
Remove stray stdout/stderr files 2024-02-29 20:07:01 +00:00
Matthias Krüger
b07419b6d9
Rollup merge of #121806 - RalfJung:const-metadata, r=oli-obk
add const test for ptr::metadata

https://github.com/rust-lang/rust/pull/121199 uncovered this as a gap in our test suite.

r? `@oli-obk`
2024-02-29 20:50:05 +01:00
Matthias Krüger
255fdcc858
Rollup merge of #121782 - RalfJung:mutable-ref-in-static, r=oli-obk
allow statics pointing to mutable statics

Fixes https://github.com/rust-lang/rust/issues/120450 for good. We can even simplify our checks: no need to specifically go looking for mutable references in const, we can just reject any reference that points to something mutable.

r? `@oli-obk`
2024-02-29 20:50:04 +01:00
Matthias Krüger
419f7aeed6
Rollup merge of #121681 - jswrenn:nix-visibility-analysis, r=compiler-errors
Safe Transmute: Revise safety analysis

This PR migrates `BikeshedIntrinsicFrom` to a simplified safety analysis (described [here](https://github.com/rust-lang/project-safe-transmute/issues/15)) that does not rely on analyzing the visibility of types and fields.

The revised analysis treats primitive types as safe, and user-defined types as potentially carrying safety invariants. If Rust gains explicit (un)safe fields, this PR is structured so that it will be fairly easy to thread support for those annotations into the analysis.

Notably, this PR removes the `Context` type parameter from `BikeshedIntrinsicFrom`. Most of the files changed by this PR are just UI tests tweaked to accommodate the removed parameter.

r? `@compiler-errors`
2024-02-29 20:50:03 +01:00
Matthias Krüger
dd4ecd1cf4
Rollup merge of #121326 - fmease:detect-empty-leading-where-clauses-on-ty-aliases, r=compiler-errors
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 = (); }`
2024-02-29 20:50:02 +01:00
bors
878c8a2a62 Auto merge of #118247 - spastorino:type-equality-subtyping, r=lcnr
change equate for binders to not rely on subtyping

*summary by `@spastorino` and `@lcnr*`

### Context

The following code:

```rust
type One = for<'a> fn(&'a (), &'a ());
type Two = for<'a, 'b> fn(&'a (), &'b ());

mod my_api {
    use std::any::Any;
    use std::marker::PhantomData;

    pub struct Foo<T: 'static> {
        a: &'static dyn Any,
        _p: PhantomData<*mut T>, // invariant, the type of the `dyn Any`
    }

    impl<T: 'static> Foo<T> {
        pub fn deref(&self) -> &'static T {
            match self.a.downcast_ref::<T>() {
                None => unsafe { std::hint::unreachable_unchecked() },
                Some(a) => a,
            }
        }

        pub fn new(a: T) -> Foo<T> {
           Foo::<T> {
                a: Box::leak(Box::new(a)),
                _p: PhantomData,
            }
        }
    }
}

use my_api::*;

fn main() {
    let foo = Foo::<One>::new((|_, _| ()) as One);
    foo.deref();
    let foo: Foo<Two> = foo;
    foo.deref();
}
```

has UB from hitting the `unreachable_unchecked`. This happens because `TypeId::of::<One>()` is not the same as `TypeId::of::<Two>()` despite them being considered the same types by the type checker.

Currently the type checker considers binders to be equal if subtyping succeeds in both directions: `for<'a> T<'a> eq for<'b> U<'b>` holds if `for<'a> exists<'b> T<'b> <: T'<a> AND for<'b> exists<'a> T<'a> <: T<'b>` holds. This results in `for<'a> fn(&'a (), &'a ())` and `for<'a, 'b> fn(&'a (), &'b ())` being equal in the type system.

`TypeId` is computed by looking at the *structure* of a type. Even though these types are semantically equal, they have a different *structure* resulting in them having different `TypeId`. This can break invariants of unsafe code at runtime and is unsound when happening at compile time, e.g. when using const generics.

So as seen in `main`, we can assign a value of type `Foo::<One>` to a binding of type `Foo<Two>` given those are considered the same type but then when we call `deref`, it calls `downcast_ref` that relies on `TypeId` and we would hit the `None` arm as these have different `TypeId`s.

As stated in https://github.com/rust-lang/rust/issues/97156#issuecomment-1879030033, this causes the API of existing crates to be unsound.

## What should we do about this

The same type resulting in different `TypeId`s  is a significant footgun, breaking a very reasonable assumptions by authors of unsafe code. It will also be unsound by itself once they are usable in generic contexts with const generics.

There are two options going forward here:
- change how the *structure* of a type is computed before relying on it. i.e. continue considering `for<'a> fn(&'a (), &'a ())` and `for<'a, 'b> fn(&'a (), &'b ())` to be equal, but normalize them to a common representation so that their `TypeId` are also the same.
- change how the semantic equality of binders to match the way we compute the structure of types. i.e. `for<'a> fn(&'a (), &'a ())` and `for<'a, 'b> fn(&'a (), &'b ())` still have different `TypeId`s but are now also considered to not be semantically equal.

---

Advantages of the first approach:
- with the second approach some higher ranked types stop being equal, even though they are subtypes of each other

General thoughts:
- changing the approach in the future will be breaking
    - going from first to second may break ordinary type checking, as types which were previously equal are now distinct
    - going from second to first may break coherence, because previously disjoint impls overlap as the used types are now equal
    - both of these are quite unlikely. This PR did not result in any crater failures, so this should not matter too much

Advantages of the second approach:
- the soundness of the first approach requires more non-local reasoning. We have to make sure that changes to subtyping do not cause the representative computation to diverge from semantic equality
    - e.g. we intend to consider higher ranked implied bounds when subtyping to [fix] https://github.com/rust-lang/rust/issues/25860, I don't know how this will interact and don't feel confident making any prediction here.
- computing a representative type is non-trivial and soundness critical, therefore adding complexity to the "core type system"

---

This PR goes with the second approach. A crater run did not result in any regressions. I am personally very hesitant about trying the first approach due to the above reasons. It feels like there are more unknowns when going that route.

### Changing the way we equate binders

Relating bound variables from different depths already results in a universe error in equate. We therefore only need to make sure that there is 1-to-1 correspondence between bound variables when relating binders. This results in concrete types being structurally equal after anonymizing their bound variables.

We implement this by instantiating one of the binder with placeholders and the other with inference variables and then equating the instantiated types. We do so in both directions.

More formally, we change the typing rules as follows:

```
for<'r0, .., 'rn> exists<'l0, .., 'ln> LHS<'l0, .., 'ln> <: RHS<'r0, .., 'rn>
for<'l0, .., 'ln> exists<'r0, .., 'rn> RHS<'r0, .., 'rn> <: LHS<'l0, .., 'ln>
--------------------------------------------------------------------------
for<'l0, .., 'ln> LHS<'l0, .., 'ln> eq for<'r0, .., 'rn> RHS<'r0, .., 'rn>
```

to
```
for<'r0, .., 'rn> exists<'l0, .., 'ln> LHS<'l0, .., 'ln> eq RHS<'r0, .., 'rn>
for<'l0, .., 'ln> exists<'r0, .., 'rn> RHS<'r0, .., 'rn> eq LHS<'l0, .., 'ln>
--------------------------------------------------------------------------
for<'l0, .., 'ln> LHS<'l0, .., 'ln> eq for<'r0, .., 'rn> RHS<'r0, .., 'rn>
```

---

Fixes #97156

r? `@lcnr`
2024-02-29 19:18:41 +00:00
Santiago Pastorino
0479287a38
Make nll higher ranked equate use bidirectional subtyping in invariant context 2024-02-29 15:27:59 -03:00
Santiago Pastorino
23ae3dbb31
Make infer higher ranked equate use bidirectional subtyping in invariant context 2024-02-29 15:27:56 -03:00
Ralf Jung
3ed175cc54 add const test for ptr::metadata 2024-02-29 18:48:04 +01:00
León Orell Valerian Liehr
cce81289e6
Detect empty leading where-clauses on type aliases 2024-02-29 17:20:04 +01:00
Guillaume Gomez
a5945b5d8d
Rollup merge of #121669 - nnethercote:count-stashed-errs-again, r=estebank
Count stashed errors again

Stashed diagnostics are such a pain. Their "might be emitted, might not" semantics messes with lots of things.

#120828 and #121206 made some big changes to how they work, improving some things, but still leaving some problems, as seen by the issues caused by #121206. This PR aims to fix all of them by restricting them in a way that eliminates the "might be emitted, might not" semantics while still allowing 98% of their benefit. Details in the individual commit logs.

r? `@oli-obk`
2024-02-29 17:08:38 +01:00
Oli Scherer
7849230740 Forbid implementing Freeze even if the trait is stabilized 2024-02-29 14:10:29 +00:00
Oli Scherer
f030d49536 Expose Freeze trait again 2024-02-29 13:55:11 +00:00
Guillaume Gomez
8e817af3ae Update ui tests 2024-02-29 14:43:43 +01:00
Guillaume Gomez
8a74df9c22
Rollup merge of #121792 - GuillaumeGomez:improve-suggestion, r=michaelwoerister
Improve renaming suggestion when item starts with underscore

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

It goes from:

```terminal
error[E0433]: failed to resolve: use of undeclared type `Foo`
 --> src/foo.rs:6:13
  |
6 |     let _ = Foo::Bar;
  |             ^^^ use of undeclared type `Foo`
  |
help: an enum with a similar name exists, consider changing it
  |
1 | enum Foo {
  |      ~~~
```

to:

```terminal
error[E0433]: failed to resolve: use of undeclared type `Foo`
 --> foo.rs:6:13
  |
6 |     let _ = Foo::Bar;
  |             ^^^ use of undeclared type `Foo`
  |
help: an enum with a similar name exists, consider renaming `_Foo` into `Foo`
  |
1 | enum Foo {
  |      ~~~

error: aborting due to 1 previous error
```
2024-02-29 14:33:53 +01:00
Guillaume Gomez
5978b6ff83
Rollup merge of #121654 - compiler-errors:async-fn-for-fn-def, r=oli-obk
Fix `async Fn` confirmation for `FnDef`/`FnPtr`/`Closure` types

Fixes three issues:
1. The code in `extract_tupled_inputs_and_output_from_async_callable` was accidentally getting the *future* type and the *output* type (returned by the future) messed up for fnptr/fndef/closure types. :/
2. We have a (class of) bug(s) in the old solver where we don't really support higher ranked built-in `Future` goals for generators. This is not possible to hit on stable code, but [can be hit with `unboxed_closures`](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=e935de7181e37e13515ad01720bcb899) (#121653).
    * I'm opting not to fix that in this PR. Instead, I just instantiate placeholders when confirming `async Fn` goals.
4. Fixed a bug when generating `FnPtr` shims for `async Fn` trait goals.

r? oli-obk
2024-02-29 14:33:50 +01:00
Guillaume Gomez
451fd98153 Update UI test checking suggestion message to rename type starting with underscore 2024-02-29 12:08:03 +01:00
yukang
08fa734e32 rename testcase 2024-02-29 19:06:31 +08:00
yukang
97feb71254 Suggest moving if non-found macro_rules! is defined later 2024-02-29 19:01:45 +08:00
Jacob Pratt
23351388d0
Rollup merge of #121745 - compiler-errors:refining-impl-trait-deeply-norm, r=lcnr
Deeply normalize obligations in `refining_impl_trait`

We somewhat awkwardly use semantic comparison when checking the `refining_impl_trait` lint. This relies on us being able to normalize bounds eagerly to avoid cases where an unnormalized alias is not considered equal to a normalized alias. Since `normalize` in the new solver is a noop, let's use `deeply_normalize` instead.

r? lcnr

cc ``@tmandry,`` this should fix your bug lol
2024-02-29 05:25:28 -05:00
lcnr
8c5e83df85 track overflowing goals for overfow errors 2024-02-29 10:28:22 +01:00
lcnr
5ec9b8d778 distinguish recursion limit based overflow for diagnostics
also change the number of allowed fixpoint steps to be fixed instead
of using the `log` of the total recursion depth.
2024-02-29 10:14:02 +01:00
Ralf Jung
a9596fbf2a make mutable_references_err not bitwidth-dependent 2024-02-29 09:34:15 +01:00
Ralf Jung
3cc8c8d44b allow statics pointing to mutable statics 2024-02-29 09:34:15 +01:00
yukang
e2ce5d74a5 renaming test cases 2024-02-29 08:46:00 +08:00
Veera
cc13f8278f Update item order in test 2024-02-28 19:28:34 -05:00
Veera
49961947c8 Improve error messages for generics with default parameters
Fixes #120785
2024-02-28 19:28:18 -05:00
yukang
e6f48fa0bb Suggest removing superfluous semicolos when statements used as expressions 2024-02-29 08:24:00 +08:00
Nicholas Nethercote
260ae70140 Overhaul how stashed diagnostics work, again.
Stashed errors used to be counted as errors, but could then be
cancelled, leading to `ErrorGuaranteed` soundness holes. #120828 changed
that, closing the soundness hole. But it introduced other difficulties
because you sometimes have to account for pending stashed errors when
making decisions about whether errors have occured/will occur and it's
easy to overlook these.

This commit aims for a middle ground.
- Stashed errors (not warnings) are counted immediately as emitted
  errors, avoiding the possibility of forgetting to consider them.
- The ability to cancel (or downgrade) stashed errors is eliminated, by
  disallowing the use of `steal_diagnostic` with errors, and introducing
  the more restrictive methods `try_steal_{modify,replace}_and_emit_err`
  that can be used instead.

Other things:
- `DiagnosticBuilder::stash` and `DiagCtxt::stash_diagnostic` now both
  return `Option<ErrorGuaranteed>`, which enables the removal of two
  `delayed_bug` calls and one `Ty::new_error_with_message` call. This is
  possible because we store error guarantees in
  `DiagCtxt::stashed_diagnostics`.
- Storing the guarantees also saves us having to maintain a counter.
- Calls to the `stashed_err_count` method are no longer necessary
  alongside calls to `has_errors`, which is a nice simplification, and
  eliminates two more `span_delayed_bug` calls and one FIXME comment.
- Tests are added for three of the four fixed PRs mentioned below.
- `issue-121108.rs`'s output improved slightly, omitting a non-useful
  error message.

Fixes #121451.
Fixes #121477.
Fixes #121504.
Fixes #121508.
2024-02-29 11:08:27 +11:00
Nicholas Nethercote
ec25d6db53 Don't cancel stashed TraitMissingMethod errors.
This gives one extra error message on two tests, but is necessary to fix
bigger problems caused by the cancellation of stashed errors.

(Note: why not just avoid stashing altogether? Because that resulted in
additional output changes.)
2024-02-29 11:05:40 +11:00
Nicholas Nethercote
c4ec196c7e Don't cancel stashed OpaqueHiddenTypeMismatch errors.
This gives one extra error message on one test, but is necessary to fix
bigger problems caused by the cancellation of stashed errors.

(Note: why not just avoid stashing altogether? Because that resulted in
additional output changes.)
2024-02-29 11:05:38 +11:00
Matthias Krüger
9f9daed889
Rollup merge of #121743 - compiler-errors:opportunistically-resolve-regions, r=jackh726
Opportunistically resolve regions when processing region outlives obligations

Due to the matching in `TypeOutlives` being structural, we should attempt to opportunistically resolve regions before processing region obligations. Thanks ``@lcnr`` for finding this.

r? lcnr
2024-02-29 00:17:01 +01:00
Matthias Krüger
686a4b1c17
Rollup merge of #121724 - nnethercote:LitKind-Err-for-floats, r=fmease
Use `LitKind::Err` for malformed floats

#121120 changed `StringReader::cook_lexer_literal` to return `LitKind::Err` for malformed integer literals. This commit does the same for float literals, for consistency.

r? ``@fmease``
2024-02-29 00:17:00 +01:00
许杰友 Jieyou Xu (Joe)
a1dbb61c09
Unify long type name file and note in note_obligation_cause_code 2024-02-28 19:54:05 +00:00
Trevor Gross
406790e9d1 Add a basic test for f16 and f128 2024-02-28 12:58:32 -05:00
Gil Shoshan
bf8756d2dd
Don't lint snake-case on executable crate name
Co-authored-by: Jieyou Xu <jieyouxu@outlook.com>
2024-02-28 16:55:00 +00:00
Michael Goulet
75e15f7cf4 Deeply normalize obligations in refining_impl_trait 2024-02-28 16:09:29 +00:00
Michael Goulet
5cdbe83af8 Opportunistically resolve regions when processing region outlives obligations 2024-02-28 15:44:04 +00:00
Guillaume Gomez
1b08d1a92c
Rollup merge of #121702 - compiler-errors:coerce-alias-relate, r=lcnr
Process alias-relate obligations in CoerceUnsized loop

After #119106, we now emit `AliasRelate` goals when relating `?0` and `Alias<T, ..>` in the new solver. In the ad-hoc `CoerceUnsized` selection loop, we now may have `AliasRelate` goals which must be processed to constrain type variables which are mentioned in other goals.

---

For example, in the included test, we try to coerce `&<ManuallyDrop<T> as Deref>::Target` to `&dyn Foo`. This requires proving:
* 1 `&<ManuallyDrop<T> as Deref>::Target: CoerceUnsized<&dyn Foo>`
    * 2 `<ManuallyDrop<T> as Deref>::Target alias-relate ?0`
    * 3 `?0: Unsize<dyn Foo>`
        * 4 `?0: Foo`
        * 5 `?0: Sized`

If we don't process goal (2.) before processing goal (3.), then we hit ambiguity since `?0` is never constrained, and therefore we bail out, refusing to coerce the types. After processing (2.), we know `?0 := T`, and the rest of the goals can be processed normally.
2024-02-28 16:04:54 +01:00
Guillaume Gomez
ca69a1ff75
Rollup merge of #121698 - rcvalle:rust-cfi-fix-typo, r=compiler-errors
CFI: Fix typo in test file names

Fixes typo (i.e., saniziter) in test file names.
2024-02-28 16:04:54 +01:00
Guillaume Gomez
a0027e86aa
Rollup merge of #121686 - compiler-errors:rpitit-printing, r=lcnr
Adjust printing for RPITITs

1. Call RPITITs `{synthetic#N}` instead of `{opaque#N}`.
2. Fall back to printing the RPITIT like an opaque even when printed as an `AliasTy`, just like we do for `ty::Alias`.

You could argue that (2.) is misleading, but I believe it's more consistent than naming `{synthetic#N}`, which I assume approximately nobody knows where that def path name comes from.

r? lcnr
2024-02-28 16:04:52 +01:00
Guillaume Gomez
d8e6550838
Rollup merge of #121527 - Enselic:unix_sigpipe-tests-fixes, r=davidtwco
unix_sigpipe: Simple fixes and improvements in tests

In https://github.com/rust-lang/rust/pull/120832 I included 5 preparatory commits.

It will take a while before discussions there and in https://github.com/rust-lang/rust/issues/62569 is settled, so here is a PR that splits out 4 of the commits that are easy to review, to get them out of the way.

r? ``@davidtwco`` who already approved these commits in https://github.com/rust-lang/rust/pull/120832 (but I have tweaked them a bit and rebased them since then).

For the convenience of my reviewer, here are the full commit messages of the commits:
<details>
<summary>Click to expand</summary>

```
commit 948b1d68ab (HEAD -> unix_sigpipe-tests-fixes, origin/unix_sigpipe-tests-fixes)
Author: Martin Nordholts <martin.nordholts@codetale.se>
Date:   Fri Feb 9 07:57:27 2024 +0100

    tests: Add unix_sigpipe-different-duplicates.rs test variant

    To make sure that

        #[unix_sigpipe = "x"]
        #[unix_sigpipe = "y"]

    behaves like

        #[unix_sigpipe = "x"]
        #[unix_sigpipe = "x"]

commit d14f15862d
Author: Martin Nordholts <martin.nordholts@codetale.se>
Date:   Fri Feb 9 08:47:47 2024 +0100

    tests: Combine unix_sigpipe-not-used.rs and unix_sigpipe-only-feature.rs

    The only difference between the files is the presence/absence of

        #![feature(unix_sigpipe)]

    attribute. Avoid duplication by using revisions instead.

commit a1cb3dba84
Author: Martin Nordholts <martin.nordholts@codetale.se>
Date:   Fri Feb 9 06:44:56 2024 +0100

    tests: Rename unix_sigpipe.rs to unix_sigpipe-bare.rs for clarity

    The test is for the "bare" variant of the attribute that looks like this:

        #[unix_sigpipe]

    which is not allowed, because it must look like this:

        #[unix_sigpipe = "sig_ign"]

commit e060274e55
Author: Martin Nordholts <martin.nordholts@codetale.se>
Date:   Fri Feb 9 05:48:24 2024 +0100

    tests: Fix typo unix_sigpipe-error.rs -> unix_sigpipe-sig_ign.rs

    There is no error expected. It's simply the "regular" test for sig_ign.
    So rename it.
```

</details>

Tracking issue: https://github.com/rust-lang/rust/issues/97889
2024-02-28 16:04:50 +01:00
Guillaume Gomez
c5dafe66ba
Rollup merge of #121226 - chenyukang:yukang-fix-import-alias, r=davidtwco
Fix issues in suggesting importing extern crate paths

Fixes #121168

r? ``@petrochenkov``
2024-02-28 16:04:49 +01:00
许杰友 Jieyou Xu (Joe)
c0ce0f3c3f
Display short types for unimplemented trait 2024-02-28 14:13:42 +00:00
Nicholas Nethercote
840c8d3243 Use LitKind::Err for floats with unsupported bases.
This slightly changes error messages in `float-field.rs`, but nothing of
real importance.
2024-02-28 20:59:32 +11:00
Nicholas Nethercote
79766098a4 Reformat float-field.rs test.
- Put every literal in its own braces, rather than just some of them,
  for maximal error recovery.
- Add a blank line between every case, for readability.
2024-02-28 20:59:32 +11:00
Nicholas Nethercote
951f2d9ae2 Use LitKind::Err for floats with empty exponents.
This prevents a follow-up type error in a test, which seems fine.
2024-02-28 20:59:27 +11:00
Oli Scherer
c86974d94f test that fudging with opaque types is the same in the new solver 2024-02-28 09:54:44 +00:00
Nadrieril
97bfa106c7 Add test for the known case that doesn't work 2024-02-28 01:41:25 +01:00
Michael Goulet
cc584ba245 Process alias-relate obligations in CoerceUnsized loop 2024-02-27 20:07:58 +00:00
Ramon de C Valle
c7476f86b5 CFI: Fix typo in test file names
Fixes typo (i.e., saniziter) in test file names.
2024-02-27 11:03:02 -08:00
Michael Goulet
b57ddfe079 Print RPITIT like an opaque 2024-02-27 17:43:40 +00:00
Michael Goulet
1feef44daf rename RPITIT from opaque to synthetic 2024-02-27 17:43:40 +00:00
lcnr
af0d5082ee update comments 2024-02-27 18:40:58 +01:00
Michael Goulet
c8e3f35eb6 Flesh out a few more tests 2024-02-27 17:39:20 +00:00
Michael Goulet
2252ff7302 Also support fnptr(): async Fn in codegen 2024-02-27 17:21:40 +00:00
Michael Goulet
a6727bad88 Support {async closure}: Fn in new solver 2024-02-27 17:21:39 +00:00
Jack Wrenn
23ab1bda92 safe transmute: revise safety analysis
Migrate to a simplified safety analysis that does not use visibility.

Closes https://github.com/rust-lang/project-safe-transmute/issues/15
2024-02-27 16:22:32 +00:00
lcnr
6591c80eea use typeck root when checking closure oblig 2024-02-27 17:13:51 +01:00
Ryan Levick
f115064631 Add the wasm32-wasi-preview2 target
Signed-off-by: Ryan Levick <me@ryanlevick.com>
2024-02-27 09:58:04 -05:00
lcnr
71d82c2899 when defining opaques, require the hidden type to be well-formed 2024-02-27 15:57:49 +01:00
lcnr
93bc7a428c wf-check RPITs 2024-02-27 15:00:22 +01:00
Georg Semmler
d013b5a462
Stabilize the #[diagnostic] namespace and #[diagnostic::on_unimplemented] attribute
This PR stabilizes the `#[diagnostic]` attribute namespace and a minimal
option of the `#[diagnostic::on_unimplemented]` attribute.

The `#[diagnostic]` attribute namespace is meant to provide a home for
attributes that allow users to influence error messages emitted by the
compiler. The compiler is not guaranteed to use any of this hints,
however it should accept any (non-)existing attribute in this namespace
and potentially emit lint-warnings for unused attributes and options.
This is meant to allow discarding certain attributes/options in the
future to allow fundamental changes to the compiler without the need to
keep then non-meaningful options working.

The `#[diagnostic::on_unimplemented]` attribute is allowed to appear
on a trait definition. This allows crate authors to hint the compiler
to emit a specific error message if a certain trait is not implemented.
For the `#[diagnostic::on_unimplemented]` attribute the following
options are implemented:

* `message` which provides the text for the top level error message
* `label` which provides the text for the label shown inline in the
broken code in the error message
* `note` which provides additional notes.

The `note` option can appear several times, which results in several
note messages being emitted. If any of the other options appears several
times the first occurrence of the relevant option specifies the actually
used value. Any other occurrence generates an lint warning. For any
other non-existing option a lint-warning is generated.

All three options accept a text as argument. This text is allowed to
contain format parameters referring to generic argument or `Self` by
name via the `{Self}` or `{NameOfGenericArgument}` syntax. For any
non-existing argument a lint warning is generated.

Tracking issue: #111996
2024-02-27 08:50:56 +01:00
Michael Goulet
e0a726ca4b Adjust error yield/await lowering 2024-02-27 03:20:10 +00:00
bors
71ffdf7ff7 Auto merge of #121655 - matthiaskrgr:rollup-qpx3kks, r=matthiaskrgr
Rollup of 4 pull requests

Successful merges:

 - #121598 (rename 'try' intrinsic to 'catch_unwind')
 - #121639 (Update books)
 - #121648 (Update Vec and String `{from,into}_raw_parts`-family docs)
 - #121651 (Properly emit `expected ;` on `#[attr] expr`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-27 00:55:14 +00:00
Matthias Krüger
ec5c5b7da8
Rollup merge of #121651 - ShE3py:issue-121647, r=estebank
Properly emit `expected ;` on `#[attr] expr`

Fixes #121647

See #118182, #120586

---
r? estebank
2024-02-27 00:40:01 +01:00
Matthias Krüger
d95c321062
Rollup merge of #121598 - RalfJung:catch_unwind, r=oli-obk
rename 'try' intrinsic to 'catch_unwind'

The intrinsic has nothing to do with `try` blocks, and corresponds to the stable `catch_unwind` function, so this makes a lot more sense IMO.

Also rename Miri's special function while we are at it, to reflect the level of abstraction it works on: it's an unwinding mechanism, on which Rust implements panics.
2024-02-27 00:40:00 +01:00
bors
5c786a7fe3 Auto merge of #121516 - RalfJung:platform-intrinsics-begone, r=oli-obk
remove platform-intrinsics ABI; make SIMD intrinsics be regular intrinsics

`@Amanieu` `@workingjubilee` I don't think there is any reason these need to be "special"? The [original RFC](https://rust-lang.github.io/rfcs/1199-simd-infrastructure.html) indicated eventually making them stable, but I think that is no longer the plan, so seems to me like we can clean this up a bit.

Blocked on https://github.com/rust-lang/stdarch/pull/1538, https://github.com/rust-lang/rust/pull/121542.
2024-02-26 22:24:16 +00:00
Lieselotte
1658ca082a
Properly emit expected ; on #[attr] expr 2024-02-26 21:47:10 +01:00
Matthias Krüger
218be2771d
Rollup merge of #121628 - gurry:121534-ice-asymm-binop, r=oli-obk
Do not const prop unions

Unions can produce values whose types don't match their underlying layout types which can lead to ICEs on eval.

Fixes #121534
2024-02-26 16:06:04 +01:00
Matthias Krüger
4f167b4baf
Rollup merge of #121617 - compiler-errors:async-closure-kind-check, r=oli-obk
Actually use the right closure kind when checking async Fn goals

Dumb copy-paste mistake on my part from #120712. Sorry!

r? oli-obk

Fixes #121599
2024-02-26 16:06:04 +01:00
bors
b8de591b65 Auto merge of #119106 - lcnr:decrement-universes, r=BoxyUwU
avoid generalization inside of aliases

The basic idea of this PR is that we don't generalize aliases when the instantiation could fail later on, either due to the *occurs check* or because of a universe error. We instead replace the whole alias with an inference variable and emit a nested `AliasRelate` goal. This `AliasRelate` then fully normalizes the alias before equating it with the inference variable, at which point the alias can be treated like any other rigid type.

We now treat aliases differently depending on whether they are *rigid* or not. To detect whether an alias is rigid we check whether `NormalizesTo` fails. While we already do so inside of `AliasRelate` anyways, also doing so when instantiating a query response would be both ugly/difficult and likely inefficient. To avoid that I change `instantiate_and_apply_query_response` to relate types completely structurally. This change generally removes a lot of annoying complexity, which is nice. It's implemented by adding a flag to `Equate` to change it to structurally handle aliases.

We currently always apply constraints from canonical queries right away. By providing all the necessary information to the canonical query, we can guarantee that instantiating the query response never fails, which further simplifies the implementation. This does add the invariant that *any information which could cause instantiating type variables to fail must also be available inside of the query*.

While it's acceptable for canonicalization to result in more ambiguity, we must not cause the solver to incompletely structurally relate aliases by erasing information. This means we have to be careful when merging universes during canonicalization. As we only generalize for type and const variables we have to make sure that anything nameable by such a type or const variable inside of the canonical query is also nameable outside of it. Because of this we both stop merging universes of existential variables when canonicalizing inputs, we put all uniquified regions into a higher universe which is not nameable by any type or const variable.

I will look into always replacing aliases with inference variables when generalizing in a later PR unless the alias references bound variables. This should both pretty much fix https://github.com/rust-lang/trait-system-refactor-initiative/issues/4. This may allow us to merge the universes of existential variables again by changing generalize to not consider their universe when deciding whether to generalize aliases. This requires some additional non-trivial changes to alias-relate, so I am leaving that as future work.

Fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/79. While it would be nice to decrement universe indices when existing a `forall`, that was surprisingly difficult and not necessary to fix this issue. I am really happy with the approach in this PR think it is the correct way forward to also fix the remaining cases of https://github.com/rust-lang/trait-system-refactor-initiative/issues/8.
2024-02-26 12:11:58 +00:00
Ralf Jung
b4ca582b89 rename 'try' intrinsic to 'catch_unwind' 2024-02-26 11:10:18 +01:00
lcnr
1c264ca9ca add regression tests 2024-02-26 11:01:31 +01:00
lcnr
2c7ede8f52 update tests 2024-02-26 10:57:46 +01:00
Gurinder Singh
633c92cd6d Do not const pop unions
as they can made to produce values whose types don't
match their underlying layout types which can lead to
ICEs on eval
2024-02-26 15:22:22 +05:30
Guillaume Gomez
76f303d658
Rollup merge of #121620 - nnethercote:fix-even-more-121208-fallout, r=lcnr
Fix more #121208 fallout (round 3)

#121208 converted lots of delayed bugs to bugs. Unsurprisingly, there were a few invalid conversion found via fuzzing.

r? `@lcnr`
2024-02-26 10:27:43 +01:00
Guillaume Gomez
5bd909227d
Rollup merge of #121554 - Enselic:sigaction, r=oli-obk
Don't unnecessarily change `SIGPIPE` disposition in `unix_sigpipe` tests

In `auxiliary/sigpipe-utils.rs`, all we want to know is the current `SIGPIPE` disposition. We should not change it. So use `libc::sigaction` instead of `libc::signal`. That way we can also remove the code that restores it.

Part of https://github.com/rust-lang/rust/issues/97889.
2024-02-26 10:27:42 +01:00
Guillaume Gomez
91d337dfa8
Rollup merge of #120840 - HTGAzureX1212:HTGAzureX1212/unicode-identifier-types, r=fmease,Manishearth
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.
2024-02-26 10:27:41 +01:00
HTGAzureX1212.
8bccceb8fc separate messages for individual categories 2024-02-26 10:09:03 +08:00
Michael Goulet
ff07f55db5 Actually use the right closure kind when checking async Fn goals 2024-02-26 01:36:14 +00:00
bors
0250ef2571 Auto merge of #121461 - reitermarkus:generic-nonzero-tests, r=dtolnay
Use generic `NonZero` in tests.

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

r? `@dtolnay`
2024-02-26 01:16:16 +00:00
Nicholas Nethercote
edda2a7d3e Revert some span_bugs to span_delayed_bug.
Fixes #121503.
Fixes #121597.
2024-02-26 10:57:30 +11:00
bors
b0d3e04ca9 Auto merge of #120393 - Urgau:rfc3373-non-local-defs, r=WaffleLapkin
Implement RFC 3373: Avoid non-local definitions in functions

This PR implements [RFC 3373: Avoid non-local definitions in functions](https://github.com/rust-lang/rust/issues/120363).
2024-02-25 19:11:06 +00:00
Matthias Krüger
a4423884c1
Rollup merge of #121586 - gurry:121532-ice-unwrap-on-none, r=cjgillot
Don't use `unwrap()` in `ArrayIntoIter` lint when typeck fails

Fixes #121532
2024-02-25 17:05:23 +01:00
Matthias Krüger
4d442f5a58
Rollup merge of #121409 - compiler-errors:atb-cycle, r=cjgillot
Prevent cycle in implied predicates computation

Makes #65913 from hang -> fail. I believe fail is the correct state for this test to remain for the long term.
2024-02-25 17:05:22 +01:00
Matthias Krüger
c99902e2f9
Rollup merge of #120805 - RalfJung:const-pat-partial-eq, r=oli-obk
make non-PartialEq-typed consts as patterns a hard error

This lint was introduced in https://github.com/rust-lang/rust/pull/115893, for Rust 1.74, so we just had the third stable release where this is shown as a future-compat lint (which is shown for dependencies). Not a single comment or backreference showed up in the tracking issue, https://github.com/rust-lang/rust/issues/116122. So this seems fairly safe to turn into a hard error.

Of course we should do a crater run first.

This is part of https://github.com/rust-lang/rust/issues/120362.
Closes https://github.com/rust-lang/rust/issues/116122.
2024-02-25 17:05:20 +01:00
Matthias Krüger
e13f454874
Rollup merge of #119590 - ChrisDenton:cfg-target-abi, r=Nilstrieb
Stabilize `cfg_target_abi`

This stabilizes the `cfg` option called `target_abi`:

```rust
#[cfg(target_abi = "eabihf")]
```

Tracking issue: #80970

fixes #78791
resolves #80970
2024-02-25 17:05:19 +01:00
Gurinder Singh
fa7557181f Don't use unwrap() in ArrayIntoIter lint when typeck fails 2024-02-25 17:51:56 +05:30
Markus Reiter
b2fbb8a053
Use generic NonZero in tests. 2024-02-25 12:03:48 +01:00
Ralf Jung
5b7786cd1d make non-PartialEq-typed consts as patterns a hard error 2024-02-25 11:30:10 +01:00
Suyashtnt
748c6151be
make unused_imports less assertive in test modules
closes #121502
2024-02-25 09:37:57 +02:00
Ralf Jung
c1d0e489e5 fix use of platform_intrinsics in tests 2024-02-25 08:15:44 +01:00
yukang
3bcef2dc1b Fix issues in suggesting importing extern crate paths 2024-02-25 11:29:13 +08:00
bors
2ae1bb6711 Auto merge of #121569 - matthiaskrgr:rollup-awglrax, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #121343 (Add examples for some methods on slices)
 - #121374 (match lowering: Split off `test_candidates` into several functions and improve comments)
 - #121474 (Ignore compiletest test directive migration commits)
 - #121515 (promotion: don't promote int::MIN / -1)
 - #121530 (Fix incorrect doc of ScopedJoinHandle::is_finished)
 - #121551 (Forbid use of `extern "C-unwind"` inside standard library)
 - #121556 (Use `addr_of!`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-24 23:08:21 +00:00
Chris Denton
93ec0e6299
Stabilize cfg_target_abi 2024-02-24 17:52:03 -03:00
Gary Guo
4677a71369 Add tests for asm goto 2024-02-24 19:49:16 +00:00
Martin Nordholts
f5b9eaf18f Don't unnecessarily change SIGPIPE disposition in unix_sigpipe tests
In `auxiliary/sigpipe-utils.rs`, all we want to know is the current
`SIGPIPE` disposition. We should not change it. So use `libc::sigaction`
instead of `libc::signal`. That way we can also remove the code that
restores it.
2024-02-24 16:18:34 +01:00
Matthias Krüger
b87a713b9d
Rollup merge of #121522 - RalfJung:insert-extract-boundscheck, r=oli-obk
check that simd_insert/extract indices are in-bounds

Fixes https://github.com/rust-lang/rust/issues/77477
r? `@oli-obk`
2024-02-24 15:35:14 +01:00
Matthias Krüger
b10ef3c6bc
Rollup merge of #121435 - estebank:rpitit-static-119773, r=compiler-errors
Account for RPITIT in E0310 explicit lifetime constraint suggestion

When given

```rust
trait Original {
    fn f() -> impl Fn();
}

trait Erased {
    fn f(&self) -> Box<dyn Fn()>;
}

impl<T: Original> Erased for T {
    fn f(&self) -> Box<dyn Fn()> {
        Box::new(<T as Original>::f())
    }
}
```

emit do not emit an invalid suggestion restricting the `Trait::{opaque}` type in a `where` clause:

```
error[E0310]: the associated type `<T as Original>::{opaque#0}` may not live long enough
  --> $DIR/missing-static-bound-from-impl.rs:11:9
   |
LL |         Box::new(<T as Original>::f())
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |         |
   |         the associated type `<T as Original>::{opaque#0}` must be valid for the static lifetime...
   |         ...so that the type `impl Fn()` will meet its required lifetime bounds
```

Partially address #119773. Ideally we'd suggest modifying `Erased::f` instead.

r? `@compiler-errors`
2024-02-24 15:35:12 +01:00
Ralf Jung
f32095cd8d promotion: don't promote int::MIN / -1 2024-02-24 12:17:37 +01:00
Martin Nordholts
948b1d68ab tests: Add unix_sigpipe-different-duplicates.rs test variant
To make sure that

    #[unix_sigpipe = "x"]
    #[unix_sigpipe = "y"]

behaves like

    #[unix_sigpipe = "x"]
    #[unix_sigpipe = "x"]
2024-02-23 22:03:09 +01:00
Martin Nordholts
d14f15862d tests: Combine unix_sigpipe-not-used.rs and unix_sigpipe-only-feature.rs
The only difference between the files is the presence/absence of

    #![feature(unix_sigpipe)]

attribute. Avoid duplication by using revisions instead.
2024-02-23 22:03:09 +01:00
Martin Nordholts
a1cb3dba84 tests: Rename unix_sigpipe.rs to unix_sigpipe-bare.rs for clarity
The test is for the "bare" variant of the attribute that looks like this:

    #[unix_sigpipe]

which is not allowed, because it must look like this:

    #[unix_sigpipe = "sig_ign"]
2024-02-23 22:02:27 +01:00
Martin Nordholts
e060274e55 tests: Fix typo unix_sigpipe-error.rs -> unix_sigpipe-sig_ign.rs
There is no error expected. It's simply the "regular" test for sig_ign.
So rename it.
2024-02-23 21:59:35 +01:00
Ralf Jung
8e0dd993d6 check that simd_insert/extract indices are in-bounds 2024-02-23 19:43:59 +01:00
Matthias Krüger
06e54f8d49
Rollup merge of #121510 - RalfJung:lint-overflowing-ops, r=oli-obk
lint-overflowing-ops: unify cases and remove redundancy

Follow-up to https://github.com/rust-lang/rust/pull/121432
r? `@oli-obk`
2024-02-23 17:02:06 +01:00
Matthias Krüger
4d5c4e5205
Rollup merge of #121470 - clubby789:anon-struct-in-enum, r=fmease
Don't ICE on anonymous struct in enum variant

Fixes #121446

Computing `adt_def` for the anon struct calls `adt_def` on the parent to find its repr. If the parent is a non-item (e.g. an enum variant) we should have already emitted at least one error, so we just use the repr of the anonymous struct to avoid an ICE.

cc ``@frank-king``
2024-02-23 17:02:04 +01:00
Matthias Krüger
26cb6c7287
Rollup merge of #120742 - Nadrieril:use-min_exh_pats, r=compiler-errors
mark `min_exhaustive_patterns` as complete

This is step 1 and 2 of my [proposal](https://github.com/rust-lang/rust/issues/119612#issuecomment-1918097361) to move `min_exhaustive_patterns` forward. The vast majority of in-tree use cases of `exhaustive_patterns` are covered by `min_exhaustive_patterns`. There are a few cases that still require `exhaustive_patterns` in tests and they're all behind references.

r? ``@ghost``
2024-02-23 17:02:03 +01:00
Ralf Jung
9a2d550050 lint-overflowing-ops: unify cases and remove redundancy 2024-02-23 15:29:33 +01:00
clubby789
35a9e73521 Don't ICE on anonymous struct in enum variant 2024-02-23 12:25:23 +00:00
Matthias Krüger
52805b0cb4
Rollup merge of #121482 - nnethercote:fix-121455, r=oli-obk
Allow for a missing `adt_def` in `NamePrivacyVisitor`.

This was caused by 72b172bdf6 in #121206. That commit removed an early return from `analysis` when there are stashed errors. As a result, it's possible to reach privacy analysis when there are stashed errors, which means more code paths can be reached. One such code path was handled in that commit, where a `span_bug` was changed to a `span_delayed_bug`.

This commit handles another such code path uncovered by fuzzing, in much the same way.

Fixes #121455.

r? `@oli-obk`
2024-02-23 09:42:13 +01:00
Matthias Krüger
5de3a4ce0e
Rollup merge of #121480 - nnethercote:fix-more-121208-fallout, r=lcnr
Fix more #121208 fallout

#121208 converted lots of delayed bugs to bugs. Unsurprisingly, there were a few invalid conversion found via fuzzing.

r? `@lcnr`
2024-02-23 09:42:12 +01:00
Matthias Krüger
86727df4ed
Rollup merge of #121471 - estebank:lint-clone, r=TaKO8Ki
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);
   |
```
2024-02-23 09:42:11 +01:00
Matthias Krüger
6e00f0d189
Rollup merge of #121434 - nnethercote:fix-121208-fallout, r=lcnr
Fix #121208 fallout

#121208 converted lots of delayed bugs to bugs. Unsurprisingly, there were a few invalid conversion found via fuzzing.

r? `@lcnr`
2024-02-23 09:42:10 +01:00
bors
dda102c190 Auto merge of #121432 - mj10021:issue-119851-fix, r=nnethercote
Move as many tests from tests/ui/numbers-arithmetic to tests/ui/lint as possible

Fixes #119851 , and also consolidates as many individual tests as possible from numbers-arithmetic.  I might have moved the tests in too aggressively, so let me know
2024-02-23 05:42:20 +00:00
bors
a28d221a4b Auto merge of #120730 - estebank:confusable-api, r=oli-obk
Provide suggestions through `rustc_confusables` annotations

Help with common API confusion, like asking for `push` when the data structure really has `append`.

```
error[E0599]: no method named `size` found for struct `Vec<{integer}>` in the current scope
  --> $DIR/rustc_confusables_std_cases.rs:17:7
   |
LL |     x.size();
   |       ^^^^
   |
help: you might have meant to use `len`
   |
LL |     x.len();
   |       ~~~
help: there is a method with a similar name
   |
LL |     x.resize();
   |       ~~~~~~
```

Fix #59450 (we can open subsequent tickets for specific cases).

Fix #108437:

```
error[E0599]: `Option<{integer}>` is not an iterator
   --> f101.rs:3:9
    |
3   |     opt.flat_map(|val| Some(val));
    |         ^^^^^^^^ `Option<{integer}>` is not an iterator
    |
   ::: /home/gh-estebank/rust/library/core/src/option.rs:571:1
    |
571 | pub enum Option<T> {
    | ------------------ doesn't satisfy `Option<{integer}>: Iterator`
    |
    = note: the following trait bounds were not satisfied:
            `Option<{integer}>: Iterator`
            which is required by `&mut Option<{integer}>: Iterator`
help: you might have meant to use `and_then`
    |
3   |     opt.and_then(|val| Some(val));
    |         ~~~~~~~~
```

On type error of method call arguments, look at confusables for suggestion. Fix #87212:

```
error[E0308]: mismatched types
    --> f101.rs:8:18
     |
8    |     stuff.append(Thing);
     |           ------ ^^^^^ expected `&mut Vec<Thing>`, found `Thing`
     |           |
     |           arguments to this method are incorrect
     |
     = note: expected mutable reference `&mut Vec<Thing>`
                           found struct `Thing`
note: method defined here
    --> /home/gh-estebank/rust/library/alloc/src/vec/mod.rs:2025:12
     |
2025 |     pub fn append(&mut self, other: &mut Self) {
     |            ^^^^^^
help: you might have meant to use `push`
     |
8    |     stuff.push(Thing);
     |           ~~~~
```
2024-02-23 00:42:56 +00:00
Nicholas Nethercote
21bb1a4359 Allow for a missing adt_def in NamePrivacyVisitor.
This was caused by 72b172bdf6 in #121206. That commit removed an early
return from `analysis` when there are stashed errors. As a result, it's
possible to reach privacy analysis when there are stashed errors, which
means more code paths can be reached. One such code path was handled in
that commit, where a `span_bug` was changed to a `span_delayed_bug`.

This commit handles another such code path uncovered by fuzzing, in much
the same way.

Fixes #121455.
2024-02-23 10:57:11 +11:00
Nicholas Nethercote
109321ac47 Revert some span_bugs to span_delayed_bug.
Fixes #121445.
Fixes #121457.
2024-02-23 10:04:32 +11:00
Nicholas Nethercote
4f83e50f98 Revert some span_bugs to span_delayed_bug.
Fixes #121410.
Fixes #121414.
Fixes #121418.
Fixes #121431.
2024-02-23 08:35:18 +11:00
bors
397937d812 Auto merge of #119989 - lcnr:sub_relations-bye-bye, r=compiler-errors
remove `sub_relations` from the `InferCtxt`

While doing so, I tried to remove the `delay_span_bug` in `rematch_impl` again, which lead me to discover another `freshen` bug, fixing that one in the second commit. See commit descriptions for the reasoning behind each change.

r? `@compiler-errors`
2024-02-22 20:45:24 +00:00
Esteban Küber
5e6da720f6 Account for RPITIT in E0310 explicit lifetime constraint suggestion
When given

```rust
trait Original {
    fn f() -> impl Fn();
}

trait Erased {
    fn f(&self) -> Box<dyn Fn()>;
}

impl<T: Original> Erased for T {
    fn f(&self) -> Box<dyn Fn()> {
        Box::new(<T as Original>::f())
    }
}
```

avoid suggestion to restrict the `Trait::{opaque}` type in a `where` clause:

```
error[E0310]: the associated type `<T as Original>::{opaque#0}` may not live long enough
  --> $DIR/missing-static-bound-from-impl.rs:11:9
   |
LL |         Box::new(<T as Original>::f())
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |         |
   |         the associated type `<T as Original>::{opaque#0}` must be valid for the static lifetime...
   |         ...so that the type `impl Fn()` will meet its required lifetime bounds
```

CC #119773.
2024-02-22 18:56:07 +00:00
Esteban Küber
91d0b371ef Fix rebase 2024-02-22 18:38:10 +00:00
Esteban Küber
fdaaaa1951 fix test 2024-02-22 18:05:28 +00:00
Esteban Küber
28c028737d Deduplicate some logic and reword output 2024-02-22 18:05:28 +00:00
Esteban Küber
caa216d245 Tweak wording of "implemented trait isn't imported" suggestion 2024-02-22 18:05:27 +00:00
Esteban Küber
14277ef201 Better account for associated const found for fn call expr 2024-02-22 18:04:55 +00:00
Esteban Küber
76885673d6 fix test 2024-02-22 18:04:55 +00:00
Esteban Küber
e1e4da2b0a Make confusable suggestions verbose 2024-02-22 18:04:55 +00:00
Esteban Küber
385eea1d46 Consider methods from traits when suggesting typos
Do not provide a structured suggestion when the arguments don't match.

```
error[E0599]: no method named `test_mut` found for struct `Vec<{integer}>` in the current scope
  --> $DIR/auto-ref-slice-plus-ref.rs:7:7
   |
LL |     a.test_mut();
   |       ^^^^^^^^
   |
   = help: items from traits can only be used if the trait is implemented and in scope
note: `MyIter` defines an item `test_mut`, perhaps you need to implement it
  --> $DIR/auto-ref-slice-plus-ref.rs:14:1
   |
LL | trait MyIter {
   | ^^^^^^^^^^^^
help: there is a method `get_mut` with a similar name, but with different arguments
  --> $SRC_DIR/core/src/slice/mod.rs:LL:COL
```

Consider methods beyond inherent ones when suggesting typos.

```
error[E0599]: no method named `owned` found for reference `&dyn Foo` in the current scope
  --> $DIR/object-pointer-types.rs:11:7
   |
LL |     fn owned(self: Box<Self>);
   |                    --------- the method might not be found because of this arbitrary self type
...
LL |     x.owned();
   |       ^^^^^ help: there is a method with a similar name: `to_owned`
```

Fix #101013.
2024-02-22 18:04:55 +00:00
Esteban Küber
d30dfb0af7 Provide more and more accurate suggestions when calling the wrong method
```
error[E0308]: mismatched types
  --> $DIR/rustc_confusables_std_cases.rs:20:14
   |
LL |     x.append(42);
   |       ------ ^^ expected `&mut Vec<{integer}>`, found integer
   |       |
   |       arguments to this method are incorrect
   |
   = note: expected mutable reference `&mut Vec<{integer}>`
                           found type `{integer}`
note: method defined here
  --> $SRC_DIR/alloc/src/vec/mod.rs:LL:COL
help: you might have meant to use `push`
   |
LL |     x.push(42);
   |       ~~~~
```
2024-02-22 18:04:55 +00:00
Esteban Küber
0e89465672 On type error of method call arguments, look at confusables for suggestion 2024-02-22 18:04:55 +00:00
Esteban Küber
e5b3c7ef14 Add rustc_confusables annotations to some stdlib APIs
Help with common API confusion, like asking for `push` when the data structure really has `append`.

```
error[E0599]: no method named `size` found for struct `Vec<{integer}>` in the current scope
  --> $DIR/rustc_confusables_std_cases.rs:17:7
   |
LL |     x.size();
   |       ^^^^
   |
help: you might have meant to use `len`
   |
LL |     x.len();
   |       ~~~
help: there is a method with a similar name
   |
LL |     x.resize();
   |       ~~~~~~
```

#59450
2024-02-22 18:04:55 +00:00
Esteban Küber
6017de46f7 When encountering <&T as Clone>::clone(x) because T: Clone, suggest #[derive(Clone)]
CC #40699.
2024-02-22 18:01:20 +00:00
lcnr
c71484eefd change error messages to be incorrect, but more helpful 2024-02-22 18:18:33 +01:00
Matthias Krüger
379ef9bd36
Rollup merge of #121386 - oli-obk:no_higher_ranked_opaques, r=lcnr
test that we do not support higher-ranked regions in opaque type inference

We already do all the right checks in `check_opaque_type_parameter_valid`, and we have done so since at least 2 years.

I collected the tests from https://github.com/rust-lang/rust/pull/116935 and https://github.com/rust-lang/rust/pull/100503 and added some more

cc https://github.com/rust-lang/rust/issues/96146

r? `@lcnr`
2024-02-22 18:09:52 +01:00
Matthias Krüger
702225e290
Rollup merge of #120598 - compiler-errors:no-rigid-check, r=lcnr
No need to `validate_alias_bound_self_from_param_env` in `assemble_alias_bound_candidates`

We already fully normalize the self type before we reach `assemble_alias_bound_candidates`, so there's no reason to double check that a projection is truly rigid by checking param-env bounds.

I think this is also blocked on us making sure to always normalize opaques: #120549.

r? lcnr
2024-02-22 18:09:52 +01:00
Oli Scherer
1efb7479ef Remove some annotations that just specify the default 2024-02-22 16:56:26 +00:00
lcnr
49dc0f22f4 do not use <: in subtyping overflow msg 2024-02-22 17:43:59 +01:00
lcnr
f7cdff825c overflow errors: change source to a concrete enum 2024-02-22 17:43:57 +01:00
lcnr
f392a870e9 freshen: resolve root vars
Without doing so we use the same candidate cache entry
for `?0: Trait<?1>` and `?0: Trait<?0>`. These goals are different
and we must not use the same entry for them.
2024-02-22 17:29:26 +01:00
lcnr
91535ad026 remove sub_relations from infcx, recompute in diagnostics
we don't track them when canonicalizing or when freshening,
resulting in instable caching in the old solver, and issues when
instantiating query responses in the new one.
2024-02-22 17:29:25 +01:00
James Dietz
669f891845 remove exception 2024-02-22 10:04:20 -05:00
Oli Scherer
e3021eb245 Preserve the Span from prove_predicate all the way to registering opaque types 2024-02-22 14:05:01 +00:00
bors
52dba5ffe7 Auto merge of #121225 - RalfJung:simd-extract-insert-const-idx, r=oli-obk,Amanieu
require simd_insert, simd_extract indices to be constants

As discussed in https://github.com/rust-lang/rust/issues/77477 (see in particular [here](https://github.com/rust-lang/rust/issues/77477#issuecomment-703149102)). This PR doesn't touch codegen yet -- the first step is to ensure that the indices are always constants; the second step is to then make use of this fact in backends.

Blocked on https://github.com/rust-lang/stdarch/pull/1530 propagating to the rustc repo.
2024-02-22 09:59:41 +00:00
Oli Scherer
9e016a8b84 Avoid emitting type mismatches against {type error} 2024-02-22 09:22:50 +00:00
bors
f70f19fef4 Auto merge of #121129 - nnethercote:codegen-Diags, r=estebank
Improve codegen diagnostic handling

Clarify the workings of the temporary `Diagnostic` type used to send diagnostics from codegen threads to the main thread.

r? `@estebank`
2024-02-22 08:01:37 +00:00
bors
c1b478efd3 Auto merge of #121223 - RalfJung:simd-intrinsics, r=Amanieu
intrinsics::simd: add missing functions, avoid UB-triggering fast-math

Turns out stdarch declares a bunch more SIMD intrinsics that are still missing from libcore.
I hope I got the docs and in particular the safety requirements right for these "unordered" and "nanless" intrinsics.

Many of these are unused even in stdarch, but they are implemented in the codegen backend, so we may as well list them here.

r? `@Amanieu`
Cc `@calebzulawski` `@workingjubilee`
2024-02-22 04:02:31 +00:00
James Dietz
03f095f9f2 consolidate tests 2024-02-21 22:41:47 -05:00
Nicholas Nethercote
ad5d7f43c9 Overhaul rustc_codegen_ssa:🔙:write::Diagnostic.
- Make it more closely match `rustc_errors::Diagnostic`, by making the
  field names match, and adding `children`, which requires adding
  `rustc_codegen_ssa:🔙:write::Subdiagnostic`.
- Check that we aren't missing important info when converting
  diagnostics.
- Add better comments.
- Tweak `rustc_errors::Diagnostic::replace_args` so that we don't need
  to do any cloning when converting diagnostics.
2024-02-22 12:51:11 +11:00
Matthias Krüger
35650a42a2
Rollup merge of #121406 - compiler-errors:tests, r=Nilstrieb
Add a couple tests

Fixes #119857
Fixes #115497
2024-02-21 22:49:00 +01:00
Nicholas Nethercote
72b172bdf6 Overhaul the handling of errors at the top-level.
Currently `emit_stashed_diagnostic` is called from four(!) different
places: `print_error_count`, `DiagCtxtInner::drop`, `abort_if_errors`,
and `compile_status`.

And `flush_delayed` is called from two different places:
`DiagCtxtInner::drop` and `Queries`.

This is pretty gross! Each one should really be called from a single
place, but there's a bunch of entanglements. This commit cleans up this
mess.

Specifically, it:
- Removes all the existing calls to `emit_stashed_diagnostic`, and adds
  a single new call in `finish_diagnostics`.
- Removes the early `flush_delayed` call in `codegen_and_build_linker`,
  replacing it with a simple early return if delayed bugs are present.
- Changes `DiagCtxtInner::drop` and `DiagCtxtInner::flush_delayed` so
  they both assert that the stashed diagnostics are empty (i.e.
  processed beforehand).
- Changes `interface::run_compiler` so that any errors emitted during
  `finish_diagnostics` (i.e. late-emitted stashed diagnostics) are
  counted and cannot be overlooked. This requires adding
  `ErrorGuaranteed` return values to several functions.
- Removes the `stashed_err_count` call in `analysis`. This is possible
  now that we don't have to worry about calling `flush_delayed` early
  from `codegen_and_build_linker` when stashed diagnostics are pending.
- Changes the `span_bug` case in `handle_tuple_field_pattern_match` to a
  `delayed_span_bug`, because it now can be reached due to the removal
  of the `stashed_err_count` call in `analysis`.
- Slightly changes the expected output of three tests. If no errors are
  emitted but there are delayed bugs, the error count is no longer
  printed. This is because delayed bugs are now always printed after the
  error count is printed (or not printed, if the error count is zero).

There is a lot going on in this commit. It's hard to break into smaller
pieces because the existing code is very tangled. It took me a long time
and a lot of effort to understand how the different pieces interact, and
I think the new code is a lot simpler and easier to understand.
2024-02-22 08:03:47 +11:00
Ralf Jung
07b6240947 remove simd_reduce_{min,max}_nanless 2024-02-21 20:50:47 +01:00
Michael Goulet
6edbc8d875 Prevent cycle in implied predicates computation 2024-02-21 19:05:45 +00:00
Michael Goulet
f8fbb7060c Add a non-lifetime-binders test 2024-02-21 18:05:58 +00:00
Michael Goulet
a233b1656e Add an ATB test 2024-02-21 17:16:35 +00:00
León Orell Valerian Liehr
8d27fc86f2
Rollup merge of #121359 - lcnr:typesystem-cleanup, r=compiler-errors
miscellaneous type system improvements

see review comments for rationale

r? `@compiler-errors`
2024-02-21 16:32:58 +01:00
León Orell Valerian Liehr
2d98f05cf1
Rollup merge of #121347 - davidtwco:compiletest-aux-aux, r=oli-obk
compiletest: support auxiliaries with auxiliaries

To test behaviour that depends on the extern options of intermediate crates, compiletest auxiliaries must have their own auxiliaries.

Auxiliary compilation previously did not trigger compilation of any auxiliaries in the auxiliary's headers. In addition, those auxiliaries would need to be in an `auxiliary/auxiliary` directory, which is unnecessary and makes some crate graphs harder to write tests for, such as when A depends on B and C, and B depends on C.

For a test `tests/ui/$path/root.rs`, with the following crate graph:

```
root
|-- grandparent
`-- parent
    `-- grandparent
```

then the intermediate outputs from compiletest will be:

```
build/$target/test/ui/$path/
|-- auxiliary
|   |-- libgrandparent.dylib
|   |-- libparent.dylib
|   |-- grandparent
|   |   |-- grandparent.err
|   |   `-- grandparent.out
|   `-- parent
|       |-- parent.err
|       `-- parent.out
|-- libroot.rmeta
|-- root.err
`-- root.out
```
2024-02-21 16:32:58 +01:00
León Orell Valerian Liehr
082b97ad05
Rollup merge of #121044 - compiler-errors:mbe-async-trait-bounds, r=fmease
Support async trait bounds in macros

r? fmease

This is similar to your work on const trait bounds. This theoretically regresses `impl async $ident:ident` in macros, but I doubt this is occurring in practice.
2024-02-21 16:32:56 +01:00
David Wood
a2aa9672f6
compiletest: support auxiliaries with auxiliaries
To test behaviour that depends on the extern options of intermediate
crates, compiletest auxiliaries must have their own auxiliaries.

Auxiliary compilation previously did not trigger compilation of any
auxiliaries in the auxiliary's headers. In addition, those auxiliaries
would need to be in an `auxiliary/auxiliary` directory, which is
unnecessary and makes some crate graphs harder to write tests for,
such as when A depends on B and C, and B depends on C.

For a test `tests/ui/$path/root.rs`, with the following crate graph:

```
root
|-- grandparent
`-- parent
    `-- grandparent
```

then the intermediate outputs from compiletest will be:

```
build/$target/test/ui/$path/
|-- auxiliary
|   |-- libgrandparent.dylib
|   |-- libparent.dylib
|   |-- grandparent
|   |   |-- grandparent.err
|   |   `-- grandparent.out
|   `-- parent
|       |-- parent.err
|       `-- parent.out
|-- libroot.rmeta
|-- root.err
`-- root.out
```

Signed-off-by: David Wood <david@davidtw.co>
2024-02-21 14:37:13 +00:00
Ali MJ Al-Nasrawy
66bd6453e0 test that we do not support higher-ranked regions in opaque type inference 2024-02-21 09:08:45 +00:00
Oli Scherer
31478cd712 Add more tests 2024-02-21 09:08:45 +00:00
Dylan DPC
e10b3b88b4
Rollup merge of #121338 - jieyouxu:ambiguous_wide_pointer_comparisons_suggestion, r=Nadrieril
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.
2024-02-21 08:55:58 +00:00
Dylan DPC
4a205bba5e
Rollup merge of #121328 - ffmancera:ff/verbose_long_type, r=compiler-errors
Make --verbose imply -Z write-long-types-to-disk=no

When shortening the type it is necessary to take into account the `--verbose` flag, if it is activated, we must always show the entire type and not write it in a file.

Fixes: https://github.com/rust-lang/rust/issues/119130
2024-02-21 08:55:57 +00:00
Dylan DPC
d5206c6ecd
Rollup merge of #121208 - nnethercote:delayed_bug-to-bug, r=lcnr
Convert `delayed_bug`s to `bug`s.

I have a suspicion that quite a few delayed bug paths are impossible to reach, so I did an experiment.

I converted every `delayed_bug` to a `bug`, ran the full test suite, then converted back every `bug` that was hit. A surprising number were never hit.

This is too dangerous to merge. Increased coverage (fuzzing or a crater run) would likely hit more cases. But it might be useful for people to look at and think about which paths are genuinely unreachable.

r? `@ghost`
2024-02-21 08:55:56 +00:00
Nicholas Nethercote
2903bbbc15 Convert bugs back to delayed_bugs.
This commit undoes some of the previous commit's mechanical changes,
based on human judgment.
2024-02-21 10:35:54 +11:00
Fernando Fernandez Mancera
e35481f90b Suggest using --verbose when writing type to a file 2024-02-20 23:48:59 +01:00
lcnr
5fb67e2ad4 some type system cleanup 2024-02-20 20:42:10 +01:00
Matthias Krüger
433180e0cb
Rollup merge of #121350 - compiler-errors:resolve, r=oli-obk
Fix stray trait mismatch in `resolve_associated_item` for `AsyncFn`

Copy-paste error meant that we were calling `fn_trait_kind_from_def_id` instead of `async_fn_trait_kind_from_def_id`. But turns out we don't even need to do that, since we already matched the trait def id above.

Fixes #121306

r? oli-obk
2024-02-20 19:35:42 +01:00
Matthias Krüger
532b3eacb7
Rollup merge of #121344 - fmease:lta-constr-by-input, r=oli-obk
Expand weak alias types before collecting constrained/referenced late bound regions + refactorings

Fixes #114220.
Follow-up to #120780.

r? `@oli-obk`
2024-02-20 19:35:41 +01:00
Matthias Krüger
e3ff2a8e38
Rollup merge of #121323 - compiler-errors:raw-param-types, r=oli-obk
Don't use raw parameter types in `find_builder_fn`

We shouldn't really ever be using `EarlyBinder::skip_binder` then performing type equality, since param types will never be equal to other types. When checking compatibility with the signature, we instead create some fresh args.

Fixes #121314
2024-02-20 19:35:41 +01:00
Matthias Krüger
d43fd29bf2
Rollup merge of #121322 - compiler-errors:next-solver-fulfillment-ice, r=lcnr
Don't ICE when hitting overflow limit in fulfillment loop in next solver

As the title says, let's not ICE when hitting the overflow limit in fulfill. On the other hand, we don't want to treat these as true errors, since it means that whether something is considered a true error or an ambiguity is dependent on overflow handling in the solver, which seems not worth it.

Now that we use the presence of true errors in fulfillment for implicit negative coherence, we especially don't want to tie together coherence and overflow.

I guess I could also drain these errors out of fulfillment and put them into some `ambiguities` storage so we could return them in `select_all_or_error` without having to re-process them every time we call `select_where_possible`. Let me know if that's desired.

r? lcnr
2024-02-20 19:35:40 +01:00
许杰友 Jieyou Xu (Joe)
4d386d9f04
Downgrade ambiguous_wide_pointer_comparisons suggestions to MaybeIncorrect
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>.
2024-02-20 17:21:01 +00:00
León Orell Valerian Liehr
515d805a0e
Introduce expand_weak_alias_tys 2024-02-20 17:31:49 +01:00
bors
bb594538fc Auto merge of #121345 - Nilstrieb:rollup-reb0xge, r=Nilstrieb
Rollup of 8 pull requests

Successful merges:

 - #121167 (resolve: Scale back unloading of speculatively loaded crates)
 - #121196 (Always inline check in `assert_unsafe_precondition` with cfg(debug_assertions))
 - #121241 (Implement `NonZero` traits generically.)
 - #121278 (Remove the "codegen" profile from bootstrap)
 - #121286 (Rename `ConstPropLint` to `KnownPanicsLint`)
 - #121291 (target: Revert default to the medium code model on LoongArch targets)
 - #121302 (Remove `RefMutL` hack in `proc_macro::bridge`)
 - #121318 (Trigger `unsafe_code` lint on invocations of `global_asm`)

Failed merges:

 - #121206 (Top level error handling)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-20 16:22:48 +00:00
Michael Goulet
9c8b107955 Support async trait bounds in macros 2024-02-20 16:09:09 +00:00
Michael Goulet
762febdaf3 Fix stray trait mismatch in resolve_associated_item for AsyncFn 2024-02-20 15:45:05 +00:00
Nilstrieb
d61adbffe1
Rollup merge of #121318 - kadiwa4:no_assembly_in_supposedly_safe_code, r=Nilstrieb
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
2024-02-20 15:13:55 +01:00
Nilstrieb
f6b4080592
Rollup merge of #121241 - reitermarkus:generic-nonzero-traits, r=dtolnay
Implement `NonZero` traits generically.

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

r? ````@dtolnay````
2024-02-20 15:13:52 +01:00
Nilstrieb
073d2983a4
Rollup merge of #121167 - petrochenkov:unload2, r=wesleywiser
resolve: Scale back unloading of speculatively loaded crates

Fixes https://github.com/rust-lang/rust/issues/120830 and fixes https://github.com/rust-lang/rust/issues/120909 while still unblocking https://github.com/rust-lang/rust/pull/117772.

I cannot reproduce https://github.com/parasyte/crash-rustc as an UI test for some reason, but I tested all the cases linked above manually.
2024-02-20 15:13:50 +01:00
bors
2b43e75c98 Auto merge of #120863 - saethlin:slice-get-checked, r=the8472
Use intrinsics::debug_assertions in debug_assert_nounwind

This is the first item in https://github.com/rust-lang/rust/issues/120848.

Based on the benchmarking in this PR, it looks like, for the programs in our benchmark suite, enabling all these additional checks does not introduce significant compile-time overhead, with the single exception of `Alignment::new_unchecked`. Therefore, I've added `#[cfg(debug_assertions)]` to that one call site, so that it remains compiled out in the distributed standard library.

The trailing commas in the previous calls to `debug_assert_nounwind!` were causing the macro to expand to `panic_nouwnind_fmt`, which requires more work to set up its arguments, and that overhead alone is measured between this perf run and the next: https://github.com/rust-lang/rust/pull/120863#issuecomment-1937423502
2024-02-20 14:04:57 +00:00
bors
cce6a6e22e Auto merge of #121087 - oli-obk:eager_const_failures, r=lcnr
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.
2024-02-20 09:02:34 +00:00
Ralf Jung
90f5fed05b update tests 2024-02-20 07:58:18 +01:00
Nilstrieb
599768d930
Rollup merge of #121319 - compiler-errors:err, r=oli-obk
return `ty::Error` when equating `ty::Error`

This helps iron out a difference in diagnostics between `Sub` and `Equate` relations, which I'm currently trying to unify.

r? oli-obk
2024-02-20 07:35:49 +01:00
Nilstrieb
930566fe1a
Rollup merge of #121308 - kadiwa4:test_103369, r=TaKO8Ki
Add regression test for #103369

The issue was fixed in 1.70.0.
Closes #103369.
2024-02-20 07:35:48 +01:00
Nilstrieb
ac030bcf05
Rollup merge of #121307 - estebank:drive-by, r=compiler-errors
Drive-by `DUMMY_SP` -> `Span` and fmt changes

Noticed these while doing something else. There's no practical change, but it's preferable to use `DUMMY_SP` as little as possible, particularly when we have perfectlly useful `Span`s available.
2024-02-20 07:35:47 +01:00
Nilstrieb
5b8b435d5d
Rollup merge of #120716 - spastorino:change-some-lint-msgs, r=lcnr
Change leak check and suspicious auto trait lint warning messages

The leak check lint message "this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!" is misleading as some cases may not be phased out and could end being accepted. This is under discussion still.

The suspicious auto trait lint the change in behavior already happened, so the new message is probably more accurate.

r? `@lcnr`

Closes #93367
2024-02-20 07:35:45 +01:00
Michael Goulet
1c80aadb05 test 2024-02-20 03:01:35 +00:00
Michael Goulet
18fdf59bf5 Don't use raw parameter types in find_builder_fn 2024-02-20 02:58:07 +00:00
Michael Goulet
994d55158d Simply do not ICE 2024-02-20 02:16:36 +00:00
Ben Kimock
581e171773 Convert debug_assert_nounwind to intrinsics::debug_assertions 2024-02-19 20:38:09 -05:00
Michael Goulet
84baf2f6f8 return ty::Error when equating ty::Error
This helps iron out a difference between Sub and Equate
2024-02-19 23:54:49 +00:00
Kalle Wachsmuth
dc7a01610f
trigger unsafe_code on global_asm! invocations 2024-02-20 00:14:53 +01:00
Oli Scherer
9062697917 Always evaluate free constants and statics, even if previous errors occurred 2024-02-19 22:11:13 +00:00
bors
0395fa387a Auto merge of #121211 - lcnr:nll-relate-handle-infer, r=BoxyUwU
deduplicate infer var instantiation

Having 3 separate implementations of one of the most subtle parts of our type system is not a good strategy if we want to maintain a sound type system  while working on this I already found some subtle bugs in the existing code, so that's awesome 🎉 cc #121159

This was necessary as I am not confident in my nll changes in #119106, so I am first cleaning this up in a separate PR.

r? `@BoxyUwU`
2024-02-19 22:04:58 +00:00
Santiago Pastorino
086463b227
Remove suspicious auto trait lint 2024-02-19 17:41:48 -03:00
Kalle Wachsmuth
7fd7b47c1f
regression test for #103369 2024-02-19 18:16:11 +01:00
Esteban Küber
b4a424feb8 Drive-by DUMMY_SP -> Span and fmt changes
Noticed these while doing something else. There's no practical change, but it's preferable to use `DUMMY_SP` as little as possible, particularly when we have perfectlly useful `Span`s available.
2024-02-19 17:04:23 +00:00
Matthias Krüger
3fe809b38d
Rollup merge of #121275 - tshepang:test-panicking-proc-macros, r=nnethercote
add test for panicking attribute macros
2024-02-19 13:04:34 +01:00
Matthias Krüger
cf0b36a1c5
Rollup merge of #121041 - Nilstrieb:into-the-future-of-2024, r=Mark-Simulacrum
Add `Future` and `IntoFuture` to the 2024 prelude

Implements rust-lang/rfcs#3509.
2024-02-19 13:04:33 +01:00
Matthias Krüger
25bba60e9d
Rollup merge of #121032 - oli-obk:cyclic_type_ice, r=cjgillot
Continue reporting remaining errors instead of silently dropping them

I was too eager to add assertions in https://github.com/rust-lang/rust/pull/120342/files#diff-593003090e0fb5c21f31413ce5feb506e235ec33c4775da88b853980429b9ff1R741

fixes #120864
2024-02-19 13:04:33 +01:00
Nilstrieb
bd8a1a417a Add Future and IntoFuture to the 2024 prelude
Implements RFC 3509.
2024-02-18 23:20:05 +01:00
Santiago Pastorino
eee9d2a773
Change leak check lint message to behavior is likely to change in the future 2024-02-18 19:16:17 -03:00
Tshepang Mbambo
9f614cb1a0 add test for panicking attribute macros 2024-02-18 22:51:19 +02:00
bors
2bf78d12d3 Auto merge of #119673 - petrochenkov:dialoc5, r=compiler-errors,cjgillot
macro_rules: Preserve all metavariable spans in a global side table

This PR preserves spans of `tt` metavariables used to pass tokens to declarative macros.
Such metavariable spans can then be used in span combination operations like `Span::to` to improve all kinds of diagnostics.

Spans of non-`tt` metavariables are currently kept in nonterminal tokens, but the long term plan is remove all nonterminal tokens from rustc parser and rely on the proc macro model with invisible delimiters (#114647, #67062).
In particular, `NtIdent` nonterminal (corresponding to `ident` metavariables) becomes easy to remove when this PR lands (#119412 does it).

The metavariable spans are kept in a global side table keyed by `Span`s of original tokens.
The alternative to the side table is keeping them in `SpanData` instead, but the performance regressions would be large because any spans from tokens passed to declarative macros would stop being inline and would work through span interner instead, and the penalty would be paid even if we never use the metavar span for the given original span.
(But also see the comment on `fn maybe_use_metavar_location` describing the map collision issues with the side table approach.)

There are also other alternatives - keeping the metavar span in `Token` or `TokenTree`, but associating it with `Span` itsel is the most natural choice because metavar spans are used in span combining operations, and those operations are not necessarily tied to tokens.
2024-02-18 20:51:16 +00:00
Vadim Petrochenkov
24cffbf703 resolve: Scale back unloading of speculatively loaded crates 2024-02-18 20:59:19 +03:00
Matthias Krüger
57d9523a95
Rollup merge of #121247 - scottmcm:intrinsic-reminder, r=petrochenkov
Add help to `hir_analysis_unrecognized_intrinsic_function`

To help remind forgetful people like me what step they forgot.

(If this just ICE'd, https://github.com/rust-lang/compiler-team/issues/620 style, the stack trace would point me here, but since there's a "nice" error that information is lost.)
2024-02-18 18:54:33 +01:00
Matthias Krüger
ddf6c6dbc6
Rollup merge of #121067 - tshepang:make-expand-translatable, r=fmease
make "invalid fragment specifier" translatable
2024-02-18 18:54:32 +01:00
bors
8b21296b5d Auto merge of #117772 - surechen:for_117448, r=petrochenkov
Tracking import use types for more accurate redundant import checking

fixes #117448

By tracking import use types to check whether it is scope uses or the other situations like module-relative uses,  we can do more accurate redundant import checking.

For example unnecessary imports in std::prelude that can be eliminated:

```rust
use std::option::Option::Some;//~ WARNING the item `Some` is imported redundantly
use std::option::Option::None; //~ WARNING the item `None` is imported redundantly
```
2024-02-18 13:56:07 +00:00
León Orell Valerian Liehr
8bb49e22b5
Propagate the resolved type of assoc const bindings via query feeding 2024-02-18 10:29:22 +01:00
surechen
a61126cef6 By tracking import use types to check whether it is scope uses or the other situations like module-relative uses, we can do more accurate redundant import checking.
fixes #117448

For example unnecessary imports in std::prelude that can be eliminated:

```rust
use std::option::Option::Some;//~ WARNING the item `Some` is imported redundantly
use std::option::Option::None; //~ WARNING the item `None` is imported redundantly
```
2024-02-18 16:38:11 +08:00
Vadim Petrochenkov
9f8d05f29f macro_rules: Preserve all metavariable spans in a global side table 2024-02-18 11:19:24 +03:00
bors
bcb3545164 Auto merge of #121034 - obeis:improve-static-mut-ref, r=RalfJung
Improve wording of `static_mut_ref`

Close #120964
2024-02-18 08:00:34 +00:00
Scott McMurray
5793f82030 Add help to hir_analysis_unrecognized_intrinsic_function
To help remind forgetful people like me what step they forgot.
2024-02-17 23:16:30 -08:00
bors
23a3d777c8 Auto merge of #121252 - fmease:rollup-x7zogl8, r=fmease
Rollup of 7 pull requests

Successful merges:

 - #120526 (rustdoc: Correctly handle long crate names on mobile)
 - #121100 (Detect when method call on argument could be removed to fulfill failed trait bound)
 - #121160 (rustdoc: fix and refactor HTML rendering a bit)
 - #121198 (Add more checks for `unnamed_fields` during HIR analysis)
 - #121218 (Fix missing trait impls for type in rustc docs)
 - #121221 (AstConv: Refactor lowering of associated item bindings a bit)
 - #121237 (Use better heuristic for printing Cargo specific diagnostics)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-18 06:02:16 +00:00
León Orell Valerian Liehr
5628786484
Rollup merge of #121237 - Urgau:better-cargo-heuristic, r=compiler-errors
Use better heuristic for printing Cargo specific diagnostics

It was [reported](https://github.com/rust-lang/rust/issues/82450#issuecomment-1948574677) in the check-cfg call for testing that the Rust for Linux project is setting the `CARGO` env without compiling with it, which is an issue since we are using the `CARGO` env as a proxy for "was launched from Cargo".

This PR switch to the `CARGO_CRATE_NAME` [Cargo env](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates), which shouldn't collide (as much) with other build systems. I also took the opportunity to consolidate all the checks under the same function.
2024-02-18 05:10:18 +01:00
León Orell Valerian Liehr
68cf5372b3
Rollup merge of #121198 - clubby789:unnamed-fields-hir-checks, r=compiler-errors
Add more checks for `unnamed_fields` during HIR analysis

Fixes #121151

I also found that we don't prevent enums here so
```rs
#[repr(C)]
#[derive(Debug)]
enum A {
    #[default]
    B,
    C,
}

#[repr(C)]
#[derive(Debug)]
struct D {
    _: A,
}
```
leads to an ICE on an `self.is_struct() || self.is_union()` assertion, so fixed that too.
2024-02-18 05:10:17 +01:00
León Orell Valerian Liehr
6499eb5577
Rollup merge of #121100 - estebank:issue-71252, r=compiler-errors
Detect when method call on argument could be removed to fulfill failed trait bound

When encountering

```rust
struct Foo;
struct Bar;
impl From<Bar> for Foo {
    fn from(_: Bar) -> Self { Foo }
}
fn qux(_: impl From<Bar>) {}
fn main() {
    qux(Bar.into());
}
```

Suggest removing `.into()`:

```
error[E0283]: type annotations needed
 --> f100.rs:8:13
  |
8 |     qux(Bar.into());
  |     ---     ^^^^
  |     |
  |     required by a bound introduced by this call
  |
  = note: cannot satisfy `_: From<Bar>`
note: required by a bound in `qux`
 --> f100.rs:6:16
  |
6 | fn qux(_: impl From<Bar>) {}
  |                ^^^^^^^^^ required by this bound in `qux`
help: try using a fully qualified path to specify the expected types
  |
8 |     qux(<Bar as Into<T>>::into(Bar));
  |         +++++++++++++++++++++++   ~
help: consider removing this method call, as the receiver has type `Bar` and `Bar: From<Bar>` trivially holds
  |
8 -     qux(Bar.into());
8 +     qux(Bar);
  |
```

Fix #71252
2024-02-18 05:10:16 +01:00
bors
d3df8ff851 Auto merge of #120780 - fmease:lta-in-impls, r=oli-obk
Properly deal with weak alias types as self types of impls

Fixes #114216.
Fixes #116100.

Not super happy about the two ad hoc “normalization” implementations for weak alias types:

1. In `inherent_impls`: The “peeling”, normalization to [“WHNF”][whnf]: Semantically that's exactly what we want (neither proper normalization nor shallow normalization would be correct here). Basically a weak alias type is “nominal” (well...^^) if the WHNF is nominal. [#97974](https://github.com/rust-lang/rust/pull/97974) followed the same approach.
2. In `constrained_generic_params`: Generic parameters are constrained by a weak alias type if the corresp. “normalized” type constrains them (where we only normalize *weak* alias types not arbitrary ones). Weak alias types are injective if the corresp. “normalized” type is injective.

Both have ad hoc overflow detection mechanisms.

**Coherence** is handled in #117164.

r? `@oli-obk` or types

[whnf]: https://en.wikipedia.org/wiki/Lambda_calculus_definition#Weak_head_normal_form
2024-02-18 03:58:56 +00:00
Obei Sideg
408eeae59d Improve wording of static_mut_ref
Rename `static_mut_ref` lint to `static_mut_refs`.
2024-02-18 06:01:40 +03:00
Markus Reiter
f12d248a6a
Implement NonZero traits generically. 2024-02-17 21:58:56 +01:00
Matthias Krüger
df3712ce21
Rollup merge of #121193 - compiler-errors:coherence-fulfillment, r=lcnr
Use fulfillment in next trait solver coherence

Use fulfillment in the new trait solver's `impl_intersection_has_impossible_obligation` routine. This means that inference that falls out of processing other obligations can influence whether we can determine if an obligation is impossible to satisfy. See the committed test.

This should be completely sound, since evaluation and fulfillment both respect intercrate mode equally.

We run the risk of breaking coherence later if we were to change the rules of fulfillment and/or inference during coherence, but this is a problem which affects evaluation, as nested obligations from a trait goal are processed together and can influence each other in the same way.

r? lcnr
cc #114862

Also changed obligationctxt -> fulfillmentctxt because it feels kind of redundant to use an ocx here. I don't really care enough and can change it back if it really matters much.
2024-02-17 18:47:42 +01:00
Urgau
d988d8f4ba Use better heuristic for printing Cargo specific diagnostics 2024-02-17 16:49:01 +01:00
clubby789
62b789fba4 Add more checks for unnamed_field during HIR analysis 2024-02-17 15:12:33 +00:00
Urgau
63469ab762 Add cargo update suggestion for non local defs 2024-02-17 14:00:08 +01:00
Urgau
85e3a2ee04 Add const-anon suggestion for non local impl 2024-02-17 13:59:46 +01:00
Urgau
80c81c53ac Allow newly added non_local_definitions lint in tests 2024-02-17 13:59:45 +01:00
Urgau
6170394313 Implement RFC3373 non local definitions lint 2024-02-17 13:59:45 +01:00
Tshepang Mbambo
e3859d206c add test to guard against inaccurate diagnostic
Also replaces an incomplete test
2024-02-17 14:15:22 +02:00
Guillaume Boisseau
936b666c4a
Rollup merge of #121192 - oli-obk:intrinsics2.0, r=WaffleLapkin
Give some intrinsics fallback bodies

cc #93145
2024-02-17 11:23:08 +01:00
Guillaume Boisseau
f70f13a1d3
Rollup merge of #120932 - RalfJung:mut-ptr-to-static, r=oli-obk
const_mut_refs: allow mutable pointers to statics

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

Writing this PR became a bit messy, see [Zulip](https://rust-lang.zulipchat.com/#narrow/stream/146212-t-compiler.2Fconst-eval/topic/Statics.20pointing.20to.20interior.20mutable.20statics) for some of my journey.^^ Turns out there was a long-standing bug in our qualif logic that led to us incorrectly classifying certain places as "no interior mut" when they actually had interior mut. Due to that the `const_refs_to_cell` feature gate was required far less often than it otherwise would, e.g. in [this code](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=9e0c042c451b3d11d64dd6263679a164). Fixing this however would be a massive breaking change all over libcore and likely the wider ecosystem. So I also changed the const-checking logic to just not require the feature gate for the affected cases. While doing so I discovered a bunch of logic that is not explained and that I could not explain. However I think stabilizing some const-eval feature will make most of that logic inconsequential so I just added some FIXMEs and left it at that.

r? `@oli-obk`
2024-02-17 11:23:03 +01:00
Ralf Jung
340f8aac7e const_mut_refs: allow mutable refs to statics 2024-02-17 10:19:17 +01:00
León Orell Valerian Liehr
fde4556785
Properly check constrainedness of gen params in the presence of weak alias types 2024-02-17 08:39:01 +01:00
León Orell Valerian Liehr
8677d64c72
Support weak alias types as self type of inherent impls 2024-02-17 08:38:59 +01:00
Gurinder Singh
5010ca001c Enable ConstPropLint for promoteds
This fixes the issue wherein the lint didn't fire for promoteds
in the case of SHL/SHR operators in non-optimized builds
and all arithmetic operators in optimized builds
2024-02-17 10:44:46 +05:30
lcnr
5c540044d6 use instantiate_ty_var in nll
we already use `instantiate_const_var`. This does lose some debugging
info for nll because we stop populating the `reg_var_to_origin` table with
`RegionCtxt::Existential(None)`, I don't think that matters however.
Supporting this adds additional complexity to one of the most involved
parts of the type system, so I really don't think it's worth it.
2024-02-17 02:32:19 +01:00
lcnr
88a559fa9f move ty var instantiation into the generalize module 2024-02-17 01:42:36 +01:00
Michael Goulet
228441dbd6 Use fulfillment in next trait solver coherence 2024-02-16 23:53:09 +00:00
Oli Scherer
dd40a80102 Give the (un)likely intrinsics fallback bodies 2024-02-16 22:26:01 +00:00
许杰友 Jieyou Xu (Joe)
ec2cc761bc
[AUTO-GENERATED] Migrate ui tests from // to //@ directives 2024-02-16 20:02:50 +00:00
许杰友 Jieyou Xu (Joe)
e53d6dd35b
Implement infra support for migrating from // to //@ ui test directives 2024-02-16 19:40:23 +00:00
Guillaume Gomez
f82875e242
Rollup merge of #121181 - oli-obk:normalize_with_conflicting_impls, r=cjgillot
Fix an ICE in the recursion lint

fixes #121170

I looked into it, and there is no good path towards tainting mir_build (where the ICE happens), but using `try_normalize` in a lint seems generally better anyway
2024-02-16 17:08:14 +01:00
Guillaume Gomez
0c92146034
Rollup merge of #121179 - RalfJung:zst-mutable-refs, r=oli-obk
allow mutable references in const values when they point to no memory

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

The second commit is just some drive-by test suite cleanup.

r? `@oli-obk`
2024-02-16 17:08:13 +01:00
Guillaume Gomez
f60576b3df
Rollup merge of #121137 - GuillaumeGomez:add-clippy-cfg, r=Urgau,Nilstrieb
Add clippy into the known `cfg` list

In clippy, we are removing the `feature = "cargo-clippy"` cfg to replace it with `clippy` in https://github.com/rust-lang/rust-clippy/pull/12292. But for it to work, we need to declare `clippy` as cfg. It makes it more coherent with other existing tools like rustdoc.

cc `@flip1995`
2024-02-16 17:08:13 +01:00
Guillaume Gomez
670bdbf808
Rollup merge of #121111 - trevyn:associated-type-suggestion, r=davidtwco
For E0038, suggest associated type if available

Closes #116434
2024-02-16 17:08:12 +01:00
Guillaume Gomez
e5a743c4c2
Rollup merge of #121020 - oli-obk:diagnostics_ice, r=davidtwco
Avoid an ICE in diagnostics

fixes #121004

just a slice usage in diagnostics code. Sadly we can't yet bubble the `ErrorGuaranteed` from wf check to borrowck for these cases, as that causes cycle errors iirc
2024-02-16 17:08:12 +01:00
Guillaume Gomez
f81fd901db
Rollup merge of #119928 - d-sonuga:into-iter-sugg, r=compiler-errors
suggest `into_iter()` when `Iterator` method called on `impl IntoIterator`

Fix for issue #117711.
2024-02-16 17:08:11 +01:00
Ralf Jung
d3fc69ae45 add test ensuring we detect a static actually having a mutable reference 2024-02-16 11:38:11 +01:00