Commit Graph

38211 Commits

Author SHA1 Message Date
Nicholas Nethercote
9d908a2877 Use ForceCollect in parse_attr_item.
Instead of a `bool`. Because `ForceCollect` is used in this way
everywhere else.
2024-07-19 08:24:54 +10:00
Nicholas Nethercote
7d7e2a173a Don't always force collect tokens in recover_stmt_local_after_let.
Use a parameter to decide whether to force collect, as is done for the
closely related `parse_local_mk` method.
2024-07-19 08:24:53 +10:00
Nicholas Nethercote
e69ff1c106 Remove an unnecessary ForceCollect::Yes.
No need to collect tokens on this recovery path, because the parsed
statement isn't even looked at.
2024-07-19 08:20:57 +10:00
Michael Goulet
2f5a84ea16 Don't allow unsafe statics outside of extern blocks 2024-07-18 18:02:29 -04:00
Veera
4cad705017 Parser: Suggest Placing the Return Type After Function Parameters 2024-07-18 17:56:34 -04:00
Matthias Krüger
d1250bc1d5
Rollup merge of #127929 - estebank:addr_of, r=compiler-errors
Use more accurate span for `addr_of!` suggestion

Use a multipart suggestion instead of a single whole-span replacement:

```
error[E0796]: creating a shared reference to a mutable static
  --> $DIR/reference-to-mut-static-unsafe-fn.rs:10:18
   |
LL |         let _y = &X;
   |                  ^^ shared reference to mutable static
   |
   = note: this shared reference has lifetime `'static`, but if the static ever gets mutated, or a mutable reference is created, then any further use of this shared reference is Undefined Behavior
help: use `addr_of!` instead to create a raw pointer
   |
LL |         let _y = addr_of!(X);
   |                  ~~~~~~~~~ +
```
2024-07-18 23:05:24 +02:00
Matthias Krüger
11688370dd
Rollup merge of #127925 - compiler-errors:tag, r=lcnr
Remove tag field from `Relation`s

Can just use the relation name w/ `std::any::type_name`. Also changes some printing to use instrument. Also changes some instrument levels to `trace` since I expect relations are somewhat hot, so having them print on debug is probably noisy.

r? lcnr
2024-07-18 23:05:24 +02:00
Matthias Krüger
65de5d0472
Rollup merge of #127871 - compiler-errors:recursive, r=estebank
Mention that type parameters are used recursively on bivariance error

Right now when a type parameter is used recursively, even with indirection (so it has a finite size) we say that the type parameter is unused:

```
struct B<T>(Box<B<T>>);
```

This is confusing, because the type parameter is *used*, it just doesn't have its variance constrained. This PR tweaks that message to mention that it must be used *non-recursively*.

Not sure if we should actually mention "variance" here, but also I'd somewhat prefer we don't keep the power users in the dark w.r.t the real underlying issue, which is that the variance isn't constrained. That technical detail is reserved for a note, though.

cc `@fee1-dead`

Fixes #118976
Fixes #26283
Fixes #53191
Fixes #105740
Fixes #110466
2024-07-18 23:05:22 +02:00
Matthias Krüger
4d5ba0d2c7
Rollup merge of #127858 - Zalathar:pair-tree, r=Nadrieril
match lowering: Rename `MatchPair` to `MatchPairTree`

In #120904, `MatchPair` became able to store other match pairs as children, forming a tree. That has made the old name confusing, so this patch renames the type to `MatchPairTree`.

This PR also includes a patch renaming the `test` method to `pick_test_for_match_pair`, since it would conflict with the main change.

r? `@Nadrieril`
2024-07-18 23:05:22 +02:00
Matthias Krüger
50a90e394e
Rollup merge of #127835 - estebank:issue-127823, r=compiler-errors
Fix ICE in suggestion caused by `⩵` being recovered as `==`

The second suggestion shown here would previously incorrectly assume that the span corresponding to `⩵` was 2 bytes wide composed by 2 1 byte wide chars, so a span pointing at `==` could point only at one of the `=` to remove it. Instead, we now replace the whole thing (as we should have the whole time):

```
error: unknown start of token: \u{2a75}
  --> $DIR/unicode-double-equals-recovery.rs:1:16
   |
LL | const A: usize ⩵ 2;
   |                ^
   |
help: Unicode character '⩵' (Two Consecutive Equals Signs) looks like '==' (Double Equals Sign), but it is not
   |
LL | const A: usize == 2;
   |                ~~

error: unexpected `==`
  --> $DIR/unicode-double-equals-recovery.rs:1:16
   |
LL | const A: usize ⩵ 2;
   |                ^
   |
help: try using `=` instead
   |
LL | const A: usize = 2;
   |                ~
```

Fix #127823.
2024-07-18 23:05:21 +02:00
Trevor Gross
8410348b1c Update the binary_asm_label message
The link pointed to a closed issue. Create a new one and point the link
to it.

Also add a help message to hint what change the user could make.

Fixes: https://github.com/rust-lang/rust/issues/127821
2024-07-18 17:00:43 -04:00
Michael Goulet
e0ba1931f4 Revert "sort suggestions for object diagnostic"
This reverts commit 540be28f6c.
2024-07-18 16:51:06 -04:00
Michael Goulet
d4fa5648c3 Move query providers 2024-07-18 16:47:00 -04:00
Michael Goulet
b5d0608761 Avoid unnecessary sorting of traits 2024-07-18 16:41:44 -04:00
Esteban Küber
9dffe9573b Make unicode text flow control chars visible as �
We already point these out quite aggressively, telling people not to use them, but would normally be rendered as nothing. Having them visible will make it easier for people to actually deal with them.

```
error: unicode codepoint changing visible direction of text present in literal
  --> $DIR/unicode-control-codepoints.rs:26:22
   |
LL |     println!("{:?}", '�');
   |                      ^-^
   |                      ||
   |                      |'\u{202e}'
   |                      this literal contains an invisible unicode text flow control codepoint
   |
   = note: these kind of unicode codepoints change the way text flows on applications that support them, but can cause confusion because they change the order of characters on the screen
   = help: if their presence wasn't intentional, you can remove them
help: if you want to keep them but make them visible in your source code, you can escape them
   |
LL |     println!("{:?}", '\u{202e}');
   |                       ~~~~~~~~
```

vs the previous

```
error: unicode codepoint changing visible direction of text present in literal
  --> $DIR/unicode-control-codepoints.rs:26:22
   |
LL |     println!("{:?}", '');
   |                      ^-
   |                      ||
   |                      |'\u{202e}'
   |                      this literal contains an invisible unicode text flow control codepoint
   |
   = note: these kind of unicode codepoints change the way text flows on applications that support them, but can cause confusion because they change the order of characters on the screen
   = help: if their presence wasn't intentional, you can remove them
help: if you want to keep them but make them visible in your source code, you can escape them
   |
LL |     println!("{:?}", '\u{202e}');
   |                       ~~~~~~~~
```
2024-07-18 20:08:43 +00:00
Esteban Küber
2d7795dfb9 Be more accurate about calculating display_col from a BytePos
No longer track "zero-width" chars in `SourceMap`, read directly from the line when calculating the `display_col` of a `BytePos`. Move `char_width` to `rustc_span` and use it from the emitter.

This change allows the following to properly align in terminals (depending on the font, the replaced control codepoints are rendered as 1 or 2 width, on my terminal they are rendered as 1, on VSCode text they are rendered as 2):

```
error: this file contains an unclosed delimiter
  --> $DIR/issue-68629.rs:5:17
   |
