Commit Graph

6284 Commits

Author SHA1 Message Date
Michael Goulet
8ca7aac3eb Add tests for shortcomings of associated type bounds 2024-03-21 10:34:53 -04:00
Matthias Krüger
62e414d3af
Rollup merge of #122806 - compiler-errors:type-ascribe, r=fmease
Make `type_ascribe!` not a built-in

The only weird thing is the macro expansion note. I wonder if we should suppress these 🤔

r? ````@fmease```` since you told me about builtin# lol
2024-03-21 12:05:09 +01:00
Matthias Krüger
3331d0d1e7
Rollup merge of #122801 - celinval:smir-pretty, r=compiler-errors
Fix misc printing issues in emit=stable_mir

Trying to continue the work that ````@ouz-a```` started here: https://github.com/rust-lang/rust/pull/118364

Few modifications beyond fixes:
1. I made the `pretty_*` functions private.
2. I added a function to print the instance body
3. Changed a bunch of signatures to write to the writer directly.
4. Added a function to translate the place to its internal representation, so we could use the internal debug implementation.
5. Also removed `pretty_ty`, replaced by Display implementation of Ty which uses the internal display.
2024-03-21 12:05:08 +01:00
Matthias Krüger
300d3fb2fd
Rollup merge of #122799 - estebank:issue-122569, r=fee1-dead
Replace closures with `_` when suggesting fully qualified path for method call

```
error[E0283]: type annotations needed
  --> $DIR/into-inference-needs-type.rs:12:10
   |
LL |         .into()?;
   |          ^^^^
   |
   = note: cannot satisfy `_: From<...>`
   = note: required for `FilterMap<...>` to implement `Into<_>`
help: try using a fully qualified path to specify the expected types
   |
LL ~     let list = <FilterMap<Map<std::slice::Iter<'_, &str>, _>, _> as Into<T>>::into(vec
LL |         .iter()
LL |         .map(|s| s.strip_prefix("t"))
LL ~         .filter_map(Option::Some))?;
   |
```

Fix #122569.
2024-03-21 12:05:08 +01:00
Matthias Krüger
e78522fd00
Rollup merge of #122358 - compiler-errors:bound-regions-in-generator, r=lcnr
Don't ICE when encountering bound regions in generator interior type

I'm pretty sure this meant to say "`has_free_regions`", probably just a typo in 4a4fc3bb5b. We can have bound regions (because we only convert non-bound regions into existential regions in generator interiors), but we can't have (non-ReErased) free regions.

r? lcnr
2024-03-21 12:05:05 +01:00
Matthias Krüger
0867025cc8
Rollup merge of #122222 - Nadrieril:deref-pat-feature-gate, r=compiler-errors
deref patterns: bare-bones feature gate and typechecking

I am restarting the deref patterns experimentation. This introduces a feature gate under the lang-team [experimental feature](https://github.com/rust-lang/lang-team/blob/master/src/how_to/experiment.md) process, with [````@cramertj```` as lang-team liaison](https://github.com/rust-lang/lang-team/issues/88) (it's been a while though, you still ok with this ````@cramertj?).```` Tracking issue: https://github.com/rust-lang/rust/issues/87121.

This is the barest-bones implementation I could think of:
- explicit syntax, reusing `box <pat>` because that saves me a ton of work;
- use `Deref` as a marker trait (instead of a yet-to-design `DerefPure`);
- no support for mutable patterns with `DerefMut` for now;
- MIR lowering will come in the next PR. It's the trickiest part.

My goal is to let us figure out the MIR lowering part, which might take some work. And hopefully get something working for std types soon.

This is in large part salvaged from ````@fee1-dead's```` https://github.com/rust-lang/rust/pull/119467.

r? ````@compiler-errors````
2024-03-21 12:05:05 +01:00
Oli Scherer
d8470bb00b Sorting arbitrary constants should not be done, as it relies on DefId ordering, which breaks incremental compilation. 2024-03-21 10:45:30 +00:00
Oli Scherer
cda209bf43 Stop ConstraintCategory Ord impl from relying on Ty's Ord impl. 2024-03-21 10:45:30 +00:00
bors
df8ac8f1d7 Auto merge of #122568 - RalfJung:mentioned-items, r=oli-obk
recursively evaluate the constants in everything that is 'mentioned'

This is another attempt at fixing https://github.com/rust-lang/rust/issues/107503. The previous attempt at https://github.com/rust-lang/rust/pull/112879 seems stuck in figuring out where the [perf regression](https://perf.rust-lang.org/compare.html?start=c55d1ee8d4e3162187214692229a63c2cc5e0f31&end=ec8de1ebe0d698b109beeaaac83e60f4ef8bb7d1&stat=instructions:u) comes from. In  https://github.com/rust-lang/rust/pull/122258 I learned some things, which informed the approach this PR is taking.

Quoting from the new collector docs, which explain the high-level idea:
```rust
//! One important role of collection is to evaluate all constants that are used by all the items
//! which are being collected. Codegen can then rely on only encountering constants that evaluate
//! successfully, and if a constant fails to evaluate, the collector has much better context to be
//! able to show where this constant comes up.
//!
//! However, the exact set of "used" items (collected as described above), and therefore the exact
//! set of used constants, can depend on optimizations. Optimizing away dead code may optimize away
//! a function call that uses a failing constant, so an unoptimized build may fail where an
//! optimized build succeeds. This is undesirable.
//!
//! To fix this, the collector has the concept of "mentioned" items. Some time during the MIR
//! pipeline, before any optimization-level-dependent optimizations, we compute a list of all items
//! that syntactically appear in the code. These are considered "mentioned", and even if they are in
//! dead code and get optimized away (which makes them no longer "used"), they are still
//! "mentioned". For every used item, the collector ensures that all mentioned items, recursively,
//! do not use a failing constant. This is reflected via the [`CollectionMode`], which determines
//! whether we are visiting a used item or merely a mentioned item.
//!
//! The collector and "mentioned items" gathering (which lives in `rustc_mir_transform::mentioned_items`)
//! need to stay in sync in the following sense:
//!
//! - For every item that the collector gather that could eventually lead to build failure (most
//!   likely due to containing a constant that fails to evaluate), a corresponding mentioned item
//!   must be added. This should use the exact same strategy as the ecollector to make sure they are
//!   in sync. However, while the collector works on monomorphized types, mentioned items are
//!   collected on generic MIR -- so any time the collector checks for a particular type (such as
//!   `ty::FnDef`), we have to just onconditionally add this as a mentioned item.
//! - In `visit_mentioned_item`, we then do with that mentioned item exactly what the collector
//!   would have done during regular MIR visiting. Basically you can think of the collector having
//!   two stages, a pre-monomorphization stage and a post-monomorphization stage (usually quite
//!   literally separated by a call to `self.monomorphize`); the pre-monomorphizationn stage is
//!   duplicated in mentioned items gathering and the post-monomorphization stage is duplicated in
//!   `visit_mentioned_item`.
//! - Finally, as a performance optimization, the collector should fill `used_mentioned_item` during
//!   its MIR traversal with exactly what mentioned item gathering would have added in the same
//!   situation. This detects mentioned items that have *not* been optimized away and hence don't
//!   need a dedicated traversal.

enum CollectionMode {
    /// Collect items that are used, i.e., actually needed for codegen.
    ///
    /// Which items are used can depend on optimization levels, as MIR optimizations can remove
    /// uses.
    UsedItems,
    /// Collect items that are mentioned. The goal of this mode is that it is independent of
    /// optimizations: the set of "mentioned" items is computed before optimizations are run.
    ///
    /// The exact contents of this set are *not* a stable guarantee. (For instance, it is currently
    /// computed after drop-elaboration. If we ever do some optimizations even in debug builds, we
    /// might decide to run them before computing mentioned items.) The key property of this set is
    /// that it is optimization-independent.
    MentionedItems,
}
```
And the `mentioned_items` MIR body field docs:
```rust
    /// Further items that were mentioned in this function and hence *may* become monomorphized,
    /// depending on optimizations. We use this to avoid optimization-dependent compile errors: the
    /// collector recursively traverses all "mentioned" items and evaluates all their
    /// `required_consts`.
    ///
    /// This is *not* soundness-critical and the contents of this list are *not* a stable guarantee.
    /// All that's relevant is that this set is optimization-level-independent, and that it includes
    /// everything that the collector would consider "used". (For example, we currently compute this
    /// set after drop elaboration, so some drop calls that can never be reached are not considered
    /// "mentioned".) See the documentation of `CollectionMode` in
    /// `compiler/rustc_monomorphize/src/collector.rs` for more context.
    pub mentioned_items: Vec<Spanned<MentionedItem<'tcx>>>,
```

Fixes #107503
2024-03-21 09:01:18 +00:00
Oli Scherer
6623bdf68b Strip placeholders from hidden types before remapping generic parameter in the hidden type to the generic parameters of the definition of the opaque 2024-03-21 08:17:12 +00:00
Ralf Jung
8c01b85dba make sure we don't inline these generic fn as that could monomorphize them 2024-03-21 09:05:47 +01:00
Georg Semmler
5568c569c0
Make #[diagnostic::on_unimplemented] format string parsing more robust
This commit fixes several issues with the format string parsing of the
`#[diagnostic::on_unimplemented]` attribute that were pointed out by
@ehuss.
In detail it fixes:

* Appearing format specifiers (display, etc). For these we generate a
warning that the specifier is unsupported. Otherwise we ignore them
* Positional arguments. For these we generate a warning that positional
arguments are unsupported in that location and replace them with the
format string equivalent (so `{}` or `{n}` where n is the index of the
positional argument)
* Broken format strings with enclosed }. For these we generate a warning
about the broken format string and set the emitted message literally to
the provided unformatted string
* Unknown format specifiers. For these we generate an additional warning
about the unknown specifier. Otherwise we emit the literal string as
message.

This essentially makes those strings behave like `format!` with the
minor difference that we do not generate hard errors but only warnings.
After that we continue trying to do something unsuprising (mostly either
ignoring the broken parts or falling back to just giving back the
literal string as provided).

Fix #122391
2024-03-21 08:27:26 +01:00
bors
47dd709bed Auto merge of #121123 - compiler-errors:item-assumptions, r=oli-obk
Split an item bounds and an item's super predicates

This is the moral equivalent of #107614, but instead for predicates this applies to **item bounds**. This PR splits out the item bounds (i.e. *all* predicates that are assumed to hold for the alias) from the item *super predicates*, which are the subset of item bounds which share the same self type as the alias.

## Why?

Much like #107614, there are places in the compiler where we *only* care about super-predicates, and considering predicates that possibly don't have anything to do with the alias is problematic. This includes things like closure signature inference (which is at its core searching for `Self: Fn(..)` style bounds), but also lints like `#[must_use]`, error reporting for aliases, computing type outlives predicates.

Even in cases where considering all of the `item_bounds` doesn't lead to bugs, unnecessarily considering irrelevant bounds does lead to a regression (#121121) due to doing extra work in the solver.

## Example 1 - Trait Aliases

This is best explored via an example:

```
type TAIT<T> = impl TraitAlias<T>;

trait TraitAlias<T> = A + B where T: C;
```

The item bounds list for `Tait<T>` will include:
* `Tait<T>: A`
* `Tait<T>: B`
* `T: C`

While `item_super_predicates` query will include just the first two predicates.

Side-note: You may wonder why `T: C` is included in the item bounds for `TAIT`? This is because when we elaborate `TraitAlias<T>`, we will also elaborate all the predicates on the trait.

## Example 2 - Associated Type Bounds

```
type TAIT<T> = impl Iterator<Item: A>;
```

The `item_bounds` list for `TAIT<T>` will include:
* `Tait<T>: Iterator`
* `<Tait<T> as Iterator>::Item: A`

But the `item_super_predicates` will just include the first bound, since that's the only bound that is relevant to the *alias* itself.

## So what

This leads to some diagnostics duplication just like #107614, but none of it will be user-facing. We only see it in the UI test suite because we explicitly disable diagnostic deduplication.

Regarding naming, I went with `super_predicates` kind of arbitrarily; this can easily be changed, but I'd consider better names as long as we don't block this PR in perpetuity.
2024-03-21 06:12:24 +00:00
bors
6e1f7b538a Auto merge of #121587 - ShoyuVanilla:fix-issue-121267, r=TaKO8Ki
Fix bad span for explicit lifetime suggestions

Fixes #121267

Current explicit lifetime suggestions are not showing correct spans for some lifetimes - e.g. elided lifetime generic parameters;

This should be done correctly regarding elided lifetime kind like the following code

43fdd4916d/compiler/rustc_resolve/src/late/diagnostics.rs (L3015-L3044)
2024-03-21 04:11:09 +00:00
Michael Goulet
a015b90953 Make type_ascribe! not a built-in 2024-03-20 22:28:56 -04:00
Shoyu Vanilla
c270a42fea Fix bad span for explicit lifetime suggestion
Move verbose logic to a function

Minor renaming
2024-03-21 10:31:04 +09:00
Jacob Pratt
4e792df4ed
Rollup merge of #122749 - aliemjay:region-err, r=compiler-errors
make `type_flags(ReError) & HAS_ERROR`

Self-explanatory. `TypeVisitableExt::references_error(ReError)` incorrectly returned `false`.
2024-03-20 20:29:45 -04:00
Esteban Küber
5fae665924 Replace closures with _ when suggesting fully qualified path for method call
```
error[E0283]: type annotations needed
  --> $DIR/into-inference-needs-type.rs:12:10
   |
LL |         .into()?;
   |          ^^^^
   |
   = note: cannot satisfy `_: From<...>`
   = note: required for `FilterMap<...>` to implement `Into<_>`
help: try using a fully qualified path to specify the expected types
   |
LL ~     let list = <FilterMap<Map<std::slice::Iter<'_, &str>, _>, _> as Into<T>>::into(vec
LL |         .iter()
LL |         .map(|s| s.strip_prefix("t"))
LL ~         .filter_map(Option::Some))?;
   |
```

Fix #122569.
2024-03-21 00:07:44 +00:00
Esteban Küber
6b24fdf811 Provide structured suggestion for unconstrained generic constant
```
error: unconstrained generic constant
  --> $DIR/const-argument-if-length.rs:18:10
   |
LL |     pad: [u8; is_zst::<T>()],
   |          ^^^^^^^^^^^^^^^^^^^
   |
help: try adding a `where` bound
   |
LL | pub struct AtLeastByte<T: ?Sized> where [(); is_zst::<T>()]: {
   |                                   ++++++++++++++++++++++++++
```

Detect when the constant expression isn't `usize` and suggest casting:

```
error: unconstrained generic constant
 --> f300.rs:6:10
  |
6 |     bb::<{!N}>();
  |          ^^^^
-Ztrack-diagnostics: created at compiler/rustc_trait_selection/src/traits/error_reporting/type_err_ctxt_ext.rs:3539:36
  |
help: try adding a `where` bound
  |
5 | fn b<const N: bool>() where [(); {!N} as usize]: {
  |                       ++++++++++++++++++++++++++
```

Fix #122395.
2024-03-21 00:03:59 +00:00
Veera
afc99cc976 Update test for aarch64 2024-03-20 19:38:36 -04:00
Nicholas Nethercote
8ac16c6193 Rewrite parse_meta_item.
It can't use `maybe_whole`, but it can match `maybe_whole` more closely.

Also add a test for a case that wasn't previously covered.
2024-03-21 10:16:09 +11:00
Celina G. Val
ff504a09fe Improve emit stable mir body 2024-03-20 15:55:35 -07:00
Nadrieril
120d3570aa Add barest-bones deref patterns
Co-authored-by: Deadbeef <ent3rm4n@gmail.com>
2024-03-20 22:30:27 +01:00
Ali MJ Al-Nasrawy
0dc006b3a8 register opaques that reference errors 2024-03-20 17:30:19 +00:00
Ali MJ Al-Nasrawy
19e0ea4a6d make type_flags(ReError) & HAS_ERROR 2024-03-20 17:29:58 +00:00
Michael Goulet
ce5f8c93fa Bless test fallout (duplicate diagnostics) 2024-03-20 13:00:34 -04:00
Michael Goulet
aa39dbb962 Split item bounds and item super predicates 2024-03-20 13:00:34 -04:00
Alex Macleod
a8452461dc Ignore paths from expansion in unused_qualifications 2024-03-20 16:30:26 +00:00
bors
c86f3ac24f Auto merge of #120717 - compiler-errors:cap-closure-kind, r=oli-obk
For async closures, cap closure kind, get rid of `by_mut_body`

Right now we have three `AsyncFn*` traits, and three corresponding futures that are returned by the `call_*` functions for them. This is fine, but it is a bit excessive, since the future returned by `AsyncFn` and `AsyncFnMut` are identical. Really, the only distinction we need to make with these bodies is "by ref" and "by move".

This PR removes `AsyncFn::CallFuture` and renames `AsyncFnMut::CallMutFuture` to `AsyncFnMut::CallRefFuture`. This simplifies MIR building for async closures, since we don't need to build an extra "by mut" body, but just a "by move" body which is materially different.

We need to do a bit of delicate handling of the ClosureKind for async closures, since we need to "cap" it to `AsyncFnMut` in some cases when we only care about what body we're looking for.

This also fixes a bug where `<{async closure} as Fn>::call` was returning a body that takes the async-closure receiver *by move*.

This also helps align the `AsyncFn` traits to the `LendingFn` traits' eventual designs.
2024-03-20 11:40:45 +00:00
Ralf Jung
682991d2c7 explicitly set opt-level=0 2024-03-20 11:07:12 +01:00
Ralf Jung
0d6a16ac4b mentioned_items: record all callee and coerced closure types, whether they are FnDef/Closure or not
They may become FnDef during monomorphization!
2024-03-20 11:07:12 +01:00
Ralf Jung
f1ec494c32 mentioned items: also handle closure-to-fn-ptr coercions 2024-03-20 11:07:12 +01:00
Ralf Jung
347ca50bc8 mentioned items: also handle vtables 2024-03-20 11:07:12 +01:00
Ralf Jung
91b35a1b40 fix comments in required-consts tests 2024-03-20 11:07:12 +01:00
Ralf Jung
712fe36611 collector: recursively traverse 'mentioned' items to evaluate their constants 2024-03-20 11:07:12 +01:00
bohan
7f45f53204 store segment and module in UnresolvedImportError 2024-03-20 18:04:47 +08:00
David Rheinsberg
31d23c436a compiler: allow transmute of ZST arrays with generics
Extend the `SizeSkeleton` evaluator to shortcut zero-sized arrays, thus
considering `[T; 0]` to have a compile-time fixed-size of 0.

The existing evaluator already deals with generic arrays under the
feature-guard `transmute_const_generics`. However, it merely allows
comparing fixed-size types with fixed-size types, and generic types with
generic types. For generic types, it merely compares whether their
arguments match (ordering them first). Even if their exact sizes are not
known at compile time, it can ensure that they will eventually be the
same.

This patch extends this by shortcutting the size-evaluation of zero
sized arrays and thus allowing size comparisons of `()` with `[T; 0]`,
where one contains generics and the other does not.

