Commit Graph

758 Commits

Author SHA1 Message Date
bors
c5283576ec Auto merge of #108012 - compiler-errors:issue-107999, r=oli-obk
Don't ICE in `might_permit_raw_init` if reference is polymorphic

Emitting optimized MIR for a polymorphic function may require computing layout of a type that isn't (yet) known. This happens in the instcombine pass, for example. Let's fail gracefully in that condition.

cc `@saethlin`
fixes #107999
2023-02-15 20:56:07 +00:00
Matthias Krüger
8259755069
Rollup merge of #108066 - compiler-errors:better-labels-for-bad-impl-trait, r=petrochenkov
Better names for illegal impl trait positions

Just some wording tweaks, no behavior changes.
2023-02-15 21:30:58 +01:00
Matthias Krüger
897f56ed28
Rollup merge of #108049 - clubby789:dont-suggest-unstable, r=compiler-errors
Don't suggest `#[doc(hidden)]` trait methods with matching return type

Fixes #107983, addressing the bad suggestion.
The test can probably be made more specific to this  case, but I'm unsure how.

`@rustbot` label +A-diagnostics
2023-02-15 21:30:58 +01:00
Matthias Krüger
d40c13ae02
Rollup merge of #107972 - saethlin:fix-test-ub, r=michaelwoerister
Fix unintentional UB in ui tests

`@matthiaskrgr` found UB in a bunch of the ui tests. This PR fixes a batch of miscellaneous tests I didn't think needed reviewers from a particular part of the project.
2023-02-15 21:30:56 +01:00
Martin Gammelsæter
e159c1e0ec Skip method calls with arity mismatch 2023-02-15 18:52:23 +01:00
Martin Gammelsæter
08cc628e73 Add point-at-inference ui test for wrong arity case 2023-02-15 18:44:03 +01:00
bors
2d14db321b Auto merge of #108006 - cjgillot:def-impl, r=oli-obk
Avoid accessing HIR when it can be avoided

Experiment to see if it helps some incremental cases.

Will be rebased once https://github.com/rust-lang/rust/pull/107942 gets merged.

r? `@ghost`
2023-02-15 16:14:10 +00:00
Ben Kimock
de01ea26c9 Fix unintentional UB in ui tests 2023-02-15 09:05:05 -05:00
clubby789
f4de121951 Don't suggest #[doc(hidden)] methods 2023-02-15 12:31:38 +00:00
bors
999ac5f777 Auto merge of #108070 - Dylan-DPC:rollup-v6xw7vk, r=Dylan-DPC
Rollup of 7 pull requests

Successful merges:

 - #105300 (rework min_choice algorithm of member constraints)
 - #107163 (Remove some superfluous type parameters from layout.rs.)
 - #107173 (Suggest the correct array length on mismatch)
 - #107411 (Handle discriminant in DataflowConstProp)
 - #107968 (Enable `#[thread_local]` on armv6k-nintendo-3ds)
 - #108032 (Un📦ing the Resolver)
 - #108060 (Revert to using `RtlGenRandom` as a fallback)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-02-15 08:48:44 +00:00
Dylan DPC
a110cf5d16
Rollup merge of #107173 - clubby789:suggest-array-length, r=compiler-errors
Suggest the correct array length on mismatch

Fixes #107156

I wasn't able to find a way to get the `Span` for the actual array size unfortunately, so this suggestion can't be applied automatically.

``@rustbot`` label +A-diagnostics
2023-02-15 12:24:54 +05:30
Dylan DPC
83f10ea5b7
Rollup merge of #105300 - aliemjay:member-lower, r=oli-obk
rework min_choice algorithm of member constraints

