Commit graph

1308 commits

Author SHA1 Message Date
Oli Scherer
56178ddc90 Treat safe target_feature functions as unsafe by default 2025-01-15 08:58:17 +00:00
Oli Scherer
a907c56a77 Add hir::HeaderSafety to make follow up commits simpler 2025-01-14 10:54:11 +00:00
Oli Scherer
ad7bb20344 Stable Hash: Ignore all HirIds that just identify the node itself 2025-01-10 09:16:16 +00:00
bors
251206c27b Auto merge of #135268 - pietroalbini:pa-bump-stage0, r=Mark-Simulacrum
Master bootstrap update

Part of the release process.

r? `@Mark-Simulacrum`
2025-01-09 13:33:16 +00:00
Matthias Krüger
e4e2d9ceb8
Rollup merge of #128110 - veera-sivarajan:bugfix-80173, r=cjgillot
Suggest Replacing Comma with Semicolon in Incorrect Repeat Expressions

Fixes #80173

This PR detects typos in repeat expressions like `["_", 10]` and `vec![String::new(), 10]` and suggests replacing comma with semicolon.

Also, improves code in other place by adding doc comments and making use of a helper function to check if a type implements `Clone`.

References:
1. For `vec![T; N]`: https://doc.rust-lang.org/std/macro.vec.html
2. For `[T; N]`: https://doc.rust-lang.org/std/primitive.array.html
2025-01-09 06:02:39 +01:00
Pietro Albini
2af3ba9a8a
update cfg(bootstrap) 2025-01-08 21:26:39 +01:00
Oli Scherer
4a8773a3af Rename PatKind::Lit to Expr 2025-01-08 07:34:59 +00:00
Oli Scherer
c9365dd09f Exhaustively handle expressions in patterns 2025-01-08 07:33:46 +00:00
Matthias Krüger
a20d0d5a5c
Rollup merge of #134989 - max-niederman:guard-patterns-hir, r=oli-obk
Lower Guard Patterns to HIR.

Implements lowering of [guard patterns](https://rust-lang.github.io/rfcs/3637-guard-patterns.html) (see the [tracking issue](#129967)) to HIR.
2025-01-07 21:39:40 +01:00
bors
fd127a3a84 Auto merge of #135031 - RalfJung:intrinsics-without-body, r=oli-obk
rustc_intrinsic: support functions without body

We synthesize a HIR body `loop {}` but such bodyless intrinsics.

Most of the diff is due to turning `ItemKind::Fn` into a brace (named-field) enum variant, because it carries a `bool`-typed field now. This is to remember whether the function has a body. MIR building panics to avoid ever translating the fake `loop {}` body, and the intrinsic logic uses the lack of a body to implicitly mark that intrinsic as must-be-overridden.

I first tried actually having no body rather than generating the fake body, but there's a *lot* of code that assumes that all function items have HIR and MIR, so this didn't work very well. Then I noticed that even `rustc_intrinsic_must_be_overridden` intrinsics have MIR generated (they are filled with an `Unreachable` terminator) so I guess I am not the first to discover this. ;)

r? `@oli-obk`
2025-01-04 12:50:38 +00:00
Ralf Jung
3cd3649c6c rustc_intrinsic: support functions without body; they are implicitly marked as must-be-overridden 2025-01-04 11:41:51 +01:00
Ralf Jung
be65012aa3 turn hir::ItemKind::Fn into a named-field variant 2025-01-04 11:35:31 +01:00
Michael Goulet
c5d4996404 nit: Make get_infer_ret_ty name more consistent with is_suggestable_infer_ty 2025-01-02 23:39:16 +00:00
Matthias Krüger
92dbfcc2c0
Rollup merge of #135000 - compiler-errors:opaque-captures-dupe, r=lqd
Fix ICE when opaque captures a duplicated/invalid lifetime

See description on test.

