Commit Graph

4506 Commits

Author SHA1 Message Date
Urgau
f6617d050d Remove dangling check-cfg ui tests files 2023-12-13 17:48:04 +01:00
Urgau
5345a166fe Add more suggestion to unexpected cfg names and values 2023-12-13 17:48:04 +01:00
bors
2fdd9eda0c Auto merge of #118534 - RalfJung:extern-type-size-of-val, r=WaffleLapkin
codegen: panic when trying to compute size/align of extern type

The alignment is also computed when accessing a field of extern type at non-zero offset, so we also panic in that case.

Previously `size_of_val` worked because the code path there assumed that "thin pointer" means "sized". But that's not true any more with extern types. The returned size and align are just blatantly wrong, so it seems better to panic than returning wrong results. We use a non-unwinding panic since code probably does not expect size_of_val to panic.
2023-12-13 08:33:05 +00:00
bors
f651b436ce Auto merge of #117050 - c410-f3r:here-we-go-again, r=petrochenkov
[`RFC 3086`] Attempt to try to resolve blocking concerns

Implements what is described at https://github.com/rust-lang/rust/issues/83527#issuecomment-1744822345 to hopefully make some progress.

It is unknown if such approach is or isn't desired due to the lack of further feedback, as such, it is probably best to nominate this PR to the official entities.

`@rustbot` labels +I-compiler-nominated
2023-12-13 06:37:08 +00:00
Jubilee
f9078a40ee
Rollup merge of #118891 - compiler-errors:async-gen-blocks, r=eholk
Actually parse async gen blocks correctly

1. I got the control flow in `parse_expr_bottom` messed up, and obviously forgot a test for `async gen`, so we weren't actually ever parsing it correctly.
2. I forgot to gate the span for `async gen {}`, so even if we did parse it, we wouldn't have correctly denied it in `cfg(FALSE)`.

r? eholk
2023-12-12 18:48:55 -08:00
Michael Goulet
1d78ce681e Actually parse async gen blocks correctly 2023-12-12 20:13:37 +00:00
bors
028b6d152e Auto merge of #118881 - matthiaskrgr:rollup-0rl3tir, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #116740 (dont ICE when ConstKind::Expr for is_const_evaluatable)
 - #117914 (On borrow return type, suggest borrowing from arg or owned return type)
 - #117927 (Clarify how to choose a FutureIncompatibilityReason variant.)
 - #118855 (Improve an error involving attribute values.)
 - #118856 (rustdoc-search: clean up parser)
 - #118865 (rustc_codegen_llvm: Enforce `rustc::potential_query_instability` lint)
 - #118866 (llvm-wrapper: adapt for LLVM API change)
 - #118868 (Correctly gate the parsing of match arms without body)
 - #118877 (tests: CGU tests require build-pass, not check-pass (remove FIXME))

r? `@ghost`
`@rustbot` modify labels: rollup
2023-12-12 18:20:37 +00:00
Matthias Krüger
d661974017
Rollup merge of #118868 - Nadrieril:correctly-gate-never_patterns-parsing, r=petrochenkov
Correctly gate the parsing of match arms without body

https://github.com/rust-lang/rust/pull/118527 accidentally allowed the following to parse on stable:
```rust
match Some(0) {
    None => { foo(); }
    #[cfg(FALSE)]
    Some(_)
}
```

This fixes that oversight. The way I choose which error to emit is the best I could think of, I'm open if you know a better way.

r? `@petrochenkov` since you're the one who noticed
2023-12-12 17:40:56 +01:00
Matthias Krüger
cd7809b953
Rollup merge of #118855 - nnethercote:improve-attribute-value-error, r=compiler-errors,petrochenkov
Improve an error involving attribute values.

Attribute values must be literals. The error you get when that doesn't hold is pretty bad, e.g.:
```
unexpected expression: 1 + 1
```
You also get the same error if the attribute value is a literal, but an invalid literal, e.g.:
```
unexpected expression: "foo"suffix
```

This commit does two things.
- Changes the error message to "attribute value must be a literal", which gives a better idea of what the problem is and how to fix it. It also no longer prints the invalid expression, because the carets below highlight it anyway.
- Separates the "not a literal" case from the "invalid literal" case. Which means invalid literals now get the specific error at the literal level, rather than at the attribute level.

r? `@compiler-errors`
2023-12-12 17:40:54 +01:00
Matthias Krüger
ffdb471872
Rollup merge of #117914 - estebank:issue-85843, r=wesleywiser
On borrow return type, suggest borrowing from arg or owned return type

When we encounter a function with a return type that has an anonymous lifetime with no argument to borrow from, besides suggesting the `'static` lifetime we now also suggest changing the arguments to be borrows or changing the return type to be an owned type.

```
error[E0106]: missing lifetime specifier
  --> $DIR/variadic-ffi-6.rs:7:6
   |
LL | ) -> &usize {
   |      ^ expected named lifetime parameter
   |
   = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
help: consider using the `'static` lifetime, but this is uncommon unless you're returning a borrowed value from a `const` or a `static`
   |
LL | ) -> &'static usize {
   |       +++++++
help: instead, you are more likely to want to change one of the arguments to be borrowed...
   |
LL |     x: &usize,
   |        +
help: ...or alternatively, to want to return an owned value
   |