See [this comment](https://github.com/rust-lang/rust/pull/105300#issuecomment-1384312743) for the description of the new algorithm.

Fixes #63033
Fixes #104639

This uses a more general algorithm than #89056 that doesn't treat `'static` as a special case. It thus accepts more code. For example:
```rust
async fn test2<'s>(_: &'s u8, _: &'_ &'s u8, _: &'_ &'s u8) {}
```
I claim it's more correct as well because it fixes #104639.

cc ``@nikomatsakis`` ``@lqd`` ``@tmandry`` ``@eholk`` ``@chenyukang`` ``@oli-obk``

r? types
2023-02-15 12:24:53 +05:30
bors
068161ea48 Auto merge of #107940 - BoxyUwU:const_ty_assertion_use_semantic_equality, r=compiler-errors
use semantic equality for const param type equality assertion

Fixes #107898

See added test for what caused this ICE

---

The current in assertion in `relate.rs` is rather inadequate when keeping in mind future expansions to const generics:
- it will ICE when there are infer vars in a projection in a const param ty
- it will spurriously return false when either ty has infer vars because of using `==` instead of `infcx.at(..).eq`
- i am also unsure if it would be possible with `adt_const_params` to craft a situation where the const param type is not wf causing `normalize_erasing_regions` to `bug!` when we would have emitted a diagnostic.

This impl feels pretty Not Great to me  although i am not sure what a better idea would be.

- We have to have the logic behind a query because neither `relate.rs` or `combine.rs` have access to trait solving machinery (without evaluating nested obligations this assert will become _far_ less useful under lazy norm, which consts are already doing)
- `relate.rs` does not have access to canonicalization machinery which is necessary in order to have types potentially containing infer vars in query arguments.

We could possible add a method to `TypeRelation` to do this assertion rather than a query but to avoid implementing the same logic over and over we'd probably end up with the logic in a free function somewhere in `rustc_trait_selection` _anyway_ so I don't think that would be much better.

We could also just remove this assertion, it should not actually be necessary for it to be present. It has caught some bugs in the past though so if possible I would like to keep it.

r? `@compiler-errors`
2023-02-15 05:17:58 +00:00
Wesley Norris
19714385e0 Add kernel-address sanitizer support for freestanding targets 2023-02-14 20:54:25 -05:00
Michael Goulet
3f80017f03 Better label for illegal impl trait types 2023-02-14 23:12:27 +00:00
bors
0416b1a6f6 Auto merge of #108056 - matthiaskrgr:rollup-oa6bxvh, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #107573 (Update the minimum external LLVM to 14)
 - #107626 (Fix `x fix` on the standard library itself)
 - #107673 (update ICU4X to 1.1.0)
 - #107733 (Store metrics from `metrics.json` to CI PGO timer)
 - #108007 (Use `is_str` instead of string kind comparison)
 - #108033 (add an unstable `#[rustc_coinductive]` attribute)
 - #108039 (Refactor refcounted structural_impls via functors)
 - #108040 (Use derive attributes for uninteresting traversals)
 - #108044 (interpret: rename Pointer::from_addr → from_addr_invalid)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-02-14 21:07:04 +00:00
Camille GILLOT
facecf6e1b Fetch less HIR in signature check. 2023-02-14 20:26:03 +00:00
Esteban Küber
dff10d0668 Re-add replacement logic and add comment explaining it 2023-02-14 20:22:10 +00:00
Esteban Küber
755252bf51 Show the effects of weird code commented out 2023-02-14 20:22:10 +00:00
Esteban Küber
bd176ee591 Make removal suggestion not verbose 2023-02-14 20:22:10 +00:00
Esteban Küber
5d63e10318 rebase and review comments 2023-02-14 20:22:10 +00:00
Esteban Küber
287cd5974c Avoid trailing commas 2023-02-14 20:22:10 +00:00
Esteban Küber
f02d8ec15e More accurate spans for arg removal suggestion 2023-02-14 20:22:09 +00:00
Matthias Krüger
edcdab08a4
Rollup merge of #108033 - lcnr:coinductive-attr, r=compiler-errors
add an unstable `#[rustc_coinductive]` attribute

useful to test coinduction, especially in the new solver.

as this attribute should remain permanently unstable I don't think this needs any official approval. cc ``@rust-lang/types``

had to weaken the check for stable query results in the solver to prevent an ICE if there's a coinductive cycle with constraints.

r? ``@compiler-errors``
2023-02-14 18:24:42 +01:00
Matthias Krüger
a1ba861190
Rollup merge of #107573 - cuviper:drop-llvm-13, r=nagisa
Update the minimum external LLVM to 14

With this change, we'll have stable support for LLVM 14 through 16 (pending release).
For reference, the previous increase to LLVM 13 was #100460.
2023-02-14 18:24:40 +01:00
Matthias Krüger
1f486f0a9b
Rollup merge of #108003 - chenyukang:yukang/fix-107998, r=compiler-errors
Avoid ICE when the generic_span is empty

Fixes #107998
r? ```@TaKO8Ki```
2023-02-14 18:02:51 +01:00
Matthias Krüger
202c70666f
Rollup merge of #103478 - SpanishPear:spanishpear/issue_103366_fix, r=TaKO8Ki
Suggest fix for misplaced generic params on fn item #103366

fixes #103366

This still has some work to go, but works for 2/3 of the initial base cases described in #1033366

simple fn:
```
error: expected identifier, found `<`
 --> shreys/test_1.rs:1:3
  |
1 | fn<T> id(x: T) -> T { x }
  |   ^ expected identifier
  |
help: help: place the generic parameter list after the function name:
  |
1 | fn id<T>(x: T) -> T { x }
  |    ~~~~

```

Complicated bounds
```
error: expected identifier, found `<`
 --> spanishpear/test_2.rs:1:3
  |
1 | fn<'a, B: 'a + std::ops::Add<Output = u32>> f(_x: B) { }
  |   ^ expected identifier
  |
help: help: place the generic parameter list after the function name:
  |
1 | fn f<'a, B: 'a + std::ops::Add<Output = u32>>(_x: B) { }
  |    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```

Opening a draft PR for comments on approach, particularly I have the following questions:
 -  [x]  Is it okay to be using `err.span_suggestion` over struct derives? I struggled to get the initial implementation (particularly the correct suggestion message) on struct derives, although I think given what I've learned since starting, I could attempt re-doing it with that approach.
  -  [x] in the case where the snippet cannot be obtained from a span, is the `help` but no suggestion okay? I think yes (also, when does this case occur?)
  -  [x] are there any red flags for the generalisation of this work for relevant item kinds (i.e. `struct`, `enum`, `trait`, and `union`). My basic testing indicates it does work for those types except the help tip is currently hardcoded to `after the function name` - which should change dependent on the item.
  - [x] I am planning to not show the suggestion if there is already a `<` after the item identifier, (i.e. if there are already generics, as after a function name per the original issue). Any major objections?
  - [x] Is the style of error okay? I wasn't sure if there was a way to make it display nicer, or if thats handled by span_suggestion

These aren't blocking questions, and I will keep working on:
  - check if there is a `<` after the ident (and if so, not showing the suggestion)
  - generalize the help message
  - figuring out how to write/run/etc ui tests (including reading the docs for them)
  - logic cleanups
2023-02-14 18:02:50 +01:00
lcnr
51671cd435 add test for coinduction in new solver 2023-02-14 12:18:33 +01:00
许杰友 Jieyou Xu (Joe)
98b82aedba
Update numeric lifetime test 2023-02-14 18:17:59 +08:00
bors
9bb6e60d1f Auto merge of #103695 - LYF1999:yf/103563, r=lcnr
fix: Unexpected trait bound not satisfied in HRTB and Associated Type

fix https://github.com/rust-lang/rust/issues/103563
2023-02-14 10:01:19 +00:00
许杰友 Jieyou Xu (Joe)
380fa26413
Don't recover lifetimes/labels containing emojis as character literals
Note that at the time of this commit, `unic-emoji-char` seems to have
data tables only up to Unicode 5.0, but Unicode is already newer than
this.

A newer emoji such as `🥺` will not be recognized as an emoji
but older emojis such as `🐱` will.
2023-02-14 17:31:58 +08:00
yukang
3180f1c828 Fix #107998, avoid ICE when the generic_span is empty 2023-02-14 03:46:43 +00:00
Michael Goulet
087a0136d0 Don't ICE in might_permit_raw_init if reference is polymorphic 2023-02-14 01:03:06 +00:00
Matthias Krüger
5f3d360844
Rollup merge of #107942 - compiler-errors:tighter-inherent-impl-bad-spans, r=Nilstrieb
Tighter spans for bad inherent `impl` self types

Self-explanatory
2023-02-13 23:25:12 +01:00
Matthias Krüger
73b022b8e1
Rollup merge of #107902 - vincenzopalazzo:macros/async_fn_suggestion, r=compiler-errors
fix: improve the suggestion on future not awaited

Considering the following code

```rust
fn foo() -> u8 {
    async fn async_fn() -> u8 {  22 }

    async_fn()
}

fn main() {}
```

the error generated before this commit from the compiler is

```
➜  rust git:(macros/async_fn_suggestion) ✗ rustc test.rs --edition 2021
error[E0308]: mismatched types
 --> test.rs:4:5
  |
1 | fn foo() -> u8 {
  |             -- expected `u8` because of return type
...
4 |     async_fn()
  |     ^^^^^^^^^^ expected `u8`, found opaque type
  |
  = note:     expected type `u8`
          found opaque type `impl Future<Output = u8>`
help: consider `await`ing on the `Future`
  |
4 |     async_fn().await
  |               ++++++

error: aborting due to previous error
```

In this case the error is nor perfect, and can confuse the user that do not know that the opaque type is the future.

So this commit will propose (and conclude the work start in https://github.com/rust-lang/rust/issues/80658)
to change the string `opaque type` to `future` when applicable and also remove the Expected vs Received note by adding a more specific one regarding the async function that return a future type.

So the new error emitted by the compiler is

```
error[E0308]: mismatched types
 --> test.rs:4:5
  |
1 | fn foo() -> u8 {
  |             -- expected `u8` because of return type
...
4 |     async_fn()
  |     ^^^^^^^^^^ expected `u8`, found future
  |
note: calling an async function returns a future
 --> test.rs:4:5
  |
4 |     async_fn()
  |     ^^^^^^^^^^
help: consider `await`ing on the `Future`
  |
4 |     async_fn().await
  |               ++++++

error: aborting due to previous error
```

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

It remains to rework the case described in the following issue https://github.com/rust-lang/rust/issues/107899 but I think this deserves its own PR after we discuss a little bit how to handle these kinds of cases.

r? `@eholk`

`@rustbot` label +I-async-nominated

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2023-02-13 23:25:11 +01:00
Michael Goulet
e20f6ff1dc Tighter spans for bad inherent impl types 2023-02-13 18:41:18 +00:00
bors
a3c9eede5d Auto merge of #107924 - eggyal:move_fold_visit_traits_to_type_lib_with_trait_alias, r=oli-obk
Move folding & visiting traits into type library

This is a rework of #107712, following feedback on that PR.

In particular, this version uses trait aliases to reduce the API churn for trait consumers.  Doing so requires a workaround for #107747 until its fix in #107803 is merged into the stage0 compiler; this workaround, which uses conditional compilation based on the `bootstrap` configuration predicate, sits in dedicated commit b409329c for ease of reversion.

The possibility of the `rustc_middle` crate retaining its own distinct versions of each folding/visiting trait, blanket-implemented on all types that implement the respective trait in the type library, was also explored: however since this would necessitate making each `rustc_middle` trait a subtrait of the respective type library trait (so that such blanket implementations can delegate their generic methods), no benefit would be gained.

r? types
2023-02-13 16:50:33 +00:00
Vincenzo Palazzo
2bdc9a046a
fix: improve the suggestion on future not awaited
Considering the following code

```rust
fn foo() -> u8 {
    async fn async_fn() -> u8 {  22 }

    async_fn()
}

fn main() {}
```

the error generated before this commit from the compiler is

```
➜  rust git:(macros/async_fn_suggestion) ✗ rustc test.rs --edition 2021
error[E0308]: mismatched types
 --> test.rs:4:5
  |
1 | fn foo() -> u8 {
  |             -- expected `u8` because of return type
...
4 |     async_fn()
  |     ^^^^^^^^^^ expected `u8`, found opaque type
  |
  = note:     expected type `u8`
          found opaque type `impl Future<Output = u8>`
help: consider `await`ing on the `Future`
  |
4 |     async_fn().await
  |               ++++++

error: aborting due to previous error
```

In this case the error is nor perfect, and can confuse the user
that do not know that the opaque type is the future.

So this commit will propose (and conclude the work start in
https://github.com/rust-lang/rust/issues/80658)
to change the string `opaque type` to `future` when applicable
and also remove the Expected vs Received note by adding a more
specific one regarding the async function that return a future type.

So the new error emitted by the compiler is

```
error[E0308]: mismatched types
 --> test.rs:4:5
  |
1 | fn foo() -> u8 {
  |             -- expected `u8` because of return type
...
4 |     async_fn()
  |     ^^^^^^^^^^ expected `u8`, found future
  |
note: calling an async function returns a future
 --> test.rs:4:5
  |
4 |     async_fn()
  |     ^^^^^^^^^^
help: consider `await`ing on the `Future`
  |
4 |     async_fn().await
  |               ++++++

error: aborting due to previous error
```

Signed-off-by: Vincenzo Palazzo <vincenzopalazzodev@gmail.com>
2023-02-13 16:23:23 +01:00
yifei
d164448038 fix: Unexpected trait bound not satisfied in HRTB 2023-02-13 19:39:44 +08:00
Matthias Krüger
3e5c11b855
Rollup merge of #107931 - cjgillot:issue-107353, r=WaffleLapkin
Intern span when length is MAX_LEN with parent.

Fixes https://github.com/rust-lang/rust/issues/107353
2023-02-13 11:34:58 +01:00
Matthias Krüger
780beae7bd
Rollup merge of #107838 - estebank:terminal_hyperlinks, r=nagisa
Introduce `-Zterminal-urls` to use OSC8 for error codes

Terminals supporting the OSC8 Hyperlink Extension can support inline anchors where the text is user defineable but clicking on it opens a browser to a specified URLs, just like `<a href="URL">` does in HTML.

https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
2023-02-13 11:34:57 +01:00
Alan Egerton
ba55a453eb
Alias folding/visiting traits instead of re-export 2023-02-13 10:24:46 +00:00
Dylan DPC
4bf58083ac
Rollup merge of #107973 - saethlin:fix-simd-test-ub, r=workingjubilee
Fix unintentional UB in SIMD tests

r? `@workingjubilee`
2023-02-13 11:12:52 +05:30
Ben Kimock
9c4696b940 Fix unintentional UB in SIMD tests 2023-02-12 20:18:48 -05:00
b-naber
6e1d228285 only require sub type relation on field projection types 2023-02-12 23:18:15 +01:00
Ralf Jung
0ea0c90d58 fix UB in ancient test 2023-02-12 16:30:37 +01:00
bors
51cb5614dd Auto merge of #105601 - BelovDV:change-rlib-with-not-stable, r=petrochenkov
Enable new rlib in non stable cases

If bundled static library uses cfg (unstable) or whole-archive (wasn't supported) bundled libs are packed even without packed_bundled_libs.

r? `@petrochenkov`
2023-02-12 07:15:27 +00:00
clubby789
903ca873f7 Suggest the correct array length on mismatch 2023-02-12 02:15:41 +00:00
Boxy
a85b0101e6 make relate's const ty assertion use semantic equality 2023-02-11 23:05:16 +00:00
Camille GILLOT
84bb373b2a Pacify tidy. 2023-02-11 18:07:06 +00:00
Camille GILLOT
e80afa6501 Intern span when length is MAX_LEN with parent. 2023-02-11 17:46:22 +00:00
bors
8dabf5da9e Auto merge of #107167 - the8472:rawvec-simpler-layout, r=thomcc
simplify layout calculations in rawvec

The use of `Layout::array` was introduced in #83706 which lead to a [perf regression](https://github.com/rust-lang/rust/pull/83706#issuecomment-1048377719).

This PR basically reverts that change since rust currently only supports stride == size types, but to be on the safe side it leaves a const-assert there to make sure this gets caught if those assumptions ever change.
2023-02-11 15:08:30 +00:00
bors
71f6675de1 Auto merge of #107919 - Dylan-DPC:rollup-fkl9swa, r=Dylan-DPC
Rollup of 9 pull requests

Successful merges:

 - #105019 (Add parentheses properly for borrowing suggestion)
 - #106001 (Stop at the first `NULL` argument when iterating `argv`)
 - #107098 (Suggest function call on pattern type mismatch)
 - #107490 (rustdoc: remove inconsistently-present sidebar tooltips)
 - #107855 (Add a couple random projection tests for new solver)
 - #107857 (Add ui test for implementation on projection)
 - #107878 (Clarify `new_size` for realloc means bytes)
 - #107888 (revert #107074, add regression test)
 - #107900 (Zero the `REPARSE_MOUNTPOINT_DATA_BUFFER` header)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-02-11 09:19:07 +00:00
bors
1623ab0246 Auto merge of #107507 - BoxyUwU:deferred_projection_equality, r=lcnr
Implement `deferred_projection_equality` for erica solver

Somewhat of a revival of #96912. When relating projections now emit an `AliasEq` obligation instead of attempting to determine equality of projections that may not be as normalized as possible (i.e. because of lazy norm, or just containing inference variables that prevent us from resolving an impl). Only do this when the new solver is enabled
2023-02-11 05:46:24 +00:00
Dylan DPC
745361d17d
Rollup merge of #107888 - lcnr:opaque-ty-validate, r=wesleywiser
revert #107074, add regression test

fixes #107346
2023-02-11 11:15:57 +05:30
Dylan DPC
2228c86bad
Rollup merge of #107857 - GuillaumeGomez:ui-test-impl-projections, r=oli-obk
Add ui test for implementation on projection

The error in full can be seen in https://github.com/rust-lang/rust/pull/107263 and is part of why the PR is blocked (it still requires the approval from the team for supporting it).

r? ``@oli-obk``
2023-02-11 11:15:56 +05:30
Dylan DPC
27454012c1
Rollup merge of #107855 - compiler-errors:new-solver-random-tests, r=lcnr
Add a couple random projection tests for new solver

Self-explanatory, they're just some cases that have been on my mind in the past (especially `tests/ui/traits/new-solver/param-candidate-doesnt-shadow-project.rs`).
2023-02-11 11:15:56 +05:30
Dylan DPC
400b03ac3c
Rollup merge of #107098 - compiler-errors:pat-mismatch-fn-call, r=lcnr
Suggest function call on pattern type mismatch

Fixes #101208

This could definitely be generalized to support more suggestions in pattern matches. We can't use all of [`FnCtxt::emit_type_mismatch_suggestions`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir_typeck/fn_ctxt/struct.FnCtxt.html#method.emit_type_mismatch_suggestions), but it's on my to-do list to play around with more suggestions that would be productive in this position.
2023-02-11 11:15:55 +05:30
Dylan DPC
0781d5dd8e
Rollup merge of #105019 - chenyukang:yukang/fix-104961-borrow, r=cjgillot
Add parentheses properly for borrowing suggestion

Fixes #104961
2023-02-11 11:15:54 +05:30
Josh Stone
a06aaa4a9e Update the minimum external LLVM to 14 2023-02-10 16:06:25 -08:00
Michael Goulet
0eba2f3c16 Suggest fn call on pattern type mismatch 2023-02-10 18:18:08 +00:00
Michael Goulet
9790d6fbdd Add a couple random projection tests 2023-02-10 18:14:09 +00:00
Boxy
4c98429d8c Add tests 2023-02-10 14:56:28 +00:00
Matthias Krüger
dc7559b599
Rollup merge of #107789 - jieyouxu:issue-107745, r=lcnr
Avoid exposing type parameters and implementation details sourced from macro expansions

Fixes #107745.

~~I would like to **request some guidance** for this issue, because I don't think this is a good fix (a band-aid at best).~~

### The Problem

The code

```rust
fn main() {
    println!("{:?}", []);
}
```

gets desugared into (`rustc +nightly --edition=2018 issue-107745.rs -Z unpretty=hir`):

```rust
#[prelude_import]
use std::prelude::rust_2018::*;
#[macro_use]
extern crate std;
fn main() {
        {
                ::std::io::_print(<#[lang = "format_arguments"]>::new_v1(&["",
                                    "\n"], &[<#[lang = "format_argument"]>::new_debug(&[])]));
            };
    }
```

so the diagnostics code tries to be as specific and helpful as possible, and I think it finds that `[]` needs a type parameter and so does `new_debug`. But since `[]` doesn't have an origin for the type parameter definition, it points to `new_debug` instead and leaks the internal implementation detail since all `[]` has is an type inference variable.

### ~~The Bad Fix~~

~~This PR currently tries to fix the problem by bypassing the generated function `<#[lang = "format_argument"]>::new_debug` to avoid its generic parameter (I think it is auto-generated from the argument `[_; 0]`?) from getting collected as an `InsertableGenericArg`. This is problematic because it also prevents the help from getting displayed.~~

~~I think this fix is not ideal and hard-codes the format generated code pattern, but I can't think of a better fix. I have tried asking on Zulip but no responses there yet.~~
2023-02-10 15:28:47 +01:00
lcnr
3a72238aa6 revert #107074 2023-02-10 15:24:39 +01:00
Guillaume Gomez
a03da2bdeb Add test for implementation on projection 2023-02-10 14:44:54 +01:00
bors
d1ac43a9b9 Auto merge of #107652 - estebank:re_error, r=oli-obk
Introduce `ReError`

CC #69314

r? `@nagisa`
2023-02-10 10:10:12 +00:00
Daniil Belov
601fc8b36b [link] enable packed bundled lib in non stable cases 2023-02-10 12:51:12 +03:00
bors
9b8dbd558c Auto merge of #107870 - matthiaskrgr:rollup-3z1q4rm, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #107043 (Support `true` and `false` as boolean flag params)
 - #107831 (Query refactoring)
 - #107841 (Handled snap curl issue inside Rust)
 - #107852 (rustdoc: remove unused fn parameter `tab`)
 - #107861 (Sync release notes for 1.67.1)
 - #107863 (Allow multiple candidates with same response in new solver)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-02-10 06:20:01 +00:00
Matthias Krüger
9300617dab
Rollup merge of #107863 - compiler-errors:new-solver-multiple-candidates, r=jackh726
Allow multiple candidates with same response in new solver

Treat >1 candidates as *not* ambiguous if they return the same response.
2023-02-10 06:09:59 +01:00
Matthias Krüger
8fc9ed51f0
Rollup merge of #107043 - Nilstrieb:true-and-false-is-false, r=wesleywiser
Support `true` and `false` as boolean flag params

Implements [MCP 577](https://github.com/rust-lang/compiler-team/issues/577).
2023-02-10 06:09:56 +01:00
bors
a697573463 Auto merge of #101680 - jackh726:implied-cleanup, r=lcnr
Fix implied outlives bounds logic for projections

The logic here is subtly wrong. I put a bit of an explanation in a767d7b5165cea8ee5cbe494a4a636c50ef67c9c.

TL;DR: we register outlives predicates to be proved, because wf code normalizes projections (from the unnormalized types) to type variables. This causes us to register those as constraints instead of implied. This was "fine", because we later added that implied bound in the normalized type, and delayed registering constraints. When I went to cleanup `free_region_relations` to *not* delay adding constraints, this bug was uncovered.

cc. `@aliemjay` because this caused your test failure in #99832 (I only realized as I was writing this)

r? `@nikomatsakis`
2023-02-10 03:21:39 +00:00
Jack Huey
1a663c0f53 Cleanup free_region_relations a bit 2023-02-09 20:38:27 -05:00
Michael Goulet
3c4e1f85cb Multiple candidates with same response is not ambiguous 2023-02-10 00:35:25 +00:00
bors
a12d31d5a6 Auto merge of #102963 - ilammy:xray-basic, r=estebank
Add `-Z instrument-xray` flag

Implement MCP https://github.com/rust-lang/compiler-team/issues/561, adding `-Z instrument-xray` flag which enables XRay instrumentation in LLVM.
2023-02-10 00:02:43 +00:00
Dylan DPC
b080a1a4fc
Rollup merge of #107815 - compiler-errors:new-solver-no-auto-if-impl, r=lcnr
Disqualify `auto trait` built-in impl in new solver if explicit `impl` exists
2023-02-09 23:18:37 +05:30
Dylan DPC
16a4138387
Rollup merge of #107803 - eggyal:do_not_bring_trait_alias_supertraits_into_scope, r=compiler-errors
Do not bring trait alias supertraits into scope

Fixes #107747
cc #41517
2023-02-09 23:18:36 +05:30
Dylan DPC
39ba11036a
Rollup merge of #107786 - compiler-errors:new-solver-some-tweaks, r=lcnr
Implement some tweaks in the new solver

I've been testing the new solver on some small codebases, and these are a few small changes I've needed to make.

The most "controversial" here is implementing `trait_candidate_should_be_dropped_in_favor_of`, which I just implemented to always return false. This surprisingly allows some code to compile, without us having to actually decide on any semantics yet.

r? `@rust-lang/initiative-trait-system-refactor`
2023-02-09 23:18:35 +05:30
Dylan DPC
5aa062e249
Rollup merge of #107659 - bvanjoi:issue-107649, r=estebank
test: snapshot for derive suggestion in diff files

fixed #107649
2023-02-09 23:18:35 +05:30
Dylan DPC
be1789a56d
Rollup merge of #107648 - matthiaskrgr:unused_lifetime_104432_fix, r=cjgillot
unused-lifetimes: don't warn about lifetimes originating from expanded code

previously, we would warn like this:

````
warning: lifetime parameter `'s` never used
 --> /tmp/unusedlif/code.rs:6:62
  |
5 | #[derive(Clone)]
  |          - help: elide the unused lifetime
6 | struct ShimMethod4<T: Trait2 + 'static>(pub &'static dyn for<'s> Fn(&'s mut T::As));
  |                                                              ^^
  |
  = note: requested on the command line with `-W unused-lifetimes`
````

Fixes #104432
2023-02-09 23:18:34 +05:30
Michael Goulet
68e27b3052 Disqualify auto-trait builtin impl in new solver if impl exists 2023-02-09 17:23:50 +00:00
Michael Goulet
8987e68247 Implement a dummy drop-in-favor-of for the new solver 2023-02-09 17:22:37 +00:00
Michael Goulet
8c67ecd124 Use elaborated item bounds for alias types 2023-02-09 17:16:47 +00:00
Esteban Küber
a576514e13 Introduce -Zterminal-urls to use OSC8 for error codes
Terminals supporting the OSC8 Hyperlink Extension can support inline
anchors where the text is user defineable but clicking on it opens a
browser to a specified URLs, just like `<a href="URL">` does in HTML.

https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
2023-02-09 14:52:54 +00:00
bohan
7615045ebd test: snapshot for derive suggestion in diff files 2023-02-09 22:28:53 +08:00
Esteban Küber
30cf7a3f51 Introduce ReError
CC #69314
2023-02-09 10:26:49 +00:00
Matthias Krüger
3b9543c89d
Rollup merge of #107446 - clubby789:rustc-parse-diag-migrate, r=compiler-errors
Migrate some of `rustc_parse` to derive diagnostics

`@rustbot` label +A-translation
r? rust-lang/diagnostics
cc #100717
2023-02-09 11:21:57 +01:00
许杰友 Jieyou Xu (Joe)
b58347a9c6
Don't expose type parameters and implementation details from macro expansion 2023-02-09 15:15:15 +08:00
bors
c40919b7a7 Auto merge of #106938 - GuillaumeGomez:normalize-projection-field-ty, r=oli-obk
Add missing normalization for union fields types

Overshadows https://github.com/rust-lang/rust/pull/106808.
From the experiment https://github.com/rust-lang/rust/pull/103985.

In short, it allows to use projections as a type for union's fields.

cc `@compiler-errors`
r? `@oli-obk`
2023-02-09 07:08:19 +00:00
Michael Goulet
ab09405e99
Rollup merge of #107813 - compiler-errors:bad-impl-trait-in-macro-is-ok, r=estebank
Do not eagerly recover for bad `impl Trait` types in macros

Fixes #107796

cc #106712, ```@estebank``` and ```@Ezrashaw``` please make sure to use [`Parser::may_recover`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_parse/parser/struct.Parser.html#method.may_recover) for all eager-token-consuming parser recoveries.

This also fixes a separate regression from #99915, that was introduced before we added `may_recover` though.
2023-02-08 20:01:26 -08:00
Michael Goulet
46c7c91ce7
Rollup merge of #107799 - lcnr:update-provisional-result, r=oli-obk
correctly update goals in the cache

we may want to actually write the response for our goal into the provisional or global cache instead of simply using the result from the last iteration '^^

r? ```@rust-lang/initiative-trait-system-refactor```
2023-02-08 20:01:26 -08:00
Michael Goulet
32bb73eede
Rollup merge of #107761 - oli-obk:miri_🪵, r=TaKO8Ki
Replace a command line flag with an env var to allow tools to initialize the tracing loggers at their own discretion

fixes https://github.com/rust-lang/miri/issues/2778

this was introduced in https://github.com/rust-lang/rust/pull/104645, so this PR reverts the flag-part and uses an env var instead.
2023-02-08 20:01:25 -08:00
Oleksii Lozovskyi
54b26f49e6 Test XRay only for supported targets
Now that the compiler accepts "-Z instrument-xray" option only when
targeting one of the supported targets, make sure to not run the
codegen tests where the compiler will fail.

Like with other compiletests, we don't have access to internals,
so simply hardcode a list of supported architectures here.
2023-02-09 12:29:43 +09:00
Oleksii Lozovskyi
3561dc948c Emit an error if -Z instrument-xray is not supported
This is somewhat important because LLVM enables the pass based on
target architecture, but support by the target OS also matters.

For example, XRay attributes are processed by codegen for macOS
targets, but Apple linker fails to process relocations in XRay
data sections, so the feature as a whole is not supported there
for the time being.
2023-02-09 12:29:40 +09:00
Oleksii Lozovskyi
d748f08547 UI tests for -Z instrument-xray
I'm tired of testing it manually, just codify my expectations in tests.
They're pretty low-maintenance.
2023-02-09 12:27:58 +09:00
yukang
8f736a4042 fix #104961, Add parentheses properly for borrowing suggestion 2023-02-09 02:38:55 +00:00
Nicholas Nethercote
a70d03b624 Extend BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE.
To temporarily allow a `str` field in a packed struct using `derive`,
along with `[u8]`.
2023-02-09 11:47:12 +11:00
Alan Egerton
38ec810c37
Do not assemble supertraits for trait aliases 2023-02-08 19:55:50 +00:00
lcnr
4c7c5e597f add (currently ICEing) test 2023-02-08 19:11:14 +01:00
Michael Goulet
0017822b70 Do not eagerly recover for bad impl-trait in macros 2023-02-08 17:56:08 +00:00
Matthias Krüger
5b8403c463
Rollup merge of #107777 - compiler-errors:derive_const-actually-derive-const, r=fee1-dead
Make `derive_const` derive properly const-if-const impls

Fixes #107774
Fixes #107666

Also fixes rendering of const-if-const bounds in pretty printing.

r? ```@oli-obk``` or ```@fee1-dead```
2023-02-08 18:32:43 +01:00
Matthias Krüger
fe26182281
Rollup merge of #107779 - compiler-errors:issue-107775, r=jackh726
Remove astconv usage in diagnostic

Fixes #107775

Location of the test sucks, I know, but I needed to put it somewhere 😓
The issue here is that the root cause of the issue has nothing to do with what's being tested, so I couldn't really give it a better name. Oh well.
2023-02-08 07:13:29 +01:00
Matthias Krüger
31345cd70a
Rollup merge of #107771 - estebank:ice-msg, r=compiler-errors
Tweak ICE message

Modify main message to be more conversational and emit one fewer note.
2023-02-08 07:13:27 +01:00
Matthias Krüger
fabefe3f31
Rollup merge of #107769 - compiler-errors:pointer-like, r=eholk
Rename `PointerSized` to `PointerLike`

The old name was unnecessarily vague. This PR renames a nightly language feature that I added, so I don't think it needs any additional approval, though anyone can feel free to speak up if you dislike the rename.

It's still unsatisfying that we don't the user which of {size, alignment} is wrong, but this trait really is just a stepping stone for a more generalized mechanism to create `dyn*`, just meant for nightly testing, so I don't think it really deserves additional diagnostic machinery for now.

Fixes #107696, cc ``@RalfJung``
r? ``@eholk``
2023-02-08 07:13:26 +01:00
bors
b082e80e20 Auto merge of #107688 - lukas-code:projection-with-lifetime, r=jackh726
ReErased regions are local

fix https://github.com/rust-lang/rust/issues/107678
fix https://github.com/rust-lang/rust/issues/107684
fix https://github.com/rust-lang/rust/issues/107686
fix https://github.com/rust-lang/rust/issues/107691
fix https://github.com/rust-lang/rust/issues/107730
2023-02-08 00:34:18 +00:00
Michael Goulet
6fdfdea8b1 Remove astconv usage in diagnostic 2023-02-07 23:08:25 +00:00
Michael Goulet
7a4505900d Add ~const bounds trait bounds when using derive_const 2023-02-07 21:00:12 +00:00
Michael Goulet
56bf28d4f4 Expand const-if-const trait bounds correctly 2023-02-07 21:00:12 +00:00
Esteban Küber
a7597a1526 Tweak ICE message
Modify main message to be more conversational and emit one fewer note.
2023-02-07 19:17:24 +00:00
Michael Goulet
2b70cbb8a5 Rename PointerSized to PointerLike 2023-02-07 19:05:53 +00:00
bors
bd39bbb4bb Auto merge of #107767 - matthiaskrgr:rollup-9m1qfso, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #100599 (Add compiler error E0523 long description and test)
 - #107471 (rustdoc: do not include empty default-settings tag in HTML)
 - #107555 (Modify existing bounds if they exist)
 - #107662 (Turn projections into copies in CopyProp.)
 - #107695 (Add test for Future inflating arg size to 3x )
 - #107700 (Run the tools builder on all PRs)
 - #107706 (Mark 'atomic_mut_ptr' methods const)
 - #107709 (Fix problem noticed in PR106859 with char -> u8 suggestion)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-02-07 17:19:47 +00:00
Matthias Krüger
0e3af6af47
Rollup merge of #107709 - tialaramex:master, r=compiler-errors
Fix problem noticed in PR106859 with char -> u8 suggestion

HN reader `@ayosec` noticed that my #106859 a few weeks back, malfunctions if you have a Unicode escape, the code suggested b'\u{0}' if you tried to use '\u{0}' where a byte should be, when of course b'\u{0}' is not a byte literal, regardless of the codepoint you can't write Unicode escapes in a byte literal at all.

My proposed fix here just checks that the "character" you wrote is fewer than 5 bytes, thus allowing \x7F and similar escapes but conveniently forbidding even the smallest Unicode escape \u{0} before offering the suggestion as before.

I have provided an updated test which includes examples which do and don't work because of this additional rule.
2023-02-07 17:57:17 +01:00
Matthias Krüger
4b859c3f2f
Rollup merge of #107695 - Swatinem:futcallx3, r=compiler-errors
Add test for Future inflating arg size to 3x

This adds one more test that should track improvements to generator
layout, like https://github.com/rust-lang/rust/issues/62958 and https://github.com/rust-lang/rust/issues/62575.

In particular, this test highlights suboptimal layout, as the storage
for the argument future is not being reused across its usage as `upvar`,
`local` and `awaitee` (being polled to completion).

This is on top of https://github.com/rust-lang/rust/pull/107692 (as those would conflict with each other)

It is a minimal repro for code mentioned in https://github.com/moka-rs/moka/issues/212#issuecomment-1416914616 (CC `@tatsuya6502)`
2023-02-07 17:57:15 +01:00
Matthias Krüger
917662a8f6
Rollup merge of #107555 - edward-shen:edward-shen/dup-trait-suggestion, r=compiler-errors
Modify existing bounds if they exist

Fixes #107335.

This implementation is kinda gross but I don't really see a better way to do it.

This primarily does two things: Modifies `suggest_constraining_type_param` to accept a new parameter that indicates a span to be replaced instead of added, if presented, and limit the additive suggestions to either suggest a new bound on an existing bound (see newly added unit test) or add the generics argument if a generics argument wasn't found.

The former change is required to retain the capability to add an entirely new bounds if it was entirely omitted.

r? ``@compiler-errors``
2023-02-07 17:57:14 +01:00
Matthias Krüger
6d225bb080
Rollup merge of #100599 - MatthewPeterKelly:add-E0523-description-and-test, r=compiler-errors,GuillaumeGomez
Add compiler error E0523 long description and test

This PR is one step towards addressing:  https://github.com/rust-lang/rust/issues/61137.
2023-02-07 17:57:13 +01:00
Oli Scherer
f95b553eb4 Replace a command line flag with an env var to allow tools to initialize the tracing loggers at their own discretion 2023-02-07 16:33:03 +00:00
bors
5dd0e1b7ae Auto merge of #107671 - CastilloDel:master, r=estebank
Fix suggestions rendering when the diff span is multiline

Fixes #92741

cc `@estebank`

I think, I finally fixed. I still want to go back and try to clean up the code a bit. I'm open to suggestions.

Some examples of the new suggestions:

```
help: consider removing the borrow
  |
2 -     &
  |
```
```
help: consider removing the borrow
  |
2 -     &
3 -     mut
  |
```
```
help: consider removing the borrow
  |
2 -     &
3 -     mut if true { true } else { false }
2 +     if true { true } else { false }
  |
```

Should we add a test to ensure this behavior doesn't disappear in the future?
2023-02-07 13:29:45 +00:00
Arpad Borsos
7a7b2e3521
Add test for Future inflating arg size to 3x
This adds one more test that should track improvements to generator
layout, like #62958 and #62575.

In particular, this test highlights suboptimal layout, as the storage
for the argument future is not being reused across its usage as `upvar`,
`local` and `awaitee` (being polled to completion).
2023-02-07 08:52:15 +01:00
Nick Lamb
747cdc0dfd Fix problem noticed in PR106859 with char -> u8 suggestion 2023-02-06 21:48:10 +00:00
Matthias Krüger
a5288a7803
Rollup merge of #107692 - Swatinem:printsizeyield, r=compiler-errors
Sort Generator `print-type-sizes` according to their yield points

Especially when trying to diagnose runaway future sizes, it might be more intuitive to sort the variants according to the control flow (aka their yield points) rather than the size of the variants.
2023-02-06 21:16:41 +01:00
Matthias Krüger
800221b5b8
Rollup merge of #106477 - Nathan-Fenner:nathanf/refined-error-span-trait-impl, r=compiler-errors
Refine error spans for "The trait bound `T: Trait` is not satisfied" when passing literal structs/tuples

This PR adds a new heuristic which refines the error span reported for "`T: Trait` is not satisfied" errors, by "drilling down" into individual fields of structs/enums/tuples to point to the "problematic" value.

Here's a self-contained example of the difference in error span:

```rs
struct Burrito<Filling> {
    filling: Filling,
}
impl <Filling: Delicious> Delicious for Burrito<Filling> {}
fn eat_delicious_food<Food: Delicious>(food: Food) {}
fn will_type_error() {
    eat_delicious_food(Burrito { filling: Kale });
    //                 ^~~~~~~~~~~~~~~~~~~~~~~~~ (before) The trait bound `Kale: Delicious` is not satisfied
    //                                    ^~~~   (after)  The trait bound `Kale: Delicious` is not satisfied
}
```
(kale is fine, this is just a silly food-based example)

Before this PR, the error span is identified as the entire argument to the generic function `eat_delicious_food`. However, since only `Kale` is the "problematic" part, we can point at it specifically. In particular, the primary error message itself mentions the missing `Kale: Delicious` trait bound, so it's much clearer if this part is called out explicitly.

---

The _existing_ heuristic tries to label the right function argument in `point_at_arg_if_possible`. It goes something like this:
- Look at the broken base trait `Food: Delicious` and find which generics it mentions (in this case, only `Food`)
- Look at the parameter type definitions and find which of them mention `Filling` (in this case, only `food`)
- If there is exactly one relevant parameter, label the corresponding argument with the error span, instead of the entire call

This PR extends this heuristic by further refining the resulting expression span in the new `point_at_specific_expr_if_possible` function. For each `impl` in the (broken) chain, we apply the following strategy:

The strategy to determine this span involves connecting information about our generic `impl`
with information about our (struct) type and the (struct) literal expression:
- Find the `impl` (`impl <Filling: Delicious> Delicious for Burrito<Filling>`)
  that links our obligation (`Kale: Delicious`) with the parent obligation (`Burrito<Kale>: Delicious`)
- Find the "original" predicate constraint in the impl (`Filling: Delicious`) which produced our obligation.
- Find all of the generics that are mentioned in the predicate (`Filling`).
- Examine the `Self` type in the `impl`, and see which of its type argument(s) mention any of those generics.
- Examing the definition for the `Self` type, and identify (for each of its variants) if there's a unique field
  which uses those generic arguments.
- If there is a unique field mentioning the "blameable" arguments, use that field for the error span.

Before we do any of this logic, we recursively call `point_at_specific_expr_if_possible` on the parent
obligation. Hence we refine the `expr` "outwards-in" and bail at the first kind of expression/impl we don't recognize.

This function returns a `Result<&Expr, &Expr>` - either way, it returns the `Expr` whose span should be
reported as an error. If it is `Ok`, then it means it refined successfull. If it is `Err`, then it may be
only a partial success - but it cannot be refined even further.

---

I added a new test file which exercises this new behavior. A few existing tests were affected, since their error spans are now different. In one case, this leads to a different code suggestion for the autofix - although the new suggestion isn't _wrong_, it is different from what used to be.

This change doesn't create any new errors or remove any existing ones, it just adjusts the spans where they're presented.

---

Some considerations: right now, this check occurs in addition to some similar logic in `adjust_fulfillment_error_for_expr_obligation` function, which tidies up various kinds of error spans (not just trait-fulfillment error). It's possible that this new code would be better integrated into that function (or another one) - but I haven't looked into this yet.

Although this code only occurs when there's a type error, it's definitely not as efficient as possible. In particular, there are definitely some cases where it degrades to quadratic performance (e.g. for a trait `impl` with 100+ generic parameters or 100 levels deep nesting of generic types). I'm not sure if these are realistic enough to worry about optimizing yet.

There's also still a lot of repetition in some of the logic, where the behavior for different types (namely, `struct` vs `enum` variant) is _similar_ but not the same.

---

I think the biggest win here is better targeting for tuples; in particular, if you're using tuples + traits to express variadic-like functions, the compiler can't tell you which part of a tuple has the wrong type, since the span will cover the entire argument. This change allows the individual field in the tuple to be highlighted, as in this example:

```
// NEW
LL |     want(Wrapper { value: (3, q) });
   |     ----                      ^ the trait `T3` is not implemented for `Q`

// OLD
LL |     want(Wrapper { value: (3, q) });
   |     ---- ^~~~~~~~~~~~~~~~~~~~~~~~~ the trait `T3` is not implemented for `Q`
```
Especially with large tuples, the existing error spans are not very effective at quickly narrowing down the source of the problem.
2023-02-06 21:16:39 +01:00
Edward Shen
af5a37e844
Modify existing bounds if they exist 2023-02-06 11:26:36 -08:00
bors
7ff69b49df Auto merge of #107727 - Dylan-DPC:rollup-b1yexcl, r=Dylan-DPC
Rollup of 5 pull requests

Successful merges:

 - #107553 (Suggest std::ptr::null if literal 0 is given to a raw pointer function argument)
 - #107580 (Recover from lifetimes with default lifetimes in generic args)
 - #107669 (rustdoc: combine duplicate rules in ayu CSS)
 - #107685 (Suggest adding a return type for async functions)
 - #107687 (Adapt SROA MIR opt for aggregated MIR)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-02-06 16:28:18 +00:00
clubby789
521c5f36d6 Migrate rustc_parse to derive diagnostics 2023-02-06 14:40:35 +00:00
CastilloDel
f0830c0ade Add run-rustfix to tests/ui/issues/issue-92741.rs 2023-02-06 15:34:47 +01:00
CastilloDel
039f70e926 Add more test cases to tests/ui/issues/issue-92741.rs 2023-02-06 15:30:29 +01:00
Dylan DPC
675976eb21
Rollup merge of #107685 - jieyouxu:issue-90027, r=compiler-errors
Suggest adding a return type for async functions

Fixes #90027.
2023-02-06 19:54:15 +05:30
Dylan DPC
8ddbfadda0
Rollup merge of #107580 - lenko-d:default_value_for_a_lifetime_generic_parameter_produces_confusing_diagnostic, r=compiler-errors
Recover from lifetimes with default lifetimes in generic args

Fixes [#107492](https://github.com/rust-lang/rust/issues/107492)
2023-02-06 19:54:14 +05:30
Dylan DPC
496adf81de
Rollup merge of #107553 - edward-shen:edward-shen/suggest-null-ptr, r=WaffleLapkin
Suggest std::ptr::null if literal 0 is given to a raw pointer function argument

Implementation feels a little sus (we're parsing the span for a `0`) but it seems to fall in line the string-expected-found-char condition right above this check, so I think it's fine.

Feedback appreciated on help text? I think it's consistent but it does sound a little awkward maybe?

Fixes #107517
2023-02-06 19:54:13 +05:30
bors
044a28a409 Auto merge of #103761 - chenyukang:yukang/fix-103320-must-use, r=compiler-errors
Add explanatory message for [#must_use] in ops

Fixes #103320
2023-02-06 12:57:37 +00:00
Matthew Kelly
2bcd4e256a Add extended error message for E0523
Adds the extended error documentation for E0523 to indicate that the
error is no longer produced by the compiler.

Update the E0464 documentation to include example code that produces the
error.

Remove the error message E0523 from the compiler and replace it with an
internal compiler error.
2023-02-06 06:58:30 -05:00
许杰友 Jieyou Xu (Joe)
6b05b80690
Suggest return type for async function without return type 2023-02-06 13:02:04 +08:00
Lukas Markeffsky
e2a1a2ab79 yet another ui test 2023-02-05 22:51:37 +01:00
bors
75a0be98f2 Auto merge of #107526 - obeis:for-missing-iterator, r=estebank,compiler-errors
Recover form missing expression in `for` loop

Close #78537
r? `@estebank`
2023-02-05 20:33:05 +00:00
CastilloDel
9cdc07538d Add UI test for issue #92741 2023-02-05 19:12:41 +01:00
bors
a676496750 Auto merge of #107663 - matthiaskrgr:107423-point-at-EOF-code, r=compiler-errors
don't point at nonexisting code beyond EOF when warning about delims

Previously we would show this:
```
warning: unnecessary braces around block return value
 --> /tmp/bad.rs:1:8
  |
1 | fn a(){{{
  |        ^  ^
  |
  = note: `#[warn(unused_braces)]` on by default
help: remove these braces
  |
1 - fn a(){{{
1 + fn a(){{
  |
```

which is now hidden in this case.
We would create a span spanning between the pair of redundant {}s but there is only EOF instead of the `}` so we would previously point at nothing. This would cause the debug assertion ice to trigger. I would have loved to just only point at the second delim and say "you can remove that" but I'm not sure how to do that without refactoring the entire diagnostic which seems tricky. :( But given that this does not seem to regress any other tests we have, I think this edge-casey enough be acceptable.

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

r? `@compiler-errors`
2023-02-05 17:32:26 +00:00
Arpad Borsos
dae00152e7
Sort Generator print-type-sizes according to their yield points
Especially when trying to diagnose runaway future sizes, it might be
more intuitive to sort the variants according to the control flow
(aka their yield points) rather than the size of the variants.
2023-02-05 17:34:33 +01:00
Obei Sideg
17b6bd6b70 Add ui test for missing expression in for loop 2023-02-05 17:33:17 +03:00
Lukas Markeffsky
9d110847ab ReErased regions are local 2023-02-05 15:29:07 +01:00
Boxy
d85d906f8c emit ConstEquate in TypeRelating<D> 2023-02-05 07:24:54 +00:00
Edward Shen
32967296b4
Suggest null ptr if 0 is given as a raw ptr arg 2023-02-04 20:13:16 -08:00
Lenko Donchev
d9f60052d2 Recover from default value for a lifetime in generic parameters. 2023-02-04 17:04:09 -06:00
Matthias Krüger
d381eca5dc
Rollup merge of #107646 - estebank:specific-span, r=compiler-errors
Provide structured suggestion for binding needing type on E0594

Partially address #45405.
2023-02-04 20:29:06 +01:00
bors
9dee4e4c42 Auto merge of #107267 - cjgillot:keep-aggregate, r=oli-obk
Do not deaggregate MIR

This turns out to simplify a lot of things.
I haven't checked the consequences for miri yet.

cc `@JakobDegen`
r? `@oli-obk`
2023-02-04 15:17:32 +00:00
Matthias Krüger
ed58c01959 don't point at nonexisting code beyond EOF when warning about unused delims
Previously we would show this:
```
warning: unnecessary braces around block return value
 --> /tmp/bad.rs:1:8
  |
1 | fn a(){{{
  |        ^  ^
  |
  = note: `#[warn(unused_braces)]` on by default
help: remove these braces
  |
1 - fn a(){{{
1 + fn a(){{
  |
```

which is now hidden in this case.
We would create a span spanning between the pair of redundant {}s but there is only EOF instead of the `}` so we would previously point at nothing.
This would cause the debug assertion ice to trigger.
I would have loved to just only point at the second delim and say "you can remove that" but I'm not sure how to do that without refactoring the entire diagnostic which seems tricky. :(
But given that this does not seem to regress any other tests we have, I think this edge-casey enough be acceptable.

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

r? @compiler-errors
2023-02-04 13:36:14 +01:00
Michael Goulet
e99e05d135
Rollup merge of #107551 - fee1-dead-contrib:rm_const_fnmut_helper, r=oli-obk
Replace `ConstFnMutClosure` with const closures

Also fixes a parser bug. cc `@oli-obk` for compiler changes
2023-02-03 14:15:22 -08:00
Michael Goulet
0b5941aa11 Make const/fn return params more suggestable 2023-02-03 21:37:41 +00:00
Matthias Krüger
a3637032db unused-lifetimes: don't warn about lifetimes originating from expanded code
previously, we would warn like this:

````
warning: lifetime parameter `'s` never used
 --> /tmp/unusedlif/code.rs:6:62
  |
5 | #[derive(Clone)]
  |          - help: elide the unused lifetime
6 | struct ShimMethod4<T: Trait2 + 'static>(pub &'static dyn for<'s> Fn(&'s mut T::As));
  |                                                              ^^
  |
  = note: requested on the command line with `-W unused-lifetimes`
````

Fixes #104432
2023-02-03 21:18:34 +01:00
Esteban Küber
da1360d981 Provide structured suggestion for binding needing type on E0594
Partially address #45405.
2023-02-03 18:53:27 +00:00
bors
658fad6c55 Auto merge of #107642 - Dylan-DPC:rollup-edcqhm5, r=Dylan-DPC
Rollup of 6 pull requests

Successful merges:

 - #107082 (Autotrait bounds on dyn-safe trait methods)
 - #107427 (Add candidates for DiscriminantKind builtin)
 - #107539 (Emit warnings on unused parens in index expressions)
 - #107544 (Improve `TokenCursor`.)
 - #107585 (Don't cause a cycle when formatting query description that references a FnDef)
 - #107633 (Fix suggestion for coercing Option<&String> to Option<&str>)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-02-03 17:53:49 +00:00
Dylan DPC
c9270272df
Rollup merge of #107633 - clubby789:option-string-coerce-fix, r=Nilstrieb
Fix suggestion for coercing Option<&String> to Option<&str>

Fixes #107604

This also makes the diagnostic `MachineApplicable`, and runs `rustfix` to check we're not producing incorrect code.

``@rustbot`` label +A-diagnostics
2023-02-03 23:04:52 +05:30
Dylan DPC
d6f0c51e98
Rollup merge of #107585 - compiler-errors:fndef-sig-cycle, r=oli-obk
Don't cause a cycle when formatting query description that references a FnDef

When a function returns `-> _`, we use typeck to compute what the resulting type of the body _should_ be. If we call another query inside of typeck and hit a cycle error, we attempt to report the cycle error which requires us to compute all of the query descriptions for the stack.

However, if one of the queries in that cycle has a query description that references this function as a FnDef type, we'll cause a *second* cycle error from within the cycle error reporting code, since rendering a FnDef requires us to compute its signature. This causes an unwrap to ICE, since during the *second* cycle reporting code, we try to look for a job that isn't in the active jobs list.

We can avoid this by using `with_no_queries!` when computing these query descriptions.

Fixes #107089

The only drawback is that the rendering of opaque types in cycles regresses a bit :| I'm open to alternate suggestions about how we may handle this...
2023-02-03 23:04:52 +05:30
Dylan DPC
d9db35785d
Rollup merge of #107539 - PossiblyAShrub:unused-parens-in-index, r=lcnr
Emit warnings on unused parens in index expressions

Fixes: #96606.

I am not sure what the best term for "index expression" is. Is there a better term we could use?
2023-02-03 23:04:51 +05:30
David Tolnay
4501d3abe1
Autotrait bounds on dyn-safe trait methods 2023-02-03 08:33:40 -08:00
David Tolnay
9e1c600f74
Disallow impl autotrait for trait object 2023-02-03 08:33:40 -08:00
yukang
cb55d10eb2 Fix #103320, add explanatory message for [#must_use] 2023-02-04 00:27:03 +08:00
bors
9545094994 Auto merge of #107599 - clubby789:debug-less-ref, r=nnethercote
Don't generate unecessary `&&self.field` in deriving Debug

Since unsized fields may only be the last one in a struct, we only need to generate a double reference (`&&self.field`) for the  final one.

cc `@nnethercote`
2023-02-03 14:22:42 +00:00
clubby789
f874f6768c Fix suggestion for coercing Option<&String> to Option<&str> 2023-02-03 11:44:23 +00:00
Matthias Krüger
743ca67edf
Rollup merge of #107602 - estebank:anon-enum-access, r=compiler-errors
Parse and recover from type ascription in patterns

Reintroduce part of #106960, which was reverted in #107478.

r? `@compiler-errors`
2023-02-03 06:30:24 +01:00
Matthias Krüger
22aa680c44
Rollup merge of #107500 - bryangarza:future-sizes-baseline-test, r=compiler-errors
Add tests to assert current behavior of large future sizes

Based on a couple of sources:
- https://swatinem.de/blog/future-size/
- https://github.com/rust-lang/rust/issues/62958
2023-02-03 06:30:23 +01:00
Matthias Krüger
2fdb3559c4
Rollup merge of #106805 - madsravn:master, r=compiler-errors
Suggest `{var:?}` when finding `{?:var}` in inline format strings

Link to issue: https://github.com/rust-lang/rust/issues/106572

This is my first PR to this project, so hopefully I can get some good pointers with me from the first PR.

Currently my idea was to test out whether or not this is the correct solution to this issue and then hopefully expand upon the idea to not only work for Debug formatting but for all of  them. If this is a valid solution, I will create a new issue to give a better error message to a broader range of wrong-order formatting.
2023-02-03 06:30:23 +01:00
Matthias Krüger
6b94f4dccc
Rollup merge of #106575 - estebank:issue-64008, r=pnkfelix
Suggest `move` in nested closure when appropriate

Fix #64008.
2023-02-03 06:30:22 +01:00
Camille GILLOT
10ec94930b Bless tests. 2023-02-02 23:26:26 +00:00
clubby789
d8651aae22 Don't generate unecessary &&self.field in deriving Debug 2023-02-02 22:06:23 +00:00
Aidan Olsen
c3a71ede7c Emit warnings on unused parens/braces in index expressions 2023-02-02 12:46:31 -07:00
Esteban Küber
0ba687a95e Parse and recover from type ascription in patterns 2023-02-02 17:18:48 +00:00
Esteban Küber
e6b84eb797 Suggest move in nested closure when appropriate
Fix #64008.
2023-02-02 16:26:01 +00:00
Matthias Krüger
08181eabfe
Rollup merge of #107577 - nnethercote:reinstate-hir-stats, r=jyn514
Reinstate the `hir-stats.rs` tests on stage 1.

r? ```@the8472```
2023-02-02 17:14:08 +01:00
Matthias Krüger
3e0995a440
Rollup merge of #107532 - compiler-errors:erase-regions-in-uninhabited, r=jackh726
Erase regions before doing uninhabited check in borrowck

~Also, fingerprint query keys/values when debug assertions are enabled. This should make it easier to check for issues like this without `-Cincremental`, and make UI tests a bit cleaner.~ edit: moving that to a separate PR

Fixes #107505
2023-02-02 17:14:07 +01:00
Matthias Krüger
e9c4e291c4
Rollup merge of #107493 - clubby789:range-fat-arrow-followup, r=estebank
Improve diagnostic for missing space in range pattern

Improves the diagnostic in #107425 by turning it into a note explaining the parsing issue.

r? `@compiler-errors`
2023-02-02 17:14:05 +01:00
Matthias Krüger
8f47954742
Rollup merge of #106919 - compiler-errors:underscore-typo-in-field-pat, r=jackh726
Recover `_` as `..` in field pattern
2023-02-02 17:14:05 +01:00
clubby789
4ab75de934 Improve diagnostic for missing space in range pattern 2023-02-02 13:18:12 +00:00
bors
97872b792c Auto merge of #107478 - compiler-errors:anon-enum-tys-are-ambiguous, r=estebank
Revert "Teach parser to understand fake anonymous enum syntax" and related commits

anonymous enum types are currently ambiguous in positions like:

* `|` operator: `a as fn() -> B | C`
* closure args: `|_: as fn() -> A | B`

I first tried to thread around `RecoverAnonEnum` into all these positions, but the resulting complexity in the compiler is IMO not worth it, or at least worth a bit more thinking time. In the mean time, let's revert this syntax for now, so we can go back to the drawing board.

Fixes #107461

cc: `@estebank` `@cjgillot` #106960

---
### Squashed revert commits:

Revert "review comment: Remove AST AnonTy"

This reverts commit 020cca8d36.

Revert "Ensure macros are not affected"

This reverts commit 12d18e4031.

Revert "Emit fewer errors on patterns with possible type ascription"

This reverts commit c847a01a3b.

Revert "Teach parser to understand fake anonymous enum syntax"

This reverts commit 2d82420665.
2023-02-02 12:01:17 +00:00
Mads Ravn
f922c8395d PR fixing wrong order of format parameters in strings. Issue #106572
Adding

Adding

Fixing small issues for PR

Adding tests

Removing unused binding

Changing the wording on note

Fixing PR comment
2023-02-02 12:56:04 +01:00
Michael Goulet
9dd5d3e8e4 Recover _ as .. in field pattern 2023-02-02 06:10:02 +00:00
Michael Goulet
39db65c526 Add a test 2023-02-02 05:54:35 +00:00
Michael Goulet
e4b2936983 Revert "Teach parser to understand fake anonymous enum syntax" and related commits
Revert "review comment: Remove AST AnonTy"

This reverts commit 020cca8d36.

Revert "Ensure macros are not affected"

This reverts commit 12d18e4031.

Revert "Emit fewer errors on patterns with possible type ascription"

This reverts commit c847a01a3b.

Revert "Teach parser to understand fake anonymous enum syntax"

This reverts commit 2d82420665.
2023-02-02 05:54:35 +00:00
Matthias Krüger
643fc97fd3
Rollup merge of #107576 - P1n3appl3:master, r=tmandry
Add proc-macro boilerplate to crt-static test

I was seeing this failure when running ui tests with with a `-Cpanic=abort` stdlib targeting fuchsia:

```
---- [ui] tests/ui/proc-macro/crt-static.rs stdout ----
normalized stderr:
warning: building proc macro crate with `panic=abort` may crash the compiler should the proc-macro panic

warning: 1 warning emitted

The actual stderr differed from the expected stderr.
```

`force-host` was enough to stop it from running/failing, not sure if I should also add `needs-unwind`?
2023-02-02 06:52:15 +01:00
Matthias Krüger
150b9d753b
Rollup merge of #107488 - nnethercote:fix-PartialEq-syntax, r=RalfJung
Fix syntax in `-Zunpretty-expanded` output for derived `PartialEq`.

If you do `derive(PartialEq)` on a packed struct, the output shown by `-Zunpretty=expanded` includes expressions like this:
```
{ self.x } == { other.x }
```
This is invalid syntax. This doesn't break compilation, because the AST nodes are constructed within the compiler. But it does mean anyone using `-Zunpretty=expanded` output as a guide for hand-written impls could get a nasty surprise.

This commit fixes things by instead using this form:
```
({ self.x }) == ({ other.x })
```

r? ``@RalfJung``
2023-02-02 06:52:14 +01:00
Matthias Krüger
480c4a18d5
Rollup merge of #107201 - compiler-errors:confusing-async-fn-note, r=estebank
Remove confusing 'while checking' note from opaque future type mismatches

Maybe I'm just misinterpreting the wording of the note. The only value I can see in this note is that it points out where the async's opaque future is coming from, but the way it's doing it is misleading IMO.

For example:

```rust
note: while checking the return type of the `async fn`
  --> $DIR/dont-suggest-missing-await.rs:7:24
   |
LL | async fn make_u32() -> u32 {
   |                        ^^^ checked the `Output` of this `async fn`, found opaque type
```

We point at the type `u32` in the HIR, but then say "found opaque type". We also say "while checking"... but we're typechecking a totally different function when we get this type mismatch!

r? ``@estebank`` but feel free to reassign and/or take your time reviewing this. I'd be inclined to also discuss reworking the presentation of this type mismatch to restore some of these labels in a way that makes it more clear what it's trying to point out.
2023-02-02 06:52:13 +01:00
Michael Goulet
64f5293956 Don't cause a cycle when formatting query description that references a FnDef 2023-02-02 05:49:07 +00:00
Bryan Garza
1a65219a49 Bless tests after rebase 2023-02-02 01:38:14 +00:00
Bryan Garza
776918971d Update test to not trigger stack overflow 2023-02-02 01:20:12 +00:00
Bryan Garza
cb6de47d3b Move ignore-pass to large-arg test 2023-02-02 01:20:12 +00:00
Bryan Garza
7e56265ea0 Update based on PR comments 2023-02-02 01:20:12 +00:00
Bryan Garza
cc8f990e91 Add tests to assert current behavior of large future sizes
Based on a couple of sources:
- https://swatinem.de/blog/future-size/
- https://github.com/rust-lang/rust/issues/62958
2023-02-02 01:20:12 +00:00
Nicholas Nethercote
e30cd18fcc Reinstate the hir-stats.rs tests on stage 1. 2023-02-02 10:24:30 +11:00
Joseph Ryan
fb38578082 Add proc-macro boilerplate to crt-static test 2023-02-01 13:35:36 -08:00
Xiretza
87ef37dbd7 rustc_parse: migrate more to diagnostic structs 2023-02-01 21:50:34 +01:00
Xiretza
ac9c66bff5 tests: rename test cases to match new behaviour 2023-02-01 21:50:34 +01:00
Xiretza
0757d5f83f Fix condition for "missing struct" diagnostic on tuple structs
The check previously matched this, and suggested adding a missing
`struct`:

pub Foo(...):

It was probably intended to match this instead (semicolon instead of
colon):

pub Foo(...);
2023-02-01 21:50:34 +01:00
bors
11d96b5930 Auto merge of #107257 - inquisitivecrystal:ffi-attr, r=davidtwco
Strengthen validation of FFI attributes

Previously, `codegen_attrs` validated the attributes `#[ffi_pure]`, `#[ffi_const]`, and `#[ffi_returns_twice]` to make sure that they were only used on foreign functions. However, this validation was insufficient in two ways:

1. `codegen_attrs` only sees items for which code must be generated, so it was unable to raise errors when the attribute was incorrectly applied to macros and the like.
2. the validation code only checked that the item with the attr was foreign, but not that it was a foreign function, allowing these attributes to be applied to foreign statics as well.

This PR moves the validation to `check_attr`, which sees all items. It additionally changes the validation to ensure that the attribute's target is `Target::ForeignFunction`, only allowing the attributes on foreign functions and not foreign statics. Because these attributes are unstable, there is no risk for backwards compatibility. The changes also ending up making the code much easier to read.

This PR is best reviewed commit by commit. Additionally, I was considering moving the tests to the `attribute` subdirectory, to get them out of the general UI directory. I could do that as part of this PR or a follow-up, as the reviewer prefers.

CC: #58328, #58329
2023-02-01 11:37:24 +00:00
Léo Lanteri Thauvin
b379d216ee Stabilize #![feature(target_feature_11)] 2023-02-01 08:53:02 +01:00
SpanishPear
a3d32bbbbe fix formatting + test syntax 2023-02-01 18:11:37 +11:00
Deadbeef
679dde7338 fix parser mistaking const closures for const item 2023-02-01 06:44:30 +00:00
Matthias Krüger
f41f154dfb
Rollup merge of #107533 - pnkfelix:distinguish-generator-state-in-print-type-sizes, r=compiler-errors
Extend `-Z print-type-sizes` to distinguish generator upvars+locals from "normal" fields.

For example, for this code:

```rust
async fn wait() {}

async fn test(arg: [u8; 8192]) {
    wait().await;
    drop(arg);
}

async fn test_ideal(_rg: [u8; 8192]) {
    wait().await;
    // drop(arg);
}

fn main() {
    let gen_t = test([0; 8192]);
    let gen_i = test_ideal([0; 8192]);
    println!("expect {}, got: {}",
             std::mem::size_of_val(&gen_i),
             std::mem::size_of_val(&gen_t));
}
```

the `-Z print-type-sizes` output used to start with:

```
print-type-size type: `[async fn body@issue-62958-a.rs:3:32: 6:2]`: 16386 bytes, alignment: 1 bytes
print-type-size     discriminant: 1 bytes
print-type-size     variant `Suspend0`: 16385 bytes
print-type-size         field `.arg`: 8192 bytes, offset: 0 bytes, alignment: 1 bytes
print-type-size         field `.arg`: 8192 bytes
print-type-size         field `.__awaitee`: 1 bytes
...
print-type-size type: `std::mem::ManuallyDrop<[u8; 8192]>`: 8192 bytes, alignment: 1 bytes
print-type-size     field `.value`: 8192 bytes
...
```

but with this change, it now instead prints:

```
print-type-size type: `[async fn body@issue-62958-a.rs:3:32: 6:2]`: 16386 bytes, alignment: 1 bytes
print-type-size     discriminant: 1 bytes
print-type-size     variant `Suspend0`: 16385 bytes
print-type-size         upvar `.arg`: 8192 bytes, offset: 0 bytes, alignment: 1 bytes
print-type-size         local `.arg`: 8192 bytes
print-type-size         local `.__awaitee`: 1 bytes
...
print-type-size type: `std::mem::ManuallyDrop<[u8; 8192]>`: 8192 bytes, alignment: 1 bytes
print-type-size     field `.value`: 8192 bytes
```

(spawned off of investigation of https://github.com/rust-lang/rust/issues/62958 )
2023-02-01 05:54:40 +01:00
Matthias Krüger
a37a59f45e
Rollup merge of #107499 - compiler-errors:deduce_sig_from_projection-generator-tweak, r=michaelwoerister
Do not depend on Generator trait when deducing closure signature

1. Do not depend on `Generator` trait when deducing closure signature.
2. Compare the name of the `Generator::Return` associated item, rather than its order in the trait. Seems more stable this way.
2023-02-01 05:54:39 +01:00
Matthias Krüger
6390d25eab
Rollup merge of #107487 - edward-shen:edward-shen/107213-round-2, r=estebank
Make the "extra if in let...else block" hint a suggestion

Changes the hint to a suggestion, suggested in #107213.

r? ```@estebank```
2023-02-01 05:54:39 +01:00
Matthias Krüger
0d2ab67742
Rollup merge of #107389 - zvavybir:master, r=estebank
Fixing confusion between mod and remainder

Like many programming languages, rust too confuses remainder and modulus.  The `%` operator and the associated `Rem` trait is (as the trait name suggests) the remainder, but since most people are linguistically more familiar with the modulus the documentation sometimes claims otherwise.  This PR tries to fix this problem in rustc.
2023-02-01 05:54:37 +01:00
Nicholas Nethercote
75e87d1f81 Fix syntax in -Zunpretty-expanded output for derived PartialEq.
If you do `derive(PartialEq)` on a packed struct, the output shown by
`-Zunpretty=expanded` includes expressions like this:
```
{ self.x } == { other.x }
```
This is invalid syntax. This doesn't break compilation, because the AST
nodes are constructed within the compiler. But it does mean anyone using
`-Zunpretty=expanded` output as a guide for hand-written impls could get
a nasty surprise.

This commit fixes things by instead using this form:
```
({ self.x }) == ({ other.x })
```
2023-02-01 15:14:05 +11:00
Michael Goulet
2c23c7f0cd Erase regions before uninhabited check 2023-02-01 01:14:34 +00:00
Felix S. Klock II
362c4fa755 Bless updated output from print-type-sizes tests. 2023-01-31 20:00:54 -05:00
Ralf Jung
dfc4a7b2d0 make unaligned_reference a hard error 2023-01-31 20:28:11 +01:00
Deadbeef
3aeb43cb78 add and bless tests 2023-01-31 17:26:06 +00:00
Deadbeef
6bf2c4d739 implement const iterator using rustc_do_not_const_check 2023-01-31 17:09:30 +00:00
bors
f361413cbf Auto merge of #106399 - estebank:type-err-span-label, r=nagisa
Modify primary span label for E0308

Looking at the reactions to https://hachyderm.io/`@ekuber/109622160673605438,` a lot of people seem to have trouble understanding the current output, where the primary span label on type errors talks about the specific types that diverged, but these can be deeply nested type parameters. Because of that we could see "expected i32, found u32" in the label while the note said "expected Vec<i32>, found Vec<u32>". This understandably confuses people. I believe that once people learn to read these errors it starts to make more sense, but this PR changes the output to be more in line with what people might expect, without sacrificing terseness.

Fix #68220.
2023-01-31 13:53:40 +00:00
SpanishPear
70bfcc2518 move to multipart spans 2023-01-31 21:44:11 +11:00
Michael Goulet
7892cc3c5f Do not depend on Generator trait when deducing closure signature 2023-01-31 02:59:36 +00:00
Yuki Okushi
f95f835470
Rollup merge of #107479 - compiler-errors:probe-can-call-ocx, r=BoxyUwU
Use `ObligationCtxt::new_in_snapshot` in `satisfied_from_param_env`

We can evaluate nested `ConstEvaluatable` obligations in an evaluation probe, which will ICE if we use `ObligationCtxt::new`.

Fixes #107474
Fixes #106666

r? `@BoxyUwU` but feel free to reassign
cc `@JulianKnodt` who i think added this assertion code

Not sure if the rustdoc test is needed, but can't hurt. They're the same root cause, though.
2023-01-31 11:46:25 +09:00
Yuki Okushi
6eeb981a58
Rollup merge of #107245 - compiler-errors:new-solver-unsizing, r=lcnr
Implement unsizing in the new trait solver

This makes hello world compile! Ignore the first commit, that's just #107146 which is waiting on merge.

I'll leave some comments inline about design choices that might be debatable.

r? `@lcnr` (until we have a new trait solver reviewer group...)
2023-01-31 11:46:22 +09:00
bors
487e83b711 Auto merge of #105650 - cassaundra:float-literal-suggestion, r=pnkfelix
Fix invalid float literal suggestions when recovering an integer

Only suggest adding a zero to integers with a preceding dot when the change will result in a valid floating point literal.

For example, `.0x0` should not be turned into `0.0x0`.

r? nnethercote
2023-01-31 00:03:08 +00:00
Edward Shen
e905b93706
Make the "extra if in let...else block" hint a suggestion 2023-01-30 14:09:40 -08:00
Esteban Küber
449dfc64f0 Fix unquoted projection types in label 2023-01-30 22:02:30 +00:00
Esteban Küber
d86835769c Make structured suggestion for fn casting verbose 2023-01-30 21:55:25 +00:00
Esteban Küber
6c2c8edac3 Tweak E0271 wording 2023-01-30 21:51:35 +00:00
Esteban Küber
5ae8e23816 Mention fn coercion rules (needs to be expanded) 2023-01-30 21:51:33 +00:00
Cassaundra Smith
80fcd7c40e
Fix invalid float literal suggestions when recovering an integer
Only suggest adding a zero to integers with a preceding dot when the change will
result in a valid floating point literal.

For example, `.0x0` should not be turned into `0.0x0`.
2023-01-30 13:39:25 -08:00
Esteban Küber
153ed09fb3 Tweak use of trimmed paths 2023-01-30 20:12:21 +00:00
Esteban Küber
ab8dc9a0ad Hide lifetimes of impl Trait in force trimmed paths 2023-01-30 20:12:21 +00:00
Esteban Küber
252c43b42b Do not mention lifetime names in force trimmed paths 2023-01-30 20:12:21 +00:00
Esteban Küber
81973a39e0 Don't show for<'lt> in force trimmed paths 2023-01-30 20:12:21 +00:00
Esteban Küber
62ba3e70a1 Modify primary span label for E0308
The previous output was unintuitive to users.
2023-01-30 20:12:19 +00:00
Matthias Kaak
8d7b092a11
Improved wording of error messages of missing remainder implementations 2023-01-30 19:54:33 +00:00
Michael Goulet
c24844048f Trait upcasting support in new solver 2023-01-30 19:11:01 +00:00
Michael Goulet
085a48e798 Implement unsizing in the new trait solver 2023-01-30 19:11:01 +00:00
Michael Goulet
343a359109 Use ObligationCtxt::new_in_snapshot in satisfied_from_param_env 2023-01-30 19:04:59 +00:00
Lucille Blumire
8348f25493
Update bastion-of-the-turbofish.rs
The original tweet in the chain linked to, and thus the through line of links back to Anna's tweet where she named the turbofish (https://web.archive.org/web/20210911061514/https://twitter.com/whoisaldeka/status/914914008225816576) are lost as the user whoisaldeka has deleted their twitter account.

Switching to an archive link preserves this through line, allowing someone to browse back to see the point at which Anna created the turbofish, as was the original intent of including this context.
2023-01-30 14:22:41 +00:00
bors
fba9f33c7c Auto merge of #107463 - Dylan-DPC:rollup-6mq1li8, r=Dylan-DPC
Rollup of 6 pull requests

Successful merges:

 - #101569 (Don't re-export private/unstable ArgumentV1 from `alloc`.)
 - #106106 (Pass `branch.{branch}.remote=origin` to `git submodule update`)
 - #107146 (Make `unsizing_params_for_adt` into a query)
 - #107264 (Add option to include private items in library docs)
 - #107452 (Fix typo in `{Rc, Arc}::get_mut_unchecked` docs)
 - #107459 (end entry paragraph with a period (.))

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-01-30 11:14:21 +00:00
Dylan DPC
28340bab88
Rollup merge of #101569 - m-ou-se:alloc-no-rexport-argumentv1, r=thomcc
Don't re-export private/unstable ArgumentV1 from `alloc`.

The `alloc::fmt::ArgumentV1` re-export was marked as `#[stable]` even though the original `core::fmt::ArgumentV1` is `#[unstable]` (and `#[doc(hidden)]`).

(It wasn't usable though:

```
error[E0658]: use of unstable library feature 'fmt_internals': internal to format_args!
 --> src/main.rs:4:12
  |
4 |     let _: alloc::fmt::ArgumentV1 = todo!();
  |            ^^^^^^^^^^^^^^^^^^^^^^
  |
  = help: add `#![feature(fmt_internals)]` to the crate attributes to enable
```
)

Part of #99012
2023-01-30 15:11:44 +05:30
bors
3f25e56496 Auto merge of #104429 - nnethercote:more-deriving-on-packed-structs, r=RalfJung
More deriving on packed structs

See [here](https://github.com/rust-lang/rust/pull/104429#issuecomment-1320909245) for the t-lang nomination summary, and [here](https://github.com/rust-lang/rust/pull/104429#issuecomment-1360077895) for the approval.

r? `@RalfJung`
2023-01-30 07:02:01 +00:00
Nicholas Nethercote
2e93f2c92f Allow more deriving on packed structs.
Currently, deriving on packed structs has some non-trivial limitations,
related to the fact that taking references on unaligned fields is UB.

The current approach to field accesses in derived code:
- Normal case: `&self.0`
- In a packed struct that derives `Copy`: `&{self.0}`
- In a packed struct that doesn't derive `Copy`: `&self.0`

Plus, we disallow deriving any builtin traits other than `Default` for any
packed generic type, because it's possible that there might be
misaligned fields. This is a fairly broad restriction.

Plus, we disallow deriving any builtin traits other than `Default` for most
packed types that don't derive `Copy`. (The exceptions are those where the
alignments inherently satisfy the packing, e.g. in a type with
`repr(packed(N))` where all the fields have alignments of `N` or less
anyway. Such types are pretty strange, because the `packed` attribute is
not having any effect.)

This commit introduces a new, simpler approach to field accesses:
- Normal case: `&self.0`
- In a packed struct: `&{self.0}`

In the latter case, this requires that all fields impl `Copy`, which is
a new restriction. This means that the following example compiles under
the old approach and doesn't compile under the new approach.
```
 #[derive(Debug)]
 struct NonCopy(u8);

 #[derive(Debug)
 #[repr(packed)]
 struct MyType(NonCopy);
```
(Note that the old approach's support for cases like this was brittle.
Changing the `u8` to a `u16` would be enough to stop it working. So not
much capability is lost here.)

However, the other constraints from the old rules are removed. We can now
derive builtin traits for packed generic structs like this:
```
 trait Trait { type A; }

 #[derive(Hash)]
 #[repr(packed)]
 pub struct Foo<T: Trait>(T, T::A);
```
To allow this, we add a `T: Copy` bound in the derived impl and a `T::A:
Copy` bound in where clauses. So `T` and `T::A` must impl `Copy`.

We can now also derive builtin traits for packed structs that don't derive
`Copy`, so long as the fields impl `Copy`:
```
 #[derive(Hash)]
 #[repr(packed)]
 pub struct Foo(u32);
```
This includes types that hand-impl `Copy` rather than deriving it, such as the
following, that show up in winapi-0.2:
```
 #[derive(Clone)]
 #[repr(packed)]
 struct MyType(i32);

 impl Copy for MyType {}
```
The new approach is simpler to understand and implement, and it avoids
the need for the `unsafe_derive_on_repr_packed` check.

One exception is required for backwards-compatibility: we allow `[u8]`
fields for now. There is a new lint for this,
`byte_slice_in_packed_struct_with_derive`.
2023-01-30 12:00:42 +11:00
Mara Bos
47adb652d3 Update tests. 2023-01-29 20:19:26 +01:00
Matthias Krüger
45446824e3
Rollup merge of #107006 - b-naber:thir-tree, r=jackh726
Output tree representation on thir-tree

The current output of `-Zunpretty=thir-tree` is really cumbersome to work with, using an actual tree representation should make it easier to see what the thir looks like.
2023-01-29 20:03:37 +01:00
Matthias Krüger
8691602151
Rollup merge of #106540 - lowr:patch/remove-paren-whitespace, r=cjgillot
Insert whitespace to avoid ident concatenation in suggestion

This PR tweaks the suggestion of removing misplaced parentheses around trait bounds so as to avoid concatenating two identifiers. Although subtle, this should make outputs less surprising especially when applying the `MachineApplicable` suggestions automatically.
2023-01-29 20:03:35 +01:00
Ryo Yoshida
807ebac887
Insert whitespace to avoid ident concatenation in suggestion 2023-01-29 21:01:35 +09:00
bors
d117135f5a Auto merge of #106253 - nbdd0121:upcast, r=compiler-errors
Skip possible where_clause_object_safety lints when checking `multiple_supertrait_upcastable`

Fix #106247

To achieve this, I lifted the `WhereClauseReferencesSelf` out from `object_safety_violations` and move it into `is_object_safe` (which is changed to a new query).

cc `@dtolnay`
r? `@compiler-errors`
2023-01-29 10:20:25 +00:00
bors
a29efccb1e Auto merge of #107435 - matthiaskrgr:rollup-if5h6yu, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #106618 (Disable `linux_ext` in wasm32 and fortanix rustdoc builds.)
 - #107097 (Fix def-use dominance check)
 - #107154 (library/std/sys_common: Define MIN_ALIGN for m68k-unknown-linux-gnu)
 - #107397 (Gracefully exit if --keep-stage flag is used on a clean source tree)
 - #107401 (remove the usize field from CandidateSource::AliasBound)
 - #107413 (make more pleasant to read)
 - #107422 (Also erase substs for new infcx in pin move error)
 - #107425 (Check for missing space between fat arrow and range pattern)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-01-29 07:01:58 +00:00
Matthias Krüger
4e8f7e4fc9
Rollup merge of #107425 - clubby789:match-range-missing-space, r=compiler-errors
Check for missing space between fat arrow and range pattern

Fixes #107420

Ideally we wouldn't emit an error about expecting `=>` etc., but I'm not sure how to recover from this.

`@rustbot` label +A-diagnostics
2023-01-29 06:14:20 +01:00
Matthias Krüger
5ff6cdca7e
Rollup merge of #107422 - Nilstrieb:erase-the-ice, r=compiler-errors
Also erase substs for new infcx in pin move error

The code originally correctly erased the regions of the type it passed to the newly created infcx. But after the `fn_sig` query was made to return an `EarlyBinder<T>`, some substs that were around were substituted there without erasing their regions. They were then passed into the newly cerated infcx, which caused the ICE.

Fixes #107419

r? compiler-errors who reviewed the original PR adding this diagnostic
2023-01-29 06:14:20 +01:00
Matthias Krüger
4caa9dfa71
Rollup merge of #107097 - tmiasko:ssa, r=cjgillot
Fix def-use dominance check

A definition does not dominate a use in the same statement. For example
in MIR generated for compound assignment x += a (when overflow checks
are disabled).
2023-01-29 06:14:17 +01:00
bors
3cdd0197e7 Auto merge of #106227 - bryangarza:ctfe-limit, r=oli-obk
Use stable metric for const eval limit instead of current terminator-based logic

This patch adds a `MirPass` that inserts a new MIR instruction `ConstEvalCounter` to any loops and function calls in the CFG. This instruction is used during Const Eval to count against the `const_eval_limit`, and emit the `StepLimitReached` error, replacing the current logic which uses Terminators only.

The new method of counting loops and function calls should be more stable across compiler versions (i.e., not cause crates that compiled successfully before, to no longer compile when changes to the MIR generation/optimization are made).

Also see: #103877
2023-01-29 04:11:27 +00:00
bors
9f82651a5f Auto merge of #103659 - clubby789:improve-partialord-derive, r=nagisa
Special-case deriving `PartialOrd` for enums with dataless variants

I was able to get slightly better codegen by flipping the derived `PartialOrd` logic for two-variant enums.  I also tried to document the implementation of the derive macro to make the special-case logic a little clearer.
```rs
#[derive(PartialEq, PartialOrd)]
pub enum A<T> {
    A,
    B(T)
}
```
```diff
impl<T: ::core::cmp::PartialOrd> ::core::cmp::PartialOrd for A<T> {
   #[inline]
   fn partial_cmp(
       &self,
       other: &A<T>,
   ) -> ::core::option::Option<::core::cmp::Ordering> {
       let __self_tag = ::core::intrinsics::discriminant_value(self);
       let __arg1_tag = ::core::intrinsics::discriminant_value(other);
-      match ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag) {
-          ::core::option::Option::Some(::core::cmp::Ordering::Equal) => {
-              match (self, other) {
-                  (A::B(__self_0), A::B(__arg1_0)) => {
-                      ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0)
-                  }
-                  _ => ::core::option::Option::Some(::core::cmp::Ordering::Equal),
-              }
+      match (self, other) {
+          (A::B(__self_0), A::B(__arg1_0)) => {
+              ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0)
           }
-          cmp => cmp,
+          _ => ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag),
       }
   }
}
```
Godbolt: [Current](https://godbolt.org/z/GYjEzG1T8), [New](https://godbolt.org/z/GoK78qx15)
I'm not sure how common a case comparing two enums like this (such as `Option`) is, and if it's worth the slowdown of adding a special case to the derive. If it causes overall regressions it might be worth just manually implementing this for `Option`.
2023-01-28 22:11:11 +00:00
clubby789
4bfab39f9b Check for missing space between fat arrow and range pattern 2023-01-28 20:52:01 +00:00
Nilstrieb
832751fe1d Also erase substs for new infcx in pin move error
The code originally correctly erased the regions of the type it passed
to the newly created infcx. But after the `fn_sig` query was made to
return an `EarlyBinder<T>`, some substs that were around were
substituted there without erasing their regions. They were then passed
into the newly cerated infcx, which caused the ICE.
2023-01-28 20:43:16 +01:00
Gary Guo
66f3ab90a1 Reintroduce multiple_supertrait_upcastable lint 2023-01-28 15:08:07 +00:00
bors
bca8b4dc32 Auto merge of #107408 - matthiaskrgr:rollup-b5vz2ow, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #104012 (Improve unexpected close and mismatch delimiter hint in TokenTreesReader)
 - #104252 (Stabilize the const_socketaddr feature)
 - #105524 (Replace libc::{type} with crate::ffi::{type})
 - #107096 (Detect references to non-existant messages in Fluent resources)
 - #107355 (Add regression test for #60755)
 - #107384 (Remove `BOOL_TY_FOR_UNIT_TESTING`)
 - #107385 (Use `FallibleTypeFolder` for `ConstInferUnifier` not `TypeRelation`)
 - #107391 (rustdoc: remove inline javascript from copy-path button)
 - #107398 (Remove `ControlFlow::{BREAK, CONTINUE}`)

Failed merges:

r? `@ghost`
`@rustbot` modify labels: rollup
2023-01-28 13:12:59 +00:00
Matthias Krüger
b64a75f20b
Rollup merge of #107355 - JohnTitor:issue-60755, r=compiler-errors
Add regression test for #60755

Closes #60755
r? compiler-errors
Signed-off-by: Yuki Okushi <jtitor@2k36.org>
2023-01-28 11:11:07 +01:00
Matthias Krüger
e3048c7838
Rollup merge of #104012 - chenyukang:yukang/fix-103882-deli-indentation, r=petrochenkov
Improve unexpected close and mismatch delimiter hint in TokenTreesReader

Fixes #103882
Fixes #68987
Fixes #69259

The inner indentation mismatching will be covered by outer block, the new added function `report_error_prone_delim_block` will find out the error prone candidates for reporting.
2023-01-28 11:11:05 +01:00
bors
d8da513668 Auto merge of #106916 - lukas-code:overlapping-substs, r=estebank
Remove overlapping parts of multipart suggestions

This PR adds a debug assertion that the parts of a single substitution cannot overlap, fixes a overlapping substitution from the testsuite, and fixes https://github.com/rust-lang/rust/issues/106870.

Note that a single suggestion can still have multiple overlapping substitutions / possible edits, we just don't suggest overlapping replacements in a single edit anymore.

I've also included a fix for an unrelated bug where rustfix for `explicit_outlives_requirements` would produce multiple trailing commas for a where clause.
2023-01-28 10:00:56 +00:00
Matthias Krüger
a5caa989c9
Rollup merge of #107339 - aliemjay:covariant, r=lcnr
internally change regions to be covariant

Surprisingly, we consider the reference type `&'a T` to be contravaraint in its lifetime parameter. This is confusing and conflicts with the documentation we have in the reference, rustnomicon, and rustc-dev-guide. This also arguably not the correct use of terminology since we can use `&'static u8` in a place where `&' a u8` is expected, this implies that `&'static u8 <: &' a u8` and consequently `'static <: ' a`, hence covariance.

Because of this, when relating two types, we used to switch the argument positions in a confusing way:
`Subtype(&'a u8 <: &'b u8) => Subtype('b <: 'a) => Outlives('a: 'b) => RegionSubRegion('b <= 'a)`

The reason for the current behavior is probably that we wanted `Subtype('b <: 'a)` and `RegionSubRegion('b <= 'a)` to be equivalent, but I don' t think this is a good reason since these relations are sufficiently different in that the first is a relation in the subtyping lattice and is intrinsic to the type-systems, while the the second relation is an implementation detail of regionck.

This PR changes this behavior to use covariance, so..
`Subtype(&'a u8 <: &'b u8) => Subtype('a <: 'b) => Outlives('a: 'b) => RegionSubRegion('b <= 'a) `

Resolves #103676

r? `@lcnr`
2023-01-28 05:20:18 +01:00