Commit Graph

1342 Commits

Author SHA1 Message Date
Michael Goulet
c98d6994a3 More comments, final tweaks 2024-02-06 02:22:58 +00:00
Michael Goulet
a82bae2172 Teach typeck/borrowck/solvers how to deal with async closures 2024-02-06 02:22:58 +00:00
Michael Goulet
a20421734b Make async closures directly lower to ClosureKind::CoroutineClosure 2024-02-06 02:22:58 +00:00
Michael Goulet
b2bb51734c Make sure that async closures (and fns) only capture their parent callable's parameters by move, and nothing else 2024-02-06 02:22:57 +00:00
Nicholas Nethercote
0ac1195ee0 Invert diagnostic lints.
That is, change `diagnostic_outside_of_impl` and
`untranslatable_diagnostic` from `allow` to `deny`, because more than
half of the compiler has be converted to use translated diagnostics.

This commit removes more `deny` attributes than it adds `allow`
attributes, which proves that this change is warranted.
2024-02-06 13:12:33 +11:00
bors
f3b9d47a46 Auto merge of #120392 - compiler-errors:async-bound-modifier, r=davidtwco,fmease
Introduce support for `async` bound modifier on `Fn*` traits

Adds `async` to the list of `TraitBoundModifiers`, which instructs AST lowering to map the trait to an async flavor of the trait. For now, this is only supported for `Fn*` to `AsyncFn*`, and I expect that this manual mapping via lang items will be replaced with a better system in the future.

The motivation for adding these bounds is to separate the users of async closures from the exact trait desugaring of their callable bounds. Instead of users needing to be concerned with the `AsyncFn` trait, they should be able to write `async Fn()` and it will desugar to whatever underlying trait we decide is best for the lowering of async closures.

Note: rustfmt support can be done in the rustfmt repo after a subtree sync.
2024-02-06 00:45:11 +00:00
Vadim Petrochenkov
c5eca333fc hir: Remove the generic type parameter from MaybeOwned
It's only ever used with a reference to `OwnerInfo` as an argument.
2024-02-03 15:50:14 +03:00
Vadim Petrochenkov
f5d6eb30a8 hir: Stop keeping prefixes for most of use list stems
And make sure all other imports have non-empty resolution lists.
2024-02-03 14:41:46 +03:00
Michael Goulet
3913c9a0ca Error on incorrect item kind in async bound 2024-01-31 16:59:19 +00:00
Michael Goulet
0eb2adb7e8 Add async bound modifier to enable async Fn bounds 2024-01-31 16:59:19 +00:00
Dylan DPC
eaa100204e
Rollup merge of #120428 - petrochenkov:somehir2, r=compiler-errors
hir: Two preparatory changes for #120206

cc https://github.com/rust-lang/rust/pull/120206
r? ```@compiler-errors```
2024-01-29 12:56:54 +00:00
Nicholas Nethercote
5d9dfbd08f Stop using String for error codes.
Error codes are integers, but `String` is used everywhere to represent
them. Gross!

This commit introduces `ErrCode`, an integral newtype for error codes,
replacing `String`. It also introduces a constant for every error code,
e.g. `E0123`, and removes the `error_code!` macro. The constants are
imported wherever used with `use rustc_errors::codes::*`.

With the old code, we have three different ways to specify an error code
at a use point:
```
error_code!(E0123)  // macro call

struct_span_code_err!(dcx, span, E0123, "msg");  // bare ident arg to macro call

\#[diag(name, code = "E0123")]  // string
struct Diag;
```

With the new code, they all use the `E0123` constant.
```
E0123  // constant

struct_span_code_err!(dcx, span, E0123, "msg");  // constant

\#[diag(name, code = E0123)]  // constant
struct Diag;
```

The commit also changes the structure of the error code definitions:
- `rustc_error_codes` now just defines a higher-order macro listing the
  used error codes and nothing else.
- Because that's now the only thing in the `rustc_error_codes` crate, I
  moved it into the `lib.rs` file and removed the `error_codes.rs` file.
- `rustc_errors` uses that macro to define everything, e.g. the error
  code constants and the `DIAGNOSTIC_TABLES`. This is in its new
  `codes.rs` file.
2024-01-29 07:41:41 +11:00
Vadim Petrochenkov
b2b5b91bfb hir: Use InferArg in ArrayLen::Infer 2024-01-28 02:04:39 +03:00
Vadim Petrochenkov
5f8030dcc9 hir: Remove unnecessary HirId from hir::Let
It has 1-to-1 correspondence to its expression id.

Also remove mostly useless `visit_let_expr`.
2024-01-28 02:04:39 +03:00
clubby789
fd29f74ff8 Remove unused features 2024-01-25 14:01:33 +00:00
Josh Stone
33e0422826 Pack the u128 in LitKind::Int 2024-01-19 20:10:39 -08:00
bors
d3c9082a44 Auto merge of #120006 - cjgillot:no-hir-owner, r=wesleywiser
Get rid of the hir_owner query.

This query was meant as a firewall between `hir_owner_nodes` which is supposed to change often, and the queries that only depend on the item signature. That firewall was inefficient, leaking the contents of the HIR body through `HirId`s.

`hir_owner` incurs a significant cost, as we need to hash HIR twice in multiple modes. This PR proposes to remove it, and simplify the hashing scheme.

For the future, `def_kind`, `def_span`... are much more efficient for incremental decoupling, and should be preferred.
2024-01-19 02:36:13 +00:00
Matthias Krüger
536fc22917
Rollup merge of #119978 - compiler-errors:async-closure-captures, r=oli-obk
Move async closure parameters into the resultant closure's future eagerly

Move async closure parameters into the closure's resultant future eagerly.

Before, we used to desugar `async |p1, p2, ..| { body }` as `|p1, p2, ..| { || async { body } }`. Now, we desugar the above like `|p1, p2, ..| { async move { let p1 = p1; let p2 = p2; ... body } }`. This mirrors the same desugaring that `async fn` does with its parameter types, and the compiler literally uses the same code via a shared helper function.

This removes the necessity for E0708, since now expressions like `async |x: i32| { x }` will not give you confusing borrow errors.

This does *not* fix the case where async closures have self-borrows. This will come with a general implementation of async closures, which is still in the works.

r? oli-obk
2024-01-18 10:34:18 +01:00
Lieselotte
7889e99b55
Add PatKind::Err 2024-01-17 03:14:16 +01:00
Camille GILLOT
d59968b5f6 Simplify BodyId hashing. 2024-01-16 23:52:30 +00:00
Michael Goulet
f1ee076f81 Async closures will move params into the future always 2024-01-16 17:12:10 +00:00
Michael Goulet
8bb1eaee64 Introduce helper that deals with moving async args into the coroutine 2024-01-16 15:15:00 +00:00
George-lewis
36a69e9d39 Add check for ui_testing via promoting parameters from ParseSess to Session 2024-01-13 12:11:13 -05:00
Bryanskiy
d69cd6473c Delegation implementation: step 1 2024-01-12 14:11:16 +03:00
clubby789
f1b8b7d7ae Add error code for missing base expression in struct update syntax 2024-01-09 19:25:54 +00:00
Matthias Krüger
39b3ef17a1
Rollup merge of #119705 - fmease:tilde-const-assoc-fns-trait-impls, r=compiler-errors
Support `~const` in associated functions in trait impls

Fixes #119700.
2024-01-08 00:38:35 +01:00
Michael Goulet
7e38b70cc0 Split note, fix const/static impl trait error 2024-01-07 18:00:03 +00:00
León Orell Valerian Liehr
3acc5a0da3
effects: support ~const in assoc fns in trait impls 2024-01-07 18:22:47 +01:00
Michael Goulet
0f3957487b Inline some helpers no longer needed due to RPITIT being stable 2024-01-07 16:40:56 +00:00
Michael Goulet
8af1a6a1e5 Make ImplTraitPosition display more descriptive 2024-01-07 16:40:53 +00:00
Matthew Jasper
407cb24142 Remove hir::Guard
Use Expr instead. Use `ExprKind::Let` to represent if let guards.
2024-01-05 10:56:59 +00:00
Matthias Krüger
f4335a419f
Rollup merge of #119540 - fmease:no-effect-args-inside-dyn-trait, r=compiler-errors
Don't synthesize host effect args inside trait object types

While we were indeed emitting an error for `~const` & `const` trait bounds in trait object types, we were still synthesizing host effect args for them.

Since we don't record the original trait bound modifiers for dyn-Trait in `hir::TyKind::TraitObject` (unlike we do for let's say impl-Trait, `hir::TyKind::OpaqueTy`), AstConv just assumes `ty::BoundConstness::NotConst` in `conv_object_ty_poly_trait_ref` which given `<host> dyn ~const NonConstTrait` resulted in us not realizing that `~const` was used on a non-const trait which lead to a failed assertion in the end.