LL - ) -> &usize {
LL + ) -> usize {
   |
```

Fix #85843.
2023-12-12 17:40:53 +01:00
Matthias Krüger
b2a0175b97
Rollup merge of #116740 - lenko-d:const_evaluatable_failed_for_non_unevaluated_const, r=BoxyUwU
dont ICE when ConstKind::Expr for is_const_evaluatable

The problem is that we are not handling ConstKind::Expr inside report_not_const_evaluatable_error

Fixes [#114151]
2023-12-12 17:40:52 +01:00
Ralf Jung
edcb7aba6b also test projecting to some sized fields at non-zero offset in structs with an extern type tail 2023-12-12 17:19:19 +01:00
Ralf Jung
a47416beb5 test that both size_of_val and align_of_val panic 2023-12-12 17:19:19 +01:00
Nadrieril
19e0c984d3 Don't gate the feature twice 2023-12-12 14:52:05 +01:00
Nadrieril
e274372689 Correctly gate the parsing of match arms without body 2023-12-12 14:42:04 +01:00
lcnr
6ffe36b37d refactor writeback: emit normalization errors with new solver 2023-12-12 12:20:54 +00:00
darklyspaced
b05f211519 blessed
resolved conflicts
2023-12-12 18:12:57 +08:00
Ralf Jung
df227f78c6 make it more clear what comments refer to; avoid dangling unaligned references
Co-authored-by: Waffle Maybe <waffle.lapkin@gmail.com>
2023-12-12 08:15:17 +01:00
Ralf Jung
9ef1e35166 reject projecting to fields whose offset we cannot compute 2023-12-12 08:15:17 +01:00
Ralf Jung
b1613ebc43 codegen: panic when trying to compute size/align of extern type 2023-12-12 08:15:17 +01:00
Matthias Krüger
dfc5ffacd3
Rollup merge of #118756 - jyn514:colors, r=estebank
use bold magenta instead of bold white for highlighting

according to a poll of gay people in my phone, purple is the most popular color to use for highlighting

| color      | percentage |
| ---------- | ---------- |
| bold white | 6%         |
| blue       | 14%        |
| cyan       | 26%        |
| purple     | 37%        |
| magenta    | 17%        |

unfortunately, purple is not supported by 16-color terminals, which rustc apparently wants to support for some reason.
until we require support for full 256-color terms (e.g. by doing the same feature detection as we currently do for urls), we can't use it.

instead, i have collapsed the purple votes into magenta on the theory that they're close, and also because magenta is pretty.

before:
![image](https://github.com/rust-lang/rust/assets/23638587/9a89eee2-8b89-422e-8554-812827bb2a23)

after:
![image](https://github.com/rust-lang/rust/assets/23638587/5bf3a917-8a20-4afd-af3e-f9491d0d57f5)

other colors for comparison:
blue: ![image](https://github.com/rust-lang/rust/assets/23638587/6f199c7b-d598-4009-8ffc-6b7b1d0d1f8c)
cyan: ![image](https://github.com/rust-lang/rust/assets/23638587/a77e4fe3-563e-4aa5-ae92-745bb67287d1)
purple: ![image](https://github.com/rust-lang/rust/assets/23638587/ffe603fb-d811-4106-95a9-4dd4c955924c)
magenta without bolding: ![image](https://github.com/rust-lang/rust/assets/23638587/cf927e5f-8b25-4dc2-b8e7-32905a11a459)

r? ``@estebank``
2023-12-12 06:52:49 +01:00
Nicholas Nethercote
226edf64fa Improve an error involving attribute values.
Attribute values must be literals. The error you get when that doesn't
hold is pretty bad, e.g.:
```
unexpected expression: 1 + 1
```
You also get the same error if the attribute value is a literal, but an
invalid literal, e.g.:
```
unexpected expression: "foo"suffix
```

This commit does two things.
- Changes the error message to "attribute value must be a literal",
  which gives a better idea of what the problem is and how to fix it. It
  also no longer prints the invalid expression, because the carets below
  highlight it anyway.
- Separates the "not a literal" case from the "invalid literal" case.
  Which means invalid literals now get the specific error at the literal
  level, rather than at the attribute level.
2023-12-12 15:54:25 +11:00
Tomasz Miąsko
a48cebc4b8 Coroutine variant fields can be uninitialized
Wrap coroutine variant fields in MaybeUninit to indicate that they
might be uninitialized. Otherwise an uninhabited field will make
the entire variant uninhabited and introduce undefined behaviour.

The analogous issue in the prefix of coroutine layout was addressed by
6fae7f8071.
2023-12-12 00:00:00 +00:00
The 8472
502df1b7d4 add more niches to rawvec 2023-12-11 23:38:48 +01:00
Matthias Krüger
3a0562b93c
Rollup merge of #118726 - dtolnay:matchguardlet, r=compiler-errors
Do not parenthesize exterior struct lit inside match guards

Before this PR, the AST pretty-printer injects parentheses around expressions any time parens _could_ be needed depending on what else is in the code that surrounds that expression. But the pretty-printer did not pass around enough context to understand whether parentheses really _are_ needed on any particular expression. As a consequence, there are false positives where unneeded parentheses are being inserted.

Example:

```rust
#![feature(if_let_guard)]

macro_rules! pp {
    ($e:expr) => {
        stringify!($e)
    };
}

fn main() {
    println!("{}", pp!(match () { () if let _ = Struct {} => {} }));
}
```

**Before:**

```console
match () { () if let _ = (Struct {}) => {} }
```

**After:**

```console
match () { () if let _ = Struct {} => {} }
```

This PR introduces a bit of state that is passed across various expression printing methods to help understand accurately whether particular situations require parentheses injected by the pretty printer, and it fixes one such false positive involving match guards as shown above.

There are other parenthesization false positive cases not fixed by this PR. I intend to address these in follow-up PRs. For example here is one: the expression `{ let _ = match x {} + 1; }` is pretty-printed as `{ let _ = (match x {}) + 1; }` despite there being no reason for parentheses to appear there.
2023-12-11 20:46:49 +01:00
Guillaume Gomez
453ff1efd5 Add tests for --env usage with tracked_env::var 2023-12-11 16:44:33 +01:00
bors
8a3765582c Auto merge of #117758 - Urgau:lint_pointer_trait_comparisons, r=davidtwco
Add lint against ambiguous wide pointer comparisons

This PR is the resolution of https://github.com/rust-lang/rust/issues/106447 decided in https://github.com/rust-lang/rust/issues/117717 by T-lang.

## `ambiguous_wide_pointer_comparisons`

*warn-by-default*

The `ambiguous_wide_pointer_comparisons` lint checks comparison of `*const/*mut ?Sized` as the operands.

### Example

```rust
let ab = (A, B);
let a = &ab.0 as *const dyn T;
let b = &ab.1 as *const dyn T;

let _ = a == b;
```

### Explanation

The comparison includes metadata which may not be expected.

-------

This PR also drops `clippy::vtable_address_comparisons` which is superseded by this one.

~~One thing: is the current naming right? `invalid` seems a bit too much.~~

Fixes https://github.com/rust-lang/rust/issues/117717
2023-12-11 14:33:16 +00:00
bors
ff2c56344c Auto merge of #118823 - GuillaumeGomez:rollup-6v51gxv, r=GuillaumeGomez
Rollup of 3 pull requests

Successful merges:

 - #118802 (Remove edition umbrella features.)
 - #118807 (Remove an allocation in min_stack)
 - #118812 (rustdoc-search: do not treat associated type names as types)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-12-11 12:33:04 +00:00
Guillaume Gomez
54d6bded30
Rollup merge of #118802 - ehuss:remove-edition-preview, r=TaKO8Ki
Remove edition umbrella features.

In the 2018 edition, there was an "umbrella" feature `#[feature(rust_2018_preview)]` which was used to enable several other features at once. This umbrella mechanism was not used in the 2021 edition and likely will not be used in 2024 either. During 2018 users reported that setting the feature was awkward, especially since they already needed to opt-in via the edition mechanism.

This PR removes this mechanism because I believe it will not be used (and will clean up and simplify the code). I believe that there are better ways to handle features and editions. In short:

- For highly experimental features, that may or may not be involved in an edition, they can implement regular feature gates like `tcx.features().my_feature`.
- For experimental features that *might* be involved in an edition, they should implement gates with `tcx.features().my_feature && span.at_least_rust_20xx()`. This requires the user to still specify `#![feature(my_feature)]`, to avoid disrupting testing of other edition features which are ready and have been accepted within the edition.
- For experimental features that have graduated to definitely be part of an edition, they should implement gates with `tcx.features().my_feature || span.at_least_rust_20xx()`, or just remove the feature check altogether and just check `span.at_least_rust_20xx()`.
- For relatively simple changes, they can skip the whole feature gating thing and just check `span.at_least_rust_20xx()`, and rely on the instability of the edition itself (which requires `-Zunstable-options`) to gate it.

I am working on documenting all of this in the rustc-dev-guide.
2023-12-11 11:40:36 +01:00
bors
6f40082313 Auto merge of #118661 - fee1-dead-contrib:restore-const-partialEq, r=compiler-errors
Restore `const PartialEq`

And thus fixes a number of tests. There is a bug that still needs to be fixed, so WIP for now.

r? `@compiler-errors`
2023-12-11 10:34:51 +00:00
bors
8b1ba11cb1 Auto merge of #117116 - calebzulawski:repr-simd-packed, r=workingjubilee
Implement repr(packed) for repr(simd)

This allows creating vectors with non-power-of-2 lengths that do not have padding.  See rust-lang/portable-simd#319
2023-12-11 08:07:20 +00:00
bors
c13187c998 Auto merge of #118494 - nnethercote:default_configuration-fill_well_known, r=Mark-Simulacrum
Rearrange `default_configuration` and `CheckCfg::fill_well_known`.

There are comments saying these two functions should be kept in sync, but they have very different structures, process symbols in different orders, and there are some inconsistencies.

This commit reorders them so they're both mostly processing symbols in alphabetical order, which makes cross-checking them a lot easier. The commit also adds some macros to factor out repetitive code patterns.

The commit also moves the handling of `sym::test` out of `build_configuration` into `default_configuration`, where all the other symbols are handled.

r? `@bjorn3`
2023-12-11 06:10:44 +00:00
bors
e299752868 Auto merge of #118032 - RalfJung:char-u32, r=Mark-Simulacrum
guarantee that char and u32 are ABI-compatible

In https://github.com/rust-lang/rust/pull/116894 we added a guarantee that `char` has the same alignment as `u32`, but there is still one axis where these types could differ: function call ABI. So let's nail that down as well: in a function signature, `char` and `u32` are completely equivalent.

This is a new stable guarantee, so it will need t-lang approval.
2023-12-11 04:13:19 +00:00
bors
a9cb8ee821 Auto merge of #114571 - nnethercote:improve-print_tts, r=petrochenkov
Improve `print_tts`

By slightly changing the meaning of `tokenstream::Spacing` we can greatly improve the output of `print_tts`.

r? `@ghost`
2023-12-11 00:03:56 +00:00
Nicholas Nethercote
22b534de4f Rearrange default_configuration and CheckCfg::fill_well_known.
There are comments saying these two functions should be kept in sync,
but they have very different structures, process symbols in different
orders, and there are some inconsistencies.

This commit reorders them so they're both mostly processing symbols in
alphabetical order, which makes cross-checking them a lot easier. The
commit also adds some macros to factor out repetitive code patterns.
Plus it adds `sanitizer_cfi_normalize_{integers,pointers}` to
`fill_well_known`, which were missing.

The commit also moves the handling of `sym::test` out of
`build_configuration` into `default_configuration`, where all the other
symbols are handled.
2023-12-11 10:04:47 +11:00
Nicholas Nethercote
940c885bc4 Add a few cases with wonky formatting to stringify.rs test.
Because the spacing-based pretty-printing partially preserves that.
2023-12-11 09:36:42 +11:00
Nicholas Nethercote
4cfdbd328b Add spacing information to delimiters.
This is an extension of the previous commit. It means the output of
something like this:
```
stringify!(let a: Vec<u32> = vec![];)
```
goes from this:
```
let a: Vec<u32> = vec![] ;
```
With this PR, it now produces this string:
```
let a: Vec<u32> = vec![];
```
2023-12-11 09:36:40 +11:00
Nicholas Nethercote
925f7fad57 Improve print_tts by changing tokenstream::Spacing.
`tokenstream::Spacing` appears on all `TokenTree::Token` instances,
both punct and non-punct. Its current usage:
- `Joint` means "can join with the next token *and* that token is a
  punct".
- `Alone` means "cannot join with the next token *or* can join with the
  next token but that token is not a punct".

The fact that `Alone` is used for two different cases is awkward.
This commit augments `tokenstream::Spacing` with a new variant
`JointHidden`, resulting in:
- `Joint` means "can join with the next token *and* that token is a
  punct".
- `JointHidden` means "can join with the next token *and* that token is a
  not a punct".
- `Alone` means "cannot join with the next token".

This *drastically* improves the output of `print_tts`. For example,
this:
```
stringify!(let a: Vec<u32> = vec![];)
```
currently produces this string:
```
let a : Vec < u32 > = vec! [] ;
```
With this PR, it now produces this string:
```
let a: Vec<u32> = vec![] ;
```
(The space after the `]` is because `TokenTree::Delimited` currently
doesn't have spacing information. The subsequent commit fixes this.)

The new `print_tts` doesn't replicate original code perfectly. E.g.
multiple space characters will be condensed into a single space
character. But it's much improved.

`print_tts` still produces the old, uglier output for code produced by
proc macros. Because we have to translate the generated code from
`proc_macro::Spacing` to the more expressive `token::Spacing`, which
results in too much `proc_macro::Along` usage and no
`proc_macro::JointHidden` usage. So `space_between` still exists and
is used by `print_tts` in conjunction with the `Spacing` field.

This change will also help with the removal of `Token::Interpolated`.
Currently interpolated tokens are pretty-printed nicely via AST pretty
printing. `Token::Interpolated` removal will mean they get printed with
`print_tts`. Without this change, that would result in much uglier
output for code produced by decl macro expansions. With this change, AST
pretty printing and `print_tts` produce similar results.

The commit also tweaks the comments on `proc_macro::Spacing`. In
particular, it refers to "compound tokens" rather than "multi-char
operators" because lifetimes aren't operators.
2023-12-11 09:19:09 +11:00
bors
d86d65bbc1 Auto merge of #118368 - GuillaumeGomez:env-flag, r=Nilstrieb
Implement `--env` compiler flag (without `tracked_env` support)

Part of https://github.com/rust-lang/rust/issues/80792.
Implementation of https://github.com/rust-lang/compiler-team/issues/653.
Not an implementation of https://github.com/rust-lang/rfcs/pull/2794.

It adds the `--env` compiler flag option which allows to set environment values used by `env!` and `option_env!`.

Important to note: When trying to retrieve an environment variable value, it will first look into the ones defined with `--env`, and if there isn't one, then only it will look into the environment variables. So if you use `--env PATH=a`, then `env!("PATH")` will return `"a"` and not the actual `PATH` value.

As mentioned in the title, `tracked_env` support is not added here. I'll do it in a follow-up PR.

r? rust-lang/compiler
2023-12-10 21:48:53 +00:00
Eric Huss
f481596ee4 Remove edition umbrella features. 2023-12-10 13:03:28 -08:00
bors
7e452c123c Auto merge of #118791 - saethlin:use-immediate-type, r=nikic
Use immediate_backend_type when reading from a const alloc

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

r? `@nikic`
2023-12-10 17:50:15 +00:00
bors
b9068315db Auto merge of #116952 - compiler-errors:lifetime_capture_rules_2024, r=TaKO8Ki
Implement 2024-edition lifetime capture rules RFC

Implements rust-lang/rfcs#3498.
2023-12-10 15:51:39 +00:00
Guillaume Gomez
d2b1f94f05 Add feature gate test for --env flag 2023-12-10 14:25:57 +01:00
Guillaume Gomez
37d68093da Add ui tests for --env option 2023-12-10 14:25:57 +01:00
bors
84f6130fe3 Auto merge of #118692 - surechen:remove_unused_imports, r=petrochenkov
remove redundant imports

detects redundant imports that can be eliminated.

for #117772 :

In order to facilitate review and modification, split the checking code and removing redundant imports code into two PR.

r? `@petrochenkov`
2023-12-10 11:55:48 +00:00
Deadbeef
d464dd07ed fix tests 2023-12-10 10:42:34 +00:00
Deadbeef
d1f4bc5a19 Revert "Don't print host effect param in pretty path_generic_args"
This reverts commit f1bf874fb1.
2023-12-10 10:17:28 +00:00
Deadbeef
f635cd2e82 Restore const PartialEq 2023-12-10 09:30:07 +00:00
bors
42dfac5e08 Auto merge of #118788 - compiler-errors:const-pretty, r=fee1-dead
Don't print host effect param in pretty `path_generic_args`

Make `own_args_no_defaults` pass back the `GenericParamDef`, so that we can pass both the args *and* param definitions into `path_generic_args`. That allows us to use the `GenericParamDef` to filter out effect params.

This allows us to filter out the host param regardless of whether it's `sym::host` or `true`/`false`.

This also renames a couple of `const_effect_param` -> `host_effect_param`, and restores `~const` pretty printing to `TraitPredPrintModifiersAndPath`.

cc #118785
r? `@fee1-dead` cc `@oli-obk`
2023-12-10 06:59:25 +00:00
surechen
40ae34194c remove redundant imports
detects redundant imports that can be eliminated.

for #117772 :

In order to facilitate review and modification, split the checking code and
removing redundant imports code into two PR.
2023-12-10 10:56:22 +08:00
bors
f7253f2317 Auto merge of #118787 - GuillaumeGomez:rollup-fj5wr3q, r=GuillaumeGomez
Rollup of 5 pull requests

Successful merges:

 - #117966 (add safe compilation options)
 - #118747 (Remove extra check cfg handled by libc directly)
 - #118774 (add test for inductive cycle hangs)
 - #118775 (chore: add test case for type with generic)
 - #118782 (use `&` instead of start-process in x.ps1)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-12-10 01:02:42 +00:00
Ben Kimock
b0a580112b Use immediate_backend_type when reading from a const alloc 2023-12-09 17:13:11 -05:00
bors
06e02d5b25 Auto merge of #118308 - Nadrieril:sound-exhaustive-patterns-take-3, r=compiler-errors
Don't warn an empty pattern unreachable if we're not sure the data is valid

Exhaustiveness checking used to be naive about the possibility of a place containing invalid data. This could cause it to emit an "unreachable pattern" lint on an arm that was in fact reachable, as in https://github.com/rust-lang/rust/issues/117119.

This PR fixes that. We now track whether a place that is matched on may hold invalid data. This also forced me to be extra precise about how exhaustiveness manages empty types.

Note that this now errs in the opposite direction: the following arm is truly unreachable (because the binding causes a read of the value) but not linted as such. I'd rather not recommend writing a `match ... {}` that has the implicit side-effect of loading the value. [Never patterns](https://github.com/rust-lang/rust/issues/118155) will solve this cleanly.
```rust
match union.value {
    _x => unreachable!(),
}
```

I recommend reviewing commit by commit. I went all-in on the test suite because this went through a lot of iterations and I kept everything. The bit I'm least confident in is `is_known_valid_scrutinee` in `check_match.rs`.

Fixes https://github.com/rust-lang/rust/issues/117119.
2023-12-09 19:03:03 +00:00
Michael Goulet
afa35e90ef Print constness in TraitPredPrintModifiersAndPath 2023-12-09 17:55:07 +00:00
Michael Goulet
f1bf874fb1 Don't print host effect param in pretty path_generic_args 2023-12-09 17:42:33 +00:00
Guillaume Gomez
034d73d6d7
Rollup merge of #118775 - Young-Flash:fix, r=compiler-errors
chore: add test case for type with generic

follow up https://github.com/rust-lang/rust/pull/118502
2023-12-09 18:00:37 +01:00
Guillaume Gomez
5b9e917b64
Rollup merge of #118774 - lcnr:region-refactor-uwu, r=compiler-errors
add test for inductive cycle hangs

the same pattern is already tested for coinductive cycles, but I now understand the underlying issue and want to make sure we also test it for inductive ones

r? `@compiler-errors`
2023-12-09 18:00:37 +01:00
Lenko Donchev
69a2bd6c04 report_not_const_evaluatable_error to avoid ICEing on ConstKind::Expr 2023-12-09 10:19:19 -06:00
bors
08587a56f1 Auto merge of #118780 - GuillaumeGomez:rollup-nd0syaf, r=GuillaumeGomez
Rollup of 6 pull requests

Successful merges:

 - #117953 (Add more SIMD platform-intrinsics)
 - #118057 (dedup for duplicate suggestions)
 - #118638 (More `rustc_mir_dataflow` cleanups)
 - #118702 (Strengthen well known check-cfg names and values test)
 - #118734 (Unescaping cleanups)
 - #118766 (Lower some forgotten spans)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-12-09 14:35:10 +00:00
jyn
32e48fc36b use different revisions for testing colors on windows
this is kinda jank because it means people need both machines to bless the tests
2023-12-09 08:53:20 -05:00
Guillaume Gomez
a1c252fccd
Rollup merge of #118734 - nnethercote:literal-cleanups, r=fee1-dead
Unescaping cleanups

Minor improvements I found while working on #118699.

r? `@fee1-dead`
2023-12-09 14:05:11 +01:00
Guillaume Gomez
78d2c8e637
Rollup merge of #118702 - Urgau:check-cfg-strengthen-well-known, r=nnethercote
Strengthen well known check-cfg names and values test

https://github.com/rust-lang/rust/pull/118494 is changing the implementation of how we expect well known check-cfg names and values, but we currently don't have a test that checks every well known only some of them.

This PR therefore strengthen our well known names/values test to include all of the configs to at least avoid unintended regressions and validate new entry.

*this PR also contains some drive-by consolidation of unexpected `target_os`, `target_arch` into a single file*

r? `@nnethercote` (maybe? feel free to re-assign)
2023-12-09 14:05:10 +01:00
Guillaume Gomez
0865eefcaf
Rollup merge of #118057 - bvanjoi:fix-118048, r=cjgillot
dedup for duplicate suggestions

Fixes #118048

An easy fix.
2023-12-09 14:05:09 +01:00
Guillaume Gomez
c57b0549af
Rollup merge of #117953 - farnoy:masked-load-store, r=workingjubilee
Add more SIMD platform-intrinsics

- [x] simd_masked_load
  - [x] LLVM codegen - llvm.masked.load
  - [x] cranelift codegen - implemented but untested
- [ ] simd_masked_store
  - [x] LLVM codegen - llvm.masked.store
  - [ ] cranelift codegen

Also added a run-pass test to test both intrinsics, and additional build-fail & check-fail to cover validation for both intrinsics
2023-12-09 14:05:09 +01:00
bors
1dfb2283d7 Auto merge of #116170 - matthewjasper:remove-thir-destruction-scopes, r=cjgillot
Don't include destruction scopes in THIR

They are not used by anyone, and add memory/performance overhead.
2023-12-09 12:38:32 +00:00
Jakub Okoński
97ae5095f5
Add simd_masked_{load,store} platform-intrinsics
This maps to the LLVM intrinsics: llvm.masked.load and llvm.masked.store
2023-12-09 12:36:08 +01:00
Urgau
4c1671674e Avoid target_os and target_arch in some check-cfg tests
as they unnecessarily clutter the diagnostic output and make the
experience of adding a new target to the compiler more painful than
it should be.

target_os and target_arch are still being tested in the
well-known-values.rs test, but in one place.
2023-12-09 11:59:46 +01:00
Urgau
bba9862b95 Strengthen well known check-cfg names and values test 2023-12-09 11:59:46 +01:00
lcnr
ef796db5f0 add test for inductive cycle hangs 2023-12-09 10:35:07 +00:00
Young-Flash
cb6984217f chore: add test case for type with generic 2023-12-09 17:49:40 +08:00
Jubilee
61dfb1f8d0
Rollup merge of #118764 - compiler-errors:fused-async-iterator, r=eholk
Make async generators fused by default

I actually changed my mind about this since the implementation PR landed. I think it's beneficial for `async gen` blocks to be "fused" by default -- i.e., for them to repeatedly return `Poll::Ready(None)` -- rather than panic.

We have [`FusedStream`](https://docs.rs/futures/latest/futures/stream/trait.FusedStream.html) in futures-rs to represent streams with this capability already anyways.

r? eholk
cc ```@rust-lang/wg-async,``` would like to know if anyone else has opinions about this.
2023-12-09 00:48:11 -08:00
Jubilee
85c9de9799
Rollup merge of #118610 - krasimirgg:llvm-18-dec, r=nikic
update target feature following LLVM API change

LLVM commit e817966718 renamed* the `unaligned-scalar-mem` target feature to `fast-unaligned-access`.

(*) technically the commit folded two previous features into one, but there are no references to the other one in rust.
2023-12-09 00:48:09 -08:00
Jubilee
8f9d8277de
Rollup merge of #118512 - spastorino:add-implied-bounds-related-tests, r=jackh726
Add tests related to normalization in implied bounds

Getting ```@aliemjay's``` tests from #109763, so we can better track what's going on in every different example.

r? ```@jackh726```
2023-12-09 00:48:09 -08:00
Nadrieril
ddef5b61f1 Don't warn an empty pattern unreachable if we're not sure the data is valid 2023-12-09 00:44:49 +01:00
Nadrieril
4e376cc104 Test empty types better 2023-12-09 00:39:59 +01:00
David Tolnay
6f1d7631fb
Do not parenthesize exterior struct lit inside match guards 2023-12-08 15:15:42 -08:00
David Tolnay
419b26931b
Add if_let_guard and let_chains pretty printer tests 2023-12-08 15:14:43 -08:00
Santiago Pastorino
7079adb226
Add Bevy related test cases 2023-12-08 20:14:23 -03:00
Nicholas Nethercote
9741dba7fa Tweak the no-nuls.rs test.
The `empty!` macro calls should be outside the `cfg(FALSE)` function.
2023-12-09 09:30:32 +11:00
Michael Goulet
e987812521 Make async generators fused by default 2023-12-08 22:25:12 +00:00
Matthias Krüger
a255b52525
Rollup merge of #118736 - aliemjay:revert-ice-on-ambig, r=compiler-errors
temporarily revert "ice on ambguity in mir typeck"

Reverts #116530 as a temporary measure to fix #117577. That issue should be ultimately fixed by checking WF of type annotations prior to normalization, which is implemented in #104098 but this PR is intended to be backported to beta.

r? ``@compiler-errors`` (the reviewer of the reverted PR)
2023-12-08 23:15:14 +01:00
Matthias Krüger
943fa33daf
Rollup merge of #118730 - jyn514:cmp_refs, r=estebank,compiler-errors
recurse into refs when comparing tys for diagnostics

before:
![image](https://github.com/rust-lang/rust/assets/23638587/bf6abd62-c7f3-4c09-a47e-31b6e129de19)

after:
![image](https://github.com/rust-lang/rust/assets/23638587/b704d728-ddba-4204-aebe-c07dcbbcb55c)

this diff from the test suite is also quite nice imo:
```diff
`@@` -4,8 +4,8 `@@` error[E0308]: mismatched types
 LL |     debug_assert_eq!(iter.next(), Some(value));
    |                                   ^^^^^^^^^^^ expected `Option<<I as Iterator>::Item>`, found `Option<&<I as Iterator>::Item>`
    |
-   = note: expected enum `Option<<I as Iterator>::Item>`
-              found enum `Option<&<I as Iterator>::Item>`
+   = note: expected enum `Option<_>`
+              found enum `Option<&_>`
```
2023-12-08 23:15:13 +01:00
Matthias Krüger
d2de292017
Rollup merge of #118715 - davidtwco:issue-117997-privacy-visit-trait-ref-and-args, r=TaKO8Ki
privacy: visit trait def id of projections

Fixes #117997.

A refactoring in #117076 changed the `DefIdVisitorSkeleton` to avoid calling `visit_projection_ty` for `ty::Projection` aliases, and instead just iterate over the args - this makes sense, as `visit_projection_ty` will indirectly visit all of the same args, but in doing so, will also create a `TraitRef` containing the trait's `DefId`, which also gets visited. The trait's `DefId` isn't visited when we only visit the arguments without separating them into `TraitRef` and own args first.

Eventually this influences the reachability set and whether a function is encoded into the metadata.
2023-12-08 23:15:13 +01:00
Matthias Krüger
9041d1cec0
Rollup merge of #118502 - Young-Flash:fix, r=compiler-errors
fix: correct the arg for 'suggest to use associated function syntax' diagnostic

close https://github.com/rust-lang/rust/issues/118469
2023-12-08 23:15:12 +01:00
Santiago Pastorino
287c77e921
Add tests related to normalization in implied bounds 2023-12-08 17:48:59 -03:00
Michael Goulet
d473bdfdc3 Support bare unit structs in destructuring assignments 2023-12-08 19:55:07 +00:00
jyn
96b027f35d use magenta instead of bold for highlighting
according to a poll of gay people in my phone, purple is the most popular color to use for highlighting

| color      | percentage |
| ---------- | ---------- |
| bold white | 6%         |
| blue       | 14%        |
| cyan       | 26%        |
| purple     | 37%        |
| magenta    | 17%        |

unfortunately, purple is not supported by 16-color terminals, which rustc apparently wants to support for some reason.
until we require support for full 256-color terms (e.g. by doing the same feature detection as we currently do for urls), we can't use it.

instead, i have collapsed the purple votes into magenta on the theory that they're close, and also because magenta is pretty.
2023-12-08 14:30:48 -05:00
bors
f967532a47 Auto merge of #118420 - compiler-errors:async-gen, r=eholk
Introduce support for `async gen` blocks

I'm delighted to demonstrate that `async gen` block are not very difficult to support. They're simply coroutines that yield `Poll<Option<T>>` and return `()`.

**This PR is WIP and in draft mode for now** -- I'm mostly putting it up to show folks that it's possible. This PR needs a lang-team experiment associated with it or possible an RFC, since I don't think it falls under the jurisdiction of the `gen` RFC that was recently authored by oli (https://github.com/rust-lang/rfcs/pull/3513, https://github.com/rust-lang/rust/issues/117078).

### Technical note on the pre-generator-transform yield type:

The reason that the underlying coroutines yield `Poll<Option<T>>` and not `Poll<T>` (which would make more sense, IMO, for the pre-transformed coroutine), is because the `TransformVisitor` that is used to turn coroutines into built-in state machine functions would have to destructure and reconstruct the latter into the former, which requires at least inserting a new basic block (for a `switchInt` terminator, to match on the `Poll` discriminant).

This does mean that the desugaring (at the `rustc_ast_lowering` level) of `async gen` blocks is a bit more involved. However, since we already need to intercept both `.await` and `yield` operators, I don't consider it much of a technical burden.

r? `@ghost`
2023-12-08 19:13:57 +00:00
Michael Goulet
11375c8657 Add tests 2023-12-08 17:23:26 +00:00
Michael Goulet
a208bae00e Support async gen fn 2023-12-08 17:23:26 +00:00
bors
2b399b5275 Auto merge of #118527 - Nadrieril:never_patterns_parse, r=compiler-errors
never_patterns: Parse match arms with no body

Never patterns are meant to signal unreachable cases, and thus don't take bodies:
```rust
let ptr: *const Option<!> = ...;
match *ptr {
    None => { foo(); }
    Some(!),
}
```
This PR makes rustc accept the above, and enforces that an arm has a body xor is a never pattern. This affects parsing of match arms even with the feature off, so this is delicate. (Plus this is my first non-trivial change to the parser).

~~The last commit is optional; it introduces a bit of churn to allow the new suggestions to be machine-applicable. There may be a better solution? I'm not sure.~~ EDIT: I removed that commit

r? `@compiler-errors`
2023-12-08 17:08:52 +00:00
David Wood
5d97724002
privacy: visit trait def id of projections
A refactoring in #117076 changed the `DefIdVisitorSkeleton` to avoid
calling `visit_projection_ty` for `ty::Projection` aliases, and instead
just iterate over the args - this makes sense, as `visit_projection_ty`
will indirectly visit all of the same args, but in doing so, will also
create a `TraitRef` containing the trait's `DefId`, which also gets
visited. The trait's `DefId` isn't visited when we only visit the
arguments without separating them into `TraitRef` and own args first.

Signed-off-by: David Wood <david@davidtw.co>
2023-12-08 14:26:03 +00:00
bors
ae612bedcb Auto merge of #118689 - compiler-errors:const-drop, r=fee1-dead
Fix const drop checking

Fixes confirmation of `~const Destruct` and const drops.

r? fee1-dead
2023-12-08 13:43:12 +00:00
Krasimir Georgiev
b378059e6b update target feature following LLVM API change
LLVM commit e817966718
renamed the `unaligned-scalar-mem` target feature to `fast-unaligned-access`.
2023-12-08 13:06:07 +00:00
bors
5ea62560f2 Auto merge of #118668 - fmease:resolve-assoc-item-bindings-by-namespace, r=compiler-errors
Resolve associated item bindings by namespace

This is the 3rd commit split off from #118360 with tests reblessed (they no longer contain duplicated diags which were caused by 4c0addc80a) & slightly adapted (removed supertraits from a UI test, cc #118040).

> * Resolve all assoc item bindings (type, const, fn (feature `return_type_notation`)) by namespace instead of trying to resolve a type first (in the non-RTN case) and falling back to consts afterwards. This is consistent with RTN. E.g., for `Tr<K = {…}>` we now always try to look up assoc consts (this extends to supertrait bounds). This gets rid of assoc tys shadowing assoc consts in assoc item bindings which is undesirable & inconsistent (types and consts live in different namespaces after all)
> * Consolidate the resolution of assoc {ty, const} bindings and RTN (dedup, better diags for RTN)
> * Fix assoc consts being labeled as assoc *types* in several diagnostics
> * Make a bunch of diagnostics translatable

Fixes #112560 (error → pass).

As discussed
r? `@compiler-errors`

---

**Addendum**: What I call “associated item bindings” are commonly referred to as “type bindings” for historical reasons. Nowadays, “type bindings” include assoc type bindings, assoc const bindings and RTN (return type notation) which is why I prefer not to use this outdated term.
2023-12-08 09:30:52 +00:00
Ali MJ Al-Nasrawy
5fdb648fc3 temporarily revert "ice on ambguity in mir typeck"
Reverts #116530
2023-12-08 07:49:06 +00:00
jyn
eb53721a34 recurse into refs when comparing tys for diagnostics 2023-12-07 23:00:46 -05:00
bors
21982a4383 Auto merge of #118725 - lcnr:normalizes-to-projection-split-3, r=BoxyUwU
split `NormalizesTo` out of `Projection` 3

third attempt at #112658. Rebasing #116262 is very annoying, so I am doing it again from scratch. We should now be able to merge it without regressing anything as we handle occurs check failures involving aliases correctly since #117088.

see https://hackmd.io/ktEL8knTSYmtdfrMMnA-Hg

fixes https://github.com/rust-lang/trait-system-refactor-initiative/issues/1

r? `@compiler-errors`
2023-12-08 02:28:10 +00:00
Josh Stone
b99b5e5752 Enable stack probes on aarch64 for LLVM 18 2023-12-07 17:17:00 -08:00
lcnr
1490c58076 add regression tests 2023-12-08 01:34:40 +01:00
lcnr
ffb4c08a81 implement and use NormalizesTo 2023-12-08 01:31:18 +01:00
bors
d6fa38a9b2 Auto merge of #118442 - tmiasko:fuel-inc, r=lqd
-Zfuel is incompatible with incremental compilation
2023-12-08 00:28:32 +00:00
Tomasz Miąsko
1a47e413b2 Fuel is incompatible with incremental compilation 2023-12-08 00:00:00 +00:00
León Orell Valerian Liehr
55559d93e7
Resolve assoc item bindings by namespace
If a const is expected, resolve a const.
If a type is expected, resolve a type.
Don't try to resolve a type first falling back to consts.
2023-12-07 22:33:56 +01:00
Matthias Krüger
71a8ca0522
Rollup merge of #116420 - bvanjoi:fix-116203, r=Nilstrieb
discard invalid spans in external blocks

Fixes #116203

This PR has discarded the invalid `const_span`, thereby making the format more neat.

r? ``@Nilstrieb``
2023-12-07 21:38:07 +01:00
bors
0e7f91b75e Auto merge of #118324 - RalfJung:ctfe-read-only-pointers, r=saethlin
compile-time evaluation: detect writes through immutable pointers

This has two motivations:
- it unblocks https://github.com/rust-lang/rust/pull/116745 (and therefore takes a big step towards `const_mut_refs` stabilization), because we can now detect if the memory that we find in `const` can be interned as "immutable"
- it would detect the UB that was uncovered in https://github.com/rust-lang/rust/pull/117905, which was caused by accidental stabilization of `copy` functions in `const` that can only be called with UB

When UB is detected, we emit a future-compat warn-by-default lint. This is not a breaking change, so completely in line with [the const-UB RFC](https://rust-lang.github.io/rfcs/3016-const-ub.html), meaning we don't need t-lang FCP here. I made the lint immediately show up for dependencies since it is nearly impossible to even trigger this lint without `const_mut_refs` -- the accidentally stabilized `copy` functions are the only way this can happen, so the crates that popped up in #117905 are the only causes of such UB (in the code that crater covers), and the three cases of UB that we know about have all been fixed in their respective crates already.

The way this is implemented is by making use of the fact that our interpreter is already generic over the notion of provenance. For CTFE we now use the new `CtfeProvenance` type which is conceptually an `AllocId` plus a boolean `immutable` flag (but packed for a more efficient representation). This means we can mark a pointer as immutable when it is created as a shared reference. The flag will be propagated to all pointers derived from this one. We can then check the immutable flag on each write to reject writes through immutable pointers.

I just hope perf works out.
2023-12-07 18:11:01 +00:00
Ralf Jung
29c95e98e3 also print 'immutable' flag 2023-12-07 17:46:36 +01:00
Ralf Jung
4d93590d59 compile-time evaluation: emit a lint when a write through an immutable pointer occurs 2023-12-07 17:46:36 +01:00
Michael Goulet
efe8ae730f Fix const drop checking 2023-12-07 16:28:33 +00:00
bors
8235469e48 Auto merge of #118687 - matthiaskrgr:rollup-317ztgu, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #117981 (Remove deprecated `--check-cfg` syntax)
 - #118177 (Suppress warnings in LLVM wrapper when targeting MSVC)
 - #118317 (tip for define macro name after `macro_rules!`)
 - #118504 (Enforce `must_use` on associated types and RPITITs that have a must-use trait in bounds)
 - #118660 (rustc_arena: add `alloc_str`)
 - #118681 (Fix is_foreign_item for StableMIR instance )

r? `@ghost`
`@rustbot` modify labels: rollup
2023-12-06 22:23:25 +00:00
Matthias Krüger
1b391d4ae4
Rollup merge of #118504 - compiler-errors:must-use, r=WaffleLapkin
Enforce `must_use` on associated types and RPITITs that have a must-use trait in bounds

Warn when an RPITIT or (un-normalized) associated type with a `#[must_use]` trait in its bounds is unused.

This is pending T-lang approval, since it changes the semantics of the `#[must_use]` attribute slightly, but I think it strictly catches more strange errors.

I could also limit this to just RPITITs, but that seems less useful.

Fixes #118444
2023-12-06 21:52:32 +01:00
Matthias Krüger
aefbbc6dc6
Rollup merge of #118317 - bvanjoi:fix-118295, r=petrochenkov
tip for define macro name after `macro_rules!`

Fixes #118295

~Note that there are some bad case such as `macro_rules![]` or `macro_rules!()`. However, I think these are acceptable as they are likely to be seldom used (feel free to close this if you think its shortcomings outweigh its benefits)~

Edit: this problem was resolved by utilizing the `source_map.span_to_next_source`.

r? `@petrochenkov`
2023-12-06 21:52:31 +01:00
Matthias Krüger
f546b44ecd
Rollup merge of #117981 - Urgau:check-cfg-remove-deprecated-syntax, r=b-naber
Remove deprecated `--check-cfg` syntax

This PR removes the deprecated `--check-cfg` `names(...)` and `values(...)` syntax.

Follow up to https://github.com/rust-lang/rust/pull/111072
Part of https://github.com/rust-lang/compiler-team/issues/636

r? compiler
2023-12-06 21:52:30 +01:00
bors
1fdfe12347 Auto merge of #117936 - mu001999:master, r=petrochenkov
Use the glob binding in resolve_rustdoc_path process

Fixes #117920

Returning `None` seems enough.

I reproduces and tests this locally by `cargo +stage1 build`, but I cannot reproduce this ICE by putting [the following code](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=8b3ca8f4a7676eb90baf30437ba041a2) into `tests/ui/...` and then compiling it using `rustc +stage1 /path/to/test.rs` or `x.py test`:
```rust
#![crate_type = "lib"]

use super::Hasher;

/// [`Hasher`]
pub use core:#️⃣:*;
```

r? `@petrochenkov`
2023-12-06 20:25:17 +00:00
bors
7a34091eed Auto merge of #118679 - matthiaskrgr:rollup-zr1l9w6, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #116496 (Provide context when `?` can't be called because of `Result<_, E>`)
 - #117563 (docs: clarify explicitly freeing heap allocated memory)
 - #117874 (`riscv32` platform support)
 - #118516 (Add ADT variant infomation to StableMIR and finish implementing TyKind::internal())
 - #118650 (add comment about keeping flags in sync between bootstrap.py and bootstrap.rs)
 - #118664 (docs: remove #110800 from release notes)
 - #118669 (library: fix comment about const assert in win api)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-12-06 17:59:19 +00:00
Matthias Krüger
f1e180451b
Rollup merge of #116496 - estebank:question-method-chain-context, r=compiler-errors
Provide context when `?` can't be called because of `Result<_, E>`

When a method chain ending in `?` causes an E0277 because the expression's `Result::Err` variant doesn't have a type that can be converted to the `Result<_, E>` type parameter in the return type, provide additional context of which parts of the chain can and can't support the `?` operator.

```
error[E0277]: `?` couldn't convert the error to `String`
  --> $DIR/question-mark-result-err-mismatch.rs:27:25
   |
LL | fn bar() -> Result<(), String> {
   |             ------------------ expected `String` because of this
LL |     let x = foo();
   |             ----- this has type `Result<_, String>`
...
LL |         .map_err(|_| ())?;
   |          ---------------^ the trait `From<()>` is not implemented for `String`
   |          |
   |          this can't be annotated with `?` because it has type `Result<_, ()>`
   |
   = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
   = help: the following other types implement trait `From<T>`:
             <String as From<char>>
             <String as From<Box<str>>>
             <String as From<Cow<'a, str>>>
             <String as From<&str>>
             <String as From<&mut str>>
             <String as From<&String>>
   = note: required for `Result<(), String>` to implement `FromResidual<Result<Infallible, ()>>`
```

Fix #72124.
2023-12-06 17:21:56 +01:00
bors
f32d29837d Auto merge of #118605 - fee1-dead-contrib:rm-rustc_host, r=compiler-errors
Remove `#[rustc_host]`, use internal desugaring

Also removed a way for users to explicitly specify the host param since that isn't particularly useful. This should eliminate any pain with encoding attributes across crates and etc.

r? `@compiler-errors`
2023-12-06 16:00:24 +00:00
bohan
0f14e8ea74 tip for define macro name after macro_rules! 2023-12-06 23:19:39 +08:00
r0cky
940473adb4 Use the glob binding in resolve_rustdoc_path process 2023-12-06 21:48:19 +08:00
bors
dd6126ef56 Auto merge of #117661 - TheLazyDutchman:point_out_shadowed_associated_types, r=petrochenkov
Added shadowed hint for overlapping associated types

Previously, when you tried to set an associated type that is shadowed by an associated type in a subtrait, like this:

```rust
trait A {
    type X;
}

trait B: A {
    type X; // note: this is legal
}

impl<Y> Clone for Box<dyn B<X=Y, X=Y>> {
    fn clone(&self) -> Self {
        todo!()
    }
}

you got a confusing error message, that says nothing about the shadowing:

error[E0719]: the value of the associated type `X` (from trait `B`) is already specified
 --> test.rs:9:34
  |
9 | impl<Y> Clone for Box<dyn B<X=Y, X=Y>> {
  |                             ---  ^^^ re-bound here
  |                             |
  |                             `X` bound here first

error[E0191]: the value of the associated type `X` (from trait `A`) must be specified
 --> test.rs:9:27
  |
2 |     type X;
  |     ------ `X` defined here
...
9 | impl<Y> Clone for Box<dyn B<X=Y, X=Y>> {
  |                           ^^^^^^^^^^^ help: specify the associated type: `B<X=Y, X=Y, X = Type>`

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0191, E0719.
For more information about an error, try `rustc --explain E0191`.
```

Now instead, the error shows that the associated type is shadowed, and suggests renaming as a potential fix.

```rust
error[E0719]: the value of the associated type `X` in trait `B` is already specified
 --> test.rs:9:34
  |
9 | impl<Y> Clone for Box<dyn B<X=Y, X=Y>> {
  |                             ---  ^^^ re-bound here
  |                             |
  |                             `X` bound here first

error[E0191]: the value of the associated type `X` in `A` must be specified
 --> test.rs:9:27
  |
2 |     type X;
  |     ------ `A::X` defined here
...
6 |     type X; // note: this is legal
  |     ------ `A::X` shadowed here
...
9 | impl<Y> Clone for Box<dyn B<X=Y, X=Y>> {
  |                           ^^^^^^^^^^^ associated type `X` must be specified
  |
help: consider renaming this associated type
 --> test.rs:2:5
  |
2 |     type X;
  |     ^^^^^^
help: consider renaming this associated type
 --> test.rs:6:5
  |
6 |     type X; // note: this is legal
  |     ^^^^^^
```

error: aborting due to 2 previous errors

Some errors have detailed explanations: E0191, E0719.
For more information about an error, try `rustc --explain E0191`.

The rename help message is only emitted when the trait is local. This is true both for the supertrait as for the subtrait.

There might be cases where you can use the fully qualified path (for instance, in a where clause), but this PR currently does not deal with that.

fixes #100109

(continues from #117642, because I didn't know renaming the branch would close the PR)
2023-12-06 10:59:24 +00:00
TheLazyDutchman
3234418806 Point out shadowed associated types
Shadowing the associated type of a supertrait is allowed.
This however makes it impossible to set the associated type
of the supertrait in a dyn object.

This PR makes the error message for that case clearer, like
adding a note that shadowing is happening, as well as suggesting
renaming of one of the associated types.

r=petrochenckov
2023-12-06 11:05:22 +01:00
Urgau
5e1bfb538f Adjust tests for newly added ambiguous_wide_pointer_comparisons lint 2023-12-06 09:03:48 +01:00
Urgau
5630540ac0 Add warn-by-default lint against ambiguous wide pointer comparisons 2023-12-06 09:03:48 +01:00
bors
1dd4db5062 Auto merge of #118655 - compiler-errors:rollup-vrngyzn, r=compiler-errors
Rollup of 9 pull requests

Successful merges:

 - #117793 (Update variable name to fix `unused_variables` warning)
 - #118123 (Add support for making lib features internal)
 - #118268 (Pretty print `Fn<(..., ...)>` trait refs with parentheses (almost) always)
 - #118346 (Add `deeply_normalize_for_diagnostics`, use it in coherence)
 - #118350 (Simplify Default for tuples)
 - #118450 (Use OnceCell in cell module documentation)
 - #118585 (Fix parser ICE when recovering `dyn`/`impl` after `for<...>`)
 - #118587 (Cleanup error handlers some more)
 - #118642 (bootstrap(builder.rs): Don't explicitly warn against `semicolon_in_expressions_from_macros`)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-12-06 04:20:51 +00:00
Esteban Küber
70fe624b3d Reduce verbosity of error 2023-12-05 22:24:33 +00:00
Esteban Küber
98e5317173 Detect incorrect ; in Option::ok_or_else and Result::map_err
Fix #72124.
2023-12-05 22:24:29 +00:00
Esteban Küber
53817963ed Point at fewer methods in the chain, only those that change the E type 2023-12-05 22:22:13 +00:00
Esteban Küber
6c3879d1f1 Provide context when ? can't be called because of Result<_, E>
When a method chain ending in `?` causes an E0277 because the
expression's `Result::Err` variant doesn't have a type that can be
converted to the `Result<_, E>` type parameter in the return type,
provide additional context of which parts of the chain can and can't
support the `?` operator.

```
error[E0277]: `?` couldn't convert the error to `String`
  --> $DIR/question-mark-result-err-mismatch.rs:28:25
   |
LL | fn bar() -> Result<(), String> {
   |             ------------------ expected `String` because of this
LL |     let x = foo();
   |             ----- this can be annotated with `?` because it has type `Result<String, String>`
LL |     let one = x
LL |         .map(|s| ())
   |          ----------- this can be annotated with `?` because it has type `Result<(), String>`
LL |         .map_err(|_| ())?;
   |          ---------------^ the trait `From<()>` is not implemented for `String`
   |          |
   |          this can't be annotated with `?` because it has type `Result<(), ()>`
   |
   = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
   = help: the following other types implement trait `From<T>`:
             <String as From<char>>
             <String as From<Box<str>>>
             <String as From<Cow<'a, str>>>
             <String as From<&str>>
             <String as From<&mut str>>
             <String as From<&String>>
   = note: required for `Result<(), String>` to implement `FromResidual<Result<Infallible, ()>>`
```

Fix #72124.
2023-12-05 22:22:08 +00:00
Michael Goulet
803772e81d Enable new capture rules by default on edition 2024 2023-12-05 19:53:59 +00:00
Michael Goulet
acba7efe1b Add test for implicitly capturing late-bound var with new capture rules 2023-12-05 19:53:59 +00:00
Michael Goulet
0ad160a585 Add lifetime_capture_rules_2024 2023-12-05 19:53:59 +00:00
Michael Goulet
dbcde57171
Rollup merge of #118585 - sjwang05:issue-118564, r=compiler-errors
Fix parser ICE when recovering `dyn`/`impl` after `for<...>`

Fixes #118564
2023-12-05 14:52:43 -05:00
Michael Goulet
598ca0ea3f
Rollup merge of #118346 - compiler-errors:deeply-normalize-for-diagnostic, r=lcnr
Add `deeply_normalize_for_diagnostics`, use it in coherence

r? lcnr

Normalize trait refs used for coherence error reporting with `-Ztrait-solver=next-coherence`.

Two things:
1. I said before that we can't add this to `TyErrCtxt` because we compute `OverlapResult`s even if there are no diagnostics being emitted, e.g. for a reservation impl.
2. I didn't want to add this to an `InferCtxtExt` trait because I felt it was unnecessary. I don't particularly care about the API though.
2023-12-05 14:52:42 -05:00
Michael Goulet
ad23f30b1d
Rollup merge of #118268 - compiler-errors:pretty-print, r=estebank
Pretty print `Fn<(..., ...)>` trait refs with parentheses (almost) always

It's almost always better, at least in diagnostics, to print `Fn(i32, u32)` instead of `Fn<(i32, u32)>`.

Related to but doesn't fix #118225. That needs a separate fix.
2023-12-05 14:52:41 -05:00
Michael Goulet
19bf749560
Rollup merge of #118123 - RalfJung:internal-lib-features, r=compiler-errors
Add support for making lib features internal

We have the notion of an "internal" lang feature: a feature that is never intended to be stabilized, and using which can cause ICEs and other issues without that being considered a bug.

This extends that idea to lib features as well. It is an alternative to https://github.com/rust-lang/rust/pull/115623: instead of using an attribute to declare lib features internal, we simply do this based on the name. Everything ending in `_internals` or `_internal` is considered internal.

Then we rename `core_intrinsics` to `core_intrinsics_internal`, which fixes https://github.com/rust-lang/rust/issues/115597.
2023-12-05 14:52:41 -05:00
Trevor Gross
b225aab5ef Stabilize type_name_of_val
Make the following API stable:

    // in core::any
    pub fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str

Const stability is not added because this relies on `type_name` which is also
not const. That has a blocking issue.

Fixes #66359
2023-12-05 14:49:09 -05:00
bors
56278a6e28 Auto merge of #118457 - eholk:genfn, r=compiler-errors
Add support for `gen fn`

This builds on #116447 to add support for `gen fn` functions. For the most part we follow the same approach as desugaring `async fn`, but replacing `Future` with `Iterator` and `async {}` with `gen {}` for the body.

The version implemented here uses the return type of a `gen fn` as the yield type. For example:

```rust
gen fn count_to_three() -> i32 {
    yield 1;
    yield 2;
    yield 3;
}
```

In the future, I think we should experiment with a syntax like `gen fn count_to_three() yield i32 { ... }`, but that can go in another PR.

cc `@oli-obk` `@compiler-errors`
2023-12-05 18:37:15 +00:00
Michael Goulet
b97ff8eb16 Add print_trait_sugared 2023-12-05 17:15:46 +00:00
Michael Goulet
3448284f8d Continue folding if deep normalizer fails 2023-12-05 16:55:10 +00:00
Michael Goulet
334577f091 Add deeply_normalize_for_diagnostics, use it in coherence 2023-12-05 16:33:37 +00:00
Matthias Krüger
c6c0c658df
Rollup merge of #118608 - fee1-dead-contrib:backdoor-in-askconv, r=compiler-errors
Use default params until effects in desugaring

See the comment and [this section](https://fee1-dead.github.io/devlog001/#effects-desugaring-with-default-type-params) from my blog post

r? ``@compiler-errors``
2023-12-05 16:08:37 +01:00
Matthias Krüger
81b6263dd0
Rollup merge of #118598 - Nadrieril:remove_precise_pointer_size_matching, r=davidtwco
Remove the `precise_pointer_size_matching` feature gate

`usize` and `isize` are special for pattern matching because their range might depend on the platform. To make code portable across platforms, the following is never considered exhaustive:
```rust
let x: usize = ...;
match x {
    0..=18446744073709551615 => {}
}
```
Because of how rust handles constants, this also unfortunately counts `0..=usize::MAX` as non-exhaustive. The [`precise_pointer_size_matching`](https://github.com/rust-lang/rust/issues/56354) feature gate was introduced both for this convenience and for the possibility that the lang team could decide to allow the above.

Since then, [half-open range patterns](https://github.com/rust-lang/rust/issues/67264) have been implemented, and since #116692 they correctly support `usize`/`isize`:
```rust
match 0usize { // exhaustive!
    0..5 => {}
    5.. => {}
}
```
I believe this subsumes all the use cases of the feature gate. Moreover no attempt has been made to stabilize it in the 5 years of its existence. I therefore propose we retire this feature gate.

Closes https://github.com/rust-lang/rust/issues/56354
2023-12-05 16:08:35 +01:00
Matthias Krüger
2d01eeeeac
Rollup merge of #117922 - estebank:unclosed-generics, r=b-naber
Tweak unclosed generics errors

Remove unnecessary span label for parse errors that already have a suggestion.

Provide structured suggestion to close generics in more cases.
2023-12-05 16:08:34 +01:00
Urgau
3f0369e0f2 Remove deprecated --check-cfg names() and values() syntax 2023-12-05 13:25:11 +01:00
bors
f67523d0b3 Auto merge of #118076 - estebank:issue-109429, r=davidtwco
Tweak `.clone()` suggestion to work in more cases

When going through auto-deref, the `<T as Clone>` impl sometimes needs to be specified for rustc to actually clone the value and not the reference.

```
error[E0507]: cannot move out of dereference of `S`
  --> $DIR/needs-clone-through-deref.rs:15:18
   |
LL |         for _ in self.clone().into_iter() {}
   |                  ^^^^^^^^^^^^ ----------- value moved due to this method call
   |                  |
   |                  move occurs because value has type `Vec<usize>`, which does not implement the `Copy` trait
   |
note: `into_iter` takes ownership of the receiver `self`, which moves value
  --> $SRC_DIR/core/src/iter/traits/collect.rs:LL:COL
help: you can `clone` the value and consume it, but this might not be your desired behavior
   |
LL |         for _ in <Vec<usize> as Clone>::clone(&self.clone()).into_iter() {}
   |                  ++++++++++++++++++++++++++++++            +
```

When encountering a move error, look for implementations of `Clone` for the moved type. If there is one, check if all its obligations are met. If they are, we suggest cloning without caveats. If they aren't, we suggest cloning while mentioning the unmet obligations, potentially suggesting `#[derive(Clone)]` when appropriate.

```
error[E0507]: cannot move out of a shared reference
  --> $DIR/suggest-clone-when-some-obligation-is-unmet.rs:20:28
   |
LL |     let mut copy: Vec<U> = map.clone().into_values().collect();
   |                            ^^^^^^^^^^^ ------------- value moved due to this method call
   |                            |
   |                            move occurs because value has type `HashMap<T, U, Hash128_1>`, which does not implement the `Copy` trait
   |
note: `HashMap::<K, V, S>::into_values` takes ownership of the receiver `self`, which moves value
  --> $SRC_DIR/std/src/collections/hash/map.rs:LL:COL
help: you could `clone` the value and consume it, if the `Hash128_1: Clone` trait bound could be satisfied
   |
LL |     let mut copy: Vec<U> = <HashMap<T, U, Hash128_1> as Clone>::clone(&map.clone()).into_values().collect();
   |                            ++++++++++++++++++++++++++++++++++++++++++++           +
help: consider annotating `Hash128_1` with `#[derive(Clone)]`
   |
LL + #[derive(Clone)]
LL | pub struct Hash128_1;
   |
```

Fix #109429.

When encountering multiple mutable borrows, suggest cloning and adding
derive annotations as needed.

```
error[E0596]: cannot borrow `sm.x` as mutable, as it is behind a `&` reference
  --> $DIR/accidentally-cloning-ref-borrow-error.rs:32:9
   |
LL |     foo(&mut sm.x);
   |         ^^^^^^^^^ `sm` is a `&` reference, so the data it refers to cannot be borrowed as mutable
   |
help: `Str` doesn't implement `Clone`, so this call clones the reference `&Str`
  --> $DIR/accidentally-cloning-ref-borrow-error.rs:31:21
   |
LL |     let mut sm = sr.clone();
   |                     ^^^^^^^
help: consider annotating `Str` with `#[derive(Clone)]`
   |
LL + #[derive(Clone)]
LL | struct Str {
   |
help: consider specifying this binding's type
   |
LL |     let mut sm: &mut Str = sr.clone();
   |               ++++++++++
```

Fix #34629. Fix #76643. Fix #91532.
2023-12-05 06:34:44 +00:00
bors
9358642e3b Auto merge of #118066 - estebank:structured-use-suggestion, r=b-naber
Structured `use` suggestion on privacy error

When encoutering a privacy error on an item through a re-export that is accessible in an alternative path, provide a structured suggestion with that path.

```
error[E0603]: module import `mem` is private
  --> $DIR/private-std-reexport-suggest-public.rs:4:14
   |
LL |     use foo::mem;
   |              ^^^ private module import
   |
note: the module import `mem` is defined here...
  --> $DIR/private-std-reexport-suggest-public.rs:8:9
   |
LL |     use std::mem;
   |         ^^^^^^^^
note: ...and refers to the module `mem` which is defined here
  --> $SRC_DIR/std/src/lib.rs:LL:COL
   |
   = note: you could import this
help: import `mem` through the re-export
   |
LL |     use std::mem;
   |         ~~~~~~~~
```

Fix #42909.
2023-12-05 04:34:57 +00:00
Deadbeef
65212a07e7 Remove #[rustc_host], use internal desugaring 2023-12-05 01:15:21 +00:00
bors
25dca40751 Auto merge of #117088 - lcnr:generalize-alias, r=compiler-errors
generalize: handle occurs check failure in aliases

mostly fixes #105787, except for the `for<'a> fn(<<?x as OtherTrait>::Assoc as Trait<'a>>::Assoc) eq ?x` case in https://github.com/rust-lang/trait-system-refactor-initiative/issues/8.

r? `@compiler-errors`
2023-12-05 00:37:58 +00:00
Eric Holk
50ef8006eb
Address code review feedback 2023-12-04 14:33:46 -08:00
Esteban Küber
beaf31581a Structured use suggestion on privacy error
When encoutering a privacy error on an item through a re-export that is
accessible in an alternative path, provide a structured suggestion with
that path.

```
error[E0603]: module import `mem` is private
  --> $DIR/private-std-reexport-suggest-public.rs:4:14
   |
LL |     use foo::mem;
   |              ^^^ private module import
   |
note: the module import `mem` is defined here...
  --> $DIR/private-std-reexport-suggest-public.rs:8:9
   |
LL |     use std::mem;
   |         ^^^^^^^^
note: ...and refers to the module `mem` which is defined here
  --> $SRC_DIR/std/src/lib.rs:LL:COL
   |
   = note: you could import this
help: import `mem` through the re-export
   |
LL |     use std::mem;
   |         ~~~~~~~~
```

Fix #42909.
2023-12-04 22:26:08 +00:00