This code is guarded by `transmute_const_generics` (#109929), even
though it is unclear whether it should be. However, this assumes that a
separate stabilization PR is required to move this out of the feature
guard.

Initially reported in #98104.
2024-03-20 10:58:43 +01:00
Oli Scherer
6201ad9205 Update documentation 2024-03-20 09:49:57 +00:00
Oli Scherer
afdcae2860 Rename mir_const query to mir_built 2024-03-20 09:05:22 +00:00
Oli Scherer
36728f1cdd Replace mir_built query with a hook and use mir_const everywhere instead 2024-03-20 09:05:09 +00:00
h1467792822
92325a95b3 Fixed the private-dependency bug: If the directly dependent crate is loaded last and is not configured with --extern, it may be incorrectly set to private-dependency 2024-03-20 16:33:50 +08:00
Matthias Krüger
ffdb147aa4
Rollup merge of #122732 - compiler-errors:coroutine-captures-note, r=nnethercote
Remove redundant coroutine captures note

This note is redundant, since we'll always be printing this "captures the following types..." between *more* descriptive `BuiltinDerivedObligationCause`s.

Please review with whitespace disabled, since I also removed an unnecessary labeled break.
2024-03-20 05:51:23 +01:00
bors
b7dcabe55e Auto merge of #122119 - estebank:issue-117846, r=Nadrieril
Silence unecessary !Sized binding error

When gathering locals, we introduce a `Sized` obligation for each
binding in the pattern. *After* doing so, we typecheck the init
expression. If this has a type failure, we store `{type error}`, for
both the expression and the pattern. But later we store an inference
variable for the pattern.

We now avoid any override of an existing type on a hir node when they've
already been marked as `{type error}`, and on E0277, when it comes from
`VariableType` we silence the error in support of the type error.

Fix https://github.com/rust-lang/rust/issues/117846
2024-03-20 02:36:37 +00:00
bors
bd459c2877 Auto merge of #122029 - estebank:drive-by-ui-test, r=oli-obk
When displaying multispans, ignore empty lines adjacent to `...`

```
error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:98:18
    |
6   |       let _ = match true {
    |               ---------- `match` arms have incompatible types
7   |           true => (
    |  _________________-
8   | |             // last line shown in multispan header
...   |
96  | |
97  | |         ),
    | |_________- this is found to be of type `()`
98  |           false => "
    |  __________________^
...   |
119 | |
120 | |         ",
    | |_________^ expected `()`, found `&str`

error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:215:18
    |
122 |       let _ = match true {
    |               ---------- `match` arms have incompatible types
123 |           true => (
    |  _________________-
124 | |
125 | |         1 // last line shown in multispan header
...   |
213 | |
214 | |         ),
    | |_________- this is found to be of type `{integer}`
215 |           false => "
    |  __________________^
216 | |
217 | |
218 | |         1 last line shown in multispan
...   |
237 | |
238 | |         ",
    | |_________^ expected integer, found `&str`
```
2024-03-19 22:11:59 +00:00
Esteban Küber
b1575b71d4 Silence unecessary !Sized binding error
When gathering locals, we introduce a `Sized` obligation for each
binding in the pattern. *After* doing so, we typecheck the init
expression. If this has a type failure, we store `{type error}`, for
both the expression and the pattern. But later we store an inference
variable for the pattern.

We now avoid any override of an existing type on a hir node when they've
already been marked as `{type error}`, and on E0277, when it comes from
`VariableType` we silence the error in support of the type error.

Fix #117846.
2024-03-19 21:26:11 +00:00
Michael Goulet
05116c5c30 Only split by-ref/by-move futures for async closures 2024-03-19 16:59:23 -04:00
Esteban Küber
3f2159fda5 Add test for #117846 2024-03-19 20:56:45 +00:00
bors
a7e4de13c1 Auto merge of #116935 - oli-obk:different_lifetime_taits_in_same_sig, r=compiler-errors
Prevent opaque types being instantiated twice with different regions within the same function

addresses https://github.com/orgs/rust-lang/projects/22/views/1?pane=issue&itemId=41329537

r? `@compiler-errors`
2024-03-19 19:57:51 +00:00
bors
e760daa6a7 Auto merge of #122735 - matthiaskrgr:rollup-pgb1s90, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #122435 (Don't trigger `unused_qualifications` on global paths)
 - #122556 (Extend format arg help for simple tuple index access expression)
 - #122634 (compiletest: Add support for `//@ aux-bin: foo.rs`)
 - #122677 (Fix incorrect mutable suggestion information for binding in ref pattern.)
 - #122691 (Fix ICE: `global_asm!()` Don't Panic When Unable to Evaluate Constant)
 - #122695 (Change only_local to a enum type.)
 - #122717 (Ensure stack before parsing dot-or-call)
 - #122719 (Ensure nested statics have a HIR node to prevent various queries from ICEing)
 - #122720 ([doc]:fix error code example)
 - #122724 (add test for casting pointer to union with unsized tail)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-19 17:52:46 +00:00
Oli Scherer
3ec5042cf9 Avoid computing generic params or a param env for free const items 2024-03-19 17:30:08 +00:00
Matthias Krüger
433449a900
Rollup merge of #122724 - lukas-code:unsized-union-cast-ice-test, r=compiler-errors
add test for casting pointer to union with unsized tail

closes https://github.com/rust-lang/rust/issues/122581
2024-03-19 18:03:54 +01:00
Matthias Krüger
65618908ef
Rollup merge of #122717 - workingjubilee:handle-call-call-call-call-calling-me-maybe, r=compiler-errors
Ensure stack before parsing dot-or-call

There are many cases where, due to codegen or a massively unruly codebase, a deeply nested `call(call(call(call(call(call(call(call(call(f())))))))))` can happen. This is a spot where it would be good to grow our stack, so that we can survive to tell the programmer their code is dubiously written.

Closes https://github.com/rust-lang/rust/issues/122715
2024-03-19 18:03:52 +01:00
Matthias Krüger
2ad2492b7b
Rollup merge of #122691 - veera-sivarajan:bugfix-121099, r=Amanieu
Fix ICE: `global_asm!()` Don't Panic When Unable to Evaluate Constant

Fixes #121099

A bit of an inelegant fix but given that the error is created only
after call to `const_eval_poly()` and that the calling function
cannot propagate the error anywhere else, the error has to be
explicitly handled inside `mono_item.rs`.

r? `@Amanieu`
2024-03-19 18:03:51 +01:00
Matthias Krüger
17386b8fbf
Rollup merge of #122677 - surechen:fix_122415, r=Nadrieril
Fix incorrect mutable suggestion information for binding in ref pattern.

For ref pattern in func param, the mutability suggestion has to apply to the binding.

For example: `fn foo(&x: &i32)` -> `fn foo(&(mut x): &i32)`

fixes #122415
2024-03-19 18:03:51 +01:00
Matthias Krüger
42dec6f874
Rollup merge of #122634 - Enselic:aux-bin, r=oli-obk
compiletest: Add support for `//@ aux-bin: foo.rs`

Which enables ui tests to use auxiliary binaries. See the added
self-test for an example.

This is an enabler for the test in https://github.com/rust-lang/rust/pull/121573.
2024-03-19 18:03:50 +01:00
Matthias Krüger
45e005df42
Rollup merge of #122556 - jieyouxu:non-identifier-format-arg, r=petrochenkov
Extend format arg help for simple tuple index access expression

The help is only applicable for simple field access `a.b` and (with this PR) simple tuple index access expressions `a.0`.

Closes #122535.
2024-03-19 18:03:50 +01:00
Matthias Krüger
489c2e9918
Rollup merge of #122435 - jieyouxu:unused_qualifications_global_paths, r=petrochenkov
Don't trigger `unused_qualifications` on global paths

Fixes #122374.
2024-03-19 18:03:49 +01:00
Michael Goulet
3d56178880 Remove redundant coroutine captures note 2024-03-19 12:02:21 -04:00
bors
a385e5667c Auto merge of #122392 - BoxyUwU:misc_cleanup, r=lcnr
misc cleanups from debugging something

rename `instantiate_canonical_with_fresh_inference_vars` to `instantiate_canonical`  the substs for the canonical are not solely infer vars as that would be wildly wrong and it is rather confusing to see this method called and think that the entire canonicalization setup is completely broken when it is not 👍

also update region debug printing to be more like the custom impls for Ty/Const, right now regions in debug output are horribly verbose and make it incredibly hard to read but with this atleast boundvars and placeholders when debugging the new solver do not take up excessive amounts of space.

r? `@lcnr`
2024-03-19 15:38:41 +00:00
Martin Nordholts
3a5eb35577 compiletest: Add support for //@ aux-bin: foo.rs
Which enables ui tests to use auxiliary binaries. See the added
self-test for an example.
2024-03-19 16:37:34 +01:00
Michael Goulet
67f1c53c05 Don't ICE when encountering bound regions in generator interior type 2024-03-19 11:30:12 -04:00
bors
200e3f7995 Auto merge of #122037 - oli-obk:more_new_intrinsics, r=Nilstrieb
Move more intrinsics to rustc_intrinsic

cc https://github.com/rust-lang/rust/issues/63585
2024-03-19 13:10:01 +00:00
Lukas Markeffsky
7b21c1a457 add test for casting pointer to union with unsized tail 2024-03-19 13:57:31 +01:00
Oli Scherer
7f9830b16c Make const_eval_select a rustc_intrinsic 2024-03-19 09:12:58 +00:00
bors
8579a1856a Auto merge of #119212 - w-utter:pretty-print-const-expr, r=compiler-errors
Fix representation when printing abstract consts

Previously, when printing a const generic expr, it would only display it as `{{const expr}}`. This allows for a more legible representation when printing these out.

I also zipped the types with their constants for abstract consts that contain function calls when using type annotations, eg: `foo(S: usize, true: bool) -> usize` insteaad of `foo(S, true): fn(usize, bool) -> usize` for conciseness.
2024-03-19 09:04:41 +00:00
Jubilee Young
cdeb170fc2 Ensure stack before parsing dot-or-call
There are many cases where, due to codegen or a massively unruly codebase,
a deeply nested call(call(call(call(call(call(call(call(call(f())))))))))
can happen. This is a spot where it would be good to grow our stack, so that
we can survive to tell the programmer their code is dubiously written.
2024-03-18 21:35:18 -07:00
surechen
19f72dfe04 Fix incorrect mutable suggestion information for binding in ref pattern.
For ref pattern in func param, the mutability suggestion has to apply to the binding.

For example: `fn foo(&x: &i32)` -> `fn foo(&(mut x): &i32)`

fixes #122415
2024-03-19 12:28:23 +08:00
bors
196ff446d2 Auto merge of #122493 - lukas-code:sized-constraint, r=lcnr
clean up `Sized` checking

This PR cleans up `sized_constraint` and related functions to make them simpler and faster. This should not make more or less code compile, but it can change error output in some rare cases.

## enums and unions are `Sized`, even if they are not WF

The previous code has some special handling for enums, which made them sized if and only if the last field of each variant is sized. For example given this definition (which is not WF)
```rust
enum E<T1: ?Sized, T2: ?Sized, U1: ?Sized, U2: ?Sized> {
    A(T1, T2),
    B(U1, U2),
}
```
the enum was sized if and only if `T2` and `U2` are sized, while `T1` and `T2` were ignored for `Sized` checking. After this PR this enum will always be sized.

Unsized enums are not a thing in Rust and removing this special case allows us to return an `Option<Ty>` from `sized_constraint`, rather than a `List<Ty>`.

Similarly, the old code made an union defined like this
```rust
union Union<T: ?Sized, U: ?Sized> {
    head: T,
    tail: U,
}
```
sized if and only if `U` is sized, completely ignoring `T`. This just makes no sense at all and now this union is always sized.

## apply the "perf hack" to all (non-error) types, instead of just type parameters

This "perf hack" skips evaluating `sized_constraint(adt): Sized` if `sized_constraint(adt): Sized` exactly matches a predicate defined on `adt`, for example:

```rust
// `Foo<T>: Sized` iff `T: Sized`, but we know `T: Sized` from a predicate of `Foo`
struct Foo<T /*: Sized */>(T);
```

Previously this was only applied to type parameters and now it is applied to every type. This means that for example this type is now always sized:

```rust
// Note that this definition is WF, but the type `S<T>` not WF in the global/empty ParamEnv
struct S<T>([T]) where [T]: Sized;
```

I don't anticipate this to affect compile time of any real-world program, but it makes the code a bit nicer and it also makes error messages a bit more consistent if someone does write such a cursed type.

## tuples are sized if the last type is sized

The old solver already has this behavior and this PR also implements it for the new solver and `is_trivially_sized`. This makes it so that tuples work more like a struct defined like this:

```rust
struct TupleN<T1, T2, /* ... */ Tn: ?Sized>(T1, T2, /* ... */ Tn);
```

This might improve the compile time of programs with large tuples a little, but is mostly also a consistency fix.

## `is_trivially_sized` for more types

This function is used post-typeck code (borrowck, const eval, codegen) to skip evaluating `T: Sized` in some cases. It will now return `true` in more cases, most notably `UnsafeCell<T>` and `ManuallyDrop<T>` where `T.is_trivially_sized`.

I'm anticipating that this change will improve compile time for some real world programs.
2024-03-19 04:21:14 +00:00
Gurinder Singh
3c70d60c4f Gracefully handle AnonConst in diagnostic_hir_wf_check()
when it is the default value of a generic param
2024-03-19 09:20:23 +05:30
Veera
394821060d Update test with //@ needs-asm-support 2024-03-18 22:33:04 -04:00
bors
21d94a3d2c Auto merge of #122055 - compiler-errors:stabilize-atb, r=oli-obk
Stabilize associated type bounds (RFC 2289)

This PR stabilizes associated type bounds, which were laid out in [RFC 2289]. This gives us a shorthand to express nested type bounds that would otherwise need to be expressed with nested `impl Trait` or broken into several `where` clauses.

### What are we stabilizing?

We're stabilizing the associated item bounds syntax, which allows us to put bounds in associated type position within other bounds, i.e. `T: Trait<Assoc: Bounds...>`. See [RFC 2289] for motivation.

In all position, the associated type bound syntax expands into a set of two (or more) bounds, and never anything else (see "How does this differ[...]" section for more info).

Associated type bounds are stabilized in four positions:
* **`where` clauses (and APIT)** - This is equivalent to breaking up the bound into two (or more) `where` clauses. For example, `where T: Trait<Assoc: Bound>` is equivalent to `where T: Trait, <T as Trait>::Assoc: Bound`.
* **Supertraits** - Similar to above, `trait CopyIterator: Iterator<Item: Copy> {}`. This is almost equivalent to breaking up the bound into two (or more) `where` clauses; however, the bound on the associated item is implied whenever the trait is used. See #112573/#112629.
* **Associated type item bounds** - This allows constraining the *nested* rigid projections that are associated with a trait's associated types. e.g. `trait Trait { type Assoc: Trait2<Assoc2: Copy>; }`.
* **opaque item bounds (RPIT, TAIT)** - This allows constraining associated types that are associated with the opaque without having to *name* the opaque. For example, `impl Iterator<Item: Copy>` defines an iterator whose item is `Copy` without having to actually name that item bound.

The latter three are not expressible in surface Rust (though for associated type item bounds, this will change in #120752, which I don't believe should block this PR), so this does represent a slight expansion of what can be expressed in trait bounds.

### How does this differ from the RFC?

Compared to the RFC, the current implementation *always* desugars associated type bounds to sets of `ty::Clause`s internally. Specifically, it does *not* introduce a position-dependent desugaring as laid out in [RFC 2289], and in particular:
* It does *not* desugar to anonymous associated items in associated type item bounds.
* It does *not* desugar to nested RPITs in RPIT bounds, nor nested TAITs in TAIT bounds.

This position-dependent desugaring laid out in the RFC existed simply to side-step limitations of the trait solver, which have mostly been fixed in #120584. The desugaring laid out in the RFC also added unnecessary complication to the design of the feature, and introduces its own limitations to, for example:
* Conditionally lowering to nested `impl Trait` in certain positions such as RPIT and TAIT means that we inherit the limitations of RPIT/TAIT, namely lack of support for higher-ranked opaque inference. See this code example: https://github.com/rust-lang/rust/pull/120752#issuecomment-1979412531.
* Introducing anonymous associated types makes traits no longer object safe, since anonymous associated types are not nameable, and all associated types must be named in `dyn` types.

This last point motivates why this PR is *not* stabilizing support for associated type bounds in `dyn` types, e.g, `dyn Assoc<Item: Bound>`. Why? Because `dyn` types need to have *concrete* types for all associated items, this would necessitate a distinct lowering for associated type bounds, which seems both complicated and unnecessary compared to just requiring the user to write `impl Trait` themselves. See #120719.

### Implementation history:

Limited to the significant behavioral changes and fixes and relevant PRs, ping me if I left something out--
* #57428
* #108063
* #110512
* #112629
* #120719
* #120584

Closes #52662

[RFC 2289]: https://rust-lang.github.io/rfcs/2289-associated-type-bounds.html
2024-03-19 00:04:09 +00:00
Mads Marquart
ec5c8fec6c Add test for Apple's -weak_framework linker argument 2024-03-18 23:27:34 +01:00
Matthias Krüger
3c3b398b35
Rollup merge of #122701 - compiler-errors:allocator-suspend, r=oli-obk
Detect allocator for box in `must_not_suspend` lint

I don't expect this to happen in practice, but better to check than not.

Fixes #122643
2024-03-18 22:24:41 +01:00
Matthias Krüger
e906205607
Rollup merge of #122687 - lcnr:normalizes-to-emit-nested-goals, r=compiler-errors
`NormalizesTo`: return nested goals to caller

Fixes the regression of `paperclip-core`. see https://hackmd.io/IsVAafiOTAaPIFcUxRJufw for more details.

r? ```@compiler-errors```
2024-03-18 22:24:39 +01:00
Matthias Krüger
980248605a
Rollup merge of #122158 - estebank:feature-sugg, r=WaffleLapkin
Provide structured suggestion for `#![feature(foo)]`

```
error: `S2<'_>` is forbidden as the type of a const generic parameter
  --> $DIR/lifetime-in-const-param.rs:5:23
   |
LL | struct S<'a, const N: S2>(&'a ());
   |                       ^^
   |
   = note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
   |
LL + #![feature(adt_const_params)]
   |
```

Fix #55941.
2024-03-18 22:24:38 +01:00
Matthias Krüger
b19c67c0fc
Rollup merge of #122060 - clubby789:stabilize-imported-main, r=lcnr
Stabilize `imported_main`

FCP: https://github.com/rust-lang/rust/issues/28937#issuecomment-1977822831
Docs: https://github.com/rust-lang/reference/pull/1461
2024-03-18 22:24:37 +01:00
Matthias Krüger
2d3dcfaade
Rollup merge of #121823 - Nadrieril:never-witnesses, r=compiler-errors
never patterns: suggest `!` patterns on non-exhaustive matches

When a match is non-exhaustive we now suggest never patterns whenever it makes sense.

r? ``@compiler-errors``
2024-03-18 22:24:36 +01:00
Matthias Krüger
05f763344d
Rollup merge of #121258 - fmease:assoc-const-eq-reject-overly-generic-tys, r=compiler-errors
Reject overly generic assoc const binding types

Split off from #119385 to make #119385 easier to review.

---

In the *instantiated* type of assoc const bindings

1. reject **early-bound generic params**
   * Provide a rich error message instead of ICE'ing ([#108271](https://github.com/rust-lang/rust/issues/108271)).
   * This is a temporary and semi-artificial restriction until the arrival of *generic const generics*.
   * It's quite possible that rustc could already perfectly support this subset of generic const generics if we just removed some checks (some `.no_bound_vars().expect(…)`) but even if that was the case, I'd rather gate it behind a new feature flag. Reporting an error instead of ICE'ing is a good first step towards an eventual feature gate error.
2. reject **escaping late-bound generic params**
   * They lead to ICEs before & I'm pretty sure that they remain incorrect even in a world with *generic const generics*

---

Together with #118668 & #119385, this supersedes #118360.
Fixes #108271.
2024-03-18 22:24:36 +01:00
Michael Goulet
0db06bf004 Detect allocator for box in must_not_suspend lint 2024-03-18 14:12:28 -04:00
Boxy
8124b26122 update region debug formatting 2024-03-18 16:44:12 +00:00
Esteban Küber
957c0d3488 Side-step small SVG width divergence by setting min-width 2024-03-18 16:40:43 +00:00
Esteban Küber
cc9631a371 When displaying multispans, ignore empty lines adjacent to ...
```
error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:98:18
    |
6   |       let _ = match true {
    |               ---------- `match` arms have incompatible types
7   |           true => (
    |  _________________-
8   | |             // last line shown in multispan header
...   |
96  | |
97  | |         ),
    | |_________- this is found to be of type `()`
98  |           false => "
    |  __________________^
...   |
119 | |
120 | |         ",
    | |_________^ expected `()`, found `&str`

error[E0308]: `match` arms have incompatible types
   --> tests/ui/codemap_tests/huge_multispan_highlight.rs:215:18
    |
122 |       let _ = match true {
    |               ---------- `match` arms have incompatible types
123 |           true => (
    |  _________________-
124 | |
125 | |         1 // last line shown in multispan header
...   |
213 | |
214 | |         ),
    | |_________- this is found to be of type `{integer}`
215 |           false => "
    |  __________________^
216 | |
217 | |
218 | |         1 last line shown in multispan
...   |
237 | |
238 | |         ",
    | |_________^ expected integer, found `&str`
```
2024-03-18 16:25:36 +00:00
Esteban Küber
8ea7177af7 Move multispan test to svg output 2024-03-18 16:25:36 +00:00
Esteban Küber
3e0bf9498a Fix test for multiline span ui display
The compiler output changed in such a way that this test was no longer testing what it was meant to.
2024-03-18 16:25:36 +00:00
Esteban Küber
6c31f6ce12 Provide structured suggestion for #![feature(foo)]
```
error: `S2<'_>` is forbidden as the type of a const generic parameter
  --> $DIR/lifetime-in-const-param.rs:5:23
   |
LL | struct S<'a, const N: S2>(&'a ());
   |                       ^^
   |
   = note: the only supported types are integers, `bool` and `char`
help: add `#![feature(adt_const_params)]` to the crate attributes to enable more complex and user defined types
   |
LL + #![feature(adt_const_params)]
   |
```

Fix #55941.
2024-03-18 16:08:58 +00:00
Veera
97cc7003ca Fix ICE: global_asm!() Don't Panic When Unable to Evaluate Constant
A bit of an inelegant fix but given that the error is created only
after call to `const_eval_poly()` and that the calling function
cannot propagate the error anywhere else, the error has to be
explicitly handled inside `mono_item.rs`.
2024-03-18 11:35:40 -04:00
lcnr
efa4269e54 move tests 2024-03-18 16:29:00 +01:00
Matthias Krüger
1eb49ec5b6
Rollup merge of #122683 - tshepang:missing-test, r=Nadrieril
add missing test: expected paren or brace in macro
2024-03-18 16:27:10 +01:00
Matthias Krüger
72e2c7c45a
Rollup merge of #122680 - lqd:nested-await-args, r=compiler-errors
Do not eat nested expressions' results in `MayContainYieldPoint` format args visitor

#121563 unintentionally changed the `MayContainYieldPoint` format args visitor behavior, now missing yield points in nested expressions, as seen in #122674.

The walk can find a yield point in an expression but it was ignored.

r? ``@petrochenkov`` as the reviewer of #121563
cc ``@Jarcho`` as the author

Fixes #122674.
We're in the 1.77 release week. #121563 will land on 1.78 but beta is still 1.77.9: this PR will likely need to be backported soon after beta is cut.
2024-03-18 16:27:10 +01:00
Matthias Krüger
1ac0239bd2
Rollup merge of #122649 - cuviper:min-llvm-17, r=nikic
Update the minimum external LLVM to 17

With this change, we'll have stable support for LLVM 17 and 18.
For reference, the previous increase to LLVM 16 was #117947.
2024-03-18 16:27:09 +01:00
Veera
935842bf0a Add tests 2024-03-18 11:17:27 -04:00
lcnr
f26e1e8b63 NormalizesTo return nested goals 2024-03-18 15:53:16 +01:00
Tshepang Mbambo
0550afd97e add missing test: expected paren or brace in macro 2024-03-18 14:25:50 +02:00
Oli Scherer
be9317d1ec Prevent opaque types being instantiated twice with different regions within the same function 2024-03-18 10:26:10 +00:00
Rémy Rakic
f3e9dfaed6 add non-regression test for issue 122674 2024-03-18 10:01:35 +00:00
Matthias Krüger
069b93335f
Rollup merge of #122657 - beetrees:option-env-tests, r=compiler-errors,Nilstrieb
Move `option_env!` and `env!` tests to the `env-macro` directory

This PR moves the `option_env!` tests to there own directory (`extoption_env`), matching the naming convention used by the tests for `env!` (which live in the `extenv` directory).
2024-03-18 06:58:50 +01:00
bors
5608c7f9aa Auto merge of #121652 - estebank:move-in-loop-break-condition, r=Nadrieril
Detect when move of !Copy value occurs within loop and should likely not be cloned

When encountering a move error on a value within a loop of any kind,
identify if the moved value belongs to a call expression that should not
be cloned and avoid the semantically incorrect suggestion. Also try to
suggest moving the call expression outside of the loop instead.

```
error[E0382]: use of moved value: `vec`
  --> $DIR/recreating-value-in-loop-condition.rs:6:33
   |
LL |     let vec = vec!["one", "two", "three"];
   |         --- move occurs because `vec` has type `Vec<&str>`, which does not implement the `Copy` trait
LL |     while let Some(item) = iter(vec).next() {
   |     ----------------------------^^^--------
   |     |                           |
   |     |                           value moved here, in previous iteration of loop
   |     inside of this loop
   |
note: consider changing this parameter type in function `iter` to borrow instead if owning the value isn't necessary
  --> $DIR/recreating-value-in-loop-condition.rs:1:17
   |
LL | fn iter<T>(vec: Vec<T>) -> impl Iterator<Item = T> {
   |    ----         ^^^^^^ this parameter takes ownership of the value
   |    |
   |    in this function
help: consider moving the expression out of the loop so it is only moved once
   |
LL ~     let mut value = iter(vec);
LL ~     while let Some(item) = value.next() {
   |
```

We use the presence of a `break` in the loop that would be affected by
the moved value as a heuristic for "shouldn't be cloned".

Fix https://github.com/rust-lang/rust/issues/121466.

---

*Point at continue and break that might be in the wrong place*

Sometimes move errors are because of a misplaced `continue`, but we didn't
surface that anywhere. Now when there are more than one set of nested loops
we show them out and point at the `continue` and `break` expressions within
that might need to go elsewhere.

```
error[E0382]: use of moved value: `foo`
  --> $DIR/nested-loop-moved-value-wrong-continue.rs:46:18
   |
LL |     for foo in foos {
   |         ---
   |         |
   |         this reinitialization might get skipped
   |         move occurs because `foo` has type `String`, which does not implement the `Copy` trait
...
LL |         for bar in &bars {
   |         ---------------- inside of this loop
...
LL |                 baz.push(foo);
   |                          --- value moved here, in previous iteration of loop
...
LL |         qux.push(foo);
   |                  ^^^ value used here after move
   |
note: verify that your loop breaking logic is correct
  --> $DIR/nested-loop-moved-value-wrong-continue.rs:41:17
   |
LL |     for foo in foos {
   |     ---------------
...
LL |         for bar in &bars {
   |         ----------------
...
LL |                 continue;
   |                 ^^^^^^^^ this `continue` advances the loop at line 33
help: consider moving the expression out of the loop so it is only moved once
   |
LL ~         let mut value = baz.push(foo);
LL ~         for bar in &bars {
LL |
 ...
LL |             if foo == *bar {
LL ~                 value;
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL |                 baz.push(foo.clone());
   |                             ++++++++
```

Fix https://github.com/rust-lang/rust/issues/92531.
2024-03-18 02:10:34 +00:00
Kornel
3bbbe3cf64 Test generic arg suggestion inside nested item 2024-03-17 23:40:12 +00:00
Esteban Küber
ea1883d7b2 Silence redundant error on char literal that was meant to be a string in 2021 edition 2024-03-17 23:35:19 +00:00
Esteban Küber
6f388ef1fb Extend test to trigger on 2015, 2018 and 2021 editions 2024-03-17 23:35:19 +00:00
Esteban Küber
999a0dc300 review comment: str -> string in messages 2024-03-17 23:35:18 +00:00
Esteban Küber
4a10b01f95 Use shorter span for existing ' -> " structured suggestion 2024-03-17 23:35:18 +00:00
Esteban Küber
982918f493 Handle str literals written with ' lexed as lifetime
Given `'hello world'` and `'1 str', provide a structured suggestion for a valid string literal:

```
error[E0762]: unterminated character literal
  --> $DIR/lex-bad-str-literal-as-char-3.rs:2:26
   |
LL |     println!('hello world');
   |                          ^^^^
   |
help: if you meant to write a `str` literal, use double quotes
   |
LL |     println!("hello world");
   |              ~           ~
```
```
error[E0762]: unterminated character literal
  --> $DIR/lex-bad-str-literal-as-char-1.rs:2:20
   |
LL |     println!('1 + 1');
   |                    ^^^^
   |
help: if you meant to write a `str` literal, use double quotes
   |
LL |     println!("1 + 1");
   |              ~     ~
```

Fix #119685.
2024-03-17 23:35:18 +00:00
beetrees
36514015ff
Move option_env! and env! tests to the env-macro directory 2024-03-17 21:59:40 +00:00
Esteban Küber
f216bac861 Add HELP to test 2024-03-17 21:45:03 +00:00
Esteban Küber
78d29ad8d6 Point at continue and break that might be in the wrong place
Sometimes move errors are because of a misplaced `continue`, but we didn't
surface that anywhere. Now when there are more than one set of nested loops
we show them out and point at the `continue` and `break` expressions within
that might need to go elsewhere.

```
error[E0382]: use of moved value: `foo`
  --> $DIR/nested-loop-moved-value-wrong-continue.rs:46:18
   |
LL |     for foo in foos {
   |         ---
   |         |
   |         this reinitialization might get skipped
   |         move occurs because `foo` has type `String`, which does not implement the `Copy` trait
...
LL |         for bar in &bars {
   |         ---------------- inside of this loop
...
LL |                 baz.push(foo);
   |                          --- value moved here, in previous iteration of loop
...
LL |         qux.push(foo);
   |                  ^^^ value used here after move
   |
note: verify that your loop breaking logic is correct
  --> $DIR/nested-loop-moved-value-wrong-continue.rs:41:17
   |
LL |     for foo in foos {
   |     ---------------
...
LL |         for bar in &bars {
   |         ----------------
...
LL |                 continue;
   |                 ^^^^^^^^ this `continue` advances the loop at line 33
help: consider moving the expression out of the loop so it is only moved once
   |
LL ~         let mut value = baz.push(foo);
LL ~         for bar in &bars {
LL |
 ...
LL |             if foo == *bar {
LL ~                 value;
   |
help: consider cloning the value if the performance cost is acceptable
   |
LL |                 baz.push(foo.clone());
   |                             ++++++++
```

Fix #92531.
2024-03-17 21:32:26 +00:00
Esteban Küber
14473adf42 Detect when move of !Copy value occurs within loop and should likely not be cloned
When encountering a move error on a value within a loop of any kind,
identify if the moved value belongs to a call expression that should not
be cloned and avoid the semantically incorrect suggestion. Also try to
suggest moving the call expression outside of the loop instead.

```
error[E0382]: use of moved value: `vec`
  --> $DIR/recreating-value-in-loop-condition.rs:6:33
   |
LL |     let vec = vec!["one", "two", "three"];
   |         --- move occurs because `vec` has type `Vec<&str>`, which does not implement the `Copy` trait
LL |     while let Some(item) = iter(vec).next() {
   |     ----------------------------^^^--------
   |     |                           |
   |     |                           value moved here, in previous iteration of loop
   |     inside of this loop
   |
note: consider changing this parameter type in function `iter` to borrow instead if owning the value isn't necessary
  --> $DIR/recreating-value-in-loop-condition.rs:1:17
   |
LL | fn iter<T>(vec: Vec<T>) -> impl Iterator<Item = T> {
   |    ----         ^^^^^^ this parameter takes ownership of the value
   |    |
   |    in this function
help: consider moving the expression out of the loop so it is only moved once
   |
LL ~     let mut value = iter(vec);
LL ~     while let Some(item) = value.next() {
   |
```

We use the presence of a `break` in the loop that would be affected by
the moved value as a heuristic for "shouldn't be cloned".

Fix #121466.
2024-03-17 21:32:26 +00:00
Matthias Krüger
8e748c0a41
Rollup merge of #122578 - jieyouxu:guard-decorate, r=fee1-dead
Only invoke `decorate` if the diag can eventually be emitted

Lints can call [`trimmed_def_paths`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/print/fn.trimmed_def_paths.html#), such as through manual implementations of `LintDiagnostic` and calling `def_path_str`.

05a2be3def/compiler/rustc_lint/src/lints.rs (L1834-L1839)

The emission of a lint eventually relies on [`TyCtxt::node_lint`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/ty/context/struct.TyCtxt.html#method.node_lint), which has a `decorate` closure which is responsible for decorating the diagnostic with "lint stuff". `node_lint` in turn relies on [`lint_level`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/lint/fn.lint_level.html). Within `lint_level`, `decorate` is eventually called just before `Diag::emit` is called to decorate the diagnostic. However, if `-A warnings` or `--cap-lint=allow` are set, or if the unused_must_use lint is explicitly allowed, then `decorate` would be called, which would call `def_path_str`, but the diagnostic would never be emitted and hence would trigger the `must_produce_diag` ICE.

To avoid calling `decorate` when we don't eventually emit the diagnostic, we check that:

- if `--force-warn` is specified, then call `decorate`; otherwise
- if we can emit warnings (or higher), then call `decorate`.

Fixes #121774.
2024-03-17 19:26:22 +01:00
Matthias Krüger
3fbe203cc1
Rollup merge of #122572 - the8472:test-const-deadness, r=RalfJung
add test for #122301 to cover behavior that's on stable

If this ought to be broken it should at least happen intentionally

See #122301
2024-03-17 19:26:21 +01:00
Kornel
55067c539a Suggest _ for missing generic arguments in turbofish 2024-03-17 17:34:17 +00:00
Josh Stone
29430554f6 Update the minimum external LLVM to 17 2024-03-17 10:11:04 -07:00
许杰友 Jieyou Xu (Joe)
60de7554de
Invoke decorate when error level is beyond warning, including error 2024-03-17 14:41:37 +00:00
许杰友 Jieyou Xu (Joe)
772d8598d2
Only invoke decorate if the diag can eventually be emitted 2024-03-17 14:41:36 +00:00
The 8472
fefd06dc02 add test for #122301 to cover behavior that's on stable
if this ought to be broken it should at least happen intentionally
2024-03-17 14:58:22 +01:00
long-long-float
78e94cba77 Don't show suggestion if slice pattern is enclosed by any patterns 2024-03-17 19:21:13 +09:00
Erik Desjardins
4498cd6a8d extend extern tests to include FiveU16s
As described in the code, this extends just beyond a 64bit reg, but
isn't a round number, so it triggers some edge cases in the cast ABI.
2024-03-17 00:07:42 -04:00
bors
a615cea333 Auto merge of #121885 - reitermarkus:generic-nonzero-inner, r=oli-obk,wesleywiser
Move generic `NonZero` `rustc_layout_scalar_valid_range_start` attribute to inner type.

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

r? `@dtolnay`
2024-03-17 02:27:52 +00:00
许杰友 Jieyou Xu (Joe)
cacdf92d37
Note that type param is chosen by caller when suggesting return impl Trait 2024-03-16 23:20:42 +00:00
许杰友 Jieyou Xu (Joe)
52a1125036
Extend format arg help for simple tuple index access expression 2024-03-16 22:33:02 +00:00
León Orell Valerian Liehr
7b7a7fc891
Rollup merge of #122564 - Bryanskiy:delegation-fixes, r=compiler-errors
Delegation: fix ICE on duplicated associative items

Currently, functions delegation is only supported for delegation items with early resolved paths e.g. free functions and trait methods. During name resolution, information about function signatures is collected, including the number of parameters and whether there are self arguments. This information is then used when lowering from a delegation item into a regular function(`rustc_ast_lowering/src/delegation.rs`). The signature is usually inherited from path resolution id(`path_id`). However, in the case of trait impls `path_id` and `item_id` may be different:

```rust
trait Trait {
    fn foo(&self) -> u32 { 0 }
}

struct S;

mod to_reuse {
    use crate::S;

    pub fn foo(_: &S) -> u32 { 0 }
}

impl Trait for S {
    reuse to_reuse::foo { self }
    //~^ The signature should be inherited from item id instead of resolution id
}

```

Let's now consider an example from [issue](https://github.com/rust-lang/rust/issues/119920). Due to duplicated associative elements partial resolution for one of them will not be recorded:

9023f908cf/compiler/rustc_resolve/src/late.rs (L3153-L3162)

Which leads to an incorrect `is_in_trait_impl`

9023f908cf/compiler/rustc_ast_lowering/src/item.rs (L981-L986)

Which leads to an incorrect id for signature inheritance

9023f908cf/compiler/rustc_ast_lowering/src/delegation.rs (L99-L105)

Which lead to an ICE from original issue.

This patch fixes wrong `is_in_trait_impl`  calculation.

fixes https://github.com/rust-lang/rust/issues/119920
2024-03-16 23:28:48 +01:00
León Orell Valerian Liehr
0995508562
Rollup merge of #121720 - tmandry:split-refining, r=compiler-errors
Split refining_impl_trait lint into _reachable, _internal variants

As discussed in https://github.com/rust-lang/rust/issues/119535#issuecomment-1909352040:

> We discussed this today in triage and developed a consensus to:
>
> * Add a separate lint against impls that refine a return type defined with RPITIT even when the trait is not crate public.
> * Place that in a lint group along with the analogous crate public lint.
> * Create an issue to solicit feedback on these lints (or perhaps two separate ones).
> * Have the warnings displayed with each lint reference this issue in a similar manner to how we do that today with the required `Self: '0'` bound on GATs.
> * Make a note to review this feedback on 2-3 release cycles.

This points users to https://github.com/rust-lang/rust/issues/121718 to leave feedback.
2024-03-16 23:28:47 +01:00
León Orell Valerian Liehr
79c1e58801
Rollup merge of #121545 - gvozdvmozgu:fix-attribute-validation-associated-items, r=fmease
fix attribute validation on associated items in traits

#121537, fixed attribute validation on associated items in traits
2024-03-16 23:28:47 +01:00
Bryanskiy
b2ed9d0911 Delegation: fix ICE on duplicated associative items 2024-03-16 21:03:36 +03:00
will
7c4b07d5e8 added pretty_print_const_expr 2024-03-17 01:38:45 +11:00
bors
c563f2ee79 Auto merge of #122371 - oli-obk:visit_nested_body, r=tmiasko
Stop walking the bodies of statics for reachability, and evaluate them instead

cc `@saethlin` `@RalfJung`

cc #119214

This reuses the `DefIdVisitor` from `rustc_privacy`, because they basically try to do the same thing.

This PR's changes can probably be extended to constants, too, but let's tackle that separately, it's likely more involved.
2024-03-16 04:35:02 +00:00
bors
c03ea3dfd9 Auto merge of #121926 - tgross35:f16-f128-step3-feature-gate, r=compiler-errors,petrochenkov
`f16` and `f128` step 3: compiler support & feature gate

Continuation of https://github.com/rust-lang/rust/pull/121841, another portion of https://github.com/rust-lang/rust/pull/114607

This PR exposes the new types to the world and adds a feature gate. Marking this as a draft because I need some feedback on where I did the feature gate check. It also does not yet catch type via suffixed literals (so the feature gate test will fail, probably some others too because I haven't belssed).

If there is a better place to check all types after resolution, I can do that. If not, I figure maybe I can add a second gate location in AST when it checks numeric suffixes.

Unfortunately I still don't think there is much testing to be done for correctness (codegen tests or parsed value checks) until we have basic library support. I think that will be the next step.

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

r? `@compiler-errors`
cc `@Nilstrieb`
`@rustbot` label +F-f16_and_f128
2024-03-16 02:02:00 +00:00
bors
c67326b063 Auto merge of #122571 - matthiaskrgr:rollup-36wwovk, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #122254 (Detect calls to .clone() on T: !Clone types on borrowck errors)
 - #122495 (Visually mark 👻hidden👻 items with document-hidden-items)
 - #122543 (Add `#![rustc_never_type_mode = "..."]` crate-level attribute to allow experimenting)
 - #122560 (Safe Transmute: Use 'not yet supported', not 'unspecified' in errors)
 - #122562 (Mention labelled blocks in `break` docs)
 - #122563 (CI: cache PR CI Docker builds)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-15 21:18:36 +00:00
Matthias Krüger
b482523607
Rollup merge of #122560 - jswrenn:not-yet-supported, r=compiler-errors
Safe Transmute: Use 'not yet supported', not 'unspecified' in errors

We can (and will) support analyzing the transmutability of types whose layouts aren't completely specified by its repr. This change ensures that the error messages remain sensible after this support lands.

r? ``@compiler-errors``
2024-03-15 21:51:57 +01:00
Matthias Krüger
9e153ccd45
Rollup merge of #122254 - estebank:issue-48677, r=oli-obk
Detect calls to .clone() on T: !Clone types on borrowck errors

When encountering a lifetime error on a type that *holds* a type that doesn't implement `Clone`, explore the item's body for potential calls to `.clone()` that are only cloning the reference `&T` instead of `T` because `T: !Clone`. If we find this, suggest `T: Clone`.

```
error[E0502]: cannot borrow `*list` as mutable because it is also borrowed as immutable
  --> $DIR/clone-on-ref.rs:7:5
   |
LL |     for v in list.iter() {
   |              ---- immutable borrow occurs here
LL |         cloned_items.push(v.clone())
   |                             ------- this call doesn't do anything, the result is still `&T` because `T` doesn't implement `Clone`
LL |     }
LL |     list.push(T::default());
   |     ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL |
LL |     drop(cloned_items);
   |          ------------ immutable borrow later used here
   |
help: consider further restricting this bound
   |
LL | fn foo<T: Default + Clone>(list: &mut Vec<T>) {
   |                   +++++++
```
```
error[E0505]: cannot move out of `x` because it is borrowed
  --> $DIR/clone-on-ref.rs:23:10
   |
LL | fn qux(x: A) {
   |        - binding `x` declared here
LL |     let a = &x;
   |             -- borrow of `x` occurs here
LL |     let b = a.clone();
   |               ------- this call doesn't do anything, the result is still `&A` because `A` doesn't implement `Clone`
LL |     drop(x);
   |          ^ move out of `x` occurs here
LL |
LL |     println!("{b:?}");
   |               ----- borrow later used here
   |
help: consider annotating `A` with `#[derive(Clone)]`
   |
LL + #[derive(Clone)]
LL | struct A;
   |
```

Fix #48677.
2024-03-15 21:51:56 +01:00
bors
1ca424ca43 Auto merge of #122341 - compiler-errors:alias-wfness, r=lcnr
Consolidate WF for aliases

Make RPITs/TAITs/weak (type) aliases/projections all enforce:
1. their nominal predicates
2. their args are WF

This possibly does extra work, but is also nice for consistency sake.

r? lcnr
2024-03-15 19:19:35 +00:00
Jack Wrenn
107807d393 Safe Transmute: lowercase diagnostics 2024-03-15 17:55:49 +00:00
Jack Wrenn
dc35339514 Safe Transmute: Use 'not yet supported', not 'unspecified' in errors
We can (and will) support analyzing the transmutability of types
whose layouts aren't completely specified by its repr. This change
ensures that the error messages remain sensible after this support
lands.
2024-03-15 17:42:29 +00:00
许杰友 Jieyou Xu (Joe)
85bad8d1bf
Don't trigger unused_qualifications on global paths
# Conflicts:
#	tests/ui/lint/lint-qualification.stderr
2024-03-15 14:59:05 +00:00
Steven Trotter
8a5245e7dd Refactored a few bits:
- Firstly get all the information about generics matching out of the HIR
- Secondly the labelling for the function is more coherent now
- Lastly a few error message improvements
2024-03-15 13:37:41 +00:00
Matthias Krüger
ee940f87fc
Rollup merge of #122523 - compiler-errors:ensure-associated-types, r=oli-obk
Ensure RPITITs are created before def-id freezing

From the test:

```rust
// `ty::Error` in a trait ref will silence any missing item errors, but will also
// prevent the `associated_items` query from being called before def ids are frozen.
```

Essentially, the code that checks that `impl`s have all their items (`check_impl_items_against_trait`) is also (implicitly) responsible for fetching the `associated_items` query before, but since we early return here:
c2901f5435/compiler/rustc_hir_analysis/src/check/check.rs (L732-L737)
...that means that this never happens for trait refs that reference errors.

Fixes #122518
r? oli-obk
2024-03-15 10:14:55 +01:00
Matthias Krüger
42af99383a
Rollup merge of #122515 - jieyouxu:ice-self-ty-mismatch, r=compiler-errors
Pass the correct DefId when suggesting writing the aliased Self type out

Fixes #122467.
2024-03-15 10:14:55 +01:00
Matthias Krüger
f4afbe1389
Rollup merge of #122471 - RalfJung:const-eval-span, r=oli-obk
preserve span when evaluating mir::ConstOperand

This lets us show to the user where they were using the faulty const (which can be quite relevant when generics are involved).

I wonder if we should change "erroneous constant encountered" to something like "the above error was encountered while evaluating this constant" or so, to make this more similar to what the collector emits when showing a "backtrace" of where things get monomorphized? It seems a bit strange to rely on the order of emitted diagnostics for that but it seems the collector already [does that](da8a8c9223/compiler/rustc_monomorphize/src/collector.rs (L472-L475)).
2024-03-15 10:14:54 +01:00
Matthias Krüger
e66c7e479c
Rollup merge of #122174 - notriddle:master, r=TaKO8Ki
diagnostics: suggest `Clone` bounds when noop `clone()`

Fixes #121524
2024-03-15 10:14:54 +01:00
Steven Trotter
df93364057 Added ability to report on generic argument mismatch better
Needs some checking over and some tests have altered that need sanity checking, but overall this is starting to get somewhere now.
2024-03-15 08:37:32 +00:00
bors
ee03c286cf Auto merge of #122517 - petrochenkov:bodihash, r=oli-obk
Fill in HIR hash for associated opaque types

Fixes https://github.com/rust-lang/rust/issues/122508
2024-03-15 02:04:04 +00:00
Scott McMurray
234e383c34 Stabilize unchecked_{add,sub,mul} 2024-03-14 18:39:37 -07:00
Michael Goulet
571f945713 Ensure RPITITs are created before def-id freezing 2024-03-14 20:30:57 -04:00
bors
c2901f5435 Auto merge of #122511 - matthiaskrgr:rollup-swzilin, r=matthiaskrgr
Rollup of 10 pull requests

Successful merges:

 - #117118 ([AIX] Remove AixLinker's debuginfo() implementation)
 - #121650 (change std::process to drop supplementary groups based on CAP_SETGID)
 - #121764 (Make incremental sessions identity no longer depend on the crate names provided by source code)
 - #122212 (Copy byval argument to alloca if alignment is insufficient)
 - #122322 (coverage: Initial support for branch coverage instrumentation)
 - #122373 (Fix the conflict problem between the diagnostics fixes of lint `unnecessary_qualification`  and  `unused_imports`)
 - #122479 (Implement `Duration::as_millis_{f64,f32}`)
 - #122487 (Rename `StmtKind::Local` variant into `StmtKind::Let`)
 - #122498 (Update version of cc crate)
 - #122503 (Make `SubdiagMessageOp` well-formed)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-15 00:03:58 +00:00
Ralf Jung
48f2f0d725 preserve span when evaluating mir::ConstOperand 2024-03-14 21:55:07 +01:00
Vadim Petrochenkov
ef5513f278 Fill in HIR hash for associated opaque types 2024-03-14 23:29:12 +03:00
Lukas Markeffsky
8ad94111ad clean up ADT sized constraint computation 2024-03-14 21:28:47 +01:00
许杰友 Jieyou Xu (Joe)
87ced1561f
Pass the correct DefId when suggesting writing the aliased Self type out 2024-03-14 19:39:15 +00:00
Matthias Krüger
1f4aff7d2b
Rollup merge of #122487 - GuillaumeGomez:rename-stmtkind-local, r=oli-obk
Rename `StmtKind::Local` variant into `StmtKind::Let`

It comes from this [discussion](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Improve.20naming.20of.20.60ExprKind.3A.3ALet.60.3F).

Starting point was:

> I often end up looking at [ExprKind::Let](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/enum.ExprKind.html#variant.Let) instead of Local because of the name. I think renaming it (both the `ExprKind` variant and the Let struct) to `LetPattern` or LetPat could improve the situation as I'm not sure I'm not the only one encountering this issue.

And then it evolved into:

> It's already `Expr::Let` instead of `StmtKind::Local`. Counterproposal: rename `StmtKind::Local` to `StmtKind::Let`.

The goal here is to clear this confusion.

r? `@oli-obk`
2024-03-14 20:00:21 +01:00
Matthias Krüger
b200108bc5
Rollup merge of #122373 - surechen:fix_121331, r=petrochenkov
Fix the conflict problem between the diagnostics fixes of lint `unnecessary_qualification`  and  `unused_imports`

fixes #121331

For an `item` that triggers lint unnecessary_qualification, if the `use item` which imports this item is also trigger unused import, fixing the two lints at the same time may lead to the problem that the `item` cannot be found.
This PR will avoid reporting lint unnecessary_qualification when conflict occurs.

r? ``@petrochenkov``
2024-03-14 20:00:20 +01:00
bors
fd27e8745f Auto merge of #119849 - lcnr:eagerly-instantiate-binders, r=compiler-errors
more eagerly instantiate binders

The old solver sometimes incorrectly used `sub`, change it to explicitly instantiate binders and use `eq` instead. While doing so I also moved the instantiation before the normalize calls. This caused some observable changes, will explain these inline. This PR therefore requires a crater run and an FCP.

r? types
2024-03-14 18:58:53 +00:00
Trevor Gross
2098fec080 Add UI tests related to feature-gated primitives
Add a test that `f16` and `f128` are usable with the feature gate
enabled, as well as a test that user types with the same name as
primitives are not improperly gated.
2024-03-14 13:32:54 -04:00
Trevor Gross
2529bf2650 Remove unneeded f16 and f128 parser tests
Superceded by feature gate tests.
2024-03-14 13:32:54 -04:00
Trevor Gross
e782d27ec6 Add feature gates for f16 and f128
Includes related tests and documentation pages.

Michael Goulet: Don't issue feature error in resolver for f16/f128
unless finalize

Co-authored-by: Michael Goulet <michael@errs.io>
2024-03-14 13:32:54 -04:00
lcnr
c8f0f17ed2 add tests 2024-03-14 17:45:13 +01:00
Markus Reiter
40f8227d6d
Fix lint. 2024-03-14 17:34:57 +01:00
lcnr
323069fd59 rebase 2024-03-14 17:19:40 +01:00
lcnr
6729e0188b one must imagine tidy happy 2024-03-14 17:19:40 +01:00
lcnr
24a1729566 eagerly instantiate binders to avoid relying on sub 2024-03-14 17:19:40 +01:00
Michael Goulet
04524c8f6a Consolidate WF for aliases 2024-03-14 12:17:00 -04:00
Matthias Krüger
c0fd2db49a
Rollup merge of #122482 - weiznich:fix/122446, r=compiler-errors
Ungate the `UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES` lint

This was missed during stablisation of the `#[diagnostic]` attribute namespace.

Fixes #122446
2024-03-14 15:44:36 +01:00
Matthias Krüger
1dce191441
Rollup merge of #122368 - pavedroad:master, r=oli-obk
chore: remove repetitive words
2024-03-14 15:44:34 +01:00
Matthias Krüger
6a4dd19ade
Rollup merge of #122287 - RalfJung:simd-static-assert, r=pnkfelix
add test ensuring simd codegen checks don't run when a static assertion failed

stdarch relies on this to ensure that SIMD indices are in bounds.

I would love to know why this works, but I can't figure out where codegen decides to not codegen a function if a required-const does not evaluate. `@oli-obk` `@bjorn3` do you have any idea?
2024-03-14 15:44:33 +01:00
Oli Scherer
746e4eff26 Test and implement reachability for trait objects and generic parameters of functions 2024-03-14 14:10:45 +00:00
Guillaume Gomez
ac1b8575c0 Update tests/ui/stats/hir-stats.stderr output 2024-03-14 12:42:04 +01:00
Matthias Krüger
bdf84ea00e
Rollup merge of #122440 - RalfJung:required-consts, r=oli-obk
const-eval: organize and extend tests for required-consts

This includes some tests that are known-broken and hence disabled (due to https://github.com/rust-lang/rust/issues/107503).

r? `````@oli-obk`````
2024-03-14 11:10:00 +01:00
Georg Semmler
25411113c1
Ungate the UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES lint
This was missed during stablisation of the `#[diagnostic]` attribute
namespace.

Fixes #122446
2024-03-14 10:49:28 +01:00
bors
6f3eb1ce3d Auto merge of #122454 - matthiaskrgr:rollup-xbmufdc, r=matthiaskrgr
Rollup of 11 pull requests

Successful merges:

 - #122422 (compiletest: Allow `only-unix` in test headers)
 - #122424 (fix: typos)
 - #122425 (Increase timeout for new bors bot)
 - #122426 (Fix StableMIR `WrappingRange::is_full` computation)
 - #122429 (Add Exploit Mitigations PG to triagebot.toml)
 - #122430 (Generate link to `Local` in `hir::Let` documentation)
 - #122434 (pattern analysis: rename a few types)
 - #122437 (pattern analysis: remove `MaybeInfiniteInt::JustAfterMax`)
 - #122438 (Safe Transmute: Require that source referent is smaller than destination)
 - #122442 (extend docs of -Zprint-mono-items)
 - #122449 (Delay a bug for stranded opaques)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-14 04:54:37 +00:00
bors
5ac0b2d021 Auto merge of #122347 - oli-obk:track_errors13, r=compiler-errors
Revert "Auto merge of #122140 - oli-obk:track_errors13, r=davidtwco"

This reverts commit 65cd843ae0, reversing changes made to d255c6a57c.

reverts https://github.com/rust-lang/rust/pull/122140

It was a large regression in wall time due to trashing CPU caches
2024-03-14 02:54:10 +00:00
surechen
1a81a941ad fixes #121331 2024-03-14 09:54:42 +08:00
bors
c7fed9f854 Auto merge of #122204 - pnkfelix:downgrade-const-eval-dnagling-ptr-in-final-to-future-incompat-lint, r=wesleywiser
Downgrade const eval dangling ptr in final to future incompat lint

Short term band-aid for issue #121610, downgrading the prior hard error to a future-incompat lint (tracked in issue #122153).

Note we should not mark #121610 as resolved until after this (or something analogous) is beta backported.
2024-03-14 00:06:26 +00:00
Esteban Küber
0953608deb Account for UnOps in borrowck message 2024-03-13 23:05:17 +00:00
Esteban Küber
b367c25367 Tweak wording 2024-03-13 23:05:17 +00:00
Esteban Küber
2d3435b4df Detect calls to .clone() on T: !Clone types on borrowck errors
When encountering a lifetime error on a type that *holds* a type that
doesn't implement `Clone`, explore the item's body for potential calls
to `.clone()` that are only cloning the reference `&T` instead of `T`
because `T: !Clone`. If we find this, suggest `T: Clone`.

```
error[E0502]: cannot borrow `*list` as mutable because it is also borrowed as immutable
  --> $DIR/clone-on-ref.rs:7:5
   |
LL |     for v in list.iter() {
   |              ---- immutable borrow occurs here
LL |         cloned_items.push(v.clone())
   |                             ------- this call doesn't do anything, the result is still `&T` because `T` doesn't implement `Clone`
LL |     }
LL |     list.push(T::default());
   |     ^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
LL |
LL |     drop(cloned_items);
   |          ------------ immutable borrow later used here
   |
help: consider further restricting this bound
   |
LL | fn foo<T: Default + Clone>(list: &mut Vec<T>) {
   |                   +++++++
```
```
error[E0505]: cannot move out of `x` because it is borrowed
  --> $DIR/clone-on-ref.rs:23:10
   |
LL | fn qux(x: A) {
   |        - binding `x` declared here
LL |     let a = &x;
   |             -- borrow of `x` occurs here
LL |     let b = a.clone();
   |               ------- this call doesn't do anything, the result is still `&A` because `A` doesn't implement `Clone`
LL |     drop(x);
   |          ^ move out of `x` occurs here
LL |
LL |     println!("{b:?}");
   |               ----- borrow later used here
   |
help: consider annotating `A` with `#[derive(Clone)]`
   |
LL + #[derive(Clone)]
LL | struct A;
   |
```
2024-03-13 23:05:11 +00:00
Matthias Krüger
c52ce4eabb
Rollup merge of #122449 - compiler-errors:stranded-opaque, r=oli-obk
Delay a bug for stranded opaques

r? oli-obk

Fixes #122445
2024-03-13 20:01:58 +01:00
Matthias Krüger
89c3fa92d4
Rollup merge of #122438 - jswrenn:check-referent-size, r=compiler-errors
Safe Transmute: Require that source referent is smaller than destination

`BikeshedIntrinsicFrom` currently models transmute-via-union; i.e., it attempts to provide a `where` bound for this function:
```rust
pub unsafe fn transmute_via_union<Src, Dst>(src: Src) -> Dst {
    use core::mem::*;

    #[repr(C)]
    union Transmute<T, U> {
        src: ManuallyDrop<T>,
        dst: ManuallyDrop<U>,
    }

    let transmute = Transmute { src: ManuallyDrop::new(src) };

    // SAFETY: The caller must guarantee that the transmutation is safe.
    let dst = transmute.dst;

    ManuallyDrop::into_inner(dst)
}
```
A quirk of this model is that it admits padding extensions in value-to-value transmutation: The destination type can be bigger than the source type, so long as the excess consists of uninitialized bytes. However, this isn't permissible for reference-to-reference transmutations (introduced in #110662) — extra referent bytes cannot come from thin air.

This PR patches our analysis for reference-to-reference transmutations to require that the destination referent is no larger than the source referent.

r? `@compiler-errors`
2024-03-13 20:01:58 +01:00
Matthias Krüger
5c2aa6dc6f
Rollup merge of #122437 - Nadrieril:no-after-max, r=compiler-errors
pattern analysis: remove `MaybeInfiniteInt::JustAfterMax`

It was inherited from before half-open ranges, but it doesn't pull its weight anymore. We lose a tiny bit of diagnostic precision as can be seen in the test. I'm generally in favor of half-open ranges over explicit `x..=MAX` ranges anyway.
2024-03-13 20:01:57 +01:00
Felix S. Klock II
8f45a9e93d include 32-bit variant for updated test of miri diagnostics. 2024-03-13 14:53:04 -04:00
Michael Goulet
026eb3dd64 Delay a bug for stranded opaques 2024-03-13 13:44:00 -04:00
Ralf Jung
514b2745b3 const-eval: organize and extend tests for required-consts 2024-03-13 17:49:45 +01:00
Jack Wrenn
216df4a8e6 safe transmute: require that src referent is smaller than dst
The source referent absolutely must be smaller than the destination
referent of a ref-to-ref transmute; the excess bytes referenced
cannot arise from thin air, even if those bytes are uninitialized.
2024-03-13 15:53:48 +00:00
bors
3cbb93223f Auto merge of #121668 - erikdesjardins:commonprim, r=scottmcm,oli-obk
Represent `Result<usize, Box<T>>` as ScalarPair(i64, ptr)

This allows types like `Result<usize, std::io::Error>` (and integers of differing sign, e.g. `Result<u64, i64>`) to be passed in a pair of registers instead of through memory, like `Result<u64, u64>` or `Result<Box<T>, Box<U>>` are today.

Fixes #97540.

r? `@ghost`
2024-03-13 15:25:35 +00:00
Felix S. Klock II
1ea091a7fc Rebase. Update expected output to match current output. 2024-03-13 10:50:17 -04:00
Felix S. Klock II
354c41eeb6 Updated the test to include more output normalization. 2024-03-13 10:32:42 -04:00
Felix S. Klock II
1c3424bfc1 Added deny(const_eval_mutable_ptr_in_final_value) attribute to all tests that were expecting the hard error for it.
I attempted to do this in a manner that preserved the line numbers to reduce the
review effort on the resulting diff, but we still have to deal with the
ramifications of how a future-incompat lint behaves compared to a hard-error (in
terms of its impact on the diagnostic output).
2024-03-13 10:32:41 -04:00
Felix S. Klock II
f86b46a9cc regression test from 121610. 2024-03-13 10:32:41 -04:00
León Orell Valerian Liehr
0b2fb8db65
Reject escaping bound vars in the type of assoc const bindings 2024-03-13 14:29:27 +01:00
bors
184c5ab180 Auto merge of #121589 - bvanjoi:fix-98291, r=petrochenkov
delay expand macro bang when there has indeterminate path

Related #98291

I will attempt to clarify the root problem through several examples:

Firstly,

```rs
// rustc code.rs --edition=2018

macro_rules! wrap {
    () => {
        macro_rules! _a {
            () => {
                "Hello world"
            };
        }
    };
}

wrap!();

use _a as a;

fn main() {
    format_args!(_a!());
}
```

The above case will compile successfully because `_a` is defined after the `wrap` expaned, ensuring `_a` can be resolved without any issues.

And,

```rs
// rustc code.rs --edition=2018

macro_rules! wrap {
    () => {
        macro_rules! _a {
            () => {
                "Hello world"
            };
        }
    };
}

wrap!();

use _a as a;

fn main() {
    format_args!("{}", a!());
}
```

The above example will also compile successfully because the `parse_args` in `expand_format_args_impl` will return a value `MacroInput { fmtstr: Expr::Lit::Str, args: [Expr::MacroCall]}`. Since the graph for `args` will be build lately, `a` will eventually be resolved.

However, in the case of:

```rs
// rustc code.rs --edition=2018

macro_rules! wrap {
    () => {
        macro_rules! _a {
            () => {
                "Hello world"
            };
        }
    };
}

wrap!();

use _a as a;

fn main() {
    format_args!(a!());
}
```

The result of `parse_args` is `MacroInput {fmtstr: Expr::Lit::Macro, args: [] }`, we attempt to expand `fmtstr` **eagerly** within `expr_to_spanned_string`. Although we have recorded `(root, _a)` into resolutions, `use _a as a` is an indeterminate import, which will not try to resolve under the conditions of `expander.monotonic = false`.

Therefore, I've altered the strategy for resolving indeterminate imports, ensuring it will also resolve during eager expansion. This could be a significant change to the resolution infra. However, I think it's acceptable if the goal of avoiding resolution under eager expansion is to save time.

r? `@petrochenkov`
2024-03-13 13:20:42 +00:00
Nadrieril
c4236785c7 Remove MaybeInfiniteInt::JustAfterMax
It was inherited from before half-open ranges, but it doesn't pull its
weight anymore. We lose a tiny bit of diagnostic precision.
2024-03-13 14:17:11 +01:00
León Orell Valerian Liehr
d26c5723e7
Reject early-bound params in the type of assoc const bindings 2024-03-13 13:32:54 +01:00
bohan
8fcdf54a6b delay expand macro bang when there has indeterminate path 2024-03-13 16:11:16 +08:00
Matthias Krüger
1ffa5ded58
Rollup merge of #122400 - wutchzone:122345, r=fmease
Fix ICE in diagnostics for parenthesized type arguments

The second time is the charm 🤞 😁

Fixes #122345

r? fmease
2024-03-13 06:41:24 +01:00
Matthias Krüger
5d131407da
Rollup merge of #122360 - veera-sivarajan:bugfix-121941, r=compiler-errors
Don't Create `ParamCandidate` When Obligation Contains Errors

Fixes #121941

I'm not sure if I understand this correctly but this bug was caused by an error type incorrectly matching against `ParamCandidate`. This was introduced by the changes made in #72621 (figured using cargo-bisect-rustc).

This PR fixes it by skipping `ParamCandidate` generation when an error type is involved. Also, this is similar to #73005 but addresses `ParamCandidate` instead of `ImplCandidate`.
2024-03-13 06:41:23 +01:00
Matthias Krüger
8b9ef3b996
Rollup merge of #122226 - Zalathar:zcoverage-options, r=nnethercote
coverage: Remove or migrate all unstable values of `-Cinstrument-coverage`

(This PR was substantially overhauled from its original version, which migrated all of the existing unstable values intact.)

This PR takes the three nightly-only values that are currently accepted by `-Cinstrument-coverage`, completely removes two of them (`except-unused-functions` and `except-unused-generics`), and migrates the third (`branch`) over to a newly-introduced unstable flag `-Zcoverage-options`.

I have a few motivations for wanting to do this:

- It's unclear whether anyone actually uses the `except-unused-*` values, so this serves as an opportunity to either remove them, or prompt existing users to object to their removal.
- After #117199, the stable values of `-Cinstrument-coverage` treat it as a boolean-valued flag, so having nightly-only extra values feels out-of-place.
  - Nightly-only values also require extra ad-hoc code to make sure they aren't accidentally exposed to stable users.
- The new system allows multiple different settings to be toggled independently, which isn't possible in the current single-value system.
- The new system makes it easier to introduce new behaviour behind an unstable toggle, and then gather nightly-user feedback before possibly making it the default behaviour for all users.
- The new system also gives us a convenient place to put relatively-narrow options that won't ever be the default, but that nightly users might still want access to.
- It's likely that we will eventually want to give stable users more fine-grained control over coverage instrumentation. The new flag serves as a prototype of what that stable UI might eventually look like.

The `branch` option is a placeholder that currently does nothing. It will be used by #122322 to opt into branch coverage instrumentation.

---

I see `-Zcoverage-options` as something that will exist more-or-less indefinitely, though individual sub-options might come and go as appropriate. I think there will always be some demand for nightly-only toggles, so I don't see `-Zcoverage-options` itself ever being stable, though we might eventually stabilize something similar to it.
2024-03-13 06:41:22 +01:00
Matthias Krüger
e6ba504029
Rollup merge of #121908 - Nadrieril:dynamic-variant-collection, r=matthewjasper
match lowering: don't collect test alternatives ahead of time

I'm very happy with this one. Before this, when sorting candidates into the possible test branches, we manually computed `usize` indices to determine in which branch each candidate goes. To make this work we had a first pass that collected the possible alternatives we'd have to deal with, and a second pass that actually sorts the candidates.

In this PR, I replace `usize` indices with a dedicated enum. This makes `sort_candidates` easier to follow, and we don't need the first pass anymore.

r? ``@matthewjasper``
2024-03-13 06:41:21 +01:00
Zalathar
3407fcc12e coverage: Add -Zcoverage-options for fine control of coverage
This new nightly-only flag can be used to toggle fine-grained flags that
control the details of coverage instrumentation.

Currently the only supported flag value is `branch` (or `no-branch`), which is
a placeholder for upcoming support for branch coverage. Other flag values can
be added in the future, to prototype proposed new behaviour, or to enable
special non-default behaviour.
2024-03-13 11:14:10 +11:00
Zalathar
1f544ce305 coverage: Remove all unstable values of -Cinstrument-coverage 2024-03-13 11:14:09 +11:00
Nadrieril
b878ab6a27 Don't suggest an arm when suggesting a never pattern 2024-03-12 21:38:31 +01:00
Nadrieril
9f2aa5b85a Suggest never pattern instead of _ for empty types 2024-03-12 21:38:30 +01:00
Nadrieril
844f173b5c Run the empty_types tests with never_patterns too 2024-03-12 21:38:30 +01:00
Daniel Sedlak
eab1f30c29 Fix ICE in diagnostics for parenthesized type arguments 2024-03-12 21:32:21 +01:00
Veera
96b8225d8d Don't Create ParamCandidate When Obligation Contains Errors
Fixes #121941
2024-03-12 15:27:08 -04:00
Jubilee
0b31375248
Rollup merge of #122366 - oli-obk:opaques_defined_by_overflow, r=lcnr
Fix stack overflow with recursive associated types

fixes #122364
2024-03-12 09:04:02 -07:00
Jubilee
778c76c6a7
Rollup merge of #122363 - Enselic:unix_sigpipe-str-list, r=oli-obk
tests: Add ui/attributes/unix_sigpipe/unix_sigpipe-str-list.rs

Which is a variant of [`unix_sigpipe-list.rs`][1] but where a string is used instead of an identifier. This makes it more similar to the proper form `#[unix_sigpipe = "sig_dfl"]` and thus more likely to be written by users by mistake. Having a test for this case gives peace of mind.

Also rename the first test to be more in line with the terminology of [The Reference][2].

[1]: https://github.com/rust-lang/rust/blob/master/tests/ui/attributes/unix_sigpipe/unix_sigpipe-list.rs
[2]: https://doc.rust-lang.org/reference/attributes.html#meta-item-attribute-syntax

Tracking issue: https://github.com/rust-lang/rust/issues/97889
2024-03-12 09:04:02 -07:00
pavedroad
6b082b5e66 chore: remove repetitive words
Signed-off-by: pavedroad <qcqs@outlook.com>

chore: remove repetitive words

Signed-off-by: pavedroad <qcqs@outlook.com>
2024-03-12 20:09:33 +08:00
bors
3b85d2c7fc Auto merge of #121644 - oli-obk:unique_static_innards2, r=RalfJung,nnethercote
Ensure nested allocations in statics neither get deduplicated nor duplicated

This PR generates new `DefId`s for nested allocations in static items and feeds all the right queries to make the compiler believe these are regular `static` items. I chose this design, because all other designs are fragile and make the compiler horribly complex for such a niche use case.

At present this wrecks incremental compilation performance *in case nested allocations exist* (because any query creating a `DefId` will be recomputed and never loaded from the cache). This will be resolved later in https://github.com/rust-lang/rust/pull/115613 . All other statics are unaffected by this change and will not have performance regressions (heh, famous last words)

This PR contains various smaller refactorings that can be pulled out into separate PRs. It is best reviewed commit-by-commit. The last commit is where the actual magic happens.

r? `@RalfJung` on the const interner and engine changes

fixes https://github.com/rust-lang/rust/issues/79738
2024-03-12 10:29:15 +00:00
Arthur Carcano
701dd5bc9d Allow unused fields in some tests
The dead_code lint was previously eroneously missing those.
Since this lint bug has been fixed, the unused fields warnings need
to be fixed.

Most of them are marked as `#[allow(dead_code)]`. Other warnings are
fixed by changing visibility of modules.
2024-03-12 10:59:41 +01:00
Arthur Carcano
a0fe4138ed Replace visibility test with reachability test in dead code detection
Fixes https://github.com/rust-lang/rust/issues/119545
2024-03-12 10:59:40 +01:00
bors
b0170b693e Auto merge of #122365 - matthiaskrgr:rollup-4i350h6, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #115141 (Update Windows platform support)
 - #121865 (Add FileCheck annotations to MIR-opt unnamed-fields tests)
 - #122000 (Fix 32-bit overflows in LLVM composite constants)
 - #122194 (Enable creating backtraces via -Ztreat-err-as-bug when stashing errors)
 - #122319 (Don't ICE when non-self part of trait goal is constrained in new solver)
 - #122339 (Update books)
 - #122342 (Update /NODEFAUTLIB comment for msvc)
 - #122343 (Remove some unnecessary `allow(incomplete_features)` in the test suite)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-12 06:29:06 +00:00
Oli Scherer
783490da70 Fix stack overflow with recursive associated types 2024-03-12 06:03:43 +00:00
Oli Scherer
d3514a036d Ensure nested allocations in statics do not get deduplicated 2024-03-12 05:53:46 +00:00
Amanjeev Sethi
0a2475c50a Add tests showing how we duplicate allocations when we shouldn't 2024-03-12 05:50:10 +00:00
Matthias Krüger
39e00760ec
Rollup merge of #122343 - compiler-errors:rando, r=fmease
Remove some unnecessary `allow(incomplete_features)` in the test suite

A useless change, but I like things to be clean.
2024-03-12 06:29:05 +01:00
Matthias Krüger
cd2efff518
Rollup merge of #122319 - compiler-errors:next-solver-normalizing-self-constrains-args, r=lcnr
Don't ICE when non-self part of trait goal is constrained in new solver

Self-explanatory. See test for example when this can happen.
2024-03-12 06:29:04 +01:00
Martin Nordholts
98553ce27e tests: Add ui/attributes/unix_sigpipe/unix_sigpipe-str-list.rs
Which is a variant of [`unix_sigpipe-list.rs`][1] but where a string is
used instead of an identifier. This makes it more similar to the proper
form `#[unix_sigpipe = "sig_dfl"]` and thus more likely to be written by
users by mistake. Also rename the first test to be more in line with the
terminology of [The Reference][2].

[1]: https://github.com/rust-lang/rust/blob/master/tests/ui/attributes/unix_sigpipe/unix_sigpipe-list.rs
[2]: https://doc.rust-lang.org/reference/attributes.html#meta-item-attribute-syntax
2024-03-12 06:04:41 +01:00
bors
0fa7feaf3f Auto merge of #121282 - saethlin:gep-null-means-no-provenance, r=scottmcm
Lower transmutes from int to pointer type as gep on null

I thought of this while looking at https://github.com/rust-lang/rust/pull/121242. See that PR's description for why this lowering is preferable.

The UI test that's being changed here crashes without changing the transmutes into casts. Based on that, this PR should not be merged without a crater build-and-test run.
2024-03-12 04:11:37 +00:00
bors
dc2ffa4054 Auto merge of #122036 - alexcrichton:test-wasm-with-wasi, r=oli-obk
Test wasm32-wasip1 in CI, not wasm32-unknown-unknown

This commit changes CI to no longer test the `wasm32-unknown-unknown` target and instead test the `wasm32-wasip1` target. There was some discussion of this in a [Zulip thread], and the motivations for this PR are:

* Runtime failures on `wasm32-unknown-unknown` print nothing, meaning all you get is "something failed". In contrast `wasm32-wasip1` can print to stdout/stderr.

* The unknown-unknown target is missing lots of pieces of libstd, and while `wasm32-wasip1` is also missing some pieces (e.g. threads) it's missing fewer pieces. This means that many more tests can be run.

Overall my hope is to improve the debuggability of wasm failures on CI and ideally be a bit less of a maintenance burden.

This commit specifically removes the testing of `wasm32-unknown-unknown` and replaces it with testing of `wasm32-wasip1`. Along the way there were a number of other archiectural changes made as well, including:

* A new `target.*.runtool` option can now be specified in `config.toml` which is passed as `--runtool` to `compiletest`. This is used to reimplement execution of WebAssembly in a less-wasm-specific fashion.

* The default value for `runtool` is an ambiently located WebAssembly runtime found on the system, if any. I've implemented logic for Wasmtime.

* Existing testing support for `wasm32-unknown-unknown` and Emscripten has been removed. I'm not aware of Emscripten testing being run any time recently and otherwise `wasm32-wasip1` is in theory the focus now.

* I've added a new `//@ needs-threads` directive for `compiletest` and classified a bunch of wasm-ignored tests as needing threads. In theory these tests can run on `wasm32-wasi-preview1-threads`, for example.

* I've tried to audit all existing tests that are either `ignore-emscripten` or `ignore-wasm*`. Many now run on `wasm32-wasip1` due to being able to emit error messages, for example. Many are updated with comments as to why they can't run as well.

* The `compiletest` output matching for `wasm32-wasip1` automatically uses "match a subset" mode implemented in `compiletest`. This is because WebAssembly runtimes often add extra information on failure, such as the `unreachable` instruction in `panic!`, which isn't able to be matched against the golden output from native platforms.

* I've ported most existing `run-make` tests that use custom Node.js wrapper scripts to the new run-make-based-in-Rust infrastructure. To do this I added `wasmparser` as a dependency of `run-make-support` for the various wasm tests to use that parse wasm files. The one test that executed WebAssembly now uses `wasmtime`-the-CLI to execute the test instead. I have not ported over an exception-handling test as Wasmtime doesn't implement this yet.

* I've updated the `test` crate to print out timing information for WASI targets as it can do that (gets a previously ignored test now passing).

* The `test-various` image now builds a WASI sysroot for the WASI target and additionally downloads a fixed release of Wasmtime, currently the latest one at 18.0.2, and uses that for testing.

[Zulip thread]: https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Have.20wasm.20tests.20ever.20caused.20problems.20on.20CI.3F/near/424317944
2024-03-12 00:03:54 +00:00
Ben Kimock
2eb9c6d49e Lower transmutes from int to pointer type as gep on null 2024-03-11 18:19:17 -04:00
Oli Scherer
96d24f2dd1 Revert "Auto merge of #122140 - oli-obk:track_errors13, r=davidtwco"
This reverts commit 65cd843ae0, reversing
changes made to d255c6a57c.
2024-03-11 21:28:16 +00:00
Michael Goulet
f614eaea2c Remove some unnecessary allow(incomplete_features) 2024-03-11 19:42:04 +00:00
Michael Goulet
0b6b3307fc Move project -> normalize, move normalize tests 2024-03-11 19:16:39 +00:00
Michael Goulet
2a1d4dd6e3 Don't ICE when non-self part of trait goal is constrained in new solver 2024-03-11 19:16:39 +00:00
bors
4ccbb7dc95 Auto merge of #121796 - oli-obk:eager_opaque_checks3, r=lcnr
Make `DefiningAnchor::Bind` only store the opaque types that may be constrained, instead of the current infcx root item.

This makes `Bind` almost always be empty, so we can start forwarding it to queries, allowing us to remove `Bubble` entirely (not done in this PR)

The only behaviour change is in diagnostics.

r? `@lcnr` `@compiler-errors`
2024-03-11 19:01:15 +00:00
Oli Scherer
40d5609548 Make DefiningAnchor::Bind only store the opaque types that may be constrained, instead of the current infcx root item.
This makes `Bind` almost always be empty, so we can start forwarding it to queries, allowing us to remove `Bubble` entirely
2024-03-11 17:19:37 +00:00
bors
6554a5645a Auto merge of #122338 - workingjubilee:rollup-xzpt4v4, r=workingjubilee
Rollup of 15 pull requests

Successful merges:

 - #116791 (Allow codegen backends to opt-out of parallel codegen)
 - #116793 (Allow targets to override default codegen backend)
 - #117458 (LLVM Bitcode Linker: A self contained linker for nvptx and other targets)
 - #119385 (Fix type resolution of associated const equality bounds (take 2))
 - #121438 (std support for wasm32 panic=unwind)
 - #121893 (Add tests (and a bit of cleanup) for interior mut handling in promotion and const-checking)
 - #122080 (Clarity improvements to `DropTree`)
 - #122152 (Improve diagnostics for parenthesized type arguments)
 - #122166 (Remove the unused `field_remapping` field from `TypeLowering`)
 - #122249 (interpret: do not call machine read hooks during validation)
 - #122299 (Store backtrace for `must_produce_diag`)
 - #122318 (Revision-related tweaks for next-solver tests)
 - #122320 (Use ptradd for vtable indexing)
 - #122328 (unix_sigpipe: Replace `inherit` with `sig_dfl` in syntax tests)
 - #122330 (bootstrap readme: fix, improve, update)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-11 16:51:54 +00:00
Alex Crichton
cf6d6050f7 Update test directives for wasm32-wasip1
* The WASI targets deal with the `main` symbol a bit differently than
  native so some `codegen` and `assembly` tests have been ignored.
* All `ignore-emscripten` directives have been updated to
  `ignore-wasm32` to be more clear that all wasm targets are ignored and
  it's not just Emscripten.
* Most `ignore-wasm32-bare` directives are now gone.
* Some ignore directives for wasm were switched to `needs-unwind`
  instead.
* Many `ignore-wasm32*` directives are removed as the tests work with
  WASI as opposed to `wasm32-unknown-unknown`.
2024-03-11 09:36:35 -07:00
Jubilee
9aca5c03c1
Rollup merge of #122328 - Enselic:sig_dfl-not-inherit, r=davidtwco
unix_sigpipe: Replace `inherit` with `sig_dfl` in syntax tests

The `sig_dfl` variant of the attribute is the most likely variant to be stabilized first, and thus to become the "most allowed" variant of the attribute. Because of this, it is the most appropriate variant to use in syntax tests, because even if the most allowed variant is used, the compiler shall still emit errors if it e.g. is used in the wrong places.

r? ``@davidtwco`` who already [approved ](https://github.com/rust-lang/rust/pull/120832#pullrequestreview-1875075341) this commit in https://github.com/rust-lang/rust/pull/120832.

It would be nice to land the last preparatory commit of that PR before we begin to [rename ](https://github.com/rust-lang/rust/pull/120832#issuecomment-1987023484) things which will of course create a lot of code conflicts.
2024-03-11 09:29:38 -07:00
Jubilee
a11e6c38b5
Rollup merge of #122318 - compiler-errors:next-solver-tests, r=lcnr
Revision-related tweaks for next-solver tests

1. Add `ignore-compare-mode-next-solver` to any test that already has explicit `current next` revisions, since the test failures when testing with `--compare-mode=next-solver` will be false positives.
2. Explicitly add revisions to a handful of tests where we expect behavior to diverge.

r? lcnr
2024-03-11 09:29:37 -07:00
Jubilee
05ff86c389
Rollup merge of #122152 - wutchzone:120892, r=fmease
Improve diagnostics for parenthesized type arguments

Fixes #120892

r? fmease
2024-03-11 09:29:35 -07:00
Jubilee
9300fbbed1
Rollup merge of #121893 - RalfJung:const-interior-mut-tests, r=oli-obk
Add tests (and a bit of cleanup) for interior mut handling in promotion and const-checking

Basically these are the parts of https://github.com/rust-lang/rust/pull/121786 that can be salvaged.

r? ``@oli-obk``
2024-03-11 09:29:34 -07:00
Jubilee
a4503390ba
Rollup merge of #119385 - fmease:assoc-const-eq-fixes-2, r=oli-obk,cjgillot
Fix type resolution of associated const equality bounds (take 2)

Instead of trying to re-resolve the type of assoc const bindings inside the `type_of` query impl in an incomplete manner, transfer the already (correctly) resolved type from `add_predicates_for_ast_type_binding` to `type_of`/`anon_type_of` through query feeding.

---

Together with #118668 (merged) and #121258, this supersedes #118360.
Fixes #118040.

r? ``@ghost``
2024-03-11 09:29:33 -07:00
bors
65cd843ae0 Auto merge of #122140 - oli-obk:track_errors13, r=davidtwco
Run a single huge par_body_owners instead of many small ones after each other.

This improves parallel rustc parallelism by avoiding the bottleneck after each individual `par_body_owners` (because it needs to wait for queries to finish, so if there is one long running one, a lot of cores will be idle while waiting for the single query).
2024-03-11 14:26:09 +00:00
Ralf Jung
fb802f2e6e promote-not: add test that distinguishes promotion from outer scope rule 2024-03-11 14:17:34 +01:00
Ralf Jung
279465b5e8 const-checking: add some corner case tests, and fix some nits 2024-03-11 14:15:24 +01:00
Oli Scherer
55ea94402b Run a single huge par_body_owners instead of many small ones after each other.
This improves parallel rustc parallelism by avoiding the bottleneck after each individual `par_body_owners` (because it needs to wait for queries to finish, so if there is one long running one, a lot of cores will be idle while waiting for the single query).
2024-03-11 08:48:03 +00:00
Oli Scherer
e2e751e76d Merge various rustc_attr based tests 2024-03-11 08:48:03 +00:00
Jacob Pratt
eb1ebbfc92
Rollup merge of #122298 - RalfJung:raw-vec-into-box, r=cuviper
RawVec::into_box: avoid unnecessary intermediate reference

Fixes the problem described [here](https://github.com/rust-lang/miri/issues/3341#issuecomment-1987207195).
2024-03-11 03:47:21 -04:00
Jacob Pratt
05f22c3614
Rollup merge of #121840 - oli-obk:freeze, r=dtolnay
Expose the Freeze trait again (unstably) and forbid implementing it manually

non-emoji version of https://github.com/rust-lang/rust/pull/121501

cc #60715

This trait is useful for generic constants (associated consts of generic traits). See the test (`tests/ui/associated-consts/freeze.rs`) added in this PR for a usage example. The builtin `Freeze` trait is the only way to do it, users cannot work around this issue.

It's also a useful trait for building some very specific abstrations, as shown by the usage by the `zerocopy` crate: https://github.com/google/zerocopy/issues/941

cc ```@RalfJung```

T-lang signed off on reexposing this unstably: https://github.com/rust-lang/rust/pull/121501#issuecomment-1969827742
2024-03-11 03:47:19 -04:00
Martin Nordholts
aea60b0cc7 unix_sigpipe: Replace inherit with sig_dfl in syntax tests
The `sig_dfl` variant of the attribute is the most likely variant to be
stabilized first, and thus to become the "most allowed" variant of the
attribute. Because of this, it is the most appropriate variant to use in
syntax tests, because even if the most allowed variant is used, the
compiler shall still emit errors if it e.g. is used in the wrong places.
2024-03-11 06:19:30 +01:00
Michael Goulet
01e6b43a07 Mark some next-solver-behavior tests explicitly with revisions 2024-03-10 23:23:46 -04:00
bors
c69fda7dc6 Auto merge of #121752 - mu001999:dead_code/improve, r=pnkfelix
Detect unused struct impls pub trait

Fixes #47851
2024-03-11 02:46:47 +00:00
Michael Goulet
383051092f Ignore tests w/ current/next revisions from compare-mode=next-solver 2024-03-10 21:18:41 -04:00
Matthias Krüger
16ffeb208d
Rollup merge of #122304 - lukas-code:dyn-star-meta, r=compiler-errors
fix metadata for dyn-star in new solver

The pointee metadata of `dyn* Trait` types is `()` and not a vtable.
2024-03-10 22:16:45 +01:00
Matthias Krüger
c4b159c4a0
Rollup merge of #122293 - Enselic:no-bare-unix_sigpipe, r=fmease
diagnostics: Do not suggest using `#[unix_sigpipe]` without a value

Remove `Word` from the `unix_sigpipe` attribute template so that plain `#[unix_sigpipe]` is not included in suggestions of valid forms of the attribute. Also re-arrange diagnostics code slightly to avoid duplicate diagnostics.

Tracking issue is https://github.com/rust-lang/rust/issues/97889.
2024-03-10 22:16:44 +01:00
Lukas Markeffsky
e4bafa2b8c fix metadata for dyn-star in new solver 2024-03-10 20:24:00 +01:00
Ralf Jung
81ebaf27cb RawVec::into_box: avoid unnecessary intermediate reference 2024-03-10 18:07:34 +01:00
bors
af69f4c48c Auto merge of #121561 - jieyouxu:compiletest-directive-typo-check, r=onur-ozkan
Detect typos for compiletest test directives

Checks directives against a known list of compiletest directives collected during migration from legacy-style compiletest directives. A suggestion for the best matching known directive will be made if an invalid directive is found.

This PR does not attempt to implement checks for Makefile directives because they still have the problem of regular comments and directives sharing the same comment prefix `#`.

Closes #83551.
2024-03-10 16:26:18 +00:00
r0cky
1299aa7c18 Detect unused struct impls pub trait 2024-03-10 23:30:53 +08:00
Martin Nordholts
ee428c55b2 diagnostics: Do not suggest using #[unix_sigpipe] without a value
Remove `Word` from the `unix_sigpipe` attribute template so that plain
`#[unix_sigpipe]` is not included in suggestions of valid forms of the
attribute. Also re-arrange diagnostics code slightly to avoid duplicate
diagnostics.
2024-03-10 15:12:50 +01:00
许杰友 Jieyou Xu (Joe)
64dda8c837
Fix invalid compiletest directives in tests
- Fix invalid directive in `normalize-hidden-types`
- Update legacy directive in `two-phase-reservation-sharing-interference`
2024-03-10 13:13:09 +00:00
Markus Reiter
85dfb479df
Fix lint. 2024-03-10 13:18:07 +01:00
Markus Reiter
2d48a3a7bc
Move generic NonZero rustc_layout_scalar_valid_range_start attribute to inner type. 2024-03-10 13:18:07 +01:00
Ralf Jung
39db6a0972 add test ensuring simd codegen checks don't run when a static assertion failed 2024-03-10 12:37:10 +01:00
Matthias Krüger
8a9f3fd1be
Rollup merge of #122251 - jieyouxu:unused-lifetimes-dedup-test, r=Nadrieril
Add test to check unused_lifetimes don't duplicate "parameter is never used" error

Closes #72587.
2024-03-10 10:58:19 +01:00
Daniel Sedlak
58f6aaa710 Improve diagnostics for parenthesized type arguments 2024-03-09 22:15:50 +01:00
Guillaume Boisseau
e3c0158788
Rollup merge of #120504 - kornelski:try_with_capacity, r=Amanieu
Vec::try_with_capacity

Related to #91913

Implements try_with_capacity for `Vec`, `VecDeque`, and `String`. I can follow it up with more collections if desired.

`Vec::try_with_capacity()` is functionally equivalent to the current stable:

```rust
let mut v = Vec::new();
v.try_reserve_exact(n)?
```

However, `try_reserve` calls non-inlined `finish_grow`, which requires old and new `Layout`, and is designed to reallocate memory. There is benefit to using `try_with_capacity`, besides syntax convenience, because it generates much smaller code at the call site with a direct call to the allocator. There's codegen test included.

It's also a very desirable functionality for users of `no_global_oom_handling` (Rust-for-Linux), since it makes a very commonly used function available in that environment (`with_capacity` is used much more frequently than all `(try_)reserve(_exact)`).
2024-03-09 21:40:06 +01:00
许杰友 Jieyou Xu (Joe)
ff1459a370
Add test to check unused_lifetimes don't duplicate "parameter is never used" error 2024-03-09 18:24:45 +00:00
Matthias Krüger
d1d43b840e
Rollup merge of #122224 - gurry:add-tests, r=Nadrieril
Add missing regression tests

Add tests for issues #121612 and #121424

Closes #121612
Closes #121424
2024-03-09 16:21:19 +01:00
Matthias Krüger
985befe036
Rollup merge of #122160 - jieyouxu:eager-translate-help-use-latest-edition, r=cjgillot
Eagerly translate `HelpUseLatestEdition` in parser diagnostics

Fixes #122130.

This makes me suspicious of these other two usage of  `add_to_diagnostic()`. Would they *also* crash? I haven't attempted to construct test cases for them.

```
compiler/rustc_parse/src/parser/expr.rs
3453:            errors::HelpUseLatestEdition::new().add_to_diagnostic(e);

compiler/rustc_hir_typeck/src/expr.rs
2603:            HelpUseLatestEdition::new().add_to_diagnostic(&mut err);
```

This also seems like a footgun?
2024-03-09 16:21:16 +01:00
Matthias Krüger
a979f971b4
Rollup merge of #121813 - Urgau:misc-non_local_defs-lint, r=cjgillot
Misc improvements to non local defs lint implementation

This PR is a collection of small improvements I found when I [needlessly tried](https://www.github.com/rust-lang/rust/pull/120393#issuecomment-1971787475) to fix a "perf-regression" in the lint implementation.

I recommend looking at each commit individually.
2024-03-09 16:21:15 +01:00
bors
b054da8155 Auto merge of #122150 - ShoyuVanilla:replace-typewalker, r=lcnr
Replace `TypeWalker` usage with `TypeVisitor` in `wf.rs`

Resolves #121693
2024-03-09 12:02:25 +00:00
Gurinder Singh
b1f4657fe9 Add missing regression tests
for a couple of issues
2024-03-09 12:01:19 +05:30
bors
1b427b3bf7 Auto merge of #118879 - Nadrieril:lint-range-gap, r=estebank
Lint singleton gaps after exclusive ranges

In the discussion to stabilize exclusive range patterns (https://github.com/rust-lang/rust/issues/37854), it has often come up that they're likely to cause off-by-one mistakes. We already have the `overlapping_range_endpoints` lint, so I [proposed](https://github.com/rust-lang/rust/issues/37854#issuecomment-1845580712) a lint to catch the complementary mistake.

This PR adds a new `non_contiguous_range_endpoints` lint that catches likely off-by-one errors with exclusive range patterns. Here's the idea (see the test file for more examples):
```rust
match x {
    0..10 => ..., // WARN: this range doesn't match `10_u8` because `..` is an exclusive range
    11..20 => ..., // this could appear to continue range `0_u8..10_u8`, but `10_u8` isn't matched by either of them
    _ => ...,
}
// help: use an inclusive range instead: `0_u8..=10_u8`
```

More precisely: for any exclusive range `lo..hi`, if `hi+1` is matched by another range but `hi` isn't, we suggest writing an inclusive range `lo..=hi` instead. We also catch `lo..T::MAX`.
2024-03-09 03:49:01 +00:00
Nadrieril
8ac9a04257 Lint small gaps between ranges 2024-03-09 01:14:22 +01:00
Nadrieril
f783043ebf Allow lint where we don't care 2024-03-09 01:13:42 +01:00
Michael Goulet
c63f3feb0f Stabilize associated type bounds 2024-03-08 20:56:25 +00:00
Matthias Krüger
02b89d1676
Rollup merge of #122172 - compiler-errors:rpitit-collect-ice, r=fmease
Don't ICE if we collect no RPITITs unless there are no unification errors

Move an assertion in `collect_return_position_impl_trait_in_trait_tys` to after the `ObligationCtxt::eq` calls, so that we only assert and ICE if we have unification errors.

Fixes #121468
2024-03-08 21:02:03 +01:00
Matthias Krüger
9829ff67ba
Rollup merge of #122171 - compiler-errors:next-solver-tests, r=lcnr
Add some new solver tests

Fixes #119607
Fixes #119608

r? lcnr
2024-03-08 21:02:02 +01:00
Matthias Krüger
e76bd6214f
Rollup merge of #122100 - compiler-errors:better-capture, r=oli-obk
Better comment for implicit captures in RPITIT

Improve the error message for implicit captures. Also always set E0657.

r? oli-obk
2024-03-08 21:02:00 +01:00
Michael Goulet
ffd30e0a69 Improve error message for opaque captures 2024-03-08 19:08:13 +00:00
bors
a655e648a9 Auto merge of #122190 - matthiaskrgr:rollup-9ol4y30, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #121025 (add known-bug tests for derive failure to detect packed repr)
 - #121194 (Refactor pre-getopts command line argument handling)
 - #121563 (Use `ControlFlow` in visitors.)
 - #122173 (Don't ICE in CTFE if raw/fn-ptr types differ)
 - #122175 (Bless tidy issues order)
 - #122179 (rustc: Fix typo)
 - #122181 (Fix crash in internal late lint checking)
 - #122183 (interpret: update comment about read_discriminant on uninhabited variants)

Failed merges:

 - #122076 (Tweak the way we protect in-place function arguments in interpreters)
 - #122132 (Diagnostic renaming 3)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-08 17:31:00 +00:00
Michael Howell
c2cc90402b diagnostics: suggest Clone bounds when noop clone() 2024-03-08 09:34:38 -07:00
Michael Goulet
8dd4e2b5ca Add some new solver tests 2024-03-08 15:54:04 +00:00
Michael Goulet
07bd05e036 Don't ICE if we collect no RPITITs unless there are no unification errors 2024-03-08 15:52:29 +00:00
bors
74acabe9b0 Auto merge of #121500 - oli-obk:track_errors12, r=petrochenkov
Merge `collect_mod_item_types` query into `check_well_formed`

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

this removes more potential parallel-compiler bottlenecks and moves diagnostics for the same items next to each other, instead of grouping diagnostics by analysis kind
2024-03-08 15:06:36 +00:00
Matthias Krüger
a08a5d4292
Rollup merge of #122181 - chenyukang:yukang-fix-late-lint-crash, r=oli-obk
Fix crash in internal late lint checking

Fixes #122177
2024-03-08 13:22:28 +01:00
Matthias Krüger
3d71bada5a
Rollup merge of #122173 - compiler-errors:ptr-equality-in-ctfe, r=lcnr
Don't ICE in CTFE if raw/fn-ptr types differ

Fixes #121688

r? lcnr
2024-03-08 13:22:27 +01:00
Matthias Krüger
3e634f8c5c
Rollup merge of #121563 - Jarcho:use_cf, r=petrochenkov
Use `ControlFlow` in visitors.

Follow up to #121256

This does have a few small behaviour changes in some diagnostic output where the visitor will now find the first match rather than the last match. The change in `find_anon_types.rs` has the only affected test. I don't see this being an issue as the last occurrence isn't any better of a choice than the first.
2024-03-08 13:22:26 +01:00
Matthias Krüger
a8e3543b19
Rollup merge of #121194 - beetrees:rustc-raw-args, r=petrochenkov
Refactor pre-getopts command line argument handling

Rebased version of #111658. I've also fixed the Windows CI failure (although I don't have access to Windows to test it myself).
2024-03-08 13:22:25 +01:00
Matthias Krüger
075f1c34d4
Rollup merge of #121025 - oli-obk:taint_after_errors, r=petrochenkov
add known-bug tests for derive failure to detect packed repr

We only taint if it was a normal item. Modules and imports are untouched. Tainting them needs to be done differently, and it's unclear if that would be useful or desirable. If we just taint them into `Res::Err`, we end up losing some duplicate name messages *in the presence of other resolution errors*.

r? `@petrochenkov`
2024-03-08 13:22:25 +01:00
bors
42825768b1 Auto merge of #122078 - gurry:121443-ice-layout-is-sized-alt, r=oli-obk
Check that return type is WF in typeck

Ensures that non-WF types do not pass typeck and then later ICE in MIR/const eval

Fixes #121443
2024-03-08 12:16:42 +00:00
Shoyu Vanilla
6721b392e9 Replace TypeWalker usage with TypeVisitor 2024-03-08 20:49:03 +09:00
yukang
c81521ae54 Fix crash in late internal checking 2024-03-08 19:00:53 +08:00
Matthias Krüger
d4d18d240b
Rollup merge of #122103 - compiler-errors:taits-capture-everything, r=oli-obk
Make TAITs and ATPITs capture late-bound lifetimes in scope

This generalizes the behavior that RPITs have, where they duplicate their in-scope lifetimes so that they will always *reify* late-bound lifetimes that they capture. This allows TAITs and ATPITs to properly error when they capture in-scope late-bound lifetimes.

r? `@oli-obk` cc `@aliemjay`

Fixes #122093 and therefore https://github.com/rust-lang/rust/pull/120700#issuecomment-1981213868
2024-03-08 08:19:20 +01:00
Matthias Krüger
d774fbea7c
Rollup merge of #119365 - nbdd0121:asm-goto, r=Amanieu
Add asm goto support to `asm!`

Tracking issue: #119364

This PR implements asm-goto support, using the syntax described in "future possibilities" section of [RFC2873](https://rust-lang.github.io/rfcs/2873-inline-asm.html#asm-goto).

Currently I have only implemented the `label` part, not the `fallthrough` part (i.e. fallthrough is implicit). This doesn't reduce the expressive though, since you can use label-break to get arbitrary control flow or simply set a value and rely on jump threading optimisation to get the desired control flow. I can add that later if deemed necessary.

r? ``@Amanieu``
cc ``@ojeda``
2024-03-08 08:19:17 +01:00
Michael Goulet
025ad403a9 Don't ICE in CTFE if raw/fn-ptr types differ 2024-03-08 02:57:06 +00:00
Michael Goulet
cf299ddb6e Make TAITs capture all higher-ranked lifetimes in scope 2024-03-08 02:10:11 +00:00
许杰友 Jieyou Xu (Joe)
4663fbb2cb
Eagerly translate HelpUseLatestEdition in parser diagnostics 2024-03-07 23:03:42 +00:00
bors
9823f17315 Auto merge of #122151 - GuillaumeGomez:rollup-hfxr9kv, r=GuillaumeGomez
Rollup of 10 pull requests

Successful merges:

 - #119888 (Stabilize the `#[diagnostic]` namespace and `#[diagnostic::on_unimplemented]` attribute)
 - #121089 (Remove `feed_local_def_id`)
 - #122004 (AST validation: Improve handling of inherent impls nested within functions and anon consts)
 - #122087 (Add missing background color for top-level rust documentation page and increase contrast by setting text color to black)
 - #122136 (Include all library files in artifact summary on CI)
 - #122137 (Don't pass a break scope to `Builder::break_for_else`)
 - #122138 (Record mtime in bootstrap's LLVM linker script)
 - #122141 (sync (try_)instantiate_mir_and_normalize_erasing_regions implementation)
 - #122142 (cleanup rustc_infer)
 - #122147 (Make `std::os::unix::ucred` module private)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-07 22:43:18 +00:00
Oli Scherer
bed9d1fb7d Add known-bug tests for derive(PartialEq) mismatches with #[repr(packed)] attributes that are not visible before macro expansion 2024-03-07 21:40:11 +00:00
bors
9c3ad802d9 Auto merge of #119199 - dpaoliello:arm64ec, r=petrochenkov
Add arm64ec-pc-windows-msvc target

Introduces the `arm64ec-pc-windows-msvc` target for building Arm64EC ("Emulation Compatible") binaries for Windows.

For more information about Arm64EC see <https://learn.microsoft.com/en-us/windows/arm/arm64ec>.

## Tier 3 policy:

> A tier 3 target must have a designated developer or developers (the "target maintainers") on record to be CCed when issues arise regarding the target. (The mechanism to track and CC such developers may evolve over time.)

I will be the maintainer for this target.

> Targets must use naming consistent with any existing targets; for instance, a target for the same CPU or OS as an existing Rust target should use the same name for that CPU or OS. Targets should normally use the same names and naming conventions as used elsewhere in the broader ecosystem beyond Rust (such as in other toolchains), unless they have a very good reason to diverge. Changing the name of a target can be highly disruptive, especially once the target reaches a higher tier, so getting the name right is important even for a tier 3 target.

Target uses the `arm64ec` architecture to match LLVM and MSVC, and the `-pc-windows-msvc` suffix to indicate that it targets Windows via the MSVC environment.

> Target names should not introduce undue confusion or ambiguity unless absolutely necessary to maintain ecosystem compatibility. For example, if the name of the target makes people extremely likely to form incorrect beliefs about what it targets, the name should be changed or augmented to disambiguate it.

Target name exactly specifies the type of code that will be produced.

> If possible, use only letters, numbers, dashes and underscores for the name. Periods (.) are known to cause issues in Cargo.

Done.

> Tier 3 targets may have unusual requirements to build or use, but must not create legal issues or impose onerous legal terms for the Rust project or for Rust developers or users.

> The target must not introduce license incompatibilities.

Uses the same dependencies, requirements and licensing as the other `*-pc-windows-msvc` targets.

> Anything added to the Rust repository must be under the standard Rust license (MIT OR Apache-2.0).

Understood.

> The target must not cause the Rust tools or libraries built for any other host (even when supporting cross-compilation to the target) to depend on any new dependency less permissive than the Rust licensing policy. This applies whether the dependency is a Rust crate that would require adding new license exceptions (as specified by the tidy tool in the rust-lang/rust repository), or whether the dependency is a native library or binary. In other words, the introduction of the target must not cause a user installing or running a version of Rust or the Rust tools to be subject to any new license requirements.

> Compiling, linking, and emitting functional binaries, libraries, or other code for the target (whether hosted on the target itself or cross-compiling from another target) must not depend on proprietary (non-FOSS) libraries. Host tools built for the target itself may depend on the ordinary runtime libraries supplied by the platform and commonly used by other applications built for the target, but those libraries must not be required for code generation for the target; cross-compilation to the target must not require such libraries at all. For instance, rustc built for the target may depend on a common proprietary C runtime library or console output library, but must not depend on a proprietary code generation library or code optimization library. Rust's license permits such combinations, but the Rust project has no interest in maintaining such combinations within the scope of Rust itself, even at tier 3.

> "onerous" here is an intentionally subjective term. At a minimum, "onerous" legal/licensing terms include but are not limited to: non-disclosure requirements, non-compete requirements, contributor license agreements (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms, requirements conditional on the employer or employment of any particular Rust developers, revocable terms, any requirements that create liability for the Rust project or its developers or users, or any requirements that adversely affect the livelihood or prospects of the Rust project or its developers or users.

Uses the same dependencies, requirements and licensing as the other `*-pc-windows-msvc` targets.

> Neither this policy nor any decisions made regarding targets shall create any binding agreement or estoppel by any party. If any member of an approving Rust team serves as one of the maintainers of a target, or has any legal or employment requirement (explicit or implicit) that might affect their decisions regarding a target, they must recuse themselves from any approval decisions regarding the target's tier status, though they may otherwise participate in discussions.

> This requirement does not prevent part or all of this policy from being cited in an explicit contract or work agreement (e.g. to implement or maintain support for a target). This requirement exists to ensure that a developer or team responsible for reviewing and approving a target does not face any legal threats or obligations that would prevent them from freely exercising their judgment in such approval, even if such judgment involves subjective matters or goes beyond the letter of these requirements.

Understood, I am not a member of the Rust team.

> Tier 3 targets should attempt to implement as much of the standard libraries as possible and appropriate (core for most targets, alloc for targets that can support dynamic memory allocation, std for targets with an operating system or equivalent layer of system-provided functionality), but may leave some code unimplemented (either unavailable or stubbed out as appropriate), whether because the target makes it impossible to implement or challenging to implement. The authors of pull requests are not obligated to avoid calling any portions of the standard library on the basis of a tier 3 target not implementing those portions.

Both `core` and `alloc` are supported.

Support for `std` depends on making changes to the standard library, `stdarch` and `backtrace` which cannot be done yet as they require fixes coming in LLVM 18.

> The target must provide documentation for the Rust community explaining how to build for the target, using cross-compilation if possible. If the target supports running binaries, or running tests (even if they do not pass), the documentation must explain how to run such binaries or tests for the target, using emulation if possible or dedicated hardware if necessary.

Documentation is provided in src/doc/rustc/src/platform-support/arm64ec-pc-windows-msvc.md

> Tier 3 targets must not impose burden on the authors of pull requests, or other developers in the community, to maintain the target. In particular, do not post comments (automated or manual) on a PR that derail or suggest a block on the PR based on a tier 3 target. Do not send automated messages or notifications (via any medium, including via `@)` to a PR author or others involved with a PR regarding a tier 3 target, unless they have opted into such messages.

> Backlinks such as those generated by the issue/PR tracker when linking to an issue or PR are not considered a violation of this policy, within reason. However, such messages (even on a separate repository) must not generate notifications to anyone involved with a PR who has not requested such notifications.

> Patches adding or updating tier 3 targets must not break any existing tier 2 or tier 1 target, and must not knowingly break another tier 3 target without approval of either the compiler team or the maintainers of the other tier 3 target.

> In particular, this may come up when working on closely related targets, such as variations of the same architecture with different features. Avoid introducing unconditional uses of features that another variation of the target may not have; use conditional compilation or runtime detection, as appropriate, to let each target run code supported by that target.

Understood.
2024-03-07 20:18:54 +00:00
Guillaume Gomez
2e3bde2bc4
Rollup merge of #122004 - fmease:astvalidator-min-fix, r=compiler-errors
AST validation: Improve handling of inherent impls nested within functions and anon consts

Minimal fix for issue #121607 extracted from PR #120698 for ease of backporting and since I'd like to improve PR #120698 in such a way that it makes AST validator truly robust against such sort of regressions (AST validator is generally *beyond* footgun-y atm). The current version of PR #120698 sort of does that already but there's still room for improvement.

Fixes #89342.
Fixes [after beta-backport] #121607.
Partially addresses #119924 (#120698 aims to fully fix it).

---

### Explainer

The last commit of PR #119505 regressed issue #121607.

Previously we would reject visibilities on associated items with `visibility_not_permitted` if we were in a trait (by checking the parameter `ctxt` of `visit_assoc_item` which was 100% accurate) or if we were in a trait impl (by checking a flag called `in_trait_impl` tracked in `AstValidator` which was/is only accurate if the visitor methods correctly updated it which isn't actually the case giving rise to the old open issue #89342).

In PR #119505, I moved even more state into the `AstValidator` by generalizing the flag `in_trait_impl` to `trait_or_trait_impl` to be able to report more precise diagnostics (modeling *Trait | TraitImpl*). However since we/I didn't update `trait_or_trait_impl` in all places to reflect reality (similar to us not updating `in_trait_impl` before), this lead to https://github.com/rust-lang/rust/issues/121607#issuecomment-1963084636 getting wrongfully rejected. Since PR #119505 we reject visibilities if the “globally tracked” (wrt. to `AstValidator`) `outer_trait_or_trait_impl` is `Some`.

Crucially, when visiting an inherent impl, I never reset `outer_trait_or_trait_impl` back to `None` leading us to believe that `bar` in the stack [`trait Foo` > `fn foo` > `impl Bar` > `pub fn bar`] (from the MCVE) was an inherent associated item (we saw `trait Foo` but not `impl Bar` before it).

The old open issue #89342 is caused by the aforementioned issue of us never updating `in_trait_impl` prior to my PR #119505 / `outer_trait_or_trait` after my PR. Stack: [`impl Default for Foo` > `{` > `impl Foo` > `pub const X`] (we only saw `impl Default for Foo` but not the `impl Foo` before it).

---

This PR is only meant to be a *hot fix*. I plan on completely *rewriting* `AstValidator` from the ground up to not rely on “globally tracked” state like this or at least make it close to impossible to forget updating it when descending into nested items (etc.). Other visitors do a way better job at that (e.g. AST lowering). I actually plan on experimenting with moving more and more logic from `AstValidator` into the AST lowering pass/stage/visitor to follow the [Parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/) “pattern”.

---

r? `@compiler-errors`
2024-03-07 18:32:47 +01:00
Guillaume Gomez
4de78d2a8d
Rollup merge of #121089 - oli-obk:create_def_feed, r=petrochenkov
Remove `feed_local_def_id`

best reviewed commit by commit

Basically I returned `TyCtxtFeed` from `create_def` and then preserved that in the local caches

based on https://github.com/rust-lang/rust/pull/121084

r? ````@petrochenkov````
2024-03-07 18:32:47 +01:00
Guillaume Gomez
b0d7f2bb0e
Rollup merge of #119888 - weiznich:stablize_diagnostic_namespace, r=compiler-errors
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.

This allows to have a trait definition like:

```rust
#[diagnostic::on_unimplemented(
    message = "My Message for `ImportantTrait<{A}>` is not implemented for `{Self}`",
    label = "My Label",
    note = "Note 1",
    note = "Note 2"
)]
trait ImportantTrait<A> {}

```

which then generates for the following code

```rust
fn use_my_trait(_: impl ImportantTrait<i32>) {}

fn main() {
    use_my_trait(String::new());
}
```

this error message:

```
error[E0277]: My Message for `ImportantTrait<i32>` is not implemented for `String`
  --> src/main.rs:14:18
   |
14 |     use_my_trait(String::new());
   |     ------------ ^^^^^^^^^^^^^ My Label
   |     |
   |     required by a bound introduced by this call
   |
   = help: the trait `ImportantTrait<i32>` is not implemented for `String`
   = note: Note 1
   = note: Note 2
```

[Playground with the unstable feature](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=05133acce8e1d163d481e97631f17536)

Fixes #111996
2024-03-07 18:32:46 +01:00
Oli Scherer
ae50e36dfa Merge collect_mod_item_types query into check_well_formed 2024-03-07 14:26:31 +00:00
Guillaume Gomez
bb582c6d0f
Rollup merge of #122123 - compiler-errors:object-trait-alias-bounds, r=oli-obk
Don't require specifying unrelated assoc types when trait alias is in `dyn` type

Object types must specify the associated types for all of the principal trait ref's supertraits. However, we weren't doing elaboration properly, so we incorrectly errored with erroneous suggestions to specify associated types that were unrelated to that principal trait ref. To fix this, use proper supertrait elaboration when expanding trait aliases in `conv_object_ty_poly_trait_ref`.

**NOTE**: Please use the ignore-whitespace option when reviewing. This only touches a handful of lines.

r? oli-obk or please feel free to reassign.

Fixes #122118
2024-03-07 15:07:09 +01:00
Guillaume Gomez
9bda4e47c7
Rollup merge of #122115 - clubby789:cancel-recoverr, r=compiler-errors
Cancel parsing ever made during recovery

Fixes #122112

It would be nice if diagnostics from recovery were automatically cancelled... 🤔
2024-03-07 15:07:08 +01:00
Guillaume Gomez
66a062af86
Rollup merge of #122114 - saethlin:cant-find-crate-spam, r=WaffleLapkin
Make not finding core a fatal error

Similar to https://github.com/rust-lang/rust/pull/120472, this prevents terminal spam. In particular, it makes the good diagnostic visible when you try to use a target that's not installed.
2024-03-07 15:07:08 +01:00
Guillaume Gomez
0e3764889d
Rollup merge of #121863 - lukas-code:silence-mismatched-super-projections, r=lcnr
silence mismatched types errors for implied projections

Currently, if a trait bound is not satisfied, then we suppress any errors for the trait's supertraits not being satisfied, but still report errors for super projections not being satisfied.

For example:
```rust
trait Super {
    type Assoc;
}
trait Sub: Super<Assoc = ()> {}
```
Before this PR, if `T: Sub` is not satisfied, then errors for `T: Super` are suppressed, but errors for `<T as Super>::Assoc == ()` are still shown. This PR makes it so that errors about super projections not being satisfied are also suppressed.

The errors are only suppressed if the span of the trait obligation matches the span of the super predicate obligation to avoid silencing error that are not related. This PR removes some differences between the spans of supertraits and super projections to make the suppression work correctly.

This PR fixes the majority of the diagnostics fallout when making `Thin` a supertrait of `Sized` (in a future PR).
cc https://github.com/rust-lang/rust/pull/120354#issuecomment-1930585382
cc `@lcnr`
2024-03-07 15:07:05 +01:00
Oli Scherer
ebf1b92417 Use the same collection order as check_mod_type_wf 2024-03-07 13:37:06 +00:00
Oli Scherer
de3fb8d429 Collect mod item types in parallel, just like wfcheck 2024-03-07 12:42:49 +00:00
Gary Guo
0ee0f290a6 Bless aarch64 asm test 2024-03-07 11:57:26 +00:00
Urgau
98dbe9abac Use was_invoked_from_cargo method instead of hand-written one 2024-03-07 07:54:15 +01:00
Urgau
5c87ca2d1f Add some weird test cases to the non_local_definitions lint tests 2024-03-07 07:54:14 +01:00
Oli Scherer
8206cffc48 Merge check_mod_impl_wf and check_mod_type_wf 2024-03-07 06:27:09 +00:00
bors
aa029ce4d8 Auto merge of #122113 - matthiaskrgr:rollup-5d1jnwi, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #121958 (Fix redundant import errors for preload extern crate)
 - #121976 (Add an option to have an external download/bootstrap cache)
 - #122022 (loongarch: add frecipe and relax target feature)
 - #122026 (Do not try to format removed files)
 - #122027 (Uplift some feeding out of `associated_type_for_impl_trait_in_impl` and into queries)
 - #122063 (Make the lowering of `thir::ExprKind::If` easier to follow)
 - #122074 (Add missing PartialOrd trait implementation doc for array)
 - #122082 (remove outdated fixme comment)
 - #122091 (Note why we're using a new thread in `test_get_os_named_thread`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-07 02:30:40 +00:00
Daniel Paoliello
a6a556c2a9 Add arm64ec-pc-windows-msvc target
Introduces the `arm64ec-pc-windows-msvc` target for building Arm64EC ("Emulation Compatible") binaries for Windows.

For more information about Arm64EC see <https://learn.microsoft.com/en-us/windows/arm/arm64ec>.

Tier 3 policy:

> A tier 3 target must have a designated developer or developers (the "target maintainers") on record to be CCed when issues arise regarding the target. (The mechanism to track and CC such developers may evolve over time.)

I will be the maintainer for this target.

> Targets must use naming consistent with any existing targets; for instance, a target for the same CPU or OS as an existing Rust target should use the same name for that CPU or OS. Targets should normally use the same names and naming conventions as used elsewhere in the broader ecosystem beyond Rust (such as in other toolchains), unless they have a very good reason to diverge. Changing the name of a target can be highly disruptive, especially once the target reaches a higher tier, so getting the name right is important even for a tier 3 target.

Target uses the `arm64ec` architecture to match LLVM and MSVC, and the `-pc-windows-msvc` suffix to indicate that it targets Windows via the MSVC environment.

> Target names should not introduce undue confusion or ambiguity unless absolutely necessary to maintain ecosystem compatibility. For example, if the name of the target makes people extremely likely to form incorrect beliefs about what it targets, the name should be changed or augmented to disambiguate it.

Target name exactly specifies the type of code that will be produced.

> If possible, use only letters, numbers, dashes and underscores for the name. Periods (.) are known to cause issues in Cargo.

Done.

> Tier 3 targets may have unusual requirements to build or use, but must not create legal issues or impose onerous legal terms for the Rust project or for Rust developers or users.

> The target must not introduce license incompatibilities.

Uses the same dependencies, requirements and licensing as the other `*-pc-windows-msvc` targets.

> Anything added to the Rust repository must be under the standard Rust license (MIT OR Apache-2.0).

Understood.

> The target must not cause the Rust tools or libraries built for any other host (even when supporting cross-compilation to the target) to depend on any new dependency less permissive than the Rust licensing policy. This applies whether the dependency is a Rust crate that would require adding new license exceptions (as specified by the tidy tool in the rust-lang/rust repository), or whether the dependency is a native library or binary. In other words, the introduction of the target must not cause a user installing or running a version of Rust or the Rust tools to be subject to any new license requirements.

> Compiling, linking, and emitting functional binaries, libraries, or other code for the target (whether hosted on the target itself or cross-compiling from another target) must not depend on proprietary (non-FOSS) libraries. Host tools built for the target itself may depend on the ordinary runtime libraries supplied by the platform and commonly used by other applications built for the target, but those libraries must not be required for code generation for the target; cross-compilation to the target must not require such libraries at all. For instance, rustc built for the target may depend on a common proprietary C runtime library or console output library, but must not depend on a proprietary code generation library or code optimization library. Rust's license permits such combinations, but the Rust project has no interest in maintaining such combinations within the scope of Rust itself, even at tier 3.

> "onerous" here is an intentionally subjective term. At a minimum, "onerous" legal/licensing terms include but are not limited to: non-disclosure requirements, non-compete requirements, contributor license agreements (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms, requirements conditional on the employer or employment of any particular Rust developers, revocable terms, any requirements that create liability for the Rust project or its developers or users, or any requirements that adversely affect the livelihood or prospects of the Rust project or its developers or users.

Uses the same dependencies, requirements and licensing as the other `*-pc-windows-msvc` targets.

> Neither this policy nor any decisions made regarding targets shall create any binding agreement or estoppel by any party. If any member of an approving Rust team serves as one of the maintainers of a target, or has any legal or employment requirement (explicit or implicit) that might affect their decisions regarding a target, they must recuse themselves from any approval decisions regarding the target's tier status, though they may otherwise participate in discussions.

> This requirement does not prevent part or all of this policy from being cited in an explicit contract or work agreement (e.g. to implement or maintain support for a target). This requirement exists to ensure that a developer or team responsible for reviewing and approving a target does not face any legal threats or obligations that would prevent them from freely exercising their judgment in such approval, even if such judgment involves subjective matters or goes beyond the letter of these requirements.

Understood, I am not a member of the Rust team.

> Tier 3 targets should attempt to implement as much of the standard libraries as possible and appropriate (core for most targets, alloc for targets that can support dynamic memory allocation, std for targets with an operating system or equivalent layer of system-provided functionality), but may leave some code unimplemented (either unavailable or stubbed out as appropriate), whether because the target makes it impossible to implement or challenging to implement. The authors of pull requests are not obligated to avoid calling any portions of the standard library on the basis of a tier 3 target not implementing those portions.

Both `core` and `alloc` are supported.

Support for `std` dependends on making changes to the standard library, `stdarch` and `backtrace` which cannot be done yet as the bootstrapping compiler raises a warning ("unexpected `cfg` condition value") for `target_arch = "arm64ec"`.

> The target must provide documentation for the Rust community explaining how to build for the target, using cross-compilation if possible. If the target supports running binaries, or running tests (even if they do not pass), the documentation must explain how to run such binaries or tests for the target, using emulation if possible or dedicated hardware if necessary.

Documentation is provided in src/doc/rustc/src/platform-support/arm64ec-pc-windows-msvc.md

> Tier 3 targets must not impose burden on the authors of pull requests, or other developers in the community, to maintain the target. In particular, do not post comments (automated or manual) on a PR that derail or suggest a block on the PR based on a tier 3 target. Do not send automated messages or notifications (via any medium, including via @) to a PR author or others involved with a PR regarding a tier 3 target, unless they have opted into such messages.

> Backlinks such as those generated by the issue/PR tracker when linking to an issue or PR are not considered a violation of this policy, within reason. However, such messages (even on a separate repository) must not generate notifications to anyone involved with a PR who has not requested such notifications.

> Patches adding or updating tier 3 targets must not break any existing tier 2 or tier 1 target, and must not knowingly break another tier 3 target without approval of either the compiler team or the maintainers of the other tier 3 target.

> In particular, this may come up when working on closely related targets, such as variations of the same architecture with different features. Avoid introducing unconditional uses of features that another variation of the target may not have; use conditional compilation or runtime detection, as appropriate, to let each target run code supported by that target.

Understood.
2024-03-06 17:49:37 -08:00
Michael Goulet
850cc34da2 Don't require specifying unrelated assoc types when trait alias is in dyn type 2024-03-07 01:32:01 +00:00
beetrees
63091b105d
Make arg_expand_all not short-circuit on first error 2024-03-07 00:19:55 +00:00
Matthias Krüger
5642b04186
Rollup merge of #122109 - alexcrichton:compiletests-needs-threads, r=workingjubilee
compiletest: Add a `//@ needs-threads` directive

This commit is extracted from #122036 and adds a new directive to the `compiletest` test runner, `//@ needs-threads`. This is intended to capture the need that a target must implement threading to execute a specific test, typically one that uses `std::thread`. This is primarily done for WebAssembly targets which currently do not have threads by default. This enables transitioning a lot of `//@ ignore-wasm*`-style ignores into a more self-documenting `//@ needs-threads` directive. Additionally the `wasm32-wasi-preview1-threads` target, for example, does actually have threads, but isn't tested in CI at this time. This change enables running these tests for that target, but not other wasm targets.
2024-03-07 00:57:43 +01:00
Matthias Krüger
1d4360a621
Rollup merge of #122107 - Urgau:non_local_def-allow, r=WaffleLapkin
Temporarily make allow-by-default the `non_local_definitions` lint

T-lang [decided in their triage meeting](https://hackmd.io/U-CKiZx_RKiaANAPXtWf7g#non_local_definitions-common-issues-impl-for-ampLocal-FromltLocalgt-for-Global-%E2%80%A6-rust121621) to try to use a [better logic](https://github.com/rust-lang/rust/issues/121621#issuecomment-1976826895) for detecting non-local `impl` definitions given the [numerous reports](https://github.com/rust-lang/rust/issues/121621) we got.

Until that is done and also because the beta cut is next week, switch the lint to allow-by-default until it's implemented.

r? `@WaffleLapkin`
2024-03-07 00:57:42 +01:00
Matthias Krüger
8dc49e1b8e
Rollup merge of #122061 - workingjubilee:prefix-llvm-error, r=cuviper
Clarify FatalErrorHandler

- Identify rustc's LLVM ERRORs by prefixing them
- Comment heavily on its interior, while we are here
2024-03-07 00:57:40 +01:00
Ben Kimock
52bc7ce837 Make not finding core a fatal error 2024-03-06 18:19:13 -05:00
clubby789
8e45d0fe49 Cancel parsing ever made during recovery 2024-03-06 21:59:03 +00:00
Matthias Krüger
34cffae24c
Rollup merge of #122027 - compiler-errors:rpitit-cycle, r=spastorino
Uplift some feeding out of `associated_type_for_impl_trait_in_impl` and into queries

This PR moves the `type_of` and `generics_of` query feeding out of `associated_type_for_impl_trait_in_impl`, since eagerly feeding results in query cycles due to a subtle interaction with `resolve_bound_vars`.

Fixes #122019

r? spastorino
2024-03-06 22:41:55 +01:00
Matthias Krüger
daf89d0677
Rollup merge of #122022 - heiher:loongarch-features, r=petrochenkov
loongarch: add frecipe and relax target feature

This PR adds `frecipe` and `relax` target features to LoongArch:

* frecipe - Support frecipe.{s/d} and frsqrte.{s/d} instructions..
* relax - Enable Linker relaxation.
2024-03-06 22:41:54 +01:00
Matthias Krüger
550b8a2cf9
Rollup merge of #121958 - chenyukang:yukang-fix-121915-import, r=petrochenkov
Fix redundant import errors for preload extern crate

Fixes #121915
2024-03-06 22:41:53 +01:00
Urgau
6fc45b84ac Temporarily make allow-by-default the non_local_definitions lint 2024-03-06 22:24:25 +01:00
Matthias Krüger
e93a3d1d93
Rollup merge of #122038 - Alexendoo:unused-qualifications, r=petrochenkov
Fix linting paths with qself in `unused_qualifications`

Fixes #121999

`resolve_qpath` ends up being called again with `qself` set to `None` to check trait items from fully qualified paths. To avoid this the lint is moved to a place that accounts for this already

96561a8fd1/compiler/rustc_resolve/src/late.rs (L4074-L4088)

r? `````@petrochenkov`````
2024-03-06 22:02:47 +01:00
Matthias Krüger
c7fca03240
Rollup merge of #121190 - bvanjoi:fix-114884, r=petrochenkov
avoid overlapping privacy suggestion for single nested imports

Fixes #114884

This PR aims to avoid confusion inside braces for import suggestions.

r? ``@petrochenkov``
2024-03-06 22:02:46 +01:00
Matthias Krüger
4d9cdd6696
Rollup merge of #117199 - Zalathar:instrument-coverage-on, r=oli-obk,Nadrieril
Change the documented implicit value of `-C instrument-coverage` to `=yes`

The option-value parser for `-Cinstrument-coverage=` currently accepts the following stable values:

- `all` (implicit value of plain `-Cinstrument-coverage`)
- `yes`, `y`, `on`, `true` (undocumented aliases for `all`)
- `off` (default; same as not specifying `-Cinstrument-coverage`)
- `no`, `n`, `false`, `0` (undocumented aliases for `off`)

I'd like to rearrange and re-document the stable values as follows:

- `no` (default; same as not specifying `-Cinstrument-coverage`)
- `n`, `off`, `false` (documented aliases for `no`)
- `0` (undocumented alias for `no`)
- `yes` (implicit value of plain `-Cinstrument-coverage`)
- `y`, `on`, `true` (documented aliases for `yes`)
- `all` (documented as *currently* an alias for `yes` that may change; discouraged but not deprecated)

The main changes being:

- Documented default value changes from `off` to `no`
- Documented implicit value changes from `all` to `yes`
- Other boolean aliases (`n`, `off`, `false`, `y`, `on`, `true`) are explicitly documented
- `all` remains currently an alias for `yes`, but is explicitly documented as being able to change in the future
- `0` remains an undocumented but stable alias for `no`
- The actual behaviour of coverage instrumentation does not change

# Why?

The choice of `all` as the implicit value only really makes sense in the context of the unstable `except-unused-functions` and `except-unused-generics` values. That arrangement was fine for an unstable flag, but it's confusing for a stable flag whose only other stable value is `off`, and will only become more confusing if we eventually want to stabilize other fine-grained coverage option values.

(Currently I'm not aware of any plans to stabilize other coverage option values, but that's why I think now is a fine time to make this change, well before anyone actually has to care about it.)

For example, if we ever add support for opt-in instrumentation of things that are *not* instrumented by `-Cinstrument-coverage` by default, it will be very strange for the `all` value to not actually instrument all things that we know how to instrument.

# Compatibility impact

Because this is not a functional change, there is no immediate compatibility impact. However, changing the documented semantics of `all` opens up the possibility of future changes that could be considered retroactively breaking.

I don't think this is going to be a big deal in practice, for a few reasons:

- The exact behaviour of coverage instrumentation is allowed to change, so changing the behaviour of `all` is not a *stability-breaking* change, as long as it still exists and does something reasonable.
- `-Cinstrument-coverage` is mainly used by tools or scripts that can be easily updated if necessary. It's unusual for users to pass the flag directly, because processing the profiler output is complicated enough that tools/scripts tend to be necessary anyway.
- Most people who are using coverage are probably relying on `-Cinstrument-coverage` rather than explicitly passing `-Cinstrument-coverage=all`, so the number of users actually affected by this change is likely to be low, and plausibly zero.
2024-03-06 22:02:45 +01:00
Matthias Krüger
1b157a0987
Rollup merge of #113518 - jyn514:streaming-failures, r=cuviper
bootstrap/libtest: print test name eagerly on failure even with `verbose-tests=false` / `--quiet`

Previously, libtest would wait until all tests finished running to print the progress, which made it
annoying to run many tests at once (since you don't know which have failed). Change it to print the
names as soon as they fail.

This makes it much easier to know which test failed without having to wait for compiletest to completely finish running. Before:
```
Testing stage0 compiletest suite=ui mode=ui (x86_64-unknown-linux-gnu)

running 15274 tests
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii    88/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   176/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   264/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   352/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   440/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   528/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiFFiiiiiii
...
```

After:
```
Testing stage0 compiletest suite=ui mode=ui (x86_64-unknown-linux-gnu)

running 15274 tests
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii    88/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   176/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   264/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   352/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   440/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii   528/15274
iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii
[ui] tests/ui/associated-type-bounds/implied-in-supertrait.rs ... F

[ui] tests/ui/associated-type-bounds/return-type-notation/basic.rs#next_with ... F
iiiiiiiiiiiii
...
```

This serves a similar use case to the existing RUSTC_TEST_FAIL_FAST, but is on by default and as a result much more discoverable. We should consider unifying RUSTC_TEST_FAIL_FAST with the `--no-fail-fast` flag in the future for consistency and discoverability.
2024-03-06 22:02:45 +01:00
Alex Crichton
75fa9f6dec compiletest: Add a //@ needs-threads directive
This commit is extracted from #122036 and adds a new directive to the
`compiletest` test runner, `//@ needs-threads`. This is intended to
capture the need that a target must implement threading to execute a
specific test, typically one that uses `std::thread`. This is primarily
done for WebAssembly targets which currently do not have threads by
default. This enables transitioning a lot of `//@ ignore-wasm*`-style
ignores into a more self-documenting `//@ needs-threads` directive.
Additionally the `wasm32-wasi-preview1-threads` target, for example,
does actually have threads, but isn't tested in CI at this time. This
change enables running these tests for that target, but not other wasm
targets.
2024-03-06 12:35:07 -08:00
yukang
5a4ff2779e Fix redundant import errors for preload extern crate 2024-03-06 21:29:33 +08:00
bohan
7303014381 avoid overlapping privacy suggestion for single nested imports 2024-03-06 21:17:12 +08:00
clubby789
c7030e9b91 Stabilize imported_main 2024-03-06 12:01:54 +00:00
Gurinder Singh
ace436743f Check that return type is WF in typeck
Without it non-WF types could pass typeck and then
later fail in MIR/const eval
2024-03-06 16:51:17 +05:30
bors
09bc67b915 Auto merge of #121679 - lcnr:opaque-wf-check-2, r=oli-obk
stricter hidden type wf-check [based on #115008]

Original work by `@aliemjay` in #115008. A huge thanks to them for originally figuring out this approach ❤️

Fixes https://github.com/rust-lang/rust/issues/114728
Fixes https://github.com/rust-lang/rust/issues/114572

Instead of adding the `WellFormed` obligations when relating opaque types, we now always emit such an obligation when defining the hidden type.

This causes nested opaque types which aren't wf to error, see the comment below for the described impact. I believe this change to be desirable as it significantly reduces complexity by removing special-cases.

It also caused an issue with RPITIT: in defaulted trait methods, we add a `Projection(synthetic_assoc, rpit_of_trait_method)` clause to the `param_env`. This clause is not added to the `ParamEnv` of the nested coroutines. This caused a normalization failure in `fn check_coroutine_obligations` with the new solver. I fixed that by using the env of the typeck root instead.

r? `@oli-obk`
2024-03-06 10:04:26 +00:00
WANG Rui
e81df3f322 loongarch: add frecipe and relax target feature 2024-03-06 17:24:32 +08:00
Zalathar
9f287dd7b3 Change the documented implicit value of -C instrument-coverage to =yes 2024-03-06 17:50:13 +11:00
Jubilee Young
f7b621cfab Clarify FatalErrorHandler
Clarify the FatalErrorHandler API that we use:
- Identify rustc's LLVM ERRORs by prefixing them
- Comment heavily on its interior, while we are here
2024-03-05 20:52:54 -08:00
Ross Smyth
68a58f255a Add postfix-match experimental feature
Co-authored-by: Josh Stone <jistone@redhat.com>
2024-03-05 23:34:45 -05:00
bors
b77e0184a9 Auto merge of #122045 - matthiaskrgr:rollup-5l3vpn7, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #121065 (Add basic i18n guidance for `Display`)
 - #121744 (Stop using Bubble in coherence and instead emulate it with an intercrate check)
 - #121829 (Dummy tweaks (attempt 2))
 - #121857 (Implement async closure signature deduction)
 - #121894 (const_eval_select: make it safe but be careful with what we expose on stable for now)
 - #122014 (Change some attributes to only_local.)
 - #122016 (will_wake tests fail on Miri and that is expected)
 - #122018 (only set noalias on Box with the global allocator)
 - #122028 (Remove some dead code)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-06 02:18:22 +00:00
Jason Newcomb
822b10d428 Use ControlFlow in HIR visitors 2024-03-05 20:06:08 -05:00
Tyler Mandry
c121a26ab9 Split refining_impl_trait lint into _reachable, _internal variants 2024-03-05 16:19:16 -08:00
Matthias Krüger
b08837f180
Rollup merge of #122018 - RalfJung:box-custom-alloc, r=oli-obk
only set noalias on Box with the global allocator

As discovered in https://github.com/rust-lang/miri/issues/3341, `noalias` and custom allocators don't go well together.

rustc can now check whether a Box uses the global allocator. This replaces the previous ad-hoc and rather unprincipled check for a zero-sized allocator.

This is the rustc part of fixing that; Miri will also need a patch.
2024-03-05 22:10:02 +01:00
Matthias Krüger
327842b4ab
Rollup merge of #121894 - RalfJung:const_eval_select, r=oli-obk
const_eval_select: make it safe but be careful with what we expose on stable for now

As this is all still nightly-only I think `````@rust-lang/wg-const-eval````` can do that without involving t-lang.

r? `````@oli-obk`````
Cc `````@Nilstrieb````` -- the updated version of your RFC would basically say that we can remove these comments about not making behavior differences visible in stable `const fn`
2024-03-05 22:10:01 +01:00
Matthias Krüger
2875b10a7e
Rollup merge of #121857 - compiler-errors:async-closure-signature-deduction, r=oli-obk
Implement async closure signature deduction

Self-explanatory from title.

Regarding the interaction between signature deduction, fulfillment, and the new trait solver: I'm not worried about implementing closure signature deduction here because:

1. async closures are unstable, and
2. I'm reasonably confident we'll need to support signature deduction in the new solver somehow (i.e. via proof trees, which seem very promising).

This is in contrast to #109338, which was closed because it generalizes signature deduction for a *stable* kind of expression (`async {}` blocks and `Future` traits), and which proliferated usage may pose a stabilization hazard for the new solver.

I'll be certain to make sure sure we revisit the closure signature deduction problem by the time that async closures are being stabilized (which isn't particularly soon) (edit: Put it into the async closure tracking issue). cc `````@lcnr`````

r? `````@oli-obk`````
2024-03-05 22:10:00 +01:00
Matthias Krüger
3d6b3d0f59
Rollup merge of #121991 - oli-obk:merge_opaque_types_defined_by_queries, r=compiler-errors
Merge impl_trait_in_assoc_types_defined_by query back into `opaque_types_defined_by`

Instead, when we're collecting opaques for associated items, we choose the right collection mode depending on whether we're collecting for an associated item of a trait impl or not.

r? ```@compiler-errors```

follow up to https://github.com/rust-lang/rust/pull/121838
2024-03-05 19:53:23 +01:00
Matthias Krüger
f5ff6d5ae5
Rollup merge of #121978 - GuillaumeGomez:dylib-duplicated-path, r=bjorn3
Fix duplicated path in the "not found dylib" error

While working on the gcc backend, I couldn't figure out why I had this error:

```
error: couldn't load codegen backend /checkout/compiler/rustc_codegen_gcc/target/release/librustc_codegen_gcc.so/checkout/compiler/rustc_codegen_gcc/target/release/librustc_codegen_gcc.so: cannot open shared object file: No such file or directory
```

As you can see, the path is duplicated for some reason. After investigating a bit more, I realized that `libloading::Error::LoadLibraryExW` starts with the path of the not found dylib, making it appear twice in our error afterward (because we do render it like this: `{path}{err}`, and since the `err` starts with the path...).

Thanks to `````@bjorn3````` for linking me to https://github.com/rust-lang/rust/pull/121392. :)
2024-03-05 19:53:22 +01:00
Matthias Krüger
f560806ae0
Rollup merge of #121975 - davidtwco:issue-121757, r=petrochenkov
hir_analysis: enums return `None` in `find_field`

Fixes #121757.

Unnamed union fields with enums are checked for, but if `find_field` causes an ICE then the compiler won't get to that point.
2024-03-05 19:53:21 +01:00
Matthias Krüger
5cdf870502
Rollup merge of #121961 - surechen:add_test_20240304, r=petrochenkov
add test for #78894 #71450

fixes #78894
fixes #71450
2024-03-05 19:53:21 +01:00
Matthias Krüger
152b69054c
Rollup merge of #121846 - bvanjoi:fix-121760, r=petrochenkov
only compare ambiguity item that have hard error

Fixes #121760

An easy fix, r? ``@petrochenkov``
2024-03-05 19:53:20 +01:00
Matthias Krüger
640648b893
Rollup merge of #121202 - Urgau:check-cfg-limit-diagnostics, r=pnkfelix
Limit the number of names and values in check-cfg diagnostics

The Rust for Linux [feedback](https://github.com/rust-lang/rust/issues/82450#issuecomment-1947462977) to the check-cfg Call for Testing, revealed a weakness in the check-cfg. They are unbounded and in the case RfL they have ~20k cfgs and having them printed (even once) is unbearable.

This PR limits it to 35 (28 rustc well known + `feature` + `docsrs` + 5 custom) which feels like a good middle ground for regular users (i.e. Cargo users).

When it goes over that limit print the N first with " and X more".

``@rustbot`` label +F-check-cfg
2024-03-05 19:53:18 +01:00
Alex Macleod
6120de99f7 Fix linting paths with qself in unused_qualifications 2024-03-05 18:31:32 +00:00
Oli Scherer
da357346e8 Merge impl_trait_in_assoc_types_defined_by query back into opaque_types_defined_by
Instead, when we're collecting opaques for associated items, we choose the right collection mode depending on whether we're collecting for an associated item of a trait impl or not.
2024-03-05 16:07:25 +00:00
Michael Goulet
ebc45c8505 Uplift some feeding out of associated_type_for_impl_trait_in_impl and into queries 2024-03-05 15:55:31 +00:00
Ralf Jung
f391c0793b only set noalias on Box with the global allocator 2024-03-05 15:03:33 +01:00
bors
c7beecf3e3 Auto merge of #121992 - jieyouxu:fix-tidy-unpaired-revision, r=onur-ozkan
tidy: split dots in filename not the entire path when checking for stray stdout/stderr files

I committed a path crime by splitting the entire path on `.`, when I meant to split on the filename. This means that any parent folders which contain `.` will cause tidy failure. Added a regression test so that doesn't happen again.

### Follow-up

- [ ] Adjust rustc-dev-guide to document assert on test name not containing dots. https://github.com/rust-lang/rustc-dev-guide/pull/1927

Fixes #121986.
2024-03-05 13:02:42 +00:00
Oli Scherer
ef00fae46d Avoid using feed_unit_query from within queries 2024-03-05 10:02:39 +00:00
许杰友 Jieyou Xu (Joe)
247a080b98
Update test names to not have dots 2024-03-05 09:02:33 +00:00