Instead of updating `hir::TyKind::TraitObject` to track this kind of information, just strip the user-provided constness (similar to #119505).

Fixes #119524.
2024-01-04 08:33:26 +01:00
León Orell Valerian Liehr
8bce6fc35e
Rollup merge of #119505 - fmease:no-host-param-for-trait-fns, r=fee1-dead
Don't synthesize host effect params for trait associated functions marked const

Fixes #113378.

r? fee1-dead or compiler
2024-01-03 16:08:30 +01:00
León Orell Valerian Liehr
b5618bc222
Rollup merge of #119494 - fmease:deny-hr-param-defaults, r=compiler-errors
Deny defaults for higher-ranked generic parameters

Fixes #119489 (incl. https://github.com/rust-lang/rust/issues/119489#issuecomment-1873399208).
Partially reverts #119042.

cc ```@bvanjoi```
r? ```@compiler-errors``` or compiler
2024-01-03 16:08:29 +01:00
León Orell Valerian Liehr
695a02e0d8
Don't synthesize host effect args inside trait object types 2024-01-03 09:25:27 +01:00
León Orell Valerian Liehr
ba860344e1
Don't synthesize host effect params for trait assoc fns marked const 2024-01-02 13:49:47 +01:00
León Orell Valerian Liehr
3d0297a1e1
Deny defaults for higher-ranked generic parameters 2024-01-01 21:58:25 +01:00
bors
d868bc2842 Auto merge of #119284 - Nadrieril:fix-bodiless-arm-parse, r=cjgillot
Don't drop a hir node after lowering

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

It seems that all hir nodes that get allocated an id must be placed within the hir on pain of ICEs. In https://github.com/rust-lang/rust/pull/118527 I dropped guards on never patterns since they're not useful, which caused the ICE.
2023-12-30 22:44:33 +00:00
Arpad Borsos
2480a0f3f6
Merge Coroutine lowering functions
Instead of having separate `make_async/etc_expr` functions, this merges them them into one, reducing code duplication a bit.
2023-12-28 21:24:24 +01:00
bors
88d69b72b4 Auto merge of #119099 - fmease:always-const-trait-bounds, r=fee1-dead
Introduce `const Trait` (always-const trait bounds)

Feature `const_trait_impl` currently lacks a way to express “always const” trait bounds. This makes it impossible to define generic items like fns or structs which contain types that depend on const method calls (\*). While the final design and esp. the syntax of effects / keyword generics isn't set in stone, some version of “always const” trait bounds will very likely form a part of it. Further, their implementation is trivial thanks to the `effects` backbone.

Not sure if this needs t-lang sign-off though.

(\*):

```rs
#![feature(const_trait_impl, effects, generic_const_exprs)]

fn compute<T: const Trait>() -> Type<{ T::generate() }> { /*…*/ }

struct Store<T: const Trait>
where
    Type<{ T::generate() }>:,
{
    field: Type<{ T::generate() }>,
}
```

Lastly, “always const” trait bounds are a perfect fit for `generic_const_items`.

```rs
#![feature(const_trait_impl, effects, generic_const_items)]

const DEFAULT<T: const Default>: T = T::default();
```

Previously, we (oli, fee1-dead and I) wanted to reinterpret `~const Trait` as `const Trait` in generic const items which would've been quite surprising and not very generalizable.
Supersedes #117530.

---

cc `@oli-obk`

As discussed
r? fee1-dead (or compiler)
2023-12-27 19:24:31 +00:00
León Orell Valerian Liehr
3eb48a35c8
Introduce const Trait (always-const trait bounds) 2023-12-27 12:51:32 +01:00
bors
deace71034 Auto merge of #119324 - compiler-errors:rollup-c6eqcg9, r=compiler-errors
Rollup of 5 pull requests

Successful merges:

 - #119235 (Add missing feature gate for sanitizer CFI cfgs)
 - #119240 (Make some non-diagnostic-affecting `QPath::LangItem` into regular `QPath`s)
 - #119297 (Pass DeadItem and lint as consistent group in dead-code.)
 - #119307 (Clean up some lifetimes in `rustc_pattern_analysis`)
 - #119323 (add test for coercing never to infinite type)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-12-26 19:28:49 +00:00
Michael Goulet
e7bd402a38
Rollup merge of #119240 - compiler-errors:lang-item-more, r=petrochenkov
Make some non-diagnostic-affecting `QPath::LangItem` into regular `QPath`s

The rest of 'em affect diagnostics, so leave them alone... for now.

cc #115178
2023-12-26 13:29:13 -05:00
Nadrieril
d5b2d88a1a Don't drop a hir node after lowering 2023-12-26 09:45:54 +01:00
bohan
e16efbd23a fallback default to None during ast-loweing for lifetime binder 2023-12-26 16:10:29 +08:00
bors
1ab783112a Auto merge of #119258 - compiler-errors:closure-kind, r=eholk
Make closures carry their own ClosureKind

Right now, we use the "`movability`" field of `hir::Closure` to distinguish a closure and a coroutine. This is paired together with the `CoroutineKind`, which is located not in the `hir::Closure`, but the `hir::Body`. This is strange and redundant.

This PR introduces `ClosureKind` with two variants -- `Closure` and `Coroutine`, which is put into `hir::Closure`. The `CoroutineKind` is thus removed from `hir::Body`, and `Option<Movability>` no longer needs to be a stand-in for "is this a closure or a coroutine".

r? eholk
2023-12-26 04:25:53 +00:00
Michael Goulet
7e00e9736d Make some non-diagnostic-affecting QPath::LangItem into regular qpaths 2023-12-26 04:07:38 +00:00
Michael Goulet
3320c09eab Only regular coroutines have movability 2023-12-25 21:13:41 +00:00
Michael Goulet
909dd864f1 Make closures carry their own ClosureKind, rather than deducing what it is from movability 2023-12-25 16:29:15 +00:00
Nicholas Nethercote
99472c7049 Remove Session methods that duplicate DiagCtxt methods.
Also add some `dcx` methods to types that wrap `TyCtxt`, for easier
access.
2023-12-24 08:05:28 +11:00
Matthias Krüger
bdc4480914
Rollup merge of #119231 - aDotInTheVoid:PatKind-struct-bool-docs, r=compiler-errors
Clairify `ast::PatKind::Struct` presese of `..` by using an enum instead of a bool

The bool is mainly used for when a `..` is present, but it is also set on recovery to avoid errors. The doc comment not describes both of these cases.

See cee794ee98/compiler/rustc_parse/src/parser/pat.rs (L890-L897) for the only place this is constructed.

r? ``@compiler-errors``
2023-12-23 16:23:54 +01:00
Alona Enraght-Moony
1349d86c72 bool->enum for ast::PatKind::Struct presence of ..
See cee794ee98/compiler/rustc_parse/src/parser/pat.rs (L890-L897) for the only place this is constructed.
2023-12-23 02:50:31 +00:00
Michael Goulet
eef023c806
Rollup merge of #119222 - eholk:into-async-iterator, r=compiler-errors,dtolnay
Add `IntoAsyncIterator`

This introduces the `IntoAsyncIterator` trait and uses it in the desugaring of the unstable `for await` loop syntax. This is mostly added for symmetry with `Iterator` and `IntoIterator`.

r? `@compiler-errors`

cc `@rust-lang/libs-api,` `@rust-lang/wg-async`
2023-12-22 21:41:04 -05:00
Michael Goulet
004450506e Split coroutine desugaring kind from source 2023-12-22 23:58:29 +00:00
Eric Holk
acb6f17adf
Use IntoAsyncIterator in for await loop desugaring 2023-12-22 11:01:06 -08:00
bors
208dd2032b Auto merge of #118847 - eholk:for-await, r=compiler-errors
Add support for `for await` loops

This adds support for `for await` loops. This includes parsing, desugaring in AST->HIR lowering, and adding some support functions to the library.

Given a loop like:
```rust
for await i in iter {
    ...
}
```
this is desugared to something like:
```rust
let mut iter = iter.into_async_iter();
while let Some(i) = loop {
    match core::pin::Pin::new(&mut iter).poll_next(cx) {
        Poll::Ready(i) => break i,
        Poll::Pending => yield,
    }
} {
    ...
}
```

This PR also adds a basic `IntoAsyncIterator` trait. This is partly for symmetry with the way `Iterator` and `IntoIterator` work. The other reason is that for async iterators it's helpful to have a place apart from the data structure being iterated over to store state. `IntoAsyncIterator` gives us a good place to do this.

I've gated this feature behind `async_for_loop` and opened #118898 as the feature tracking issue.

r? `@compiler-errors`
2023-12-22 14:17:10 +00:00
bors
aaef5fe497 Auto merge of #119163 - fmease:refactor-ast-trait-bound-modifiers, r=compiler-errors
Refactor AST trait bound modifiers

Instead of having two types to represent trait bound modifiers in the parser / the AST (`parser::ty::BoundModifiers` & `ast::TraitBoundModifier`), only to map one to the other later, just use `parser::ty::BoundModifiers` (moved & renamed to `ast::TraitBoundModifiers`).

The struct type is more extensible and easier to deal with (see [here](https://github.com/rust-lang/rust/pull/119099/files#r1430749981) and [here](https://github.com/rust-lang/rust/pull/119099/files#r1430752116) for context) since it more closely models what it represents: A compound of two kinds of modifiers, constness and polarity. Modeling this as an enum (the now removed `ast::TraitBoundModifier`) meant one had to add a new variant per *combination* of modifier kind, which simply isn't scalable and which lead to a lot of explicit non-DRY matches.

NB: `hir::TraitBoundModifier` being an enum is fine since HIR doesn't need to worry representing invalid modifier kind combinations as those get rejected during AST validation thereby immensely cutting down the number of possibilities.
2023-12-22 02:00:55 +00:00
Matthias Krüger
d0d814ff48
Rollup merge of #119145 - aDotInTheVoid:variantdata-struct-struct, r=compiler-errors
Give `VariantData::Struct`  named fields, to clairfy `recovered`.

Implements https://github.com/rust-lang/rust/pull/119121#discussion_r1431467066. Supersedes #119121

This way, it's clear what the bool fields means, instead of having to find where it's generated. Changes both ast and hir.

r? `@compiler-errors`
2023-12-20 21:18:59 +01:00
León Orell Valerian Liehr
5e4f12b41a
Refactor AST trait bound modifiers 2023-12-20 19:39:46 +01:00
Vadim Petrochenkov
5e5d82e803 resolve: Eagerly feed closure visibilities
Also factor out all tcx-dependent operations performed for every created definition into `TyCtxt::create_def`
2023-12-20 13:42:58 +03:00
Alona Enraght-Moony
11337805fb Give VariantData::Struct named fields, to clairfy recovered. 2023-12-20 00:07:34 +00:00
Eric Holk
97df0d3657
Desugar for await loops 2023-12-19 12:26:27 -08:00
Eric Holk
27d6539a46
Plumb awaitness of for loops 2023-12-19 12:26:20 -08:00
bors
32f5db9890 Auto merge of #119093 - michaelwoerister:mcp533-18, r=petrochenkov
Replace some instances of FxHashMap/FxHashSet with stable alternatives (mostly in rustc_hir and rustc_ast_lowering)

Part of https://github.com/rust-lang/compiler-team/issues/533. We should be getting close to being able to remove the HashStable impl of HashMap.
2023-12-19 08:46:02 +00:00
bors
59096cdad0 Auto merge of #119061 - compiler-errors:async-gen-abi, r=wesleywiser
Desugar `yield` in `async gen` correctly, ensure `gen` always returns unit

1. Ensure `async gen` blocks desugar `yield $expr` to `task_context = yield async_gen_ready($expr)`. Previously we were not assigning the `task_context` correctly, meaning that `yield` expressions in async generators returned type `ResumeTy` instead of `()`, and that we were not storing the `task_context`  (which is probably unsound if we were reading the old task-context which has an invalidated borrow or something...)
2. Ensure that all `(async?) gen` blocks and `(async?) gen` fns return unit. Previously we were only checking this for `gen fn`, meaning that `gen {}` and `async gen {}` and `async gen fn` were allowed to return values that weren't unit. This is why #119058 was an ICE rather than an E0308.

Fixes #119058.
2023-12-19 00:42:50 +00:00
Michael Woerister
115885ba7e Replace some instances of FxHashMap/FxHashSet with stable alternatives (mostly in rustc_hir and rustc_ast_lowering)
Part of https://github.com/rust-lang/compiler-team/issues/533
2023-12-18 21:03:32 +01:00
bors
e004adb556 Auto merge of #119069 - matthiaskrgr:rollup-xxk4m30, r=matthiaskrgr
Rollup of 5 pull requests

Successful merges:

 - #118852 (coverage: Skip instrumenting a function if no spans were extracted from MIR)
 - #118905 ([AIX] Fix XCOFF metadata)
 - #118967 (Add better ICE messages for some undescriptive panics)
 - #119051 (Replace `FileAllocationInfo` with `FileEndOfFileInfo`)
 - #119059 (Deny `~const` trait bounds in inherent impl headers)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-12-18 08:03:22 +00:00
Matthias Krüger
578a7dd35e
Rollup merge of #118967 - RossSmyth:panic-messages, r=TaKO8Ki
Add better ICE messages for some undescriptive panics

Add some better messages at some panics

re: #118955

I took a look at some others but either was not able to figure out what they did, or it was unclear what they should say instead. For example in the query system whether each time a poisoned value is matched upon if they should all just call `FatalError.raise()`
2023-12-18 08:08:23 +01:00
Nicholas Nethercote
09af8a667c Rename Session::span_diagnostic as Session::dcx. 2023-12-18 16:06:21 +11:00
Michael Goulet
454bff7682 Ensure yield expressions desugar correctly in async generators 2023-12-18 01:42:19 +00:00
Vadim Petrochenkov
be321aa473 resolve: Replace visibility table in resolver outputs with query feeding
Also feed missing visibilities for import stems and trait impl items, which were previously evaluated lazily.
2023-12-18 02:26:55 +03:00
Jubilee
c5a3d98cc6
Rollup merge of #119004 - matthiaskrgr:conv, r=compiler-errors
NFC don't convert types to identical types
2023-12-15 21:33:00 -08:00
Matthias Krüger
8479945c08 NFC don't convert types to identical types 2023-12-15 23:56:24 +01:00
Jubilee
1d54949765
Rollup merge of #118396 - compiler-errors:ast-lang-items, r=cjgillot
Collect lang items from AST, get rid of `GenericBound::LangItemTrait`

r? `@cjgillot`
cc #115178

Looking forward, the work to remove `QPath::LangItem` will also be significantly more difficult, but I plan on doing it as well. Specifically, we have to change:
1. A lot of `rustc_ast_lowering` for things like expr `..`
2. A lot of astconv, since we actually instantiate lang and non-lang paths quite differently.
3. A ton of diagnostics and clippy lints that are special-cased via `QPath::LangItem`

Meanwhile, it was pretty easy to remove `GenericBound::LangItemTrait`, so I just did that here.
2023-12-15 14:08:15 -08:00
Michael Goulet
fc010de26b banish hir::GenericBound::LangItemTrait 2023-12-15 16:17:27 +00:00
Michael Goulet
ad00641b74 Collect lang items from AST 2023-12-15 16:12:27 +00:00
Michael Goulet
1cc0d7d56c Annotate some more bugs 2023-12-15 14:45:06 +00:00
Ross Smyth
663bea5a96 Add better ICE messages for some undescriptive panics 2023-12-15 00:50:55 -05:00
Matthias Krüger
dbc6ec6636
Rollup merge of #118759 - compiler-errors:bare-unit-structs, r=petrochenkov
Support bare unit structs in destructuring assignments

We should be allowed to use destructuring assignments on *bare* unit structs, not just unit structs that are located within other pattern constructors.

Fixes #118753

r? petrochenkov since you reviewed #95380, reassign if you're busy or don't want to review this.
2023-12-13 18:03:33 +01:00
Nadrieril
e274372689 Correctly gate the parsing of match arms without body 2023-12-12 14:42:04 +01:00
bors
b9068315db Auto merge of #116952 - compiler-errors:lifetime_capture_rules_2024, r=TaKO8Ki
Implement 2024-edition lifetime capture rules RFC

Implements rust-lang/rfcs#3498.
2023-12-10 15:51:39 +00:00
surechen
40ae34194c remove redundant imports
detects redundant imports that can be eliminated.

for #117772 :

In order to facilitate review and modification, split the checking code and
removing redundant imports code into two PR.
2023-12-10 10:56:22 +08:00
Guillaume Gomez
fd60c5a788
Rollup merge of #118766 - compiler-errors:lower-spans, r=spastorino
Lower some forgotten spans

I wrote a HIR visitor that visited all of the spans in the HIR, and made it ICE when we have a unlowered span. That led me to discover these unlowered spans.
2023-12-09 14:05:11 +01:00
Michael Goulet
c980fae35c Lower some forgotten coroutine spans 2023-12-09 00:10:36 +00:00
Michael Goulet
97de8fba56 Lower spans for opaque duplicated lifetimes, const infer vars 2023-12-09 00:10:36 +00:00
Michael Goulet
3818fc02c4 Lower constness span in host param 2023-12-09 00:10:36 +00:00
Michael Goulet
d5dcd85376 More nits 2023-12-08 21:46:39 +00:00
Michael Goulet
8361a7288e Introduce closure_id method on CoroutineKind 2023-12-08 21:46:39 +00:00
Michael Goulet
d473bdfdc3 Support bare unit structs in destructuring assignments 2023-12-08 19:55:07 +00:00
bors
f967532a47 Auto merge of #118420 - compiler-errors:async-gen, r=eholk
Introduce support for `async gen` blocks

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

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

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

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

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

r? `@ghost`
2023-12-08 19:13:57 +00:00
Michael Goulet
11375c8657 Add tests 2023-12-08 17:23:26 +00:00
Michael Goulet
44911b7c67 Make some matches exhaustive to avoid bugs, fix tools 2023-12-08 17:23:26 +00:00
Michael Goulet
a208bae00e Support async gen fn 2023-12-08 17:23:26 +00:00
Michael Goulet
2806c2df7b coro_kind -> coroutine_kind 2023-12-08 17:23:25 +00:00
Michael Goulet
96bb542a31 Implement async gen blocks 2023-12-08 17:23:25 +00:00
bors
2b399b5275 Auto merge of #118527 - Nadrieril:never_patterns_parse, r=compiler-errors
never_patterns: Parse match arms with no body

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

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

r? `@compiler-errors`
2023-12-08 17:08:52 +00:00
bors
f32d29837d Auto merge of #118605 - fee1-dead-contrib:rm-rustc_host, r=compiler-errors
Remove `#[rustc_host]`, use internal desugaring

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

r? `@compiler-errors`
2023-12-06 16:00:24 +00:00
Michael Goulet
803772e81d Enable new capture rules by default on edition 2024 2023-12-05 19:53:59 +00:00
Michael Goulet
0ad160a585 Add lifetime_capture_rules_2024 2023-12-05 19:53:59 +00:00
Deadbeef
65212a07e7 Remove #[rustc_host], use internal desugaring 2023-12-05 01:15:21 +00:00
Eric Holk
50ef8006eb
Address code review feedback 2023-12-04 14:33:46 -08:00
Eric Holk
26f9954971
Fix some broken tests 2023-12-04 13:03:41 -08:00
Eric Holk
f9d1f922dc
Option<CoroutineKind> 2023-12-04 13:03:37 -08:00
Eric Holk
48d5f1f0f2
Merge Async and Gen into CoroutineKind 2023-12-04 12:48:01 -08:00
Eric Holk
c104f3b629
Lower return types for gen fn to impl Iterator 2023-12-04 11:23:05 -08:00
Vadim Petrochenkov
17e799c270 rustc: Harmonize DefKind and DefPathData
`DefPathData::(ClosureExpr,ImplTrait)` are renamed to match `DefKind::(Closure,OpaqueTy)`.

`DefPathData::ImplTraitAssocTy` is replaced with `DefPathData::TypeNS(kw::Empty)` because both correspond to `DefKind::AssocTy`.
It's possible that introducing `(DefKind,DefPathData)::AssocOpaqueTy` could be a better solution, but that would be a much more invasive change.

Const generic parameters introduced for effects are moved from `DefPathData::TypeNS` to `DefPathData::ValueNS`, because constants are values.

`DefPathData` is no longer passed to `create_def` functions to avoid redundancy.
2023-12-03 16:24:56 +03:00
Nadrieril
70deb9a57f Disallow arm bodies on never patterns 2023-12-03 12:25:46 +01:00
Nadrieril
06a8ed10b6 Disallow guards on never patterns 2023-12-03 12:25:46 +01:00
Nadrieril
a2dcb3a6d9 Disallow an arm without a body (except for never patterns)
Parsing now accepts a match arm without a body, so we must make sure to
only accept that if the pattern is a never pattern.
2023-12-03 12:25:46 +01:00
Nadrieril
80bdcbf50a Parse a pattern with no arm 2023-12-03 12:25:46 +01:00
Mark Rousskov
5980a17c52 Avoid per-register closure expansions 2023-12-02 15:31:18 -05:00
bors
4e3dc976e7 Auto merge of #117912 - GeorgeWort:master, r=petrochenkov
Name explicit registers in conflict register errors for inline assembly
2023-12-02 13:38:47 +00:00
Nicholas Nethercote
61f93563d8 Inline and remove LoweringContext::handler().
It has a single call site.
2023-12-02 09:01:35 +11:00
Nicholas Nethercote
5d1d384443 Rename HandlerInner::delay_span_bug as HandlerInner::span_delayed_bug.
Because the corresponding `Level` is `DelayedBug` and `span_delayed_bug`
follows the pattern used everywhere else: `span_err`, `span_warning`,
etc.
2023-12-02 09:01:19 +11:00
Matthias Krüger
c03f8917ee
Rollup merge of #118157 - Nadrieril:never_pat-feature-gate, r=compiler-errors
Add `never_patterns` feature gate

This PR adds the feature gate and most basic parsing for the experimental `never_patterns` feature. See the tracking issue (https://github.com/rust-lang/rust/issues/118155) for details on the experiment.

`@scottmcm` has agreed to be my lang-team liaison for this experiment.
2023-11-29 12:34:47 +01:00
bors
ec1f21cb04 Auto merge of #118433 - matthiaskrgr:rollup-fi9lrwg, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #116839 (Implement thread parking for xous)
 - #118265 (remove the memcpy-on-equal-ptrs assumption)
 - #118269 (Unify `TraitRefs` and `PolyTraitRefs` in `ValuePairs`)
 - #118394 (Remove HIR opkinds)
 - #118398 (Add proper cfgs in std)
 - #118419 (Eagerly return `ExprKind::Err` on `yield`/`await` in wrong coroutine context)
 - #118422 (Fix coroutine validation for mixed panic strategy)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-11-29 08:51:01 +00:00
Matthias Krüger
82eda5865a
Rollup merge of #118401 - nnethercote:rustc_ast_lowering, r=compiler-errors
`rustc_ast_lowering` cleanups

Just some cleanups I found while looking through this code.

r? `@spastorino`
2023-11-29 04:23:29 +01:00
Matthias Krüger
8cfdccf7c8
Rollup merge of #118419 - compiler-errors:await-span2, r=cjgillot
Eagerly return `ExprKind::Err` on `yield`/`await` in wrong coroutine context

This PR does 2 things:
1. Refuses to lower `.await` or `yield` when we are outside of the right coroutine context for the operator. Instead, we lower to `hir::ExprKind::Err`, to silence subsequent redundant errors.
2. Reworks a bit of the span tracking in `LoweringContext` to fix a bad span when we have something like `let x = [0; async_fn().await]` where the `await` is inside of an anon const. The span for the "item" still kinda sucks, since it overlaps with the `await` span, but at least it's accurate.
2023-11-29 04:23:24 +01:00
Matthias Krüger
20473eba0b
Rollup merge of #118394 - nnethercote:rm-hir-Ops, r=cjgillot
Remove HIR opkinds

`hir::BinOp`, `hir::BinOpKind`, and `hir::UnOp` are identical to `ast::BinOp`, `ast::BinOpKind`, and `ast::UnOp`, respectively. This seems silly, so this PR removes the HIR ones. (A re-export lets the AST ones be referred to using a `hir::` qualifier, which avoids renaming churn.)

r? `@cjgillot`
2023-11-29 04:23:23 +01:00
Nadrieril
a3838c8550 Add never_patterns feature gate 2023-11-29 03:58:29 +01:00
Michael Goulet
f2c500bb43 Fix spans for bad await in inline const 2023-11-28 19:29:56 +00:00
Michael Goulet
a76d2e1fd1 Eagerly return ExprKind::Err on yield/await in wrong coroutine context 2023-11-28 19:29:56 +00:00
Vadim Petrochenkov
f0dc906319 resolve: Feed the def_kind query immediately on DefId creation 2023-11-28 15:39:31 +03:00
George Wort
e0bfb615da Name explicit registers in conflict register errors for inline assembly 2023-11-28 10:37:19 +00:00
Nicholas Nethercote
5c680e1bcb Remove unnecessary Option from LoweringContext::allow_{try_trait,gen_future}.
Also remove some unnecessary slicing.
2023-11-28 14:32:40 +11:00
Nicholas Nethercote
3bae9276fa Add LoweringContext::new. 2023-11-28 14:32:40 +11:00
Nicholas Nethercote
ed2868eb9d Create LoweringContext::lower_assoc_item.
By moving most of `ItemLowerer::lower_assoc_item` into it. This is
similar to `LoweringContext::lower_foreign_item`.
2023-11-28 14:32:40 +11:00
Nicholas Nethercote
dbaa78621a Reduce exposure of some things. 2023-11-28 14:32:40 +11:00
Nicholas Nethercote
3570468ce7 Remove unused feature. 2023-11-28 14:32:40 +11:00
Nicholas Nethercote
d9fef774e3 Remove hir::BinOp, hir::BinOpKind, and hir::UnOp.
They're identical to the same-named types from `ast`. I find it silly
(and inefficient) to have all this boilerplate code to convert one type
to an identical type.

There is already a small amount of type sharing between the AST and HIR,
e.g. `Attribute`, `MacroDef`.

The commit adds a `pub use` to `rustc_hir` so that, for example,
`ast::BinOp` can also be referred to as `hir::BinOp`. This is so the
many existing `hir`-qualified mentions of these types don't need to
change.

The commit also moves a couple of operations from the (removed) HIR
types to the AST types, e.g. `is_by_value`.
2023-11-28 12:14:25 +11:00
bohan
f23befe6c1 merge DefKind::Coroutine into DefKind::Closure 2023-11-26 21:05:08 +08:00
Michael Goulet
3b2f33ee28
Rollup merge of #118158 - nnethercote:reduce-fluent-boilerplate, r=compiler-errors
Reduce fluent boilerplate

Best reviewed one commit at a time.

r? `@davidtwco`
2023-11-25 17:23:33 -05:00
Nicholas Nethercote
57cd5e6551 Use rustc_fluent_macro::fluent_messages! directly.
Currently we always do this:
```
use rustc_fluent_macro::fluent_messages;
...
fluent_messages! { "./example.ftl" }
```
But there is no need, we can just do this everywhere:
```
rustc_fluent_macro::fluent_messages! { "./example.ftl" }
```
which is shorter.
2023-11-26 08:38:40 +11:00
Nicholas Nethercote
a733082be9 Avoid need for {D,Subd}iagnosticMessage imports.
The `fluent_messages!` macro produces uses of
`crate::{D,Subd}iagnosticMessage`, which means that every crate using
the macro must have this import:
```
use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage};
```

This commit changes the macro to instead use
`rustc_errors::{D,Subd}iagnosticMessage`, which avoids the need for the
imports.
2023-11-26 08:38:00 +11:00
Michael Goulet
fa7633dda1 Remove HirId from QPath::LangItem 2023-11-25 18:02:11 +00:00
Deadbeef
16040a1628 Add Span to TraitBoundModifier 2023-11-24 14:32:05 +00:00
Nilstrieb
21a870515b Fix clippy::needless_borrow in the compiler
`x clippy compiler -Aclippy::all -Wclippy::needless_borrow --fix`.

Then I had to remove a few unnecessary parens and muts that were exposed
now.
2023-11-21 20:13:40 +01:00
Matthias Krüger
aa2289d3bc
Rollup merge of #117549 - DaniPopes:more-copied, r=b-naber
Use `copied` instead of manual `map`
2023-11-17 23:04:22 +01:00
Mark Rousskov
db3e2bacb6 Bump cfg(bootstrap)s 2023-11-15 19:41:28 -05:00
Takayuki Maeda
cf21b6ef28
Rollup merge of #117858 - compiler-errors:span, r=lcnr
Compute layout with spans for better cycle errors in coroutines

Split out from #117703, this PR at least gives us a nicer span to point at when we hit a cycle error in coroutine layout cycles.
2023-11-14 00:54:16 +09:00
Michael Goulet
7994b5849c Compute layout with spans for better cycle errors in coroutines 2023-11-13 02:22:25 +00:00
Nicholas Nethercote
2e40d11f8c Remove -Zkeep-hygiene-data.
It was added way back in #28585 under the name `-Zkeep-mtwt-tables`. The
justification was:

> This is so that the resolution results can be used after analysis,
> potentially for tool support.

There are no uses of significance in the code base, and various Google
searches for both option names (and variants) found nothing of interest.

@petrochenkov says removing this part (and it's only part) of the
hygiene data is dubious. It doesn't seem that big, so let's just keep it
around.
2023-11-10 14:00:08 +11:00
Dinu Blanovschi
241a654c07 Fix remaining uses of CaptureBy::Value 2023-11-04 19:48:44 +01:00
DaniPopes
27364309a5
compiler: use copied instead of manual map 2023-11-03 17:18:56 +01:00
Nicholas Nethercote
f405ce86c2 Minimize pub usage in source_map.rs.
Most notably, this commit changes the `pub use crate::*;` in that file
to `use crate::*;`. This requires a lot of `use` items in other crates
to be adjusted, because everything defined within `rustc_span::*` was
also available via `rustc_span::source_map::*`, which is bizarre.

The commit also removes `SourceMap::span_to_relative_line_string`, which
is unused.
2023-11-02 19:35:00 +11:00
Michael Goulet
add09e66f2 Some more coroutine renamings 2023-10-30 23:46:27 +00:00
Guillaume Gomez
824e3677c2
Rollup merge of #117068 - nnethercote:clean-up-Cargo-toml, r=wesleywiser
Clean up `compiler/rustc*/Cargo.toml`

Mostly by sorting dependencies, plus some other minor things.

r? ``@wesleywiser``
2023-10-30 17:33:15 +01:00
León Orell Valerian Liehr
2915707622
Rollup merge of #117147 - DaniPopes:pphir-fn-variadic, r=compiler-errors
Print variadic argument pattern in HIR pretty printer

Variadic argument name/pattern was ignored during HIR pretty printing.
Could not figure out why it only works on normal functions (`va2`) and not in foreign ones (`va1`).
2023-10-30 10:48:17 +01:00
Nicholas Nethercote
8ff624a9f2 Clean up rustc_*/Cargo.toml.
- Sort dependencies and features sections.
- Add `tidy` markers to the sorted sections so they stay sorted.
- Remove empty `[lib`] sections.
- Remove "See more keys..." comments.

Excluded files:
- rustc_codegen_{cranelift,gcc}, because they're external.
- rustc_lexer, because it has external use.
- stable_mir, because it has external use.
2023-10-30 08:46:02 +11:00
bors
2cad938a81 Auto merge of #116447 - oli-obk:gen_fn, r=compiler-errors
Implement `gen` blocks in the 2024 edition

Coroutines tracking issue https://github.com/rust-lang/rust/issues/43122
`gen` block tracking issue https://github.com/rust-lang/rust/issues/117078

This PR implements `gen` blocks that implement `Iterator`. Most of the logic with `async` blocks is shared, and thus I renamed various types that were referring to `async` specifically.

An example usage of `gen` blocks is

```rust
fn foo() -> impl Iterator<Item = i32> {
    gen {
        yield 42;
        for i in 5..18 {
            if i.is_even() { continue }
            yield i * 2;
        }
    }
}
```

The limitations (to be resolved) of the implementation are listed in the tracking issue
2023-10-29 00:03:52 +00:00
Oli Scherer
6223744078 Prevent generators from being movable 2023-10-27 13:05:49 +00:00
Oli Scherer
cece90c65f Feature gate coroutine yield usage 2023-10-27 13:05:48 +00:00
Oli Scherer
621494382d Add gen blocks to ast and do some broken ast lowering 2023-10-27 13:05:48 +00:00
bors
698db856de Auto merge of #117171 - fee1-dead-contrib:deny-explicit-effect-params, r=oli-obk
Deny providing explicit effect params

r? `@oli-obk`

cc https://github.com/rust-lang/rust/issues/110395
2023-10-26 14:50:23 +00:00
Deadbeef
47efc90366 Deny providing explicit effect params 2023-10-26 08:24:25 +00:00
Oli Scherer
14423080f1 Add hir::GeneratorKind::Gen 2023-10-26 07:10:25 +00:00
Oli Scherer
af8a998b1e Rename AsyncCoroutineKind to CoroutineSource
similar to how we have `MatchSource`, it explains where the desugaring came from.
2023-10-25 16:14:05 +00:00
DaniPopes
6aead74ff2
Remove unnecessary CVarArgs name skipping logic 2023-10-25 17:44:17 +02:00
Oli Scherer
2d91c76d5d Rename CoroutineKind::Gen to ::Coroutine 2023-10-20 21:14:01 +00:00
Oli Scherer
e96ce20b34 s/generator/coroutine/ 2023-10-20 21:14:01 +00:00
Oli Scherer
60956837cf s/Generator/Coroutine/ 2023-10-20 21:10:38 +00:00
Michael Howell
2ff2624722 docs: add Rust logo to more compiler crates
c6e6ecb1af added it to some of the
compiler's crates, but avoided adding it to all of them to reduce
bit-rot. This commit adds to more.
2023-10-16 15:38:08 -07:00
bors
a48396984a Auto merge of #116688 - compiler-errors:rustfmt-up, r=WaffleLapkin,Nilstrieb
Format all the let-chains in compiler crates

Since rust-lang/rustfmt#5910 has landed, soon we will have support for formatting let-chains (as soon as rustfmt syncs and beta gets bumped).

This PR applies the changes [from master rustfmt to rust-lang/rust eagerly](https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/out.20formatting.20of.20prs/near/374997516), so that the next beta bump does not have to deal with a 200+ file diff and can remain concerned with other things like `cfg(bootstrap)` -- #113637 was a pain to land, for example, because of let-else.

I will also add this commit to the ignore list after it has landed.

The commands that were run -- I'm not great at bash-foo, but this applies rustfmt to every compiler crate, and then reverts the two crates that should probably be formatted out-of-tree.
```
~/rustfmt $ ls -1d ~/rust/compiler/* | xargs -I@ cargo run --bin rustfmt -- `@/src/lib.rs` --config-path ~/rust --edition=2021 # format all of the compiler crates
~/rust $ git checkout HEAD -- compiler/rustc_codegen_{gcc,cranelift} # revert changes to cg-gcc and cg-clif
```

cc `@rust-lang/rustfmt`
r? `@WaffleLapkin` or `@Nilstrieb` who said they may be able to review this purely mechanical PR :>

cc `@Mark-Simulacrum` and `@petrochenkov,` who had some thoughts on the order of operations with big formatting changes in https://github.com/rust-lang/rust/pull/95262#issue-1178993801. I think the situation has changed since then, given that let-chains support exists on master rustfmt now, and I'm fairly confident that this formatting PR should land even if *bootstrap* rustfmt doesn't yet format let-chains in order to lessen the burden of the next beta bump.
2023-10-15 13:23:55 +00:00
Michael Goulet
ef04c9795b Deprecate E0706 2023-10-13 21:01:36 +00:00
Michael Goulet
59315b8a63 Stabilize AFIT and RPITIT 2023-10-13 21:01:36 +00:00
Michael Goulet
b2d2184ede Format all the let chains in compiler 2023-10-13 08:59:36 +00:00
Matthias Krüger
8374805d67
Rollup merge of #116627 - fee1-dead-contrib:cleanup, r=spastorino
small cleanup

this is exactly the same as the `lower_param_bounds` function, so use that instead
2023-10-11 20:08:22 +02:00
Deadbeef
50b6f46f71 small cleanup 2023-10-11 08:25:43 +00:00
Jubilee
d7b02c3d40
Rollup merge of #116431 - estebank:issue-80476, r=compiler-errors
Tweak wording of E0562

Fix #80476.
2023-10-05 00:56:30 -07:00
bors
afe67fa2ef Auto merge of #116370 - nnethercote:more-arena-stuff, r=cjgillot
Remove the `TypedArena::alloc_from_iter` specialization.

It was added in #78569. It's complicated and doesn't actually help
performance.

r? `@cjgillot`
2023-10-04 22:32:46 +00:00
Esteban Küber
041e54bd92 Tweak wording of E0562
Fix #80476.
2023-10-04 19:51:43 +00:00
Nicholas Nethercote
a2051dd578 Optimize some alloc_from_iter call sites.
There's no need to collect an iterator into a `Vec`, or to call
`into_iter` at the call sites.
2023-10-03 18:12:37 +11:00
Michael Goulet
2934fe07b7 Point to full async fn for future 2023-10-03 02:25:32 +00:00
lcnr
3c52a3e280 subst -> instantiate 2023-09-26 09:37:55 +02:00
Michael Goulet
087a571e70 Record asyncness span in HIR 2023-09-21 19:18:14 +00:00
bors
bdb0fa3ee5 Auto merge of #113955 - cjgillot:name-apit, r=WaffleLapkin
Pretty-print argument-position impl trait to name it.

This removes a corner case.

RPIT and TAIT keep having no name, and it would be wrong to use the one in HIR (Ident::empty), so I make this case ICE.
2023-09-19 21:23:39 +00:00
bors
dac91a82e1 Auto merge of #115677 - matthewjasper:let-expr-recovery, r=b-naber
Improve invalid let expression handling

- Move all of the checks for valid let expression positions to parsing.
- Add a field to ExprKind::Let in AST/HIR to mark whether it's in a valid location.
- Suppress some later errors and MIR construction for invalid let expressions.
- Fix a (drop) scope issue that was also responsible for #104172.

Fixes #104172
Fixes #104868
2023-09-14 19:56:55 +00:00
yukang
f9a9ff20a2 cleanup on messages 2023-09-12 07:27:17 +08:00
Matthew Jasper
333388fd3c Move let expression checking to parsing
There was an incomplete version of the check in parsing and a second
version in AST validation. This meant that some, but not all, invalid
uses were allowed inside macros/disabled cfgs. It also means that later
passes have a hard time knowing when the let expression is in a valid
location, sometimes causing ICEs.

- Add a field to ExprKind::Let in AST/HIR to mark whether it's in a
  valid location.
- Suppress later errors and MIR construction for invalid let
  expressions.
2023-09-11 15:51:18 +00:00
Camille GILLOT
717dc1ce21 Enable incremental-relative-spans by default. 2023-09-07 20:21:13 +00:00
John Kåre Alsaker
6881eed8f6 Don't hold the definitions' lock across index_hir 2023-09-02 08:13:07 +02:00
Camille GILLOT
3907072af4 Pretty-print impl trait to name it. 2023-08-30 18:01:25 +00:00
Michael Goulet
f1679f7dd6 Capture lifetimes for associated type bounds destined to be lowered to opaques 2023-08-30 00:31:00 +00:00
Michael Goulet
13d3e57237 RPITITs capture all their lifetimes 2023-08-28 01:05:34 +00:00
bors
18be2728bd Auto merge of #115131 - frank-king:feature/unnamed-fields-lite, r=petrochenkov
Parse unnamed fields and anonymous structs or unions (no-recovery)

It is part of #114782 which implements #49804. Only parse anonymous structs or unions in struct field definition positions.

r? `@petrochenkov`
2023-08-24 12:52:35 +00:00
Frank King
868706d9b5 Parse unnamed fields and anonymous structs or unions
Anonymous structs or unions are only allowed in struct field
definitions.

Co-authored-by: carbotaniuman <41451839+carbotaniuman@users.noreply.github.com>
2023-08-24 11:17:54 +08:00
Esteban Küber
5021dde1a0 Move scrutinee HirId into MatchSource::TryDesugar 2023-08-14 21:43:56 +00:00
Deadbeef
f441fa08da Remove constness from ImplSource::Param 2023-08-14 02:17:30 +00:00
Matthias Krüger
a12c329b35
Rollup merge of #114667 - compiler-errors:issue-114664, r=davidtwco
Record binder for bare trait object in LifetimeCollectVisitor

The `LifetimeCollectVisitor` had a bug where it was not recording the binder of bate trait objects. This was uncovered in #114487, when I changed opaque type lowering to ICE if it encountered a captured fresh lifetime with no def-id to map back to: https://github.com/rust-lang/rust/pull/114487/files#diff-ad0c15bbde97a607d4758ec7eaf88248be5d6b8ae084dfc84127f81e3f7a9bb4R1585

Fixes #114664
2023-08-12 12:06:36 +02:00
Michael Goulet
94533d924e
Rollup merge of #114622 - petrochenkov:noplugin, r=oli-obk
rustc: Move `crate_types` and `stable_crate_id` from `Session` to `GlobalCtxt`

Removes two pieces of mutable state.
Follow up to https://github.com/rust-lang/rust/pull/114578.
2023-08-10 21:17:07 -07:00
Michael Goulet
bbe7a96bec Record binder for bare trait object in LifetimeCollectVisitor 2023-08-11 03:15:41 +00:00
Vadim Petrochenkov
0b89aac08d rustc: Move crate_types from Session to GlobalCtxt
Removes a piece of mutable state.
Follow up to #114578.
2023-08-09 14:17:54 +08:00
Seth Pellegrino
897c7bb23b feat: riscv-interrupt-{m,s} calling conventions
Similar to prior support added for the mips430, avr, and x86 targets
this change implements the rough equivalent of clang's
[`__attribute__((interrupt))`][clang-attr] for riscv targets, enabling
e.g.

```rust
static mut CNT: usize = 0;

pub extern "riscv-interrupt-m" fn isr_m() {
    unsafe {
        CNT += 1;
    }
}
```

to produce highly effective assembly like:

```asm
pub extern "riscv-interrupt-m" fn isr_m() {
420003a0:       1141                    addi    sp,sp,-16
    unsafe {
        CNT += 1;
420003a2:       c62a                    sw      a0,12(sp)
420003a4:       c42e                    sw      a1,8(sp)
420003a6:       3fc80537                lui     a0,0x3fc80
420003aa:       63c52583                lw      a1,1596(a0) # 3fc8063c <_ZN12esp_riscv_rt3CNT17hcec3e3a214887d53E.0>
420003ae:       0585                    addi    a1,a1,1
420003b0:       62b52e23                sw      a1,1596(a0)
    }
}
420003b4:       4532                    lw      a0,12(sp)
420003b6:       45a2                    lw      a1,8(sp)
420003b8:       0141                    addi    sp,sp,16
420003ba:       30200073                mret
```

(disassembly via `riscv64-unknown-elf-objdump -C -S --disassemble ./esp32c3-hal/target/riscv32imc-unknown-none-elf/release/examples/gpio_interrupt`)

This outcome is superior to hand-coded interrupt routines which, lacking
visibility into any non-assembly body of the interrupt handler, have to
be very conservative and save the [entire CPU state to the stack
frame][full-frame-save]. By instead asking LLVM to only save the
registers that it uses, we defer the decision to the tool with the best
context: it can more accurately account for the cost of spills if it
knows that every additional register used is already at the cost of an
implicit spill.

At the LLVM level, this is apparently [implemented by] marking every
register as "[callee-save]," matching the semantics of an interrupt
handler nicely (it has to leave the CPU state just as it found it after
its `{m|s}ret`).

This approach is not suitable for every interrupt handler, as it makes
no attempt to e.g. save the state in a user-accessible stack frame. For
a full discussion of those challenges and tradeoffs, please refer to
[the interrupt calling conventions RFC][rfc].

Inside rustc, this implementation differs from prior art because LLVM
does not expose the "all-saved" function flavor as a calling convention
directly, instead preferring to use an attribute that allows for
differentiating between "machine-mode" and "superivsor-mode" interrupts.

Finally, some effort has been made to guide those who may not yet be
aware of the differences between machine-mode and supervisor-mode
interrupts as to why no `riscv-interrupt` calling convention is exposed
through rustc, and similarly for why `riscv-interrupt-u` makes no
appearance (as it would complicate future LLVM upgrades).

[clang-attr]: https://clang.llvm.org/docs/AttributeReference.html#interrupt-risc-v
[full-frame-save]: 9281af2ecf/src/lib.rs (L440-L469)
[implemented by]: b7fb2a3fec/llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp (L61-L67)
[callee-save]: 973f1fe7a8/llvm/lib/Target/RISCV/RISCVCallingConv.td (L30-L37)
[rfc]: https://github.com/rust-lang/rfcs/pull/3246
2023-08-08 18:09:56 -07:00
bors
f88a8b71ce Auto merge of #114545 - fee1-dead-contrib:lower-impl-effect, r=oli-obk
correctly lower `impl const` to bind to host effect param

r? `@oli-obk`
2023-08-08 19:23:41 +00:00
Michael Goulet
8dcb8e0759 Unconditionally record lifetime mapping 2023-08-08 03:16:04 +00:00
Deadbeef
057be381c6 Fix ICE 2023-08-07 17:16:10 +00:00
Deadbeef
92f4c59e48 lower impl const to bind to host effect param 2023-08-06 13:34:53 +00:00
Michael Goulet
57a96893f6 Consolidate opaque ty and async fn lowering code 2023-08-05 16:53:13 +00:00
bors
e173a8e663 Auto merge of #112117 - bryangarza:track-caller-feature-gate, r=compiler-errors
Add separate feature gate for async fn track caller

This patch adds a feature gate `async_fn_track_caller` that is separate from `closure_track_caller`. This is to allow enabling `async_fn_track_caller` separately.

Fixes #110009
2023-08-04 22:17:59 +00:00
Nilstrieb
5706be1854 Improve spans for indexing expressions
Indexing is similar to method calls in having an arbitrary
left-hand-side and then something on the right, which is the main part
of the expression. Method calls already have a span for that right part,
but indexing does not. This means that long method chains that use
indexing have really bad spans, especially when the indexing panics and
that span in coverted into a panic location.

This does the same thing as method calls for the AST and HIR, storing an
extra span which is then put into the `fn_span` field in THIR.
2023-08-04 13:17:39 +02:00
Bryan Garza
673ab17c7f Add separate feature gate for async fn track caller
This patch adds a feature gate `async_fn_track_caller` that is separate from `closure_track_caller`. This is to allow enabling `async_fn_track_caller` separately.

Fixes #110009
2023-08-02 14:18:21 -07:00
León Orell Valerian Liehr
9213aec762
Lower generic const items to HIR 2023-07-28 22:21:40 +02:00
Matthias Krüger
af2b370100 more clippy::style fixes:
get_first
single_char_add_str
unnecessary_mut_passed
manual_map
manual_is_ascii_check
2023-07-23 23:39:04 +02:00
bors
c06b2b9117 Auto merge of #113847 - SparrowLii:path_clone, r=cjgillot
avoid clone path prefix when lowering to hir

Found this while trying to parallelize `lower_to_hir`.

When lowering to hir, `Nested` paths in `ast` will be split and the prefix segments will be cloned. This could be omited, since the only consequence is that the prefix segments in `Path`s in hir will have the same `HirId`s, and it seems harmless.

This simplifies the process of lowering to hir and avoids re-modification of `ResolverAstLowering`.

r? `@Aaron1011`
cc #99292
2023-07-21 11:02:47 +00:00
SparrowLii
0377945157 add comment for lower_use_tree
Signed-off-by: SparrowLii <liyuan179@huawei.com>
2023-07-19 16:48:33 +08:00
SparrowLii
c6f0a7c3c3 avoid clone path prefix when lowering to hir
Signed-off-by: SparrowLii <liyuan179@huawei.com>
2023-07-19 11:19:33 +08:00
Michael Goulet
603fd426df Properly document lifetime_mapping in OpaqueTy 2023-07-17 14:56:33 +00:00
Mark Rousskov
cc907f80b9 Re-format let-else per rustfmt update 2023-07-12 21:49:27 -04:00
Deadbeef
58c105af04 include host_effect_index in Generics 2023-07-04 17:21:52 +00:00
Deadbeef
1c837cb6f7 Add effects during lowering for ~const bounds 2023-07-04 11:47:45 +00:00
Santiago Pastorino
6f4a51e80e
Do not generate lifetime_mapping for RPIT no in_trait 2023-06-29 14:26:28 -03:00
Santiago Pastorino
4925b57782
Add bidirectional where clauses on RPITIT synthesized GATs 2023-06-29 14:26:26 -03:00
Santiago Pastorino
d70deac161
Intern OpaqueTy on ItemKind::OpaqueTy 2023-06-29 14:05:10 -03:00
Santiago Pastorino
72a32583d1
Reorganize opaque lowering code 2023-06-29 14:04:37 -03:00
Maybe Waffle
ccb71ff424 hir: Add Become expression kind 2023-06-26 08:56:32 +00:00
Maybe Waffle
d7713feb99 Syntatically accept become expressions 2023-06-19 12:54:34 +00:00
Camille GILLOT
ca4d0d4c24 Separate AnonConst from ConstBlock in HIR. 2023-06-02 21:25:18 +00:00
bors
498553fc04 Auto merge of #111235 - loongarch-rs:stabilize-asm, r=Amanieu
Stabilize inline asm for LoongArch64

This PR is used to tracking for stabilize `inline asm` for LoongArch64.

**Status**

- [x] https://github.com/rust-lang/rust/pull/111237
- [x] https://github.com/rust-lang/rust/pull/111332
- [ ] https://github.com/rust-lang/reference/pull/1357

Any others I missed?

r? `@Amanieu`
2023-05-29 13:31:53 +00:00
bors
c86212f9bc Auto merge of #111858 - clubby789:fluent-alphabetical, r=jyn514,compiler-errors
Ensure Fluent messages are in alphabetical order

Fixes #111847

This adds a tidy check to ensure Fluent messages are in alphabetical order, as well as sorting all existing messages. I think the error could be worded better, would appreciate suggestions.

<details>
<summary>Script used to sort files</summary>

```py
import sys
import re

fn = sys.argv[1]
with open(fn, 'r') as f:
    data = f.read().split("\n")

chunks = []
cur = ""
for line in data:
    if re.match(r"^([a-zA-Z0-9_]+)\s*=\s*", line):
        chunks.append(cur)
        cur = ""
    cur += line + "\n"
chunks.append(cur)
chunks.sort()

with open(fn, 'w') as f:
    f.write(''.join(chunks).strip("\n\n") + "\n")
```
</details>
2023-05-26 03:31:04 +00:00
clubby789
f97fddab91 Ensure Fluent messages are in alphabetical order 2023-05-25 23:49:35 +00:00
Michael Goulet
4692375389 Don't print newlines in APITs 2023-05-25 02:45:14 +00:00
Michael Woerister
a7d48800f9 Turn debugger_visualizers from feed- into regular query. 2023-05-16 18:50:36 +02:00
Oli Scherer
f08b517597 Require impl Trait in associated types to appear in method signatures 2023-05-12 10:24:03 +00:00
Matthias Krüger
363d158cd8
Rollup merge of #111215 - BoxyUwU:resolve_anon_consts_differently, r=cjgillot
Various changes to name resolution of anon consts

Sorry this PR is kind of all over the place ^^'

Fixes #111012

- Rewrites anon const nameres to all go through `fn resolve_anon_const` explicitly instead of `visit_anon_const` to ensure that we do not accidentally resolve anon consts as if they are allowed to use generics when they aren't. Also means that we dont have bits of code for resolving anon consts that will get out of sync (i.e. legacy const generics and resolving path consts that were parsed as type arguments)
- Renames two of the `LifetimeRibKind`, `AnonConst -> ConcreteAnonConst` and `ConstGeneric -> ConstParamTy`
- Noticed while doing this that under `generic_const_exprs` all lifetimes currently get resolved to errors without any error being emitted which was causing a bunch of tests to pass without their bugs having been fixed, incidentally fixed that in this PR and marked those tests as `// known-bug:`. I'm fine to break those since `generic_const_exprs` is a very unstable incomplete feature and this PR _does_ make generic_const_exprs "less broken" as a whole, also I can't be assed to figure out what the underlying causes of all of them are. This PR reopens #77357 #83993
- Changed `generics_of` to stop providing generics and predicates to enum variant discriminant anon consts since those are not allowed to use generic parameters
- Updated the error for non 'static lifetime in const arguments and the error for non 'static lifetime in const param tys to use `derive(Diagnostic)`

I have a vague idea why const-arg-in-const-arg.rs, in-closure.rs and simple.rs have started failing which is unfortunate since these were deliberately made to work, I think lifetime resolution being broken just means this regressed at some point and nobody noticed because the tests were not testing anything :( I'm fine breaking these too for the same reason as the tests for #77357 #83993. I couldn't get `// known-bug` to work for these ICEs and just kept getting different stderr between CI and local `--bless` so I just removed them and will create an issue to track re-adding (and fixing) the bugs if this PR lands.

r? `@cjgillot` cc `@compiler-errors`
2023-05-09 20:49:32 +02:00
Mara Bos
d5843ddaf1 Limit lifetime of format_args!() with inlined args. 2023-05-09 16:08:40 +02:00
WANG Rui
46252ef401 asm: Stabilize loongarch64 2023-05-08 23:46:48 +08:00
bors
ea0c22ea4f Auto merge of #106621 - ozkanonur:enable-elided-lifetimes-for-doctests, r=Mark-Simulacrum
enable `rust_2018_idioms` lint group for doctests

With this change, `rust_2018_idioms` lint group will be enabled for compiler/libstd doctests.

Resolves #106086
Resolves #99144

Signed-off-by: ozkanonur <work@onurozkan.dev>
2023-05-08 04:50:28 +00:00
ozkanonur
4e7c14fe9f enable rust_2018_idioms for doctests
Signed-off-by: ozkanonur <work@onurozkan.dev>
2023-05-07 00:12:29 +03:00
Boxy
442617c046 misc nameres changes for anon consts 2023-05-05 21:31:35 +01:00
Dylan DPC
80df4ab403
Rollup merge of #110791 - compiler-errors:negative-bounds, r=oli-obk
Implement negative bounds for internal testing purposes

Implements partial support the `!` negative polarity on trait bounds. This is incomplete, but should allow us to at least be able to play with the feature.

Not even gonna consider them as a public-facing feature, but I'm implementing them because would've been nice to have in UI tests, for example in #110671.
2023-05-04 00:17:23 +05:30
Nicholas Nethercote
6b62f37402 Restrict From<S> for {D,Subd}iagnosticMessage.
Currently a `{D,Subd}iagnosticMessage` can be created from any type that
impls `Into<String>`. That includes `&str`, `String`, and `Cow<'static,
str>`, which are reasonable. It also includes `&String`, which is pretty
weird, and results in many places making unnecessary allocations for
patterns like this:
```
self.fatal(&format!(...))
```
This creates a string with `format!`, takes a reference, passes the
reference to `fatal`, which does an `into()`, which clones the
reference, doing a second allocation. Two allocations for a single
string, bleh.

This commit changes the `From` impls so that you can only create a
`{D,Subd}iagnosticMessage` from `&str`, `String`, or `Cow<'static,
str>`. This requires changing all the places that currently create one
from a `&String`. Most of these are of the `&format!(...)` form
described above; each one removes an unnecessary static `&`, plus an
allocation when executed. There are also a few places where the existing
use of `&String` was more reasonable; these now just use `clone()` at
the call site.

As well as making the code nicer and more efficient, this is a step
towards possibly using `Cow<'static, str>` in
`{D,Subd}iagnosticMessage::{Str,Eager}`. That would require changing
the `From<&'a str>` impls to `From<&'static str>`, which is doable, but
I'm not yet sure if it's worthwhile.
2023-05-03 08:44:39 +10:00
Michael Goulet
6e01e910cb Implement negative bounds 2023-05-02 22:36:24 +00:00
Matthias Krüger
1b262b8b56
Rollup merge of #110823 - compiler-errors:tweak-await-span, r=b-naber
Tweak await span to not contain dot

Fixes a discrepancy between method calls and await expressions where the latter are desugared to have a span that *contains* the dot (i.e. `.await`) but method call identifiers don't contain the dot. This leads to weird suggestions suggestions in borrowck -- see linked issue.

Fixes #110761

This mostly touches a bunch of tests to tighten their `await` span.
2023-05-01 01:09:47 +02:00
Matthias Krüger
cf911ac757
Rollup merge of #110766 - m-ou-se:fmt-rt, r=jyn514
More core::fmt::rt cleanup.

- Removes the `V1` suffix from the `Argument` and `Flag` types.

- Moves more of the format_args lang items into the `core::fmt::rt` module. (The only remaining lang item in `core::fmt` is `Arguments` itself, which is a public type.)

Part of https://github.com/rust-lang/rust/issues/99012

Follow-up to https://github.com/rust-lang/rust/pull/110616
2023-04-28 07:34:02 +02:00
Michael Goulet
6d6c904431 Make async removal span more resilient to macro expansions 2023-04-27 18:25:07 +00:00
Michael Goulet
f0fc4f9acf Tweak await span 2023-04-27 17:18:11 +00:00
Michael Goulet
c18e7b765f IntoFuture::into_future is no longer unstable 2023-04-26 22:44:18 +00:00
Mara Bos
0a28977740 Restructure std::fmt::rt a bit.
This moves more of the internal/lang items into the private rt module.
2023-04-24 16:16:14 +02:00
Mara Bos
5cf3cbf3b7 Remove "V1" from ArgumentsV1 and FlagsV1. 2023-04-24 16:16:14 +02:00
Maybe Waffle
e496fbec92 Split {Idx, IndexVec, IndexSlice} into their own modules 2023-04-24 13:53:35 +00:00
Nilstrieb
74e31ec64c Also arena-allocate ast::MacroDef to make Item: Copy 2023-04-22 23:00:38 +02:00
DrMeepster
511e457c4b offset_of 2023-04-21 02:14:02 -07:00
Mara Bos
441682cca9 Update comments in format args lowering.
These lang items have been moved/renamed.
2023-04-20 18:09:32 +02:00
bors
d7f9e81650 Auto merge of #110407 - Nilstrieb:fluent-macro, r=davidtwco
Add `rustc_fluent_macro` to decouple fluent from `rustc_macros`

Fluent, with all the icu4x it brings in, takes quite some time to compile. `fluent_messages!` is only needed in further downstream rustc crates, but is blocking more upstream crates like `rustc_index`. By splitting it out, we allow `rustc_macros` to be compiled earlier, which speeds up `x check compiler` by about 5 seconds (and even more after the needless dependency on `serde_json` is removed from `rustc_data_structures`).
2023-04-19 08:26:47 +00:00
Matthias Krüger
a184557d1d
Rollup merge of #110451 - WaffleLapkin:ensure_return_elem, r=scottmcm
Minor changes to `IndexVec::ensure_contains_elem` & related methods

r? `@scottmcm`
2023-04-19 06:35:34 +02:00
Nilstrieb
b5d3d970fa Add rustc_fluent_macro to decouple fluent from rustc_macros
Fluent, with all the icu4x it brings in, takes quite some time to
compile. `fluent_messages!` is only needed in further downstream rustc
crates, but is blocking more upstream crates like `rustc_index`. By
splitting it out, we allow `rustc_macros` to be compiled earlier, which
speeds up `x check compiler` by about 5 seconds (and even more after the
needless dependency on `serde_json` is removed from
`rustc_data_structures`).
2023-04-18 18:56:22 +00:00
Maybe Waffle
9534541dd4 Use Item::expect_* and ImplItem::expect_* more 2023-04-17 18:00:27 +00:00
Maybe Waffle
e1cd99f6ff Make IndexVec::ensure_contains_elem return a reference to the element 2023-04-17 14:23:46 +00:00
bors
53ac4f8e2f Auto merge of #109588 - Nilstrieb:dropless-expr, r=compiler-errors
Alloc `hir::Lit` in an arena to remove the destructor from `Expr`

This allows allocating `Expr`s into a dropless arena, which is useful for using length prefixed thing slices in HIR, since these can only be allocated in the dropless arena and not in a typed arena.
2023-04-17 05:12:12 +00:00
Nilstrieb
34ed5c3efc Alloc hir::Lit in an arena to remove the destructor from Expr
This allows allocating `Expr`s into a dropless arena, which is useful
for using length prefixed thing slices in HIR, since these can only be
allocated in the dropless arena and not in a typed arena. This is
something I'm working on.
2023-04-16 15:35:51 +00:00