Fixes #132766
Fixes #133693
Fixes #134780
2025-01-01 22:04:18 +01:00
Michael Goulet
d3c6067275 Fix ICE when opaque captures a duplicated/invalid lifetime 2025-01-01 19:32:51 +00:00
Max Niederman
b579c36224 add guard patterns to HIR and implement lowering 2024-12-31 17:21:29 -08:00
Michael Goulet
aea2a6f836 Convert some Into impls into From impls 2024-12-31 01:56:33 +00:00
Veera
98cc3457af Suggest Semicolon in Incorrect Repeat Expressions 2024-12-21 02:30:50 +00:00
Matthias Krüger
f3b19f54fa
Rollup merge of #133782 - dtolnay:closuresjumps, r=spastorino,traviscross
Precedence improvements: closures and jumps

This PR fixes some cases where rustc's pretty printers would redundantly parenthesize expressions that didn't need it.

<table>
<tr><th>Before</th><th>After</th></tr>
<tr><td><code>return (|x: i32| x)</code></td><td><code>return |x: i32| x</code></td></tr>
<tr><td><code>(|| -> &mut () { std::process::abort() }).clone()</code></td><td><code>|| -> &mut () { std::process::abort() }.clone()</code></td></tr>
<tr><td><code>(continue) + 1</code></td><td><code>continue + 1</code></td></tr>
</table>

Tested by `echo "fn main() { let _ = $AFTER; }" | rustc -Zunpretty=expanded /dev/stdin`.

The pretty-printer aims to render the syntax tree as it actually exists in rustc, as faithfully as possible, in Rust syntax. It can insert parentheses where forced by Rust's grammar in order to preserve the meaning of a macro-generated syntax tree, for example in the case of `a * $rhs` where $rhs is `b + c`. But for any expression parsed from source code, without a macro involved, there should never be a reason for inserting additional parentheses not present in the original.

For closures and jumps (return, break, continue, yield, do yeet, become) the unneeded parentheses came from the precedence of some of these expressions being misidentified. In the same order as the table above:

- Jumps and closures are supposed to have equal precedence. The [Rust Reference](https://doc.rust-lang.org/1.83.0/reference/expressions.html#expression-precedence) says so, and in Syn they do. There is no Rust syntax that would require making a precedence distinction between jumps and closures. But in rustc these were previously 2 distinct levels with the closure being lower, hence the parentheses around a closure inside a jump (but not a jump inside a closure).

- When a closure is written with an explicit return type, the grammar [requires](https://doc.rust-lang.org/1.83.0/reference/expressions/closure-expr.html) that the closure body consists of exactly one block expression, not any other arbitrary expression as usual for closures. Parsing of the closure body does not continue after the block expression. So in `|| { 0 }.clone()` the clone is inside the closure body and applies to `{ 0 }`, whereas in `|| -> _ { 0 }.clone()` the clone is outside and applies to the closure as a whole.

- Continue never needs parentheses. It was previously marked as having the lowest possible precedence but it should have been the highest, next to paths and loops and function calls, not next to jumps.
2024-12-21 01:30:15 +01:00
Nicholas Nethercote
2620eb42d7 Re-export more rustc_span::symbol things from rustc_span.
`rustc_span::symbol` defines some things that are re-exported from
`rustc_span`, such as `Symbol` and `sym`. But it doesn't re-export some
closely related things such as `Ident` and `kw`. So you can do `use
rustc_span::{Symbol, sym}` but you have to do `use
rustc_span::symbol::{Ident, kw}`, which is inconsistent for no good
reason.

This commit re-exports `Ident`, `kw`, and `MacroRulesNormalizedIdent`,
and changes many `rustc_span::symbol::` qualifiers in `compiler/` to
`rustc_span::`. This is a 200+ net line of code reduction, mostly
because many files with two `use rustc_span` items can be reduced to
one.
2024-12-18 13:38:53 +11:00
Jonathan Dönszelmann
d50c0a5480
Add hir::Attribute 2024-12-15 19:18:46 +01:00
Stuart Cook
d48af09ffd
Rollup merge of #134285 - oli-obk:push-vwrqsqlwnuxo, r=Urgau
Add some convenience helper methods on `hir::Safety`

Makes a lot of call sites simpler and should make any refactorings needed for https://github.com/rust-lang/rust/pull/134090#issuecomment-2541332415 simpler, as fewer sites have to be touched in case we end up storing some information in the variants of `hir::Safety`
2024-12-15 20:01:38 +11:00
Matthias Krüger
db77788dc5
Rollup merge of #132939 - uellenberg:suggest-deref, r=oli-obk
Suggest using deref in patterns

Fixes #132784

This changes the following code:
```rs
use std::sync::Arc;
fn main() {
    let mut x = Arc::new(Some(1));
    match x {
        Some(_) => {}
        None => {}
    }
}
```

to output
```rs
error[E0308]: mismatched types
  --> src/main.rs:5:9
   |
LL |     match x {
   |           - this expression has type `Arc<Option<{integer}>>`
...
LL |         Some(_) => {}
   |         ^^^^^^^ expected `Arc<Option<{integer}>>`, found `Option<_>`
   |
   = note: expected struct `Arc<Option<{integer}>>`
                found enum `Option<_>`
help: consider dereferencing to access the inner value using the Deref trait
   |
LL |     match *x {
   |           ~~
```

instead of
```rs
error[E0308]: mismatched types
 --> src/main.rs:5:9
  |
4 |     match x {
  |           - this expression has type `Arc<Option<{integer}>>`
5 |         Some(_) => {}
  |         ^^^^^^^ expected `Arc<Option<{integer}>>`, found `Option<_>`
  |
  = note: expected struct `Arc<Option<{integer}>>`
               found enum `Option<_>`
```

This makes it more obvious that a Deref is available, and gives a suggestion on how to use it in order to fix the issue at hand.
2024-12-14 23:56:28 +01:00
Oli Scherer
8a4e5d7444 Add some convenience helper methods on hir::Safety 2024-12-14 20:31:07 +00:00
Michael Goulet
d714a22e7b (Re-)Implement impl_trait_in_bindings 2024-12-14 03:21:24 +00:00
bors
4a204bebdf Auto merge of #134269 - matthiaskrgr:rollup-fkshwux, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #133900 (Advent of `tests/ui` (misc cleanups and improvements) [1/N])
 - #133937 (Keep track of parse errors in `mod`s and don't emit resolve errors for paths involving them)
 - #133938 (`rustc_mir_dataflow` cleanups, including some renamings)
 - #134058 (interpret: reduce usage of TypingEnv::fully_monomorphized)
 - #134130 (Stop using driver queries in the public API)
 - #134140 (Add AST support for unsafe binders)
 - #134229 (Fix typos in docs on provenance)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-12-13 23:09:16 +00:00
uellenberg
831f4549cd Suggest using deref in patterns
Fixes #132784
2024-12-13 14:18:41 -08:00
bors
e217f94917 Auto merge of #134122 - oli-obk:push-zqnyznxtpnll, r=petrochenkov
Move impl constness into impl trait header

This PR is kind of the opposite of the rejected https://github.com/rust-lang/rust/pull/134114

Instead of moving more things into the `constness` query, we want to keep them where their corresponding hir nodes are lowered. So I gave this a spin for impls, which have an obvious place to be (the impl trait header). And surprisingly it's also a perf improvement (likely just slightly better query & cache usage).

The issue was that removing anything from the `constness` query makes it just return `NotConst`, which is wrong. So I had to change it to `bug!` out if used wrongly, and only then remove the impl blocks from the `constness` query. I think this change is good in general, because it makes using `constness` more robust (as can be seen by how few sites that had to be changed, so it was almost solely used specifically for the purpose of asking for functions' constness). The main thing where this change was not great was in clippy, which was using the `constness` query as a general DefId -> constness map. I added a `DefKind` filter in front of that. If it becomes a more common pattern we can always move that helper into rustc.
2024-12-13 16:17:34 +00:00
Michael Goulet
b8c5a0f0eb Fix tools 2024-12-12 16:43:36 +00:00
Michael Goulet
3f97c6be8d Add unwrap_unsafe_binder and wrap_unsafe_binder macro operators 2024-12-12 16:29:40 +00:00
Michael Goulet
2a9e358c72 Lower AST and resolve lifetimes for unsafe binder types 2024-12-12 16:29:40 +00:00
Matthias Krüger
958fc08e68
Rollup merge of #134173 - onur-ozkan:allow-symbol-intern-string-literal, r=jieyouxu
allow `symbol_intern_string_literal` lint in test modules

Since #133545, `x check compiler --stage 1` no longer works because compiler test modules trigger `symbol_intern_string_literal` lint errors. Bootstrap shouldn't control when to ignore or enable this lint in the compiler tree (using `Kind != Test` was ineffective for obvious reasons).

Also, conditionally adding this rustflag invalidates the build cache between `x test` and other commands.

This PR removes the `Kind` check from bootstrap and handles it directly in the compiler tree in a more natural way.
2024-12-12 08:07:03 +01:00
onur-ozkan
f11edf7611 allow symbol_intern_string_literal lint in test modules
Signed-off-by: onur-ozkan <work@onurozkan.dev>
2024-12-11 20:38:55 +03:00
Oli Scherer
c0e0d8f874 Require the constness query to only be invoked on things that can have constness 2024-12-11 11:07:02 +00:00
Michael Goulet
916d279236 Remove more traces of anonymous ADTs 2024-12-10 19:50:47 +00:00
Esteban Küber
9ac95c10c0 Introduce default_field_values feature
Initial implementation of `#[feature(default_field_values]`, proposed in https://github.com/rust-lang/rfcs/pull/3681.

Support default fields in enum struct variant

Allow default values in an enum struct variant definition:

```rust
pub enum Bar {
    Foo {
        bar: S = S,
        baz: i32 = 42 + 3,
    }
}
```

Allow using `..` without a base on an enum struct variant

```rust
Bar::Foo { .. }
```

`#[derive(Default)]` doesn't account for these as it is still gating `#[default]` only being allowed on unit variants.

Support `#[derive(Default)]` on enum struct variants with all defaulted fields

```rust
pub enum Bar {
    #[default]
    Foo {
        bar: S = S,
        baz: i32 = 42 + 3,
    }
}
```

Check for missing fields in typeck instead of mir_build.

Expand test with `const` param case (needs `generic_const_exprs` enabled).

Properly instantiate MIR const

The following works:

```rust
struct S<A> {
    a: Vec<A> = Vec::new(),
}
S::<i32> { .. }
```

Add lint for default fields that will always fail const-eval

We *allow* this to happen for API writers that might want to rely on users'
getting a compile error when using the default field, different to the error
that they would get when the field isn't default. We could change this to
*always* error instead of being a lint, if we wanted.

This will *not* catch errors for partially evaluated consts, like when the
expression relies on a const parameter.

Suggestions when encountering `Foo { .. }` without `#[feature(default_field_values)]`:

 - Suggest adding a base expression if there are missing fields.
 - Suggest enabling the feature if all the missing fields have optional values.
 - Suggest removing `..` if there are no missing fields.
2024-12-09 21:55:01 +00:00
David Tolnay
fe06c5dce1
Never parenthesize continue 2024-12-02 17:50:12 -08:00
David Tolnay
72ac961616
Raise precedence of closure that has explicit return type 2024-12-02 17:48:16 -08:00
David Tolnay
193d82797c
Squash closures and jumps into a single precedence level 2024-12-02 17:33:20 -08:00
Guillaume Gomez
7dd0c8314d
Rollup merge of #133603 - dtolnay:precedence, r=lcnr
Eliminate magic numbers from expression precedence

Context: see https://github.com/rust-lang/rust/pull/133140.

This PR continues on backporting Syn's expression precedence design into rustc. Rustc's design used mysterious integer quantities represented variously as `i8` or `usize` (e.g. `PREC_CLOSURE = -40i8`), a special significance around `0` that is never named, and an extra `PREC_FORCE_PAREN` precedence level that does not correspond to any expression. Syn's design uses a C-like enum with variants that clearly correspond to specific sets of expression kinds.

This PR is a refactoring that has no intended behavior change on its own, but it unblocks other precedence work that rustc's precedence design was poorly suited to accommodate.

- Asymmetrical precedence, so that a pretty-printer can tell `(return 1) + 1` needs parens but `1 + return 1` does not.

- Squashing the `Closure` and `Jump` cases into a single precedence level.

- Numerous remaining false positives and false negatives in rustc pretty-printer's parenthesization of macro metavariables, for example in `$e < rhs` where $e is `lhs as Thing<T>`.

FYI `@fmease` &mdash; you don't need to review if rustbot picks someone else, but you mentioned being interested in the followup PRs.
2024-12-02 17:36:03 +01:00
Jacob Pratt
811eaebf7e
Rollup merge of #133589 - voidc:remove-array-len, r=boxyuwu
Remove `hir::ArrayLen`

This refactoring removes `hir::ArrayLen`, replacing it with `hir::ConstArg`. To represent inferred array lengths (previously `hir::ArrayLen::Infer`), a new variant `ConstArgKind::Infer` is added.

r? `@BoxyUwU`
2024-12-01 22:10:23 -05:00
David Tolnay
7ced18f329
Eliminate magic numbers from expression precedence 2024-11-30 17:53:40 -08:00
Dominik Stolz
d38f01312c Remove hir::ArrayLen, introduce ConstArgKind::Infer
Remove Node::ArrayLenInfer
2024-11-30 21:00:31 +01:00
lcnr
d401a078e7 update comment 2024-11-28 12:22:02 +00:00
bors
dd2837ec5d Auto merge of #133505 - compiler-errors:rollup-xjp8hdi, r=compiler-errors
Rollup of 12 pull requests

Successful merges:

 - #133042 (btree: add `{Entry,VacantEntry}::insert_entry`)
 - #133070 (Lexer tweaks)
 - #133136 (Support ranges in `<[T]>::get_many_mut()`)
 - #133140 (Inline ExprPrecedence::order into Expr::precedence)
 - #133155 (Yet more `rustc_mir_dataflow` cleanups)
 - #133282 (Shorten the `MaybeUninit` `Debug` implementation)
 - #133326 (Remove the `DefinitelyInitializedPlaces` analysis.)
 - #133362 (No need to re-sort existential preds in relate impl)
 - #133367 (Simplify array length mismatch error reporting (to not try to turn consts into target usizes))
 - #133394 (Bail on more errors in dyn ty lowering)
 - #133410 (target check_consistency: ensure target feature string makes some basic sense)
 - #133435 (miri: disable test_downgrade_observe test on macOS)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-11-26 21:57:32 +00:00
Michael Goulet
6e5bac19d0
Rollup merge of #133140 - dtolnay:precedence, r=fmease
Inline ExprPrecedence::order into Expr::precedence

The representation of expression precedence in rustc_ast has been an obstacle to further improvements in the pretty-printer (continuing from #119105 and #119427).

Previously the operation of *"does this expression have lower precedence than that one"* (relevant for parenthesis insertion in macro-generated syntax trees) consisted of 3 steps:

1. Convert `Expr` to `ExprPrecedence` using `.precedence()`
2. Convert `ExprPrecedence` to `i8` using `.order()`
3. Compare using `<`

As far as I can guess, the reason for the separation between `precedence()` and `order()` was so that both `rustc_ast::Expr` and `rustc_hir::Expr` could convert as straightforwardly as possible to the same `ExprPrecedence` enum, and then the more finicky logic performed by `order` could be present just once.

The mapping between `Expr` and `ExprPrecedence` was intended to be as straightforward as possible:

```rust
match self.kind {
    ExprKind::Closure(..) => ExprPrecedence::Closure,
    ...
}
```

although there were exceptions of both many-to-one, and one-to-many:

```rust
    ExprKind::Underscore => ExprPrecedence::Path,
    ExprKind::Path(..) => ExprPrecedence::Path,
    ...
    ExprKind::Match(_, _, MatchKind::Prefix) => ExprPrecedence::Match,
    ExprKind::Match(_, _, MatchKind::Postfix) => ExprPrecedence::PostfixMatch,
```

Where the nature of `ExprPrecedence` becomes problematic is when a single expression kind might be associated with multiple different precedence levels depending on context (outside the expression) and contents (inside the expression). For example consider what is the precedence of an ExprKind::Closure `$closure`. Well, on the left-hand side of a binary operator it would need parentheses in order to avoid the trailing binary operator being absorbed into the closure body: `($closure) + Rhs`, so the precedence is something lower than that of `+`. But on the right-hand side of a binary operator, a closure is just a straightforward prefix expression like a unary op, which is a relatively high precedence level, higher than binops but lower than method calls: `Lhs + $closure` is fine without parens but `($closure).method()` needs them. But as a third case, if the closure contains an explicit return type, then the precedence is an even higher level than that, never needing parenthesization even in a binop left-hand side or method call: `|| -> bool { false } + Rhs` or `|| -> bool { false }.method()`.

You can see that trying to capture all of this resolution about expressions into `ExprPrecedence` violates the intention of `ExprPrecedence` being a straightforward one-to-one correspondence from each AST and HIR `ExprKind` variant. It would be possible to attempt that by doing stuff like `ExprPrecedence::Closure(Side::Leading, ReturnType::No)`, but I don't foresee the original envisioned benefit of the `precedence()`/`order()` distinction being retained in this approach. Instead I want to move toward a model that Syn has been using successfully. In Syn, there is a Precedence enum but it differs from rustc in the following ways:

- There are [relatively few variants](https://github.com/dtolnay/syn/blob/2.0.87/src/precedence.rs#L11-L47) compared to rustc's `ExprPrecedence`. For example there is no distinction at the precedence level between returns and closures, or between loops and method calls.

- We distinguish between [leading](https://github.com/dtolnay/syn/blob/2.0.87/src/fixup.rs#L293) and [trailing](https://github.com/dtolnay/syn/blob/2.0.87/src/fixup.rs#L309) precedence, taking into account an expression's context such as what token follows it (for various syntactic bail-outs in Rust's grammar, like ambiguities around break-with-value) and how it relates to operators from the surrounding syntax tree.

- There are no hardcoded mysterious integer quantities like rustc's `PREC_CLOSURE = -40`. All precedence comparisons are performed via PartialOrd on a C-like enum.

This PR is just a first step in these changes. As you can tell from Syn, I definitely think there is value in having a dedicated type to represent precedence, instead of what `order()` is doing with `i8`. But that is a whole separate adventure because rustc_ast doesn't even agree consistently on `i8` being the type for precedence order; `AssocOp::precedence` instead uses `usize` and there are casts in both directions. It is likely that a type called `ExprPrecedence` will re-appear, but it will look substantially different from the one that existed before this PR.
2024-11-26 12:03:41 -05:00
Guillaume Gomez
03f56d36ae
Rollup merge of #133443 - fmease:rm-dead-eff-code-ii, r=compiler-errors
Remove dead code stemming from the old effects desugaring (II)

Follow-up to #132374.
r? project-const-traits
2024-11-26 15:32:15 +01:00
León Orell Valerian Liehr
4301d0266d
Remove dead code stemming from the old effects desugaring (II) 2024-11-25 12:16:36 +01:00
Frank King
161221da9e Refactor where predicates, and reserve for attributes support 2024-11-25 16:38:35 +08:00
Luca Versari
9022bb2d6f Implement the unsafe-fields RFC.
Co-Authored-By: Jacob Pratt <jacob@jhpratt.dev>
2024-11-21 19:32:07 +01:00