LL | ␜␟ts␀![{i
   |       -- unclosed delimiter
   |       |
   |       unclosed delimiter
LL | ␀␀  fn rݻoa>rݻm
   |                ^
```
2024-07-18 20:08:38 +00:00
Trevor Gross
9387a7523e Change binary_asm_labels to only fire on x86 and x86_64
In <https://github.com/rust-lang/rust/pull/126922>, the
`binary_asm_labels` lint was added which flags labels such as `0:` and
`1:`. Before that change, LLVM was giving a confusing error on
x86/x86_64 because of an incorrect interpretation.

However, targets other than x86 and x86_64 never had the error message
and have not been a problem. This means that the lint was causing code
that previously worked to start failing (e.g. `compiler_builtins`),
rather than only providing a more clear messages where there has always
been an error.

Adjust the lint to only fire on x86 and x86_64 assembly to avoid this
regression.
2024-07-18 15:00:56 -05:00
Esteban Küber
89f273f40d Replace ASCII control chars with Unicode Control Pictures
```
error: bare CR not allowed in doc-comment
  --> $DIR/lex-bare-cr-string-literal-doc-comment.rs:3:32
   |
LL | /// doc comment with bare CR: '␍'
   |                                ^
```
2024-07-18 19:23:42 +00:00
Esteban Küber
abf92c049d Use more accurate span for addr_of! suggestion
Use a multipart suggestion instead of a single whole-span replacement:

```
error[E0796]: creating a shared reference to a mutable static
  --> $DIR/reference-to-mut-static-unsafe-fn.rs:10:18
   |
LL |         let _y = &X;
   |                  ^^ shared reference to mutable static
   |
   = note: this shared reference has lifetime `'static`, but if the static ever gets mutated, or a mutable reference is created, then any further use of this shared reference is Undefined Behavior
help: use `addr_of!` instead to create a raw pointer
   |
LL |         let _y = addr_of!(X);
   |                  ~~~~~~~~~ +
```
2024-07-18 18:39:20 +00:00
Michael Goulet
8dbb63a585 Remove tag field from relations 2024-07-18 14:34:05 -04:00
Esteban Küber
33bd4bdeb5 Tweak "field not found" suggestion when giving struct literal for tuple struct type
```
error[E0560]: struct `S` has no field named `x`
  --> $DIR/nested-non-tuple-tuple-struct.rs:8:19
   |
LL | pub struct S(f32, f32);
   |            - `S` defined here
...
LL |     let _x = (S { x: 1.0, y: 2.0 }, S { x: 3.0, y: 4.0 });
   |                   ^ field does not exist
   |
help: `S` is a tuple struct, use the appropriate syntax
   |
LL |     let _x = (S(/* f32 */, /* f32 */), S { x: 3.0, y: 4.0 });
   |               ~~~~~~~~~~~~~~~~~~~~~~~
```
2024-07-18 18:20:35 +00:00
Esteban Küber
ec7a188f16 More accurate suggestions when writing wrong style of enum variant literal
```
error[E0533]: expected value, found struct variant `E::Empty3`
  --> $DIR/empty-struct-braces-expr.rs:18:14
   |
LL |     let e3 = E::Empty3;
   |              ^^^^^^^^^ not a value
   |
help: you might have meant to create a new value of the struct
   |
LL |     let e3 = E::Empty3 {};
   |                        ++
```
```
error[E0533]: expected value, found struct variant `E::V`
  --> $DIR/struct-literal-variant-in-if.rs:10:13
   |
LL |     if x == E::V { field } {}
   |             ^^^^ not a value
   |
help: you might have meant to create a new value of the struct
   |
LL |     if x == (E::V { field }) {}
   |             +              +
```
```
error[E0618]: expected function, found enum variant `Enum::Unit`
  --> $DIR/suggestion-highlights.rs:15:5
   |
LL |     Unit,
   |     ---- enum variant `Enum::Unit` defined here
...
LL |     Enum::Unit();
   |     ^^^^^^^^^^--
   |     |
   |     call expression requires function
   |
help: `Enum::Unit` is a unit enum variant, and does not take parentheses to be constructed
   |
LL -     Enum::Unit();
LL +     Enum::Unit;
   |
```
```
error[E0599]: no variant or associated item named `tuple` found for enum `Enum` in the current scope
  --> $DIR/suggestion-highlights.rs:36:11
   |
LL | enum Enum {
   | --------- variant or associated item `tuple` not found for this enum
...
LL |     Enum::tuple;
   |           ^^^^^ variant or associated item not found in `Enum`
   |
help: there is a variant with a similar name
   |
LL |     Enum::Tuple(/* i32 */);
   |           ~~~~~~~~~~~~~~~~;
   |
```
2024-07-18 18:20:35 +00:00
Esteban Küber
67ec1326ee Fix ICE in suggestion caused by being recovered as ==
The second suggestion shown here would previously incorrectly assume that the span corresponding to `⩵` was 2 bytes wide composed by 2 1 byte wide chars, so a span pointing at `==` could point only at one of the `=` to remove it. Instead, we now replace the whole thing (as we should have the whole time):

```
error: unknown start of token: \u{2a75}
  --> $DIR/unicode-double-equals-recovery.rs:1:16
   |
LL | const A: usize ⩵ 2;
   |                ^
   |
help: Unicode character '⩵' (Two Consecutive Equals Signs) looks like '==' (Double Equals Sign), but it is not
   |
LL | const A: usize == 2;
   |                ~~

error: unexpected `==`
  --> $DIR/unicode-double-equals-recovery.rs:1:16
   |
LL | const A: usize ⩵ 2;
   |                ^
   |
help: try using `=` instead
   |
LL | const A: usize = 2;
   |                ~
```
2024-07-18 17:47:31 +00:00
Matthias Krüger
4ad2c99b6d
Rollup merge of #127854 - fmease:glob-import-type_ir_inherent-lint, r=compiler-errors
Add internal lint for detecting non-glob imports of `rustc_type_ir::inherent`

https://github.com/rust-lang/rust/pull/127627#issuecomment-2225295951

r? compiler-errors
2024-07-18 18:10:16 +02:00
Matthias Krüger
ec6110f00c
Rollup merge of #127656 - RalfJung:pub_use_of_private_extern_crate, r=petrochenkov
make pub_use_of_private_extern_crate show up in cargo's future breakage reports

This has been a lint for many years.

However, turns out that outright removing it right now would lead to [tons of crater regressions](https://github.com/rust-lang/rust/pull/127656#issuecomment-2233288534) due to crates depending on an ancient version of `bitflags`. So for now this PR just makes this future-compat lint show up in cargo's reports, so people are warned when they use a dependency that is affected by this.

r? `@petrochenkov`
2024-07-18 18:10:15 +02:00
bors
5753b30676 Auto merge of #117967 - adetaylor:fix-lifetime-elision-bug, r=lcnr
Fix ambiguous cases of multiple & in elided self lifetimes

This change proposes simpler rules to identify the lifetime on `self` parameters which may be used to elide a return type lifetime.

## The old rules

(copied from [this comment](https://github.com/rust-lang/rust/pull/117967#discussion_r1420554242))

Most of the code can be found in [late.rs](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html) and acts on AST types. The function [resolve_fn_params](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html#2006), in the success case, returns a single lifetime which can be used to elide the lifetime of return types.

Here's how:
* If the first parameter is called self then we search that parameter using "`self` search rules", below
* If no unique applicable lifetime was found, search all other parameters using "regular parameter search rules", below

(In practice the code does extra work to assemble good diagnostic information, so it's not quite laid out like the above.)

### `self` search rules

This is primarily handled in [find_lifetime_for_self](https://doc.rust-lang.org/stable/nightly-rustc/src/rustc_resolve/late.rs.html#2118) , and is described slightly [here](https://github.com/rust-lang/rust/issues/117715#issuecomment-1813115477) already. The code:

1. Recursively walks the type of the `self` parameter (there's some complexity about resolving various special cases, but it's essentially just walking the type as far as I can see)
2. Each time we find a reference anywhere in the type, if the **direct** referent is `Self` (either spelled `Self` or by some alias resolution which I don't fully understand), then we'll add that to a set of candidate lifetimes
3. If there's exactly one such unique lifetime candidate found, we return this lifetime.

### Regular parameter search rules

1. Find all the lifetimes in each parameter, including implicit, explicit etc.
2. If there's exactly one parameter containing lifetimes, and if that parameter contains exactly one (unique) lifetime, *and if we didn't find a `self` lifetime parameter already*, we'll return this lifetime.

## The new rules

There are no changes to the "regular parameter search rules" or to the overall flow, only to the `self` search rules which are now:

1. Recursively walks the type of the `self` parameter, searching for lifetimes of reference types whose referent **contains** `Self`.[^1]
2. Keep a record of:
   * Whether 0, 1 or n unique lifetimes are found on references encountered during the walk
4. If no lifetime was found, we don't return a lifetime. (This means other parameters' lifetimes may be used for return type lifetime elision).
5. If there's one lifetime found, we return the lifetime.
6. If multiple lifetimes were found, we abort elision entirely (other parameters' lifetimes won't be used).

[^1]: this prevents us from considering lifetimes from inside of the self-type

## Examples that were accepted before and will now be rejected

```rust
fn a(self: &Box<&Self>) -> &u32
fn b(self: &Pin<&mut Self>) -> &String
fn c(self: &mut &Self) -> Option<&Self>
fn d(self: &mut &Box<Self>, arg: &usize) -> &usize // previously used the lt from arg
```

### Examples that change the elided lifetime

```rust
fn e(self: &mut Box<Self>, arg: &usize) -> &usize
//         ^ new                ^ previous
```

## Examples that were rejected before and will now be accepted

```rust
fn f(self: &Box<Self>) -> &u32
```

---

*edit: old PR description:*

```rust
  struct Concrete(u32);

  impl Concrete {
      fn m(self: &Box<Self>) -> &u32 {
          &self.0
      }
  }
```

resulted in a confusing error.

```rust
  impl Concrete {
      fn n(self: &Box<&Self>) -> &u32 {
          &self.0
      }
  }
```

resulted in no error or warning, despite apparent ambiguity over the elided lifetime.

Fixes https://github.com/rust-lang/rust/issues/117715
2024-07-18 13:33:38 +00:00
Folkert
c2894a4297
improve error reporting 2024-07-18 14:32:10 +02:00
Ralf Jung
0871175a4d make pub_use_of_private_extern_crate show up in future breakage reports 2024-07-18 13:43:56 +02:00
León Orell Valerian Liehr
2507301de0
Add internal lint for detecting non-glob imports of rustc_type_ir::inherent 2024-07-18 13:03:26 +02:00
Folkert
6b6b8422ba
remove cmse validation from rustc_codegen_ssa
it was moved to hir_analysis in the previous commit
2024-07-18 12:42:43 +02:00
Folkert
7b63734961
move CMSE validation to hir_analysis 2024-07-18 12:42:40 +02:00
Trevor Gross
e4bc3d52bf
Rollup merge of #127864 - durin42:farewell-3dnow, r=nikic
cleanup: remove support for 3DNow! cpu features

In llvm/llvm-project@f0eb5587ce all support for 3DNow! intrinsics and instructions were removed. Per the commit message there, only AMD chips between 1998 and 2011 or so actually supported these instructions, and they were effectively replaced by SSE which was available on many more chips. I'd be very surprised if anyone had ever used these from Rust.

`@rustbot` label: +llvm-main
2024-07-18 05:14:07 -05:00
Trevor Gross
e2e0681e3a
Rollup merge of #127842 - nnethercote:rm-TrailingToken, r=petrochenkov
Remove `TrailingToken`.

It's used in `Parser::collect_tokens_trailing_token` to decide whether to capture a trailing token. But the callers actually know whether to capture a trailing token, so it's simpler for them to just pass in a bool.

Also, the `TrailingToken::Gt` case was weird, because it didn't result in a trailing token being captured. It could have been subsumed by the `TrailingToken::MaybeComma` case, and it effectively is in the new code.

r? `@petrochenkov`
2024-07-18 05:14:07 -05:00
Ralf Jung
303a2db236 remove saw_const_match_error; check if pattern contains an Error instead 2024-07-18 11:58:16 +02:00
Ralf Jung
67c99d6338 avoid creating an Instance only to immediately disassemble it again 2024-07-18 11:58:16 +02:00
Ralf Jung
86ce911f90 pattern lowering: make sure we never call user-defined PartialEq instances 2024-07-18 11:58:16 +02:00
Ralf Jung
e613bc92a1 const_to_pat: cleanup leftovers from when we had to deal with non-structural constants 2024-07-18 11:58:16 +02:00
Ralf Jung
fa74a9e6aa valtree construction: keep track of which type was valtree-incompatible 2024-07-18 11:58:16 +02:00
Ralf Jung
a7b80819e9 interpret: add sanity check in dyn upcast to double-check what codegen does 2024-07-18 11:41:10 +02:00
Nicholas Nethercote
487802d6c8 Remove TrailingToken.
It's used in `Parser::collect_tokens_trailing_token` to decide whether
to capture a trailing token. But the callers actually know whether to
capture a trailing token, so it's simpler for them to just pass in a
bool.

Also, the `TrailingToken::Gt` case was weird, because it didn't result
in a trailing token being captured. It could have been subsumed by the
`TrailingToken::MaybeComma` case, and it effectively is in the new code.
2024-07-18 17:28:49 +10:00
Matthias Krüger
77e5bbf341
Rollup merge of #127889 - estebank:anon-arg-sugg, r=compiler-errors
More accurate span for anonymous argument suggestion

Use smaller span for suggesting adding `_:` ahead of a type:

```
error: expected one of `(`, `...`, `..=`, `..`, `::`, `:`, `{`, or `|`, found `)`
  --> $DIR/anon-params-denied-2018.rs:12:47
   |
LL |     fn foo_with_qualified_path(<Bar as T>::Baz);
   |                                               ^ expected one of 8 possible tokens
   |
   = note: anonymous parameters are removed in the 2018 edition (see RFC 1685)
help: explicitly ignore the parameter name
   |
LL |     fn foo_with_qualified_path(_: <Bar as T>::Baz);
   |                                ++
```
2024-07-18 08:09:02 +02:00
Matthias Krüger
d78be31a2a
Rollup merge of #127888 - estebank:type-param-sugg, r=compiler-errors
More accurate span for type parameter suggestion

After:

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/impl-block-params-declared-in-wrong-spot-issue-113073.rs:3:10
   |
LL | impl Foo<T: Default> for String {}
   |          ^^^^^^^^^^ associated item constraint not allowed here
   |
help: declare the type parameter right after the `impl` keyword
   |
LL - impl Foo<T: Default> for String {}
LL + impl<T: Default> Foo<T> for String {}
   |
```

Before:

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/impl-block-params-declared-in-wrong-spot-issue-113073.rs:3:10
   |
LL | impl Foo<T: Default> for String {}
   |          ^^^^^^^^^^ associated item constraint not allowed here
   |
help: declare the type parameter right after the `impl` keyword
   |
LL | impl<T: Default> Foo<T> for String {}
   |     ++++++++++++     ~
```
2024-07-18 08:09:02 +02:00
Matthias Krüger
b52883decf
Rollup merge of #127886 - estebank:as-rename-suggestion, r=compiler-errors
Accurate `use` rename suggestion span

When suggesting to rename an import with `as`, use a smaller span to render the suggestion with a better format:

```
error[E0252]: the name `baz` is defined multiple times
  --> $DIR/issue-25396.rs:4:5
   |
LL | use foo::baz;
   |     -------- previous import of the module `baz` here
LL | use bar::baz;
   |     ^^^^^^^^ `baz` reimported here
   |
   = note: `baz` must be defined only once in the type namespace of this module
help: you can use `as` to change the binding name of the import
   |
LL | use bar::baz as other_baz;
   |              ++++++++++++
```
2024-07-18 08:09:01 +02:00
Matthias Krüger
a13d7dbecf
Rollup merge of #127878 - estebank:assoc-item-removal, r=fmease
Fix associated item removal suggestion

We were previously telling people to write what was already there, instead of removal (treating it as a `help`). We now properly suggest to remove the code that needs to be removed.

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/E0229.rs:13:25
   |
LL | fn baz<I>(x: &<I as Foo<A = Bar>>::A) {}
   |                         ^^^^^^^ associated item constraint not allowed here
   |
help: consider removing this associated item binding
   |
LL - fn baz<I>(x: &<I as Foo<A = Bar>>::A) {}
LL + fn baz<I>(x: &<I as Foo>::A) {}
   |
```
2024-07-18 08:09:01 +02:00
Matthias Krüger
b2b14deca5
Rollup merge of #127810 - compiler-errors:less-tcx, r=lcnr
Rename `tcx` to `cx` in `rustc_type_ir`

Self-explanatory. Forgot that we had to do this in type_ir too, and not just the new solver crate lol.

r? lcnr
2024-07-18 08:09:00 +02:00
Matthias Krüger
97d5edf4b1
Rollup merge of #127783 - compiler-errors:rtn-pretty, r=fee1-dead
Put the dots back in RTN pretty printing

Also don't render RTN-like bounds for methods with ty/const params.
2024-07-18 08:08:59 +02:00
Noah Lev
c8457e60e8 Remove some unintended changes to imports 2024-07-17 20:31:37 -07:00
Noah Lev
2e4a0e37e6 Clarify docs explaining purpose of ConstArg
Co-authored-by: Boxy <rust@boxyuwu.dev>
2024-07-17 20:31:36 -07:00
Michael Goulet
c02d0de871 Account for structs that have unused params in nested types in fields 2024-07-17 21:12:12 -04:00
Trevor Gross
fa1303662a
Rollup merge of #127806 - nnethercote:parser-improvements, r=spastorino
Some parser improvements

I was looking closely at attribute handling in the parser while debugging some issues relating to #124141, and found a few small improvements.

``@spastorino``
2024-07-17 19:53:27 -05:00
Trevor Gross
b5771e7e0d
Rollup merge of #127664 - compiler-errors:precise-capturing-better-sugg-apit, r=oli-obk
Fix precise capturing suggestion for hidden regions when we have APITs

Suggests to turn APITs into type parameters so they can be named in precise capturing syntax for hidden type lifetime errors. We also note that it may change the API.

This is currently done via a note *and* a suggestion, which feels a bit redundant, but I wasn't totally sure of a better alternative for the presentation.

Code is kind of a mess but there's a lot of cases to consider. Happy to iterate on this if you think the approach is too messy.

Based on #127619, only the last commit is relevant.
r? oli-obk

Tracking:

- https://github.com/rust-lang/rust/issues/123432
2024-07-17 19:53:26 -05:00
Trevor Gross
973d92c3cc
Rollup merge of #127652 - GuillaumeGomez:cg-gcc-fmt, r=Urgau
Unignore cg_gcc fmt

`rustc_codegen_gcc` uses `rustfmt` now so it can be unignored.

r? ``@Urgau``
2024-07-17 19:53:26 -05:00
Trevor Gross
e6f0caf197
Rollup merge of #127542 - c410-f3r:concat-again, r=petrochenkov
[`macro_metavar_expr_concat`] Add support for literals

Adds support for literals in macro parameters.

```rust
macro_rules! with_literal {
    ($literal:literal) => {
        const ${concat(FOO, $literal)}: i32 = 1;
    }
}

fn main() {
    with_literal!("_BAR");
    assert_eq!(FOO_BAR, 1);
}
```

cc #124225

r? ``@petrochenkov``
2024-07-17 19:53:25 -05:00
Esteban Küber
f6c4679547 More accurate span for anonymous argument suggestion
Use smaller span for suggesting adding `_:` ahead of a type:

```
error: expected one of `(`, `...`, `..=`, `..`, `::`, `:`, `{`, or `|`, found `)`
  --> $DIR/anon-params-denied-2018.rs:12:47
   |
LL |     fn foo_with_qualified_path(<Bar as T>::Baz);
   |                                               ^ expected one of 8 possible tokens
   |
   = note: anonymous parameters are removed in the 2018 edition (see RFC 1685)
help: explicitly ignore the parameter name
   |
LL |     fn foo_with_qualified_path(_: <Bar as T>::Baz);
   |                                ++
```
2024-07-18 00:19:27 +00:00
Esteban Küber
be9d961884 More accurate span for type parameter suggestion
After:

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/impl-block-params-declared-in-wrong-spot-issue-113073.rs:3:10
   |
LL | impl Foo<T: Default> for String {}
   |          ^^^^^^^^^^ associated item constraint not allowed here
   |
help: declare the type parameter right after the `impl` keyword
   |
LL - impl Foo<T: Default> for String {}
LL + impl<T: Default> Foo<T> for String {}
   |
```

Before:

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/impl-block-params-declared-in-wrong-spot-issue-113073.rs:3:10
   |
LL | impl Foo<T: Default> for String {}
   |          ^^^^^^^^^^ associated item constraint not allowed here
   |
help: declare the type parameter right after the `impl` keyword
   |
LL | impl<T: Default> Foo<T> for String {}
   |     ++++++++++++     ~
```
2024-07-18 00:10:48 +00:00
Esteban Küber
8eb51852a8 Accurate use rename suggestion span
When suggesting to rename an import with `as`, use a smaller span to
render the suggestion with a better format:

```
error[E0252]: the name `baz` is defined multiple times
  --> $DIR/issue-25396.rs:4:5
   |
LL | use foo::baz;
   |     -------- previous import of the module `baz` here
LL | use bar::baz;
   |     ^^^^^^^^ `baz` reimported here
   |
   = note: `baz` must be defined only once in the type namespace of this module
help: you can use `as` to change the binding name of the import
   |
LL | use bar::baz as other_baz;
   |              ++++++++++++
```
2024-07-18 00:00:04 +00:00
Ben Kimock
3623c76acb Remove in-progress allocation decoding states 2024-07-17 18:35:41 -04:00
Matthew Maurer
2abdc4e98c CFI: Support provided methods on traits
Provided methods currently don't get type erasure performed on them
because they are not in an `impl` block. If we are instantiating a
method that is an associated item, but *not* in an impl block, treat it
as a provided method instead.
2024-07-17 21:45:43 +00:00
Esteban Küber
e38032fb3a Fix associated item removal suggestion
We were previously telling people to write what was already there, instead of removal.

```
error[E0229]: associated item constraints are not allowed here
  --> $DIR/E0229.rs:13:25
   |
LL | fn baz<I>(x: &<I as Foo<A = Bar>>::A) {}
   |                         ^^^^^^^ associated item constraint not allowed here
   |
help: consider removing this associated item binding
   |
LL - fn baz<I>(x: &<I as Foo<A = Bar>>::A) {}
LL + fn baz<I>(x: &<I as Foo>::A) {}
   |
```
2024-07-17 21:30:40 +00:00
Michael Goulet
a0a251a688 Account for self ty alias 2024-07-17 16:48:17 -04:00
Caio
553279b152 Add support for literals 2024-07-17 17:00:48 -03:00
Michael Goulet
3716a3fd31 Mention that type parameters are used recursively 2024-07-17 15:57:38 -04:00
Guillaume Gomez
213782dd71 Format cg_gcc with same formatting parameters 2024-07-17 20:22:07 +02:00
Guillaume Gomez
261d92c07d Align cg_gcc rustfmt.toml with rust's 2024-07-17 20:17:44 +02:00
Augie Fackler
72e22554ca cleanup: remove support for 3DNow! cpu features
In llvm/llvm-project@f0eb5587ce all
support for 3DNow! intrinsics and instructions were removed. Per the commit message
there, only AMD chips between 1998 and 2011 or so actually supported
these instructions, and they were effectively replaced by SSE which was
available on many more chips. I'd be very surprised if anyone had ever
used these from Rust.
2024-07-17 11:45:02 -04:00
Michael Goulet
b84e2b7c98 Put the dots back 2024-07-17 11:08:28 -04:00
Michael Goulet
da2054f389 Add cross-crate precise capturing support to rustdoc 2024-07-17 11:06:10 -04:00
Michael Goulet
1d40d4c4f4 Fix precise capturing suggestion for hidden type when APITs are involved 2024-07-17 10:52:13 -04:00
Michael Goulet
0b5ce54bc2 Fix relations 2024-07-17 10:46:10 -04:00
Michael Goulet
8d90f442ca tcx -> cx in rustc_type_ir 2024-07-17 10:46:10 -04:00
Michael Goulet
a6510507e7 lift_to_tcx -> lift_to_interner 2024-07-17 10:46:10 -04:00
Matthias Krüger
1e1e64f10f
Rollup merge of #127844 - chenyukang:yukang-fix-type-bound-127555, r=jieyouxu
Remove invalid further restricting suggestion for type bound

This PR partially addresses #127555, it will remove the obvious error suggestion:

```console
   |                      ^^^^ required by this bound in `<Baz as Foo>::bar`
help: consider further restricting this bound
   |
12 |         F: FnMut() + Send + std::marker::Send,
   |                           +++++++++++++++++++
```

I may create another PR to get a better diagnostic for `impl has stricter requirements than trait` scenario.
2024-07-17 16:22:32 +02:00
Matthias Krüger
9db57bf0c9
Rollup merge of #127769 - compiler-errors:ed-2024-dep, r=oli-obk
Don't use implicit features in `Cargo.toml` in `compiler/`

Fixes compiler crates to stop using implicit features (https://github.com/rust-lang/cargo/issues/12826) which are denied in in edition 2024.
2024-07-17 16:22:31 +02:00
Matthias Krüger
23dd3a099c
Rollup merge of #127579 - surechen:fix_127285, r=lcnr
Solve a error `.clone()` suggestion when moving a mutable reference

If the moved value is a mut reference, it is used in a generic function and it's type is a generic param, suggest it can be reborrowed to avoid moving.

for example:

```rust
struct Y(u32);
// x's type is '& mut Y' and it is used in `fn generic<T>(x: T) {}`.
fn generic<T>(x: T) {}
```

fixes #127285
2024-07-17 16:22:29 +02:00
Matthias Krüger
c98487e3be
Rollup merge of #127472 - Zalathar:block-and-unit, r=fmease
MIR building: Stop using `unpack!` for `BlockAnd<()>`

This is a subset of #127416, containing only the parts related to `BlockAnd<()>`.

The first patch removes the non-assigning form of the `unpack!` macro, because it is frustratingly inconsistent with the main form. We can replace it with an ordinary method that discards the `()` and returns the block.

The second patch then finds all of the remaining code that was using `unpack!` with `BlockAnd<()>`, and updates it to use that new method instead.

---

Changes since original review of #127416:
- Renamed `fn unpack_block` → `fn into_block`
- Removed `fn unpack_discard`, replacing it with `let _: BlockAnd<()> = ...` (2 occurrences)
- Tweaked `arm_end_blocks` to unpack earlier and build `Vec<BasicBlock>` instead of `Vec<BlockAnd<()>>`
2024-07-17 16:22:28 +02:00
Matthias Krüger
2b34490da6
Rollup merge of #125042 - long-long-float:suggest-move-arg-outside, r=fmease
Use ordinal number in argument error

Add an ordinal number to two argument errors ("unexpected" and "missing") for ease of understanding error.

```
error[E0061]: this function takes 3 arguments but 2 arguments were supplied
  --> test.rs:11:5
   |
11 |     f(42, 'a');
   |     ^     --- 2nd argument of type `f32` is missing
   |
(snip)

error[E0061]: this function takes 3 arguments but 4 arguments were supplied
  --> test.rs:12:5
   |
12 |     f(42, 42, 1.0, 'a');
   |     ^   ----
   |         | |
   |         | unexpected 2nd argument of type `{integer}`
   |         help: remove the extra argument
```

To get an ordinal number, I copied `ordinalize` from other crate `rustc_resolve` because I think it is too much to link `rustc_resolve` for this small function. Please let me know if there is a better way.
2024-07-17 16:22:26 +02:00
Tobias Bucher
bf96c56e84 Rename deprecated_safe lint to deprecated_safe_2024
Create a lint group `deprecated_safe` that includes
`deprecated_safe_2024`.

Addresses https://github.com/rust-lang/rust/issues/124866#issuecomment-2142814375.
2024-07-17 14:39:56 +02:00
Zalathar
411fcb6b2d Rename test to pick_test_for_match_pair 2024-07-17 21:50:12 +10:00
Zalathar
03bfa3690e Rename MatchPair to MatchPairTree
In #120904, `MatchPair` became able to store other match pairs as children,
forming a tree. That has made the old name confusing, so this patch renames the
type to `MatchPairTree`.
2024-07-17 21:50:07 +10:00
yukang
40e07a3ab1 Remove invalid further restricting for type bound 2024-07-17 19:08:37 +08:00
Boxy
d0c11bf6e3 Split part of adt_const_params into unsized_const_params 2024-07-17 11:01:29 +01:00
Boxy
42cc42b942 Forbid !Sized types and references 2024-07-17 11:01:29 +01:00
Noah Lev
37ed7a4438 Add ConstArgKind::Path and make ConstArg its own HIR node
This is a very large commit since a lot needs to be changed in order to
make the tests pass. The salient changes are:

- `ConstArgKind` gets a new `Path` variant, and all const params are now
  represented using it. Non-param paths still use `ConstArgKind::Anon`
  to prevent this change from getting too large, but they will soon use
  the `Path` variant too.

- `ConstArg` gets a distinct `hir_id` field and its own variant in
  `hir::Node`. This affected many parts of the compiler that expected
  the parent of an `AnonConst` to be the containing context (e.g., an
  array repeat expression). They have been changed to check the
  "grandparent" where necessary.

- Some `ast::AnonConst`s now have their `DefId`s created in
  rustc_ast_lowering rather than `DefCollector`. This is because in some
  cases they will end up becoming a `ConstArgKind::Path` instead, which
  has no `DefId`. We have to solve this in a hacky way where we guess
  whether the `AnonConst` could end up as a path const since we can't
  know for sure until after name resolution (`N` could refer to a free
  const or a nullary struct). If it has no chance as being a const
  param, then we create a `DefId` in `DefCollector` -- otherwise we
  decide during ast_lowering. This will have to be updated once all path
  consts use `ConstArgKind::Path`.

- We explicitly use `ConstArgHasType` for array lengths, rather than
  implicitly relying on anon const type feeding -- this is due to the
  addition of `ConstArgKind::Path`.

- Some tests have their outputs changed, but the changes are for the
  most part minor (including removing duplicate or almost-duplicate
  errors). One test now ICEs, but it is for an incomplete, unstable
  feature and is now tracked at #127009.
2024-07-16 19:27:28 -07:00
Noah Lev
1c49d406b6 Use ConstArg for const param defaults
Now everything that actually affects the type system (i.e., excluding
const blocks, enum variant discriminants, etc.) *should* be using
`ConstArg`.
2024-07-16 19:27:28 -07:00
Noah Lev
67fccb7045 Use ConstArg for array lengths 2024-07-16 19:27:28 -07:00
Noah Lev
8818708a31 Use ConstArg for assoc item constraints 2024-07-16 19:27:28 -07:00
Noah Lev
e7c85cb1e0 Setup ty::Const functions for ConstArg 2024-07-16 19:27:28 -07:00
Noah Lev
7d7be2f0f6 Setup ast_lowering functions for ConstArg 2024-07-16 19:27:28 -07:00
Noah Lev
11b144aa98 hir: Create hir::ConstArgKind enum
This will allow lowering const params to a dedicated enum variant, rather
than to an `AnonConst` that is later examined during `ty` lowering.
2024-07-16 19:27:28 -07:00
Noah Lev
71f8aed510 Add current_def_id_parent to LoweringContext
This is needed to track anon const parents properly once we implement
`ConstArgKind::Path` (which requires moving anon const def-creation
outside of `DefCollector`):

    Why do we need this in addition to [`Self::current_hir_id_owner`]?

    Currently (as of June 2024), anonymous constants are not HIR owners;
    however, they do get their own DefIds. Some of these DefIds have to be
    created during AST lowering, rather than def collection, because we
    can't tell until after name resolution whether an anonymous constant
    will end up instead being a [`rustc_hir::ConstArgKind::Path`]. However,
    to compute which generics are available to an anonymous constant nested
    inside another, we need to make sure that the parent is recorded as the
    parent anon const, not the enclosing item. So we need to track parent
    defs differently from HIR owners, since they will be finer-grained in
    the case of anon consts.
2024-07-16 19:27:28 -07:00
surechen
4821b84b92 If the moved value is a mut reference, it is used in a generic function and it's type is a generic param, it can be reborrowed to avoid moving.
for example:

```rust
struct Y(u32);
// x's type is '& mut Y' and it is used in `fn generic<T>(x: T) {}`.
fn generic<T>(x: T) {}
```

fixes #127285
2024-07-17 10:07:02 +08:00
Trevor Gross
8840d302e5
Rollup merge of #127512 - eggyal:newline-terminate-print-linkargs, r=compiler-errors
Terminate `--print link-args` output with newline

Fixes #127507
2024-07-16 20:10:11 -05:00
Trevor Gross
606d8cf9e8
Rollup merge of #126776 - nnethercote:rustfmt-use-pre-cleanups-2, r=cuviper
Clean up more comments near use declarations

#125443 will reformat all use declarations in the repository. There are a few edge cases involving comments on use declarations that require care. This PR fixes them up so #125443 can go ahead with a simple `x fmt --all`. A follow-up to #126717.

r? ``@cuviper``
2024-07-16 20:10:10 -05:00
liushuyu
01e6e60bf3 rustc_codegen_llvm: properly passing backchain attribute to LLVM ...
... this is a special attribute that was made to be a target-feature in
LLVM 18+, but in all previous versions, this "feature" is a naked
attribute. We will have to handle this situation differently than all
other target-features.
2024-07-17 07:56:00 +08:00
liushuyu
366bc8691b rustc_codegen_ssa: add s390x_target_feature symbol 2024-07-17 07:55:56 +08:00
liushuyu
efcf35e524 rustc_target: add known safe s390x target features 2024-07-17 07:53:14 +08:00
Nicholas Nethercote
75b6ec9800 Avoid comments that describe multiple use items.
There are some comments describing multiple subsequent `use` items. When
the big `use` reformatting happens some of these `use` items will be
reordered, possibly moving them away from the comment. With this
additional level of formatting it's not really feasible to have comments
of this type. This commit removes them in various ways:

- merging separate `use` items when appropriate;

- inserting blank lines between the comment and the first `use` item;

- outright deletion (for comments that are relatively low-value);

- adding a separate "top-level" comment.

We also entirely skip formatting for four library files that contain
nothing but `pub use` re-exports, where reordering would be painful.
2024-07-17 08:02:46 +10:00
Trevor Gross
7d534dd4eb
Rollup merge of #127816 - oli-obk:misnomer, r=compiler-errors
Update method name to reflect changes to its internals

forgot to do this in https://github.com/rust-lang/rust/pull/127431
2024-07-16 16:15:17 -05:00
Trevor Gross
059222ddc9
Rollup merge of #127501 - compiler-errors:invert-infer-error-mod-struture, r=lcnr
Invert infer `error_reporting` mod struture

Parallel change to #127493, which moves `rustc_infer::infer::error_reporting` to `rustc_infer::error_reporting::infer`. After this, we should just be able to merge this into `rustc_trait_selection::error_reporting::infer`, and pull down `TypeErrCtxt` into that crate. 👍

r? lcnr
2024-07-16 16:15:16 -05:00
Trevor Gross
9833e21c5d
Rollup merge of #126762 - compiler-errors:kw-lt, r=michaelwoerister
Deny keyword lifetimes pre-expansion

https://github.com/rust-lang/rust/pull/126452#issuecomment-2179464266

> Secondly, we confirmed that we're OK with moving the validation of keywords in lifetimes to pre-expansion from post-expansion. We similarly consider this a bug fix. While the breakage of the convenience feature of the with_locals crate that relies on this is unfortunate, and we wish we had not overlooked this earlier for that reason, we're fortunate that the breakage is contained to only one crate, and we're going to accept this breakage as the extra complexity we'd need to carry in the compiler to work around this isn't deemed worth it.

T-lang considers it to be a bugfix to deny `'keyword` lifetimes in the parser, rather than during AST validation that only happens post-expansion. This has one breakage: https://github.com/rust-lang/rust/pull/126452#issuecomment-2171654756

This probably should get lang FCP'd just for consistency.
2024-07-16 16:15:15 -05:00
Trevor Gross
36ea06827b
Rollup merge of #126699 - Bryanskiy:delegation-coercion, r=compiler-errors
Delegation: support coercion for target expression

(solves https://github.com/rust-lang/rust/issues/118212#issuecomment-2160723092)

The implementation consist of 2 parts. Firstly, method call is generated instead of fully qualified call in AST->HIR lowering if there were no generic arguments or `Qpath` were provided. These restrictions are imposed due to the loss of information after desugaring. For example in

```rust
trait Trait {
  fn foo(&self) {}
}

reuse <u8 as Trait>::foo;
```

We would like to generate such a code:

```rust
fn foo<u8: Trait>(x: &u8) {
  x.foo(x)
}
```

however, the signature is inherited during HIR analysis where `u8` was discarded.

Then, we probe the single pre-resolved method.

P.S In the future, we would like to avoid restrictions on the callee path by `Self` autoref/autoderef in fully qualified calls, but at the moment it didn't work out.

r? `@petrochenkov`
2024-07-16 16:15:14 -05:00
Trevor Gross
63f239c89f
Rollup merge of #124033 - bjorn3:ar_archive_writer_0_3_0, r=davidtwco
Sync ar_archive_writer to LLVM 18.1.3

From LLVM 15.0.0-rc3. This adds support for COFF archives containing Arm64EC object files and has various fixes for AIX big archive files.
2024-07-16 16:15:13 -05:00
Folkert
09b620d179
stop running code samples in the error code .md 2024-07-16 21:28:09 +02:00
Folkert
1a7960603f
another attempt at fixing the examples in the error codes .md 2024-07-16 20:36:55 +02:00
Folkert
c7ff46c971
move cmse ABI validation into its own module
Co-authored-by: Tamme Dittrich <tamme@tweedegolf.com>
2024-07-16 18:45:03 +02:00
Folkert
36d23713fb
make function pub in error_codes markdown file
the error is only generated for functions that are actually codegen'd
2024-07-16 18:38:42 +02:00
Matthias Krüger
ab4cc440dd
Rollup merge of #127818 - oli-obk:ast_validation_simplifications, r=petrochenkov
Various ast validation simplifications

Changes pulled out of https://github.com/rust-lang/rust/pull/127524

These are needed to make ast validation a mutable visitor, as we can't keep immutable references to the AST around in that case. But I think they are simplifying things in general and can stand on their own
2024-07-16 18:09:14 +02:00
Matthias Krüger
862852fd33
Rollup merge of #127817 - oli-obk:mut_visitor_fix, r=petrochenkov
Fix a bunch of sites that were walking instead of visiting, making it impossible for visitor impls to look at these values

This doesn't affects anything right now, but a `MutVisitor` impl could be surprised by this.

The reason this doesn't affect anything is that no one overrrides `visit_lifetime` or `visit_param_bounds` currently.
2024-07-16 18:09:13 +02:00
Matthias Krüger
8fd1df8c5f
Rollup merge of #127808 - oli-obk:tainting_visitors2, r=lcnr,nnethercote
Make ErrorGuaranteed discoverable outside types, consts, and lifetimes

types like `PatKind` could contain `ErrorGuaranteed`, but not return them via `tainted_by_errors` or `error_reported` (see https://github.com/rust-lang/rust/pull/127687#discussion_r1679027883). Now this happens, but it's a bit fragile as you can see with the `TypeSuperVisitable for Ty` impl.

We will catch any problems around Ty, Region or Const at runtime with an assert, and everything using derives will not have such issues, as it will just invoke the `TypeVisitable for ErrorGuaranteed` impl
2024-07-16 18:09:12 +02:00
Matthias Krüger
73028fe483
Rollup merge of #127730 - compiler-errors:ed-2024-unsafe, r=petrochenkov
Fix and enforce `unsafe_op_in_unsafe_fn` in compiler

In preparation for edition 2024, this PR previews the fallout of enabling the `unsafe_op_in_unsafe_fn` lint in the compiler, since it's defaulting to warn in the new edition (#112038).

The major annoyance comes primarily from the `rustc_codegen_llvm` module, where there's a ton of unsafe calls. I tended to wrap individual calls to unsafe fns in `unsafe {}`, but there a handful of places I chose to just wrap several calls in an `unsafe {}` block just because it would've been excessive to wrap each call individually.

This doesn't enable the lint for the standard library, since I'm not totally certain what T-libs prefers w/ this lint.
2024-07-16 18:09:10 +02:00
Matthias Krüger
7409a5281d
Rollup merge of #127707 - Zalathar:expand-until, r=Nadrieril
match lowering: Use an iterator to find `expand_until`

A small cleanup that I noticed while looking at #127164.

This makes it easier to see that the split point is always the index after the found item, or the whole list if no stopping point was found.

r? `@Nadrieril`
2024-07-16 18:09:09 +02:00
Michael Goulet
d0a1851ec2 Deny keyword lifetimes pre-expansion 2024-07-16 12:06:25 -04:00
Oli Scherer
117ff0a4fd Fix a bunch of sites that were walking instead of visiting, making it impossible for visitor impls to look at these values 2024-07-16 15:50:36 +00:00
Oli Scherer
d9f9592924 Remove a boilerplaty abstraction 2024-07-16 15:46:45 +00:00
Oli Scherer
b879e29864 Remove a needless borrow 2024-07-16 15:46:45 +00:00
Oli Scherer
9a4c1058fa Just store a span instead of the whole item 2024-07-16 15:44:17 +00:00
Oli Scherer
6ce78bea03 Update method name to reflect changes to its internals 2024-07-16 15:34:35 +00:00
Bryanskiy
7ee97f93da Delegation: support coercion for target expression 2024-07-16 18:03:15 +03:00
Oli Scherer
53f7f8ce5c Remove an unnecessary impl 2024-07-16 14:15:44 +00:00
yukang
48ddf5e323 Fix the issue of invalid suggestion for a reference of iterator 2024-07-16 22:01:55 +08:00
Folkert
50ba821e12
add rust error message for CMSE stack spill
when the `C-cmse-nonsecure-call` ABI is used, arguments and return values must be passed via registers. Failing to do so (i.e. spilling to the stack) causes an LLVM error down the line, but now rustc will properly emit an error a bit earlier in the chain
2024-07-16 15:58:33 +02:00
Oli Scherer
fb98fbb759 Make ErrorGuaranteed discoverable outside types, consts, and lifetimes 2024-07-16 11:31:04 +00:00
Trevor Gross
1abed9fa06
Rollup merge of #127780 - compiler-errors:zip-args, r=jieyouxu
Make sure trait def ids match before zipping args in `note_function_argument_obligation`

Fixes #126416
Fixes #127745

Didn't add both tests b/c I felt like it was unnecessary.
2024-07-16 02:02:25 -05:00
Trevor Gross
47600074fe
Rollup merge of #127709 - Zalathar:pair-mod, r=Nadrieril
match lowering: Move `MatchPair` tree creation to its own module

This makes it easier to see that `MatchPair::new` has only one non-recursive caller, because the recursive callers are all in this module. No functional changes.

---

I have used `git diff --color-moved` to verify that the moved code is identical to the old code, except for reduced visibility on the helper methods.
2024-07-16 02:02:24 -05:00
Trevor Gross
12fd2f94b3
Rollup merge of #120990 - chenyukang:yukang-fix-120327-dbg, r=oli-obk
Suggest a borrow when using dbg

Fixes #120327
r? ````@estebank````
2024-07-16 02:02:23 -05:00
Nicholas Nethercote
9c4f3dbd06 Remove references to maybe_whole_expr.
It was removed in #126571.
2024-07-16 16:40:35 +10:00
Nicholas Nethercote
8cb6bc3b5a Fix a comment. 2024-07-16 16:39:19 +10:00
Nicholas Nethercote
96b39f1204 Inline and remove Parser::parse_expr_dot_or_call_with_.
It only has two call sites, and it extremely similar to
`Parser::parse_expr_dot_or_call_with`, in both name and behaviour. The
only difference is the latter has an `attrs` argument and an
`ensure_sufficient_stack` call. We can pass in an empty `attrs` as
necessary, as is already done at some `parse_expr_dot_or_call_with` call
sites.
2024-07-16 16:16:38 +10:00
Nicholas Nethercote
96cc9c99b2 Inline and remove Parser::parse_and_disallow_postfix_after_cast.
It has a single call site. Removing it removes the need for an
`ExprKind` check. The commit also clarifies the relevant comment.
2024-07-16 16:09:36 +10:00
Nicholas Nethercote
d247489ac2 Reorder Parser::parse_expr_dot_or_call_with arguments.
Put `attrs` before `e0` because that matches the order in the source
code, where outer attributes appear before expressions.
2024-07-16 15:54:34 +10:00
Nicholas Nethercote
48cdfc388d Inline Parser::parse_item_common_.
It has a single call site, it isn't that big, and its name is
confusingly similar to `Parser::parse_item_common`.
2024-07-16 15:07:42 +10:00
Nicholas Nethercote
2f305ff460 Remove an unnecessary ?. 2024-07-16 15:03:25 +10:00
Michael Goulet
28503d69ac Fix unsafe_op_in_unsafe_fn in compiler 2024-07-16 00:02:44 -04:00
Michael Goulet
71eb49c318 fmt 2024-07-16 00:02:36 -04:00
bors
5c84886056 Auto merge of #127638 - adwinwhite:cache_string, r=oli-obk
Add cache for `allocate_str`

Best effort cache for string allocation in const eval.

Fixes [rust-lang/miri#3470](https://github.com/rust-lang/miri/issues/3470).
2024-07-16 02:41:07 +00:00
Zalathar
e37b92ffd8 Use an iterator to find expand_until
This makes it easier to see that the split point is always the index after the
found item, or the whole list if no stopping point was found.
2024-07-16 11:51:52 +10:00
Michael Goulet
e86fbcfd70 Move rustc_infer::infer::error_reporting to rustc_infer::error_reporting::infer 2024-07-15 20:16:12 -04:00
Mohammad Omidvar
9b80250abb Move compiler_builtin check to the use case 2024-07-15 23:43:52 +00:00
bors
cae4a84146 Auto merge of #127629 - tesuji:suggest-option-ref-unwrap_or, r=estebank
Suggest using `map_or` when `Option<&T>::unwrap_or where T: Deref` fails

Fix #127545

Split from https://github.com/rust-lang/rust/pull/127596#pullrequestreview-2171898588
2024-07-15 23:36:22 +00:00
Michael Goulet
841b30f63e Make sure trait def ids match before zipping args in note_function_argument_obligation 2024-07-15 17:53:22 -04:00
Mohammad Omidvar
14430e66be Use the hook on tcx instead of the local function 2024-07-15 19:58:44 +00:00
Mohammad Omidvar
0d508bb0cd Introduce and provide a hook for should_codegen_locally 2024-07-15 19:54:47 +00:00
Matthias Krüger
e5d65e46ed
Rollup merge of #127758 - Zalathar:expression-used, r=oli-obk
coverage: Restrict `ExpressionUsed` simplification to `Code` mappings

In the future, branch and MC/DC mappings might have expressions that don't correspond to any single point in the control-flow graph. That makes it trickier to keep track of which expressions should expect an `ExpressionUsed` node.

We therefore sidestep that complexity by only performing `ExpressionUsed` simplification for expressions associated directly with ordinary `Code` mappings.

(This simplification step is inherited from the original coverage implementation, which only supported `Code` mappings anyway, so there's no particular reason to extend it to other kinds of mappings unless we specifically choose to.)

Relevant to:
- #124154
- #126677
- #124278

```@rustbot``` label +A-code-coverage
2024-07-15 21:11:50 +02:00
Matthias Krüger
3f13562acd
Rollup merge of #127729 - compiler-errors:ed-2024-gen, r=oli-obk
Stop using the `gen` identifier in the compiler

In preparation for edition 2024, this PR previews the fallout of removing usages of `gen` since it's being reserved as a keyword.

There are two notable changes here:
1. Had to rename `fn gen(..)` in gen/kill analysis to `gen_`. Not certain there's a better name than that.
2. There are (false?[^1]) positives in `rustc_macros` when using synstructure, which uses `gen impl` to mark an implementation. We could suppress this in a one-off way, or perhaps just ignore `gen` in macros altogether, since if an identifier ends up in expanded code then it'll get properly denied anyways.

Not relevant to the compiler, but it's gonna be really annoying to change `rand`'s `gen` fn in the library and miri...

[^1]: I haven't looked at the synstructure proc macro code itself so I'm not certain if it'll start to fail when converted to ed2024 (or, e.g., when syn starts parsing `gen` as a kw).
2024-07-15 21:11:49 +02:00
Matthias Krüger
2b82729b91
Rollup merge of #127407 - estebank:parser-suggestions, r=oli-obk
Make parse error suggestions verbose and fix spans

Go over all structured parser suggestions and make them verbose style.

When suggesting to add or remove delimiters, turn them into multiple suggestion parts.
2024-07-15 21:11:48 +02:00
Matthias Krüger
78529d9841
Rollup merge of #124921 - RalfJung:offset-from-same-addr, r=oli-obk
offset_from: always allow pointers to point to the same address

This PR implements the last remaining part of the t-opsem consensus in https://github.com/rust-lang/unsafe-code-guidelines/issues/472: always permits offset_from when both pointers have the same address, no matter how they are computed. This is required to achieve *provenance monotonicity*.

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

### What is provenance monotonicity and why does it matter?

Provenance monotonicity is the property that adding arbitrary provenance to any no-provenance pointer must never make the program UB. More specifically, in the program state, data in memory is stored as a sequence of [abstract bytes](https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#abstract-byte), where each byte can optionally carry provenance. When a pointer is stored in memory, all of the bytes it is stored in carry that provenance. Provenance monotonicity means: if we take some byte that does not have provenance, and give it some arbitrary provenance, then that cannot change program behavior or introduce UB into a UB-free program.

We care about provenance monotonicity because we want to allow the optimizer to remove provenance-stripping operations. Removing a provenance-stripping operation effectively means the program after the optimization has provenance where the program before the optimization did not -- since the provenance removal does not happen in the optimized program. IOW, the compiler transformation added provenance to previously provenance-free bytes. This is exactly what provenance monotonicity lets us do.

We care about removing provenance-stripping operations because `*ptr = *ptr` is, in general, (likely) a provenance-stripping operation. Specifically, consider `ptr: *mut usize` (or any integer type), and imagine the data at `*ptr` is actually a pointer (i.e., we are type-punning between pointers and integers). Then `*ptr` on the right-hand side evaluates to the data in memory *without* any provenance (because [integers do not have provenance](https://rust-lang.github.io/rfcs/3559-rust-has-provenance.html#integers-do-not-have-provenance)). Storing that back to `*ptr` means that the abstract bytes `ptr` points to are the same as before, except their provenance is now gone. This makes  `*ptr = *ptr`  a provenance-stripping operation  (Here we assume `*ptr` is fully initialized. If it is not initialized, evaluating `*ptr` to a value is UB, so removing `*ptr = *ptr` is trivially correct.)

### What does `offset_from` have to do with provenance monotonicity?

With `ptr = without_provenance(N)`, `ptr.offset_from(ptr)` is always well-defined and returns 0. By provenance monotonicity, I can now add provenance to the two arguments of `offset_from` and it must still be well-defined. Crucially, I can add *different* provenance to the two arguments, and it must still be well-defined. In other words, this must always be allowed: `ptr1.with_addr(N).offset_from(ptr2.with_addr(N))` (and it returns 0). But the current spec for `offset_from` says that the two pointers must either both be derived from an integer or both be derived from the same allocation, which is not in general true for arbitrary `ptr1`, `ptr2`.

To obtain provenance monotonicity, this PR hence changes the spec for offset_from to say that if both pointers have the same address, the function is always well-defined.

### What further consequences does this have?

It means the compiler can no longer transform `end2 = begin.offset(end.offset_from(begin))` into `end2 = end`. However, it can still be transformed into `end2 = begin.with_addr(end.addr())`, which later parts of the backend (when provenance has been erased) can trivially turn into `end2 = end`.

The only alternative I am aware of is a fundamentally different handling of zero-sized accesses, where a "no provenance" pointer is not allowed to do zero-sized accesses and instead we have a special provenance that indicates "may be used for zero-sized accesses (and nothing else)". `offset` and `offset_from` would then always be UB on a "no provenance" pointer, and permit zero-sized offsets on a "zero-sized provenance" pointer. This achieves provenance monotonicity. That is, however, a breaking change as it contradicts what we landed in https://github.com/rust-lang/rust/pull/117329. It's also a whole bunch of extra UB, which doesn't seem worth it just to achieve that transformation.

### What about the backend?

LLVM currently doesn't have an intrinsic for pointer difference, so we anyway cast to integer and subtract there. That's never UB so it is compatible with any relaxation we may want to apply.

If LLVM gets a `ptrsub` in the future, then plausibly it will be consistent with `ptradd` and [consider two equal pointers to be inbounds](https://github.com/rust-lang/rust/pull/124921#issuecomment-2205795829).
2024-07-15 21:11:47 +02:00
yukang
317952677a Suggest a borrow when using dbg 2024-07-16 02:48:47 +08:00
Michael Goulet
172cf9bef3 Fix unsoundness when associated types dont actually come from supertraits 2024-07-15 14:17:32 -04:00
Michael Goulet
8edf9b8084 Item bounds can reference self projections and still be object safe 2024-07-15 14:16:48 -04:00
Michael Goulet
7e1c4afb1d The rustc crate feature is called jemalloc 2024-07-15 13:01:20 -04:00
Michael Goulet
324d2e51ee Fix feature gating on rustc_index to not use implicit features 2024-07-15 12:44:24 -04:00
Michael Goulet
247ad3385c Use dep: for crate dependencies 2024-07-15 12:40:10 -04:00
Lzu Tao
bdc9df2478 Use multipart_suggestion to avoid place holder in span_to_snippet
CO-AUTHORED-BY: Esteban Küber <esteban@kuber.com.ar>
2024-07-15 12:54:00 +00:00
Lzu Tao
9c3c278b54 Add support for `Result<&T, _>' 2024-07-15 12:54:00 +00:00
Zalathar
d4f1f92426 coverage: Restrict ExpressionUsed simplification to Code mappings
In the future, branch and MC/DC mappings might have expressions that don't
correspond to any single point in the control-flow graph. That makes it
trickier to keep track of which expressions should expect an `ExpressionUsed`
node.

We therefore sidestep that complexity by only performing `ExpressionUsed`
simplification for expressions associated directly with ordinary `Code`
mappings.
2024-07-15 20:54:28 +10:00
Zalathar
741ed01646 coverage: Store a copy of num_bcbs in ExtractedMappings
This makes it possible to allocate per-BCB data structures without needing
access to the whole graph.
2024-07-15 20:37:14 +10:00
bors
adeb79d3f5 Auto merge of #127265 - harmou01:dev/harmou01/target-spec-metadata, r=Nilstrieb
Fill out target-spec metadata for all targets

**What does this PR try to resolve?**

This PR completes the target-spec metadata fields for all targets. This is required for a corresponding Cargo PR which adds a check for whether a target supports building the standard library when the `-Zbuild-std=std` flag is passed ([see this issue](https://github.com/rust-lang/wg-cargo-std-aware/issues/87). This functionality in Cargo is reliant on the output of `--print=target-spec-json`.

**How should we test and review this PR?**

Check that a given target-spec metadata has been updated with:
```
$ ./x.py build library/std
$ build/host/stage1/bin/rustc --print=target-spec-json --target <target_name> -Zunstable-options
```

**Additional Information**

A few things to note:
* Where a targets 'std' or 'host tools' support is listed as '?' in the rust docs, these are left as 'None' with this PR. The corresponding changes in cargo will only reject an attempt to build std if the 'std' field is 'Some(false)'. In the case it is 'None', cargo will continue trying to build
* There's no rush for this to be merged. I understand that the format for this is not finalised yet.
* Related: #120745
2024-07-15 08:37:39 +00:00
bors
8b72d7a9d7 Auto merge of #127718 - cjgillot:find_field, r=compiler-errors
find_field does not need to be a query.

The current implementation is quadratic in the number of nested fields.

r? `@davidtwco` as you reviewed https://github.com/rust-lang/rust/pull/115367
Fixes https://github.com/rust-lang/rust/issues/121755
2024-07-14 23:35:45 +00:00
Matthias Krüger
79000d2a8f
Rollup merge of #127630 - compiler-errors:type-ascription, r=chenyukang
Remove lang feature for type ascription (since it's a lib feature now)

It's not necessary since it's a library feature now, via the type ascription macro. We can't (and shouldn't) register it as a removed feature since I think that would give "this feature has been removed" errors even for people using the macro (well, I'm pretty sure, though I didn't check).

r? `@Nilstrieb`
2024-07-14 20:24:59 +02:00
Matthias Krüger
5d1f9e21cf
Rollup merge of #127587 - compiler-errors:all-features-at-once, r=Nilstrieb
Report usage of lib features in ast validation

No idea why it was split between ast validation for lang features and a later pass for lang features.

r? `@Nilstrieb`
2024-07-14 20:24:58 +02:00
Matthias Krüger
febe4423c1
Rollup merge of #127273 - nnethercote:fix-DebugParser, r=workingjubilee
Fix `DebugParser`.

I tried using this and it didn't work at all. `prev_token` is never eof, so the accumulator is always false, which means the `then_some` always returns `None`, which means `scan` always returns `None`, and `tokens` always ends up an empty vec. I'm not sure how this code was supposed to work.

(An aside: I find `Iterator::scan` to be a pretty wretched function, that produces code which is very hard to understand. Probably why this is just one of two uses of it in the entire compiler.)

This commit changes it to a simpler imperative style that produces a valid `tokens` vec.

r? `@workingjubilee`
2024-07-14 20:24:58 +02:00
Michael Goulet
f08c43afc7 Suppress some fallout from gen in synstructure 2024-07-14 14:22:11 -04:00
Michael Goulet
dc20733913 Stop using the gen keyword in the compiler 2024-07-14 14:01:01 -04:00
Adwin White
e595f3d13f Add cache for allocate_str 2024-07-14 22:11:46 +08:00
Camille GILLOT
b494d98b18 find_field does not need to be a query. 2024-07-14 13:25:25 +00:00
bors
88fa119c77 Auto merge of #127670 - compiler-errors:no-type-length-limit, r=jackh726
Gate the type length limit check behind a nightly flag

Effectively disables the type length limit by introducing a `-Zenforce-type-length-limit` which defaults to **`false`**, since making the length limit actually be enforced ended up having a worse fallout than expected. We still keep the code around, but the type length limit attr is now a noop (except for its usage in some diagnostics code?).

r? `@lcnr` -- up to you to decide what team consensus we need here since this reverses an FCP decision.

Reopens #125460 (if we decide to reopen it or keep it closed)
Effectively reverses the decision FCP'd in #125507
Closes #127346
2024-07-14 12:44:07 +00:00
Gurinder Singh
e13eb37eeb Fix malformed suggestion for repeated maybe unsized bounds 2024-07-14 17:46:25 +05:30
bors
a241cf1c49 Auto merge of #127713 - matthiaskrgr:rollup-zxlyexf, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #127083 (Add release notes for 1.80)
 - #127322 (handle ci-rustc incompatible options during config parse)
 - #127697 (use std for file mtime and atime modifications)
 - #127704 (Fix minor typos in std::process doc on Win argv)
 - #127710 (clarify the meaning of the version number for accepted/removed features)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-14 10:22:01 +00:00
Matthias Krüger
82f13e7215
Rollup merge of #127710 - RalfJung:features, r=compiler-errors
clarify the meaning of the version number for accepted/removed features

For accepted features this is pretty clear, we even use the version number in the warning that says "feature has been stabilized, please remove feature gate".

For removed features we are inconsistent. [This PR](8cece636b2 (diff-a82bdbaaa3c79096a30755dce8896aaf2885128a7f3f3a290072b767f05b6095)) set the version to when it got removed, but [here](https://github.com/rust-lang/rust/pull/116958/files#diff-1ff08f89ad7e972538827e989fa63732c5918b4d0216ccd921de08698d6e18ca) they just got copied over so the version says when the feature was originally added. As far as I can tell, this version number is not actually used anywhere in user-visible diagnostics.
2024-07-14 10:05:22 +02:00
bors
0ffbddd09e Auto merge of #127087 - cjgillot:small-map, r=oli-obk
Only track mentioned places for jump threading

This PR aims to reduce the state space size in jump threading and dataflow const-prop opts.

The current implementation walks the types of all locals, and creates a place for each possible projection. This can easily lead to a large number of places and tracked values, most being useless to the actual pass.

With this PR, we instead collect places that appear syntactically in the MIR (first commit). However, this is not sufficient (second commit), and we miss places that we could track in aggregate assignments. The third commit tracks such assignments to mirror place projections, see the inline comment.

This is complementary to https://github.com/rust-lang/rust/pull/127036

r? `@oli-obk`
2024-07-14 08:01:21 +00:00
Ralf Jung
2dd5369eda clarify the meaning of the version number for accepted/removed features 2024-07-14 08:18:03 +02:00
Zalathar
f7508f8816 Improve internal docs for MatchPair 2024-07-14 15:01:02 +10:00
Zalathar
ce86b2ae96 Move MatchPair tree creation to its own module
This makes it easier to see that `MatchPair::new` has only one non-recursive
caller, because the recursive callers are all in this module.
2024-07-14 15:00:57 +10:00
long-long-float
332b41dbce Use ordinal number in argument error
Fix error message

Fix tests

Format
2024-07-14 13:50:09 +09:00
Jubilee
125343e7ab
Rollup merge of #127558 - nnethercote:more-Attribute-cleanups, r=petrochenkov
More attribute cleanups

A follow-up to #127308.

r? ```@petrochenkov```
2024-07-13 20:19:46 -07:00
Jubilee
1c8ea14272
Rollup merge of #127477 - nnethercote:tweak-inner_attr_ranges, r=petrochenkov
Clear `inner_attr_ranges` regularly.

There's a comment saying we don't do it for performance reasons, but it doesn't actually affect performance.

The commit also tweaks the control flow, to make clearer that two code paths are mutually exclusive.

r? ````@petrochenkov````
2024-07-13 20:19:46 -07:00
Jubilee
1d59d22ac1
Rollup merge of #127434 - onur-ozkan:use-bootstrap-instead-of-rustbuild, r=Mark-Simulacrum
use "bootstrap" instead of "rustbuild" in comments and docs

Let's stick with the single name "bootstrap" to refer to the bootstrap project to avoid confusion. This should make it clearer, especially for new contributors.
2024-07-13 20:19:45 -07:00
bjorn3
6ff363f0ff Merge commit '659243d85c7489412bd0faa1c068d904a6042941' into sync_cg_clif-2024-07-13 2024-07-13 18:39:03 +00:00
Camille GILLOT
7ac7f135e3 Propagate places through assignments. 2024-07-13 12:02:10 +00:00
Camille GILLOT
76f5bc6a9f Create mapped places upon seeing them in the body. 2024-07-13 11:54:25 +00:00
Nicholas Nethercote
aa0e8e1475 Fix DebugParser.
It currently doesn't work at all. This commit changes it to a simpler
imperative style that produces a valid `tokens` vec.

(An aside: I find `Iterator::scan` to be a pretty wretched function,
that produces code which is very hard to understand. Probably why this
is just one of two uses of it in the entire compiler.)
2024-07-13 16:42:00 +10:00
Nicholas Nethercote
cf2dfb2ced Add a test for Parser::debug_lookahead.
That method is currently badly broken, and the test output reflects
this. The obtained tokens list is always empty, except in the case where
we go two `bump`s past the final token, whereupon it will produce as
many `Eof` tokens as asked for.
2024-07-13 15:55:40 +10:00
Jacob Pratt
cb1ccc1842
Rollup merge of #127654 - nikic:llvm-ndebug-fix, r=cuviper
Fix incorrect NDEBUG handling in LLVM bindings

We currently compile our LLVM bindings using `-DNDEBUG` if debuginfo for LLVM is disabled. However, `NDEBUG` doesn't have any relation to debuginfo, it controls whether assertions are enabled.

Split the LLVM_NDEBUG environment variable into two, so that assertions and debuginfo are controlled independently.

After this change, `LLVMRustDIBuilderInsertDeclareAtEnd` triggers an assertion failure on LLVM 19 due to an incorrect cast. Fix it by removing the unused return value entirely.

r? `@cuviper`
2024-07-13 00:24:35 -04:00
Nicholas Nethercote
69f6145ad8 Change look from a macro to a function.
Using `#[track_caller]` works if the assertion is moved outside of the
closure.
2024-07-13 12:02:12 +10:00
Michael Goulet
938ed369ad Gate the type length limit check behind a nightly flag 2024-07-12 21:16:09 -04:00
bors
336e89bd15 Auto merge of #127665 - workingjubilee:rollup-g90yr21, r=workingjubilee
Rollup of 11 pull requests

Successful merges:

 - #126502 (Ignore allocation bytes in some mir-opt tests)
 - #126922 (add lint for inline asm labels that look like binary)
 - #127209 (Added the `xop` target-feature and the `xop_target_feature` feature gate)
 - #127310 (Fix import suggestion ice)
 - #127338 (Migrate `extra-filename-with-temp-outputs` and `issue-85019-moved-src-dir` `run-make` tests to rmake)
 - #127381 (Migrate `issue-83045`, `rustc-macro-dep-files` and `env-dep-info` `run-make` tests to rmake)
 - #127535 (Fire unsafe_code lint on unsafe extern blocks)
 - #127619 (Suggest using precise capturing for hidden type that captures region)
 - #127631 (Remove `fully_normalize`)
 - #127632 (Implement `precise_capturing` support for rustdoc)
 - #127660 (Rename the internal `const_strlen` to just `strlen`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-12 22:59:30 +00:00
Jubilee
c0d949909f
Rollup merge of #127632 - compiler-errors:precise-capturing-rustdoc, r=fmease
Implement `precise_capturing` support for rustdoc

Implements rustdoc (+json) support for local (i.e. non-cross-crate-inlined) RPITs with `use<...>` precise capturing syntax.

Tests kinda suck. They're really hard to write 😰

r? `@fmease` or re-roll if you're too busy!
also cc `@aDotInTheVoid` for the json side

Tracking:
* https://github.com/rust-lang/rust/issues/127228#issuecomment-2201443216 (not fully fixed for cross-crate-inlined opaques)
* https://github.com/rust-lang/rust/issues/123432
2024-07-12 13:47:10 -07:00
Jubilee
4bfc10617a
Rollup merge of #127631 - compiler-errors:yeet-fully-norm, r=lcnr
Remove `fully_normalize`

Yeet this function and replace it w/ some `ObligationCtxt` instead. It wasn't called very often anyways.

r? lcnr
2024-07-12 13:47:09 -07:00
Jubilee
20cf4eb3b0
Rollup merge of #127619 - compiler-errors:precise-capturing-better-sugg, r=oli-obk
Suggest using precise capturing for hidden type that captures region

Adjusts the "add `+ '_`" suggestion for opaques to instead suggest adding or reusing the `+ use<>` in the opaque.

r? oli-obk or please re-roll if you're busy!
2024-07-12 13:47:09 -07:00
Jubilee
2e0591b1e9
Rollup merge of #127535 - spastorino:unsafe_code-unsafe_extern_blocks, r=oli-obk
Fire unsafe_code lint on unsafe extern blocks

Fixes #126738
2024-07-12 13:47:08 -07:00
Jubilee
afb2fbf692
Rollup merge of #127310 - chenyukang:yukang-fix-suggest-import-ice, r=estebank
Fix import suggestion ice

Fixes #127302

#127302 only crash in edition 2015
#120074 can only reproduced in edition 2021
so I added revisions in test file.
2024-07-12 13:47:07 -07:00
Jubilee
a6a7129827
Rollup merge of #127209 - sayantn:xop, r=Amanieu
Added the `xop` target-feature and the `xop_target_feature` feature gate

This is an effort towards #127208. This adds the `xop` target feature gated by `xop_target_feature`.
2024-07-12 13:47:06 -07:00
Jubilee
fc0136e4f4
Rollup merge of #126922 - asquared31415:asm_binary_label, r=estebank
add lint for inline asm labels that look like binary

fixes #94426

Due to a bug/feature in LLVM, labels composed of only the digits `0` and `1` can sometimes be confused with binary literals, even if a binary literal would not be valid in that position.

This PR adds detection for such labels and also as a drive-by change, adds a note to cases such as `asm!(include_str!("file"))` that the label that it found came from an expansion of a macro, it wasn't found in the source code.

I expect this PR to upset some people that were using labels `0:` or `1:` without issue because they never hit the case where LLVM got it wrong, but adding a heuristic to the lint to prevent this is not feasible - it would involve writing a whole assembly parser for every target that we have assembly support for.

[zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/238009-t-compiler.2Fmeetings/topic/.5Bweekly.5D.202024-06-20/near/445870628)

r? ``@estebank``
2024-07-12 13:47:05 -07:00
Jubilee
5d56572f06
Rollup merge of #126502 - cuviper:dump-mir-exclude-alloc-bytes, r=estebank
Ignore allocation bytes in some mir-opt tests

This adds `rustc -Zdump-mir-exclude-alloc-bytes` to skip writing allocation bytes in MIR dumps, and applies it to tests that were failing on s390x due to its big-endian byte order.

Fixes #126261
2024-07-12 13:47:05 -07:00
bors
c6727fc9b5 Auto merge of #123351 - beetrees:x86-ret-snan-rust, r=nikic,workingjubilee
Ensure floats are returned losslessly by the Rust ABI on 32-bit x86

Solves #115567 for the (default) `"Rust"` ABI. When compiling for 32-bit x86, this PR changes the `"Rust"` ABI to return floats indirectly instead of in x87 registers (with the exception of single `f32`s, which this PR returns in general purpose registers as they are small enough to fit in one). No change is made to the `"C"` ABI as that ABI requires x87 register usage and therefore will need a different solution.
2024-07-12 20:36:43 +00:00
Nikita Popov
8dfd3a455d Remove LLVMRustDIBuilderInsertDeclareAtEnd return value
The return value changed from an Instruction to a DbgRecord in
LLVM 19. As we don't actually use the result, drop the return
value entirely to support both.
2024-07-12 22:15:10 +02:00
Nikita Popov
776b0adaaf Fix incorrect NDEBUG handling in LLVM bindings
We currently compile our LLVM bindings using `-DNDEBUG` if
debuginfo for LLVM is disabled. However, `NDEBUG` doesn't have
any relation to debuginfo, it controls whether assertions are
enabled.

Rename the environment variable to `LLVM_ASSERTIONS` and drive
it using the `llvm_assertions` option. Also drop the explicit
`debug(false)` call, as cc already sets this up using the
cargo `DEBUG` environment variable.
2024-07-12 22:13:56 +02:00
Esteban Küber
cf09cba20c When finding item gated behind a cfg flat, point at it
Previously we would only mention that the item was gated out, and opportunisitically mention the feature flag name when possible. We now point to the place where the item was gated, which can be behind layers of macro indirection, or in different modules.

```
error[E0433]: failed to resolve: could not find `doesnt_exist` in `inner`
  --> $DIR/diagnostics-cross-crate.rs:18:23
   |
LL |     cfged_out::inner::doesnt_exist::hello();
   |                       ^^^^^^^^^^^^ could not find `doesnt_exist` in `inner`
   |
note: found an item that was configured out
  --> $DIR/auxiliary/cfged_out.rs:6:13
   |
LL |     pub mod doesnt_exist {
   |             ^^^^^^^^^^^^
note: the item is gated here
  --> $DIR/auxiliary/cfged_out.rs:5:5
   |
LL |     #[cfg(FALSE)]
   |     ^^^^^^^^^^^^^
```
2024-07-12 18:52:52 +00:00
Pavel Grigorenko
59f88d3db9 Silence clippy::derived_hash_with_manual_eq for now 2024-07-12 21:52:29 +03:00
Pavel Grigorenko
168096f663 rustc_type_ir: derivative -> derive-where 2024-07-12 21:52:04 +03:00
Pavel Grigorenko
70a11c7ba9 rustc_next_trait_solver: derivative -> derive-where 2024-07-12 21:48:16 +03:00
Pavel Grigorenko
35ba700d5e rustc_span: derivative -> derive-where 2024-07-12 21:37:43 +03:00
Pavel Grigorenko
fd16a0efeb rustc_middle: derivative -> derive-where 2024-07-12 21:33:02 +03:00
sayantn
1fd0311eab Added the xop target feature and xop_target_feature gate 2024-07-12 23:30:22 +05:30
bors
62c068feea Auto merge of #127636 - nnethercote:fix-Parser-look_ahead, r=oli-obk
Fix `Parser::look_ahead`

`Parser::look_ahead` has a slow but simple general case, and a fast special case that is hit most of the time. But the special case is buggy and behaves differently to the general case. There are also no unit tests. This PR fixes all of this, resulting in a `Parser::look_ahead` that is equally fast, slightly simpler, more correct, and better tested.

r? `@davidtwco`
2024-07-12 17:28:21 +00:00
bors
5d76a13bbe Auto merge of #127653 - matthiaskrgr:rollup-72bqgvp, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #124980 (Generalize `fn allocator` for Rc/Arc.)
 - #126639 (Add AMX target-features and `x86_amx_intrinsics` feature flag)
 - #126827 (Use pidfd_spawn for faster process spawning when a PidFd is requested)
 - #127433 (Stabilize const_cstr_from_ptr (CStr::from_ptr, CStr::count_bytes))
 - #127552 (remove unnecessary `git` usages)
 - #127613 (Update dist-riscv64-linux to binutils 2.40)
 - #127627 (generalize search graph to enable fuzzing)
 - #127648 (Lower timeout of CI jobs to 4 hours)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-12 14:55:25 +00:00
Matthias Krüger
526da2366a
Rollup merge of #127627 - lcnr:rustc_search_graph, r=compiler-errors
generalize search graph to enable fuzzing

I do not believe it to be feasible to correctly implement the search graph without fuzzing. This PR enables this by requiring a fuzzer to only implement three new traits:
- `Cx`: implemented by all `I: Interner`
- `ProofTreeBuilder`: implemented by `struct ProofTreeBuilder<D>` for all `D: SolverDelegate`
- `Delegate`: implemented for a new `struct SearchGraphDelegate<D>` for all `D: SolverDelegate`

It also moves the evaluation cache implementation into `rustc_type_ir`, requiring `Interner` to provide methods to create and access arbitrary `WithDepNode<T>` and to provide mutable access to a given `GlobalCache`. It otherwise does not change the API surface for users of the shared library.

This change should not impact behavior in any way.

r? ``@compiler-errors``
2024-07-12 14:38:00 +02:00
Matthias Krüger
18152d72a4
Rollup merge of #126639 - sayantn:amx, r=Amanieu
Add AMX target-features and `x86_amx_intrinsics` feature flag

This is an effort towards #126622. This adds support for all 5 target-features for `AMX`, and introduces the feature flag `x86_amx_intrinsics`, which would gate these target-features and the yet-to-be-implemented amx intrinsics in stdarch.
2024-07-12 14:37:57 +02:00
bors
05eac57ef6 Auto merge of #127479 - Urgau:rustc-stable-hash, r=michaelwoerister
Use rustc-stable-hash in the compiler

Following https://github.com/rust-lang/compiler-team/issues/755 and the release of the crate on crates.io, let's now use it in the compiler and remove the old implementation.

cc `@michaelwoerister`
r? ghost
2024-07-12 12:34:31 +00:00
lcnr
15f770b143 enable fuzzing of SearchGraph
fully move it into `rustc_type_ir` and make it
independent of `Interner`.
2024-07-12 06:30:19 -04:00
Michael Goulet
843f5dd93b Add rustdoc support for use<> in (local) RPITs 2024-07-12 05:24:51 -04:00
Lzu Tao
5e1cabe982 Add suggestion to use Option::map_or over erroneous Option::unwrap_or 2024-07-12 08:43:28 +00:00
bors
b286722878 Auto merge of #127635 - matthiaskrgr:rollup-foopajr, r=matthiaskrgr
Rollup of 6 pull requests

Successful merges:

 - #127164 (match lowering: Clarify the main loop of the algorithm)
 - #127422 (as_simd: fix doc comment to be in line with align_to)
 - #127596 (More suggestion for converting `Option<&Vec<T>>` to `Option<&[T]>`)
 - #127607 (compiletest: Better error message for bad `normalize-*` headers)
 - #127622 (Mark `builtin_syntax` as internal)
 - #127625 (Revert accidental comment deletion)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-12 03:40:38 +00:00
Nicholas Nethercote
100f3fd133 Add a new special case to Parser::look_ahead.
This new special case is simpler than the old special case because it
only is used when `dist == 1`. But that's still enough to cover ~98% of
cases. This results in equivalent performance to the old special case,
and identical behaviour as the general case.
2024-07-12 13:35:24 +10:00
Nicholas Nethercote
ebe1305b1e Remove the bogus special case from Parser::look_ahead.
The general case at the bottom of `look_ahead` is slow, because it
clones the token cursor. Above it there is a special case for
performance that is hit most of the time and avoids the cloning.
Unfortunately, its behaviour differs from the general case in two ways.

- When within a pair of delimiters, if you look any distance past the
  closing delimiter you get the closing delimiter instead of what comes
  after the closing delimiter.

- It uses `tree_cursor.look_ahead(dist - 1)` which totally confuses
  tokens with token trees. This means that only the first token in a
  token tree will be seen. E.g. in a sequence like `{ a }` the `a` and
  `}` will be skipped over. Bad!

It's likely that these differences weren't noticed before now because
the use of `look_ahead` in the parser is limited to small distances and
relatively few contexts.

Removing the special case causes slowdowns up of to 2% on a range of
benchmarks. The next commit will add a new, correct special case to
regain that lost performance.
2024-07-12 13:33:38 +10:00
Nicholas Nethercote
dad95578b0 Add unit tests for Parser::look_ahead.
It's currently buggy, so some of the test results are surprising, as
described in the `FIXME` comments. The bugs will be fixed in subsequent
commits.
2024-07-12 13:30:00 +10:00
Esteban Küber
71f16bdb32 Make ; suggestions inline 2024-07-12 03:22:32 +00:00
Esteban Küber
b6f518877f fix unused binding 2024-07-12 03:04:06 +00:00
Esteban Küber
377d14be88 More accurate incorrect use of await suggestion 2024-07-12 03:02:58 +00:00
Esteban Küber
b5f94c61f7 Use more accurate span for : to :: suggestion 2024-07-12 03:02:58 +00:00
Esteban Küber
c2b3287483 Make impl and ! removal suggestion short 2024-07-12 03:02:57 +00:00
Esteban Küber
692bc344d5 Make parse error suggestions verbose and fix spans
Go over all structured parser suggestions and make them verbose style.

When suggesting to add or remove delimiters, turn them into multiple suggestion parts.
2024-07-12 03:02:57 +00:00
sayantn
ec05c4ea3f Add the feature gate and target-features 2024-07-11 19:00:49 -07:00
Matthias Krüger
c2b7842555
Rollup merge of #127625 - SkiFire13:revert-comment-deletion, r=workingjubilee
Revert accidental comment deletion

This reverts an accidental comment deletion made in #113128

See also https://github.com/rust-lang/rust/pull/113128#discussion_r1674614882
2024-07-12 03:43:36 +02:00
Matthias Krüger
ca576eae4e
Rollup merge of #127622 - compiler-errors:builtin-internal, r=lqd
Mark `builtin_syntax` as internal

Tracking issue literally says:

> There will never be a general stabilization.

cc #110680 `@est31`
2024-07-12 03:43:36 +02:00
Matthias Krüger
83d1a1b252
Rollup merge of #127596 - tesuji:help-unwrap-or, r=compiler-errors
More suggestion for converting `Option<&Vec<T>>` to `Option<&[T]>`

Please review commit-by-commit.
2024-07-12 03:43:35 +02:00
Matthias Krüger
58fe37f2c3
Rollup merge of #127164 - Nadrieril:clean-lowering-loop, r=matthewjasper
match lowering: Clarify the main loop of the algorithm

Now that we expand or-patterns in a single place in the algorithm, we can move it (back) to the main part of the loop. This makes the call-graph of the main loop rather simple: `match_candidates` has three branches that each call back to `match_candidates`. The remaining tricky part is `finalize_or_candidate`.

I also factored out the whole "process a prefix of the candidates then process the rest" thing which I think helps legibility.

The first two commits are a fix for an indexing mistake I introduced in https://github.com/rust-lang/rust/pull/126553, already sumitted in https://github.com/rust-lang/rust/pull/127028 but feel free to merge this first.

r? `@matthewjasper`
2024-07-12 03:43:34 +02:00
bors
4a31a6c32a Auto merge of #127382 - estebank:const-let, r=compiler-errors
Use verbose style when suggesting changing `const` with `let`
2024-07-12 01:18:12 +00:00
Michael Goulet
a36fcc8969 Remove lang feature for type ascription 2024-07-11 20:40:38 -04:00
Michael Goulet
2c8bbeebf1 Remove fully_normalize 2024-07-11 19:15:04 -04:00
bors
5e311f933d Auto merge of #127614 - matthiaskrgr:rollup-8geziwi, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #124599 (Suggest borrowing on fn argument that is `impl AsRef`)
 - #127572 (Don't mark `DEBUG_EVENT` struct as `repr(packed)`)
 - #127588 (core: Limit remaining f16 doctests to x86_64 linux)
 - #127591 (Make sure that labels are defined after the primary span in diagnostics)
 - #127598 (Allows `#[diagnostic::do_not_recommend]` to supress trait impls in suggestions as well)
 - #127599 (Rename `lazy_cell_consume` to `lazy_cell_into_inner`)
 - #127601 (check is_ident before parse_ident)
 - #127605 (Remove extern "wasm" ABI)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-07-11 22:56:52 +00:00
Lzu Tao
a776e5f922 Add doc for deconstruct_option_or_result 2024-07-11 22:50:23 +00:00
Lzu Tao
872d7b82e1 Add suggestion for Option<&Vec<T>> -> Option<&[T] 2024-07-11 22:50:23 +00:00
Esteban Küber
cbe75486f7 Account for let foo = expr; to suggest const foo: Ty = expr; 2024-07-11 20:39:24 +00:00
Esteban Küber
b56dc8ee90 Use verbose style when suggesting changing const with let 2024-07-11 20:39:24 +00:00
Giacomo Stevanato
d9021791eb Revert accidental comment deletion 2024-07-11 22:38:34 +02:00
Michael Goulet
b77d3ef7c4 Mark builtin syntax as internal 2024-07-11 15:31:39 -04:00
Michael Goulet
42653c0045 Make it translatable too 2024-07-11 14:14:17 -04:00
Michael Goulet
03bee1e1e5 Suggest using precise capturing for hidden type that captures region 2024-07-11 14:01:29 -04:00
Matthias Krüger
fa3ce50f0b
Rollup merge of #127605 - nikic:remove-extern-wasm, r=oli-obk
Remove extern "wasm" ABI

Remove the unstable `extern "wasm"` ABI (`wasm_abi` feature tracked in #83788).

As discussed in https://github.com/rust-lang/rust/pull/127513#issuecomment-2220410679 and following, this ABI is a failed experiment that did not end up being used for anything. Keeping support for this ABI in LLVM 19 would require us to switch wasm targets to the `experimental-mv` ABI, which we do not want to do.

It should be noted that `Abi::Wasm` was internally used for two things: The `-Z wasm-c-abi=legacy` ABI that is still used by default on some wasm targets, and the `extern "wasm"` ABI. Despite both being `Abi::Wasm` internally, they were not the same. An explicit `extern "wasm"` additionally enabled the `+multivalue` feature.

I've opted to remove `Abi::Wasm` in this patch entirely, instead of keeping it as an ABI with only internal usage. Both `-Z wasm-c-abi` variants are now treated as part of the normal C ABI, just with different different treatment in
adjust_for_foreign_abi.
2024-07-11 17:01:41 +02:00
Matthias Krüger
d433f176ef
Rollup merge of #127601 - trevyn:issue-127600, r=compiler-errors
check is_ident before parse_ident

Closes #127600
2024-07-11 17:01:40 +02:00
Matthias Krüger
a10b4d1463
Rollup merge of #127598 - weiznich:diagnostic_do_not_recommend_also_skips_help, r=compiler-errors
Allows `#[diagnostic::do_not_recommend]` to supress trait impls in suggestions as well

This commit changes the error reporting mechanism for not implemented traits to skip impl marked as `#[diagnostic::do_not_recommend]` in the help part of the error message ("the following other types implement trait `Foo`:"). The main use case here is to allow crate authors to skip non-meaningful confusing suggestions. A common example for this are fully generic impls on tuples.

Related to https://github.com/rust-lang/rust/issues/51992

r? `@compiler-errors`
2024-07-11 17:01:39 +02:00
Matthias Krüger
73c500b3a7
Rollup merge of #127591 - compiler-errors:label-after-primary, r=lcnr
Make sure that labels are defined after the primary span in diagnostics

Putting a `#[label]` before a `#[primary_span]` results in that label being overwritten, due to the semantics of `Diagnostic::span` and the fact that labels are stored in the `MultiSpan` of the diagnostic.

This isn't possible to fix in general, since a lot of code actually *relies* in this overwriting behavior (e.g. `rustc_on_unimplemented`). However, it's useful to enforce this for derive-diagnostics, since this is certainly never what you intend to do in a derived diagnostic, where all the fields are meaningful parts of the diagnostic being rendered.

This only matters for `#[label]`, since those are the ones stored in the `MultiSpan` of the error.

We could also make this "just work" by sorting the attrs or processing the primary span attr first, however I think it's kinda pointless to do.

There was 1 case where this mattered, but we literally didn't have a test exercising that diagnostic 🙃
2024-07-11 17:01:38 +02:00
Matthias Krüger
8de487fdbd
Rollup merge of #124599 - estebank:issue-41708, r=wesleywiser
Suggest borrowing on fn argument that is `impl AsRef`

When encountering a move conflict, on an expression that is `!Copy` passed as an argument to an `fn` that is `impl AsRef`, suggest borrowing the expression.

```
error[E0382]: use of moved value: `bar`
  --> f204.rs:14:15
   |
12 |     let bar = Bar;
   |         --- move occurs because `bar` has type `Bar`, which does not implement the `Copy` trait
13 |     foo(bar);
   |         --- value moved here
14 |     let baa = bar;
   |               ^^^ value used here after move
   |
help: borrow the value to avoid moving it
   |
13 |     foo(&bar);
   |         +
```

Fix #41708
2024-07-11 17:01:36 +02:00
Urgau
977439d9b8 Use uplifted rustc-stable-hash crate in rustc_data_structures 2024-07-11 16:51:16 +02:00
bors
bcf1f6db45 Auto merge of #127487 - tgross35:f16-f128-simd, r=Amanieu
Add `f16` and `f128` as simd types in LLVM

`@sayantn` is working on adding SIMD for `f16` and hitting the `FloatingPointVector` error. This should fix it and unblock adding support for `simd_fma` and `simd_fabs` in stdarch.
2024-07-11 14:08:58 +00:00
lcnr
f56b2074c6 solve -> solve/mod 2024-07-11 15:39:17 +02:00
bors
c92a8e4d4d Auto merge of #127311 - oli-obk:do_not_count_errors, r=compiler-errors
Avoid follow-up errors and ICEs after missing lifetime errors on data structures

Tuple struct constructors are functions, so when we call them typeck will use the signature tuple struct constructor function to provide type hints. Since typeck mostly ignores and erases lifetimes, we end up never seeing the error lifetime in writeback, thus not tainting the typeck result.

Now, we eagerly taint typeck results by tainting from `resolve_vars_if_possible`, which is called all over the place.

I did not carry over all the `crashes` test suite tests, as they are really all the same cause (missing or unknown lifetime names in tuple struct definitions or generic arg lists).

fixes #124262
fixes #124083
fixes #125155
fixes #125888
fixes #125992
fixes #126666
fixes #126648
fixes #127268
fixes #127266
fixes #127304
2024-07-11 11:51:33 +00:00
Oli Scherer
dce98c52ff Avoid follow-up errors and ICEs after missing lifetime errors on data structures 2024-07-11 11:00:15 +00:00
Nikita Popov
8a50bcbdce Remove extern "wasm" ABI
Remove the unstable `extern "wasm"` ABI (`wasm_abi` feature tracked
in #83788).

As discussed in https://github.com/rust-lang/rust/pull/127513#issuecomment-2220410679
and following, this ABI is a failed experiment that did not end
up being used for anything. Keeping support for this ABI in LLVM 19
would require us to switch wasm targets to the `experimental-mv`
ABI, which we do not want to do.

It should be noted that `Abi::Wasm` was internally used for two
things: The `-Z wasm-c-abi=legacy` ABI that is still used by
default on some wasm targets, and the `extern "wasm"` ABI. Despite
both being `Abi::Wasm` internally, they were not the same. An
explicit `extern "wasm"` additionally enabled the `+multivalue`
feature.

I've opted to remove `Abi::Wasm` in this patch entirely, instead
of keeping it as an ABI with only internal usage. Both
`-Z wasm-c-abi` variants are now treated as part of the normal
C ABI, just with different different treatment in
adjust_for_foreign_abi.
2024-07-11 12:20:26 +02:00