Commit Graph

1155 Commits

Author SHA1 Message Date
Michael Goulet
1529c661e4 Warn against redundant use<...> 2024-05-13 23:57:56 -04:00
Matthias Krüger
0a917f89f3
Rollup merge of #124919 - nnethercote:Recovered-Yes-ErrorGuaranteed, r=compiler-errors
Add `ErrorGuaranteed` to `Recovered::Yes` and use it more.

The starting point for this was identical comments on two different fields, in `ast::VariantData::Struct` and `hir::VariantData::Struct`:
```
    // FIXME: investigate making this a `Option<ErrorGuaranteed>`
    recovered: bool
```
I tried that, and then found that I needed to add an `ErrorGuaranteed` to `Recovered::Yes`. Then I ended up using `Recovered` instead of `Option<ErrorGuaranteed>` for these two places and elsewhere, which required moving `ErrorGuaranteed` from `rustc_parse` to `rustc_ast`.

This makes things more consistent, because `Recovered` is used in more places, and there are fewer uses of `bool` and
`Option<ErrorGuaranteed>`. And safer, because it's difficult/impossible to set `recovered` to `Recovered::Yes` without having emitted an error.

r? `@oli-obk`
2024-05-09 19:09:30 +02:00
Nicholas Nethercote
fd91925bce Add ErrorGuaranteed to Recovered::Yes and use it more.
The starting point for this was identical comments on two different
fields, in `ast::VariantData::Struct` and `hir::VariantData::Struct`:
```
    // FIXME: investigate making this a `Option<ErrorGuaranteed>`
    recovered: bool
```
I tried that, and then found that I needed to add an `ErrorGuaranteed`
to `Recovered::Yes`. Then I ended up using `Recovered` instead of
`Option<ErrorGuaranteed>` for these two places and elsewhere, which
required moving `ErrorGuaranteed` from `rustc_parse` to `rustc_ast`.

This makes things more consistent, because `Recovered` is used in more
places, and there are fewer uses of `bool` and
`Option<ErrorGuaranteed>`. And safer, because it's difficult/impossible
to set `recovered` to `Recovered::Yes` without having emitted an error.
2024-05-09 20:12:07 +10:00
Nicholas Nethercote
58a06b6a99 Remove enum_from_u32.
It's a macro that just creates an enum with a `from_u32` method. It has
two arms. One is unused and the other has a single use.

This commit inlines that single use and removes the whole macro. This
increases readability because we don't have two different macros
interacting (`enum_from_u32` and `language_item_table`).
2024-05-09 09:01:59 +10:00
bors
09cd00fea4 Auto merge of #124401 - oli-obk:some_hir_cleanups, r=cjgillot
Some hir cleanups

It seemed odd to not put `AnonConst` in the arena, compared with the other types that we did put into an arena. This way we can also give it a `Span` without growing a lot of other HIR data structures because of the extra field.

r? compiler
2024-05-04 00:32:27 +00:00
Nicholas Nethercote
6341935a13 Remove extern crate tracing from numerous crates. 2024-04-30 16:47:49 +10:00
Nicholas Nethercote
7418aa1a07 Remove extern crate rustc_data_structures from numerous crates. 2024-04-29 18:45:14 +10:00
Nicholas Nethercote
4814fd0a4b Remove extern crate rustc_macros from numerous crates. 2024-04-29 10:21:54 +10:00
Oli Scherer
e4f8b93454 Spans are already 64 bit, just like references, so stop putting them behind indirections 2024-04-26 13:09:04 +00:00
Oli Scherer
4a19711b25 Move ConstArg::span to AnonConst::span 2024-04-26 13:05:00 +00:00
Oli Scherer
4dc46f7f17 put hir::AnonConst on the hir arena 2024-04-26 12:57:02 +00:00
Esteban Küber
64a4cdcfd4 review comment: rename method 2024-04-25 18:26:36 +00:00
Esteban Küber
ad6ae61246 Don't suggest split_at_mut when the multiple borrows have the same index 2024-04-25 16:55:33 +00:00
León Orell Valerian Liehr
80f2b91b20
Rollup merge of #120929 - long-long-float:wrap-dyn-in-suggestion, r=fmease
Wrap dyn type with parentheses in suggestion

Close #120223

Fix wrong suggestion that is grammatically incorrect.
Specifically, I added parentheses to dyn types that need lifetime bound.

```
help: consider adding an explicit lifetime bound
  |
4 |     executor: impl FnOnce(T) -> (dyn Future<Output = ()>) + 'static,
  |                                 +                       +++++++++++
```
2024-04-23 17:25:14 +02:00
Matthias Krüger
36316df9fe
Rollup merge of #124067 - RalfJung:weak-lang-items, r=davidtwco
weak lang items are not allowed to be #[track_caller]

For instance the panic handler will be called via this import
```rust
        extern "Rust" {
            #[lang = "panic_impl"]
            fn panic_impl(pi: &PanicInfo<'_>) -> !;
        }
```
A `#[track_caller]` would add an extra argument and thus make this the wrong signature.

The 2nd commit is a consistency rename; based on the docs [here](https://doc.rust-lang.org/unstable-book/language-features/lang-items.html) and [here](https://rustc-dev-guide.rust-lang.org/lang-items.html) I figured "lang item" is more widely used. (In the compiler output, "lang item" and "language item" seem to be pretty even.)
2024-04-23 12:10:25 +02:00
bors
aca749eefc Auto merge of #121801 - zetanumbers:async_drop_glue, r=oli-obk
Add simple async drop glue generation

This is a prototype of the async drop glue generation for some simple types. Async drop glue is intended to behave very similar to the regular drop glue except for being asynchronous. Currently it does not execute synchronous drops but only calls user implementations of `AsyncDrop::async_drop` associative function and awaits the returned future. It is not complete as it only recurses into arrays, slices, tuples, and structs and does not have same sensible restrictions as the old `Drop` trait implementation like having the same bounds as the type definition, while code assumes their existence (requires a future work).

This current design uses a workaround as it does not create any custom async destructor state machine types for ADTs, but instead uses types defined in the std library called future combinators (deferred_async_drop, chain, ready_unit).

Also I recommend reading my [explainer](https://zetanumbers.github.io/book/async-drop-design.html).

This is a part of the [MCP: Low level components for async drop](https://github.com/rust-lang/compiler-team/issues/727) work.

Feature completeness:

 - [x] `AsyncDrop` trait
 - [ ] `async_drop_in_place_raw`/async drop glue generation support for
   - [x] Trivially destructible types (integers, bools, floats, string slices, pointers, references, etc.)
   - [x] Arrays and slices (array pointer is unsized into slice pointer)
   - [x] ADTs (enums, structs, unions)
   - [x] tuple-like types (tuples, closures)
   - [ ] Dynamic types (`dyn Trait`, see explainer's [proposed design](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#async-drop-glue-for-dyn-trait))
   - [ ] coroutines (https://github.com/rust-lang/rust/pull/123948)
 - [x] Async drop glue includes sync drop glue code
 - [x] Cleanup branch generation for `async_drop_in_place_raw`
 - [ ] Union rejects non-trivially async destructible fields
 - [ ] `AsyncDrop` implementation requires same bounds as type definition
 - [ ] Skip trivially destructible fields (optimization)
 - [ ] New [`TyKind::AdtAsyncDestructor`](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#adt-async-destructor-types) and get rid of combinators
 - [ ] [Synchronously undroppable types](https://github.com/zetanumbers/posts/blob/main/async-drop-design.md#exclusively-async-drop)
 - [ ] Automatic async drop at the end of the scope in async context
2024-04-23 02:10:23 +00:00
long-long-float
31e581ec12 Wrap dyn type with parentheses in suggestion 2024-04-23 00:15:10 +09:00
bors
c25473ff62 Auto merge of #124008 - nnethercote:simpler-static_assert_size, r=Nilstrieb
Simplify `static_assert_size`s.

We want to run them on all 64-bit platforms.

r? `@ghost`
2024-04-18 09:47:45 +00:00
Nicholas Nethercote
0d97669a17 Simplify static_assert_sizes.
We want to run them on all 64-bit platforms.
2024-04-18 15:36:25 +10:00
Jules Bertholet
2a4624ddd1
Rename BindingAnnotation to BindingMode 2024-04-17 09:34:39 -04:00
Ralf Jung
8b35be741f consistency rename: language item -> lang item 2024-04-17 13:00:43 +02:00
Guillaume Gomez
14496d561e
Rollup merge of #122811 - nnethercote:mv-SourceMap-init, r=WaffleLapkin
Move `SourceMap` initialization

So it happens at the same time as `SessionGlobals` initialization, rather than shortly afterward.

r? `@WaffleLapkin`
2024-04-16 21:41:23 +02:00
zetanumbers
24a24ec6ba Add simple async drop glue generation
Explainer: https://zetanumbers.github.io/book/async-drop-design.html

https://github.com/rust-lang/rust/pull/121801
2024-04-16 20:45:07 +03:00
bors
1dea922ea6 Auto merge of #124015 - GuillaumeGomez:rollup-s46ksxa, r=GuillaumeGomez
Rollup of 14 pull requests

Successful merges:

 - #120781 (Correct usage note on OpenOptions::append())
 - #121694 (sess: stabilize `-Zrelro-level` as `-Crelro-level`)
 - #122521 (doc(bootstrap): add top-level doc-comment to utils/tarball.rs)
 - #123491 (Fix ICE in `eval_body_using_ecx`)
 - #123574 (rustdoc: rename `issue-\d+.rs` tests to have meaningful names (part 6))
 - #123687 (Update ar_archive_writer to 0.2.0)
 - #123721 (Various visionOS fixes)
 - #123797 (Better graphviz output for SCCs and NLL constraints)
 - #123990 (Make `suggest_deref_closure_return` more idiomatic/easier to understand)
 - #123995 (Make `thir_tree` and `thir_flat` into hooks)
 - #123998 (Opaque types have no namespace)
 - #124001 (Fix docs for unstable_features lint.)
 - #124006 (Move size assertions for `mir::syntax` types into the same file)
 - #124011 (rustdoc: update the module-level docs of `rustdoc::clean`)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-04-16 13:26:03 +00:00
Nicholas Nethercote
62c32aeeab Construct SourceMap at the same time as SessionGlobals.
Currently `SourceMap` is constructed slightly later than
`SessionGlobals`, and inserted. This commit changes things so they are
done at the same time.

Benefits:
- `SessionGlobals::source_map` changes from
  `Lock<Option<Lrc<SourceMap>>>` to `Option<Lrc<SourceMap>>`. It's still
  optional, but mutability isn't required because it's initialized at
  construction.
- `set_source_map` is removed, simplifying `run_compiler`, which is
  good because that's a critical function and it's nice to make it
  simpler.

This requires moving things around a bit, so the necessary inputs are
available when `SessionGlobals` is created, in particular the `loader`
and `hash_kind`, which are no longer computed by `build_session`. These
inputs are captured by the new `SourceMapInputs` type, which is threaded
through various places.
2024-04-16 13:02:53 +10:00
Michael Goulet
8d07d90572 Opaque types have no namespace 2024-04-15 21:27:30 -04:00
Michael Goulet
ac7651ccaf More polishing 2024-04-15 16:45:48 -04:00
Michael Goulet
02d7317af2 Add hir::Node::PreciseCapturingNonLifetimeArg 2024-04-15 16:45:25 -04:00
Michael Goulet
41cf87b71b Lower and resolve precise captures in HIR 2024-04-15 16:45:01 -04:00
Oli Scherer
84acfe86de Actually create ranged int types in the type system. 2024-04-08 12:02:19 +00:00
Oli Scherer
c4efc25bfa Thread pattern types through the HIR 2024-04-08 12:00:07 +00:00
bohan
889e5719c6 explaining DefKind::Field 2024-04-05 23:12:43 +08:00
bors
385fa9d845 Auto merge of #123097 - oli-obk:perf_experiment, r=petrochenkov
Try using a `dyn Debug` trait object instead of a closure

These closures were introduced in https://github.com/rust-lang/rust/pull/93098

let's see if we can't use fmt::Arguments instead

cc `@Aaron1011`
2024-04-04 20:52:52 +00:00
Oli Scherer
0dca136841 Try explicitly outlining the panic machinery 2024-04-04 09:46:53 +00:00
Jacob Pratt
4332498a6d
Rollup merge of #123401 - Zalathar:assert-size-aarch64, r=fmease
Check `x86_64` size assertions on `aarch64`, too

(Context: https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Checking.20size.20assertions.20on.20aarch64.3F)

Currently the compiler has around 30 sets of `static_assert_size!` for various size-critical data structures (e.g. various IR nodes), guarded by `#[cfg(all(target_arch = "x86_64", target_pointer_width = "64"))]`.

(Presumably this cfg avoids having to maintain separate size values for 32-bit targets and unusual 64-bit targets. Apparently it may have been necessary before the i128/u128 alignment changes, too.)

This is slightly incovenient for people on aarch64 workstations (e.g. Macs), because the assertions normally aren't checked until we push to a PR. So this PR adds `aarch64` to the `#[cfg(..)]` guarding all of those assertions in the compiler.

---

Implemented with a simple find/replace. Verified by manually inspecting each `static_assert_size!` in `compiler/`, and checking that either the replacement succeeded, or adding aarch64 wouldn't have been appropriate.
2024-04-03 20:17:06 -04:00
Vadim Petrochenkov
b40ea03f8a rustc_index: Add a ZERO constant to index types
It is commonly used.
2024-04-03 19:06:22 +03:00
Zalathar
2d47cd77ac Check x86_64 size assertions on aarch64, too
This makes it easier for contributors on aarch64 workstations (e.g. Macs) to
notice when these assertions have been violated.
2024-04-03 16:53:03 +11:00
bors
a77322c16f Auto merge of #118310 - scottmcm:three-way-compare, r=davidtwco
Add `Ord::cmp` for primitives as a `BinOp` in MIR

Update: most of this OP was written months ago.  See https://github.com/rust-lang/rust/pull/118310#issuecomment-2016940014 below for where we got to recently that made it ready for review.

---

There are dozens of reasonable ways to implement `Ord::cmp` for integers using comparison, bit-ops, and branches.  Those differences are irrelevant at the rust level, however, so we can make things better by adding `BinOp::Cmp` at the MIR level:

1. Exactly how to implement it is left up to the backends, so LLVM can use whatever pattern its optimizer best recognizes and cranelift can use whichever pattern codegens the fastest.
2. By not inlining those details for every use of `cmp`, we drastically reduce the amount of MIR generated for `derive`d `PartialOrd`, while also making it more amenable to MIR-level optimizations.

Having extremely careful `if` ordering to μoptimize resource usage on broadwell (#63767) is great, but it really feels to me like libcore is the wrong place to put that logic.  Similarly, using subtraction [tricks](https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign) (#105840) is arguably even nicer, but depends on the optimizer understanding it (https://github.com/llvm/llvm-project/issues/73417) to be practical.  Or maybe [bitor is better than add](https://discourse.llvm.org/t/representing-in-ir/67369/2?u=scottmcm)?  But maybe only on a future version that [has `or disjoint` support](https://discourse.llvm.org/t/rfc-add-or-disjoint-flag/75036?u=scottmcm)?  And just because one of those forms happens to be good for LLVM, there's no guarantee that it'd be the same form that GCC or Cranelift would rather see -- especially given their very different optimizers.  Not to mention that if LLVM gets a spaceship intrinsic -- [which it should](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Suboptimal.20inlining.20in.20std.20function.20.60binary_search.60/near/404250586) -- we'll need at least a rustc intrinsic to be able to call it.

As for simplifying it in Rust, we now regularly inline `{integer}::partial_cmp`, but it's quite a large amount of IR.  The best way to see that is with 8811efa88b (diff-d134c32d028fbe2bf835fef2df9aca9d13332dd82284ff21ee7ebf717bfa4765R113) -- I added a new pre-codegen MIR test for a simple 3-tuple struct, and this PR change it from 36 locals and 26 basic blocks down to 24 locals and 8 basic blocks.  Even better, as soon as the construct-`Some`-then-match-it-in-same-BB noise is cleaned up, this'll expose the `Cmp == 0` branches clearly in MIR, so that an InstCombine (#105808) can simplify that to just a `BinOp::Eq` and thus fix some of our generated code perf issues.  (Tracking that through today's `if a < b { Less } else if a == b { Equal } else { Greater }` would be *much* harder.)

---

r? `@ghost`
But first I should check that perf is ok with this
~~...and my true nemesis, tidy.~~
2024-04-02 19:21:44 +00:00
bors
45796d1c24 Auto merge of #123080 - Jules-Bertholet:mut-ref-mut, r=Nadrieril
Match ergonomics 2024: implement mutable by-reference bindings

Implements the mutable by-reference bindings portion of match ergonomics 2024 (#123076), with the `mut ref`/`mut ref mut` syntax, under feature gate `mut_ref`.

r? `@Nadrieril`

`@rustbot` label A-patterns A-edition-2024
2024-03-29 11:08:11 +00:00
bors
db2f9759f4 Auto merge of #122671 - Mark-Simulacrum:const-panic-msg, r=Nilstrieb
Codegen const panic messages as function calls

This skips emitting extra arguments at every callsite (of which there
can be many). For a librustc_driver build with overflow checks enabled,
this cuts 0.7MB from the resulting shared library (see [perf]).

A sample improvement from nightly:

```
        leaq    str.0(%rip), %rdi
        leaq    .Lalloc_d6aeb8e2aa19de39a7f0e861c998af13(%rip), %rdx
        movl    $25, %esi
        callq   *_ZN4core9panicking5panic17h17cabb89c5bcc999E@GOTPCREL(%rip)
```

to this PR:

```
        leaq    .Lalloc_d6aeb8e2aa19de39a7f0e861c998af13(%rip), %rdi
        callq   *_RNvNtNtCsduqIKoij8JB_4core9panicking11panic_const23panic_const_div_by_zero@GOTPCREL(%rip)
```

[perf]: https://perf.rust-lang.org/compare.html?start=a7e4de13c1785819f4d61da41f6704ed69d5f203&end=64fbb4f0b2d621ff46d559d1e9f5ad89a8d7789b&stat=instructions:u
2024-03-29 00:24:01 +00:00
Jules Bertholet
e0da13f25f
Implement mut ref/mut ref mut 2024-03-27 09:53:23 -04:00
Oli Scherer
2d4b7f287d Use a dyn Debug trait object instead of a closure.
Simplifies the API a bit.
2024-03-27 10:59:18 +00:00
Matthias Krüger
0029a11d7d
Rollup merge of #122835 - compiler-errors:deref-pure, r=Nadrieril
Require `DerefMut` and `DerefPure` on `deref!()` patterns when appropriate

Waiting on the deref pattern syntax pr to merge

r? nadrieril
2024-03-26 21:23:48 +01:00
Matthias Krüger
ff8cdc9e14
Rollup merge of #122120 - fmease:sugg-assoc-ty-bound-on-eq-bound, r=compiler-errors
Suggest associated type bounds on problematic associated equality bounds

Fixes #105056. TL;DR: Suggest `Trait<Ty: Bound>` on `Trait<Ty = Bound>` in Rust >=2021.

~~Blocked on #122055 (stabilization of `associated_type_bounds`), I'd say.~~ (merged)
2024-03-26 21:23:47 +01:00
Michael Goulet
b56279569b Require DerefPure for patterns 2024-03-25 19:39:45 -04:00
Scott McMurray
3da115a93b Add+Use mir::BinOp::Cmp 2024-03-23 23:23:41 -07:00
León Orell Valerian Liehr
d3d77a8733
Update docs of hir::TypeBinding 2024-03-22 23:06:36 +01:00
Guillaume Gomez
e0d3439226 Rename hir::Node::Local into hir::Node::LetStmt 2024-03-22 20:48:36 +01:00
Guillaume Gomez
d318bf1009 Rename hir::Node::expect_local into hir::Node::expect_let_stmt 2024-03-22 20:36:21 +01:00
Guillaume Gomez
b376f49e30 Rename hir::Local into hir::LetStmt 2024-03-22 20:36:21 +01:00
Mark Rousskov
00f4daa276 Codegen const panic messages as function calls
This skips emitting extra arguments at every callsite (of which there
can be many). For a librustc_driver build with overflow checks enabled,
this cuts 0.7MB from the resulting binary.
2024-03-22 09:55:50 -04:00
bors
1447f9d38c Auto merge of #122869 - matthiaskrgr:rollup-0navj4l, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #121619 (Experimental feature postfix match)
 - #122370 (Gracefully handle `AnonConst` in `diagnostic_hir_wf_check()`)
 - #122537 (interpret/allocation: fix aliasing issue in interpreter and refactor getters a bit)
 - #122542 (coverage: Clean up marker statements that aren't needed later)
 - #122800 (Add `NonNull::<[T]>::is_empty`.)
 - #122820 (Stop using `<DefId as Ord>` in various diagnostic situations)
 - #122847 (Suggest `RUST_MIN_STACK` workaround on overflow)
 - #122855 (Fix Itanium mangling usizes)
 - #122863 (add more ice tests )

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-22 12:29:42 +00:00
Matthias Krüger
783778c631
Rollup merge of #121619 - RossSmyth:pfix_match, r=petrochenkov
Experimental feature postfix match

This has a basic experimental implementation for the RFC postfix match (rust-lang/rfcs#3295, #121618). [Liaison is](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Postfix.20Match.20Liaison/near/423301844) ```@scottmcm``` with the lang team's [experimental feature gate process](https://github.com/rust-lang/lang-team/blob/master/src/how_to/experiment.md).

This feature has had an RFC for a while, and there has been discussion on it for a while. It would probably be valuable to see it out in the field rather than continue discussing it. This feature also allows to see how popular postfix expressions like this are for the postfix macros RFC, as those will take more time to implement.

It is entirely implemented in the parser, so it should be relatively easy to remove if needed.

This PR is split in to 5 commits to ease review.

1. The implementation of the feature & gating.
2. Add a MatchKind field, fix uses, fix pretty.
3. Basic rustfmt impl, as rustfmt crashes upon seeing this syntax without a fix.
4. Add new MatchSource to HIR for Clippy & other HIR consumers
2024-03-22 11:36:58 +01:00
León Orell Valerian Liehr
82c2c8deb1
Update (doc) comments
Several (doc) comments were super outdated or didn't provide enough context.

Some doc comments shoved everything in a single paragraph without respecting
the fact that the first paragraph should be a single sentence because rustdoc
treats these as item descriptions / synopses on module pages.
2024-03-22 06:31:51 +01:00
Matthias Krüger
1757cb5871
Rollup merge of #122829 - ShoyuVanilla:gen-block-impl-fused-iter, r=compiler-errors
Implement `FusedIterator` for `gen` block

cc #117078
2024-03-22 01:07:31 +01:00
Shoyu Vanilla
ae4c5c891e Implement FusedIterator for gen block 2024-03-22 02:02:34 +09:00
Michael Goulet
2d633317f3 Implement macro-based deref!() syntax for deref patterns
Stop using `box PAT` syntax for deref patterns, as it's misleading and
also causes their semantics being tangled up.
2024-03-21 11:42:49 -04:00
bors
6e1f7b538a Auto merge of #121587 - ShoyuVanilla:fix-issue-121267, r=TaKO8Ki
Fix bad span for explicit lifetime suggestions

Fixes #121267

Current explicit lifetime suggestions are not showing correct spans for some lifetimes - e.g. elided lifetime generic parameters;

This should be done correctly regarding elided lifetime kind like the following code

43fdd4916d/compiler/rustc_resolve/src/late/diagnostics.rs (L3015-L3044)
2024-03-21 04:11:09 +00:00
Shoyu Vanilla
c270a42fea Fix bad span for explicit lifetime suggestion
Move verbose logic to a function

Minor renaming
2024-03-21 10:31:04 +09:00
Jacob Pratt
afdbad80b1
Rollup merge of #122776 - GuillaumeGomez:rename-hir-let, r=oli-obk
Rename `hir::Let` into `hir::LetExpr`

As discussed on [zulip](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Improve.20naming.20of.20.60ExprKind.3A.3ALet.60.3F).

r? `````@Zalathar`````
2024-03-20 20:29:47 -04:00
Guillaume Gomez
98e66553a6 Rename hir::Let into hir::LetExpr 2024-03-20 16:47:11 +01:00
Mark Rousskov
02f1930595 step cfgs 2024-03-20 08:49:13 -04:00
Matthias Krüger
671a2f7d67
Rollup merge of #122719 - oli-obk:nested_static_feed_hir, r=fee1-dead
Ensure nested statics have a HIR node to prevent various queries from ICEing

fixes https://github.com/rust-lang/miri/issues/3389
2024-03-19 18:03:53 +01:00
bors
f296c162d8 Auto merge of #122021 - oli-obk:delangitemification, r=compiler-errors
Use hir::Node helper methods instead of repeating the same impl multiple times

I wanted to do something entirely different and stumbled upon a bunch of cleanups
2024-03-19 11:05:45 +00:00
Oli Scherer
bdb682eda6 The AssocOpaqueTy HIR node is not actually needed to differentiate from other hir nodes that were fed 2024-03-19 08:37:53 +00:00
Oli Scherer
419d205dad Deduplicate associated_body and body_id
They match on almost the same patterns, which is fishy.

Also turn `associated_body` into a method and do some cleanups nearby the call sites
2024-03-18 18:12:32 +00:00
Jason Newcomb
407b58cb77 Add missing try_visit calls in visitors. 2024-03-18 11:21:06 -04:00
Esteban Küber
14473adf42 Detect when move of !Copy value occurs within loop and should likely not be cloned
When encountering a move error on a value within a loop of any kind,
identify if the moved value belongs to a call expression that should not
be cloned and avoid the semantically incorrect suggestion. Also try to
suggest moving the call expression outside of the loop instead.

```
error[E0382]: use of moved value: `vec`
  --> $DIR/recreating-value-in-loop-condition.rs:6:33
   |
LL |     let vec = vec!["one", "two", "three"];
   |         --- move occurs because `vec` has type `Vec<&str>`, which does not implement the `Copy` trait
LL |     while let Some(item) = iter(vec).next() {
   |     ----------------------------^^^--------
   |     |                           |
   |     |                           value moved here, in previous iteration of loop
   |     inside of this loop
   |
note: consider changing this parameter type in function `iter` to borrow instead if owning the value isn't necessary
  --> $DIR/recreating-value-in-loop-condition.rs:1:17
   |
LL | fn iter<T>(vec: Vec<T>) -> impl Iterator<Item = T> {
   |    ----         ^^^^^^ this parameter takes ownership of the value
   |    |
   |    in this function
help: consider moving the expression out of the loop so it is only moved once
   |
LL ~     let mut value = iter(vec);
LL ~     while let Some(item) = value.next() {
   |
```

We use the presence of a `break` in the loop that would be affected by
the moved value as a heuristic for "shouldn't be cloned".

Fix #121466.
2024-03-17 21:32:26 +00:00
bors
c03ea3dfd9 Auto merge of #121926 - tgross35:f16-f128-step3-feature-gate, r=compiler-errors,petrochenkov
`f16` and `f128` step 3: compiler support & feature gate

Continuation of https://github.com/rust-lang/rust/pull/121841, another portion of https://github.com/rust-lang/rust/pull/114607

This PR exposes the new types to the world and adds a feature gate. Marking this as a draft because I need some feedback on where I did the feature gate check. It also does not yet catch type via suffixed literals (so the feature gate test will fail, probably some others too because I haven't belssed).

If there is a better place to check all types after resolution, I can do that. If not, I figure maybe I can add a second gate location in AST when it checks numeric suffixes.

Unfortunately I still don't think there is much testing to be done for correctness (codegen tests or parsed value checks) until we have basic library support. I think that will be the next step.

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

r? `@compiler-errors`
cc `@Nilstrieb`
`@rustbot` label +F-f16_and_f128
2024-03-16 02:02:00 +00:00
Matthias Krüger
1f4aff7d2b
Rollup merge of #122487 - GuillaumeGomez:rename-stmtkind-local, r=oli-obk
Rename `StmtKind::Local` variant into `StmtKind::Let`

It comes from this [discussion](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/Improve.20naming.20of.20.60ExprKind.3A.3ALet.60.3F).

Starting point was:

> I often end up looking at [ExprKind::Let](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_hir/enum.ExprKind.html#variant.Let) instead of Local because of the name. I think renaming it (both the `ExprKind` variant and the Let struct) to `LetPattern` or LetPat could improve the situation as I'm not sure I'm not the only one encountering this issue.

And then it evolved into:

> It's already `Expr::Let` instead of `StmtKind::Local`. Counterproposal: rename `StmtKind::Local` to `StmtKind::Let`.

The goal here is to clear this confusion.

r? `@oli-obk`
2024-03-14 20:00:21 +01:00
bors
fe61575228 Auto merge of #120943 - petrochenkov:somehir3, r=oli-obk
Create some minimal HIR for associated opaque types

`LocalDefId`s for opaque types in traits and impls are created after AST -> HIR lowering, so they don't have corresponding HIR and return their various properties through fed queries.

In this PR I also feed some core HIR-related queries for these `LocalDefId`s (which happen to be HIR owners).
As a result all `LocalDefId`s now have corresponding `HirId`s and HIR nodes, and "optional" methods like `opt_local_def_id_to_hir_id` and `opt_hir_node_by_def_id` can be removed.

Follow up to https://github.com/rust-lang/rust/pull/120206.
2024-03-14 14:28:58 +00:00
Guillaume Gomez
a4e0e50a3f Rename hir::StmtKind::Local into hir::StmtKind::Let 2024-03-14 12:42:04 +01:00
Trevor Gross
dc65095298 Enable f16 and f128 in HIR 2024-03-14 00:40:22 -05:00
Matthias Krüger
b84d1b8ec9
Rollup merge of #122430 - GuillaumeGomez:link-to-local, r=TaKO8Ki
Generate link to `Local` in `hir::Let` documentation

This PR adds a missing link generation to `Local` type.
2024-03-13 20:01:56 +01:00
Vadim Petrochenkov
b6312eb943 Create some minimal HIR for associated opaque types 2024-03-13 17:33:09 +03:00
Guillaume Gomez
d919b04e59 Generate link to Local in hir::Let documentation 2024-03-13 11:24:51 +01:00
Oli Scherer
e2773733f3 Some comment nits 2024-03-12 08:51:20 +00:00
Oli Scherer
926bfe5078 s/mt/mutability/ 2024-03-12 05:53:46 +00:00
Oli Scherer
d3514a036d Ensure nested allocations in statics do not get deduplicated 2024-03-12 05:53:46 +00:00
Oli Scherer
0b4cbee660 Add nested bool to DefKind::Static.
Will be used in the next commit
2024-03-12 05:53:46 +00:00
Oli Scherer
9816915954 Change DefKind::Static to a struct variant 2024-03-12 05:53:46 +00:00
Nicholas Nethercote
a09b1d33a7 Rename IntoDiagnosticArg as IntoDiagArg.
Also rename `into_diagnostic_arg` as `into_diag_arg`, and
`NotIntoDiagnosticArg` as `NotInotDiagArg`.
2024-03-11 09:12:19 +11:00
Matthias Krüger
d4d18d240b
Rollup merge of #122103 - compiler-errors:taits-capture-everything, r=oli-obk
Make TAITs and ATPITs capture late-bound lifetimes in scope

This generalizes the behavior that RPITs have, where they duplicate their in-scope lifetimes so that they will always *reify* late-bound lifetimes that they capture. This allows TAITs and ATPITs to properly error when they capture in-scope late-bound lifetimes.

r? `@oli-obk` cc `@aliemjay`

Fixes #122093 and therefore https://github.com/rust-lang/rust/pull/120700#issuecomment-1981213868
2024-03-08 08:19:20 +01:00
Matthias Krüger
d774fbea7c
Rollup merge of #119365 - nbdd0121:asm-goto, r=Amanieu
Add asm goto support to `asm!`

Tracking issue: #119364

This PR implements asm-goto support, using the syntax described in "future possibilities" section of [RFC2873](https://rust-lang.github.io/rfcs/2873-inline-asm.html#asm-goto).

Currently I have only implemented the `label` part, not the `fallthrough` part (i.e. fallthrough is implicit). This doesn't reduce the expressive though, since you can use label-break to get arbitrary control flow or simply set a value and rely on jump threading optimisation to get the desired control flow. I can add that later if deemed necessary.

r? ``@Amanieu``
cc ``@ojeda``
2024-03-08 08:19:17 +01:00
Michael Goulet
cf299ddb6e Make TAITs capture all higher-ranked lifetimes in scope 2024-03-08 02:10:11 +00:00
Ross Smyth
567c98b30f Add postfix match MatchSource to HIR 2024-03-06 00:51:48 -05:00
bors
b77e0184a9 Auto merge of #122045 - matthiaskrgr:rollup-5l3vpn7, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #121065 (Add basic i18n guidance for `Display`)
 - #121744 (Stop using Bubble in coherence and instead emulate it with an intercrate check)
 - #121829 (Dummy tweaks (attempt 2))
 - #121857 (Implement async closure signature deduction)
 - #121894 (const_eval_select: make it safe but be careful with what we expose on stable for now)
 - #122014 (Change some attributes to only_local.)
 - #122016 (will_wake tests fail on Miri and that is expected)
 - #122018 (only set noalias on Box with the global allocator)
 - #122028 (Remove some dead code)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-03-06 02:18:22 +00:00
Jason Newcomb
5abfb3775d Move visitor utils to rustc_ast_ir 2024-03-05 12:38:03 -05:00
Ralf Jung
f391c0793b only set noalias on Box with the global allocator 2024-03-05 15:03:33 +01:00
Trevor Gross
01755e3ff3 Add f16 and f128 intrinsics to HIR 2024-03-01 13:59:06 -05:00
Matthias Krüger
419f7aeed6
Rollup merge of #121681 - jswrenn:nix-visibility-analysis, r=compiler-errors
Safe Transmute: Revise safety analysis

This PR migrates `BikeshedIntrinsicFrom` to a simplified safety analysis (described [here](https://github.com/rust-lang/project-safe-transmute/issues/15)) that does not rely on analyzing the visibility of types and fields.

The revised analysis treats primitive types as safe, and user-defined types as potentially carrying safety invariants. If Rust gains explicit (un)safe fields, this PR is structured so that it will be fairly easy to thread support for those annotations into the analysis.

Notably, this PR removes the `Context` type parameter from `BikeshedIntrinsicFrom`. Most of the files changed by this PR are just UI tests tweaked to accommodate the removed parameter.

r? `@compiler-errors`
2024-02-29 20:50:03 +01:00
Michael Goulet
1feef44daf rename RPITIT from opaque to synthetic 2024-02-27 17:43:40 +00:00
Jack Wrenn
23ab1bda92 safe transmute: revise safety analysis
Migrate to a simplified safety analysis that does not use visibility.

Closes https://github.com/rust-lang/project-safe-transmute/issues/15
2024-02-27 16:22:32 +00:00
Gary Guo
93fa8579c6 Add asm label support to AST and HIR 2024-02-24 18:49:39 +00:00
clubby789
35a9e73521 Don't ICE on anonymous struct in enum variant 2024-02-23 12:25:23 +00:00
Nadrieril
5e0e5b1efb Fix liveness analysis in the presence of never patterns 2024-02-21 12:04:39 +01:00
Nilstrieb
46cab11ed1
Rollup merge of #121256 - Jarcho:visitor2, r=oli-obk
Allow AST and HIR visitors to return `ControlFlow`

Alternative to #108598.

Since rust-lang/libs-team#187 was rejected, this implements our own version of the `Try` trait (`VisitorResult`) and the `try` macro (`try_visit`). Since this change still allows visitors to return `()`, no changes have been made to the existing ones. They can be done in a separate PR.
2024-02-20 07:35:47 +01:00
Jason Newcomb
864cee3ea3 Allow AST and HIR visitors to return ControlFlow 2024-02-18 03:49:28 -05:00
clubby789
62b789fba4 Add more checks for unnamed_field during HIR analysis 2024-02-17 15:12:33 +00:00
Matthias Krüger
cb0d74be28
Rollup merge of #120958 - ShoyuVanilla:remove-subst, r=oli-obk
Dejargonize `subst`

In favor of #110793, replace almost every occurence of `subst` and `substitution` from rustc codes, but they still remains in subtrees under `src/tools/` like clippy and test codes (I'd like to replace them after this)
2024-02-12 23:18:54 +01:00
Matthias Krüger
15896bdd18
Rollup merge of #120950 - compiler-errors:miri-async-closurs, r=RalfJung,oli-obk
Fix async closures in CTFE

First commit renames `is_coroutine_or_closure` into `is_closure_like`, because `is_coroutine_or_closure_or_coroutine_closure` seems confusing and long.

Second commit fixes some forgotten cases where we want to handle `TyKind::CoroutineClosure` the same as closures and coroutines.

The test exercises the change to `ValidityVisitor::aggregate_field_path_elem` which is the source of #120946, but not the change to `UsedParamsNeedSubstVisitor`, though I feel like it's not that big of a deal. Let me know if you'd like for me to look into constructing a test for the latter, though I have no idea what it'd look like (we can't assert against `TooGeneric` anywhere?).

Fixes #120946

r? oli-obk cc ``@RalfJung``
2024-02-12 23:18:53 +01:00
Shoyu Vanilla
3856df059e Dejargnonize subst 2024-02-12 15:46:35 +09:00
Frank King
879a1e5713 Lower anonymous structs or unions to HIR 2024-02-12 12:47:23 +08:00
Matthias Krüger
4c154a1a48
Rollup merge of #120872 - petrochenkov:opthirpar, r=cjgillot
hir: Refactor getters for HIR parents

See individual commits.

I ended up removing on of the FIXMEs from https://github.com/rust-lang/rust/pull/120206 instead of addressing it.
2024-02-11 23:19:08 +01:00
Michael Goulet
cb024ba6e3 is_closure_like 2024-02-11 22:09:52 +00:00
Vadim Petrochenkov
b07283815b hir: Remove hir::Map::{opt_parent_id,parent_id,get_parent,find_parent} 2024-02-10 12:24:46 +03:00
Zalathar
a2479a4ae7 Remove unnecessary min_specialization after bootstrap
These crates all needed specialization for `newtype_index!`, which will no
longer be necessary when the current nightly eventually becomes the next
bootstrap compiler.
2024-02-10 18:15:11 +11:00
Matthias Krüger
46a0448405
Rollup merge of #120693 - nnethercote:invert-diagnostic-lints, r=davidtwco
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 been converted to use translated diagnostics.

This commit removes more `deny` attributes than it adds `allow` attributes, which proves that this change is warranted.

r? ````@davidtwco````
2024-02-09 14:41:50 +01:00
bors
1280928a99 Auto merge of #120767 - matthiaskrgr:rollup-0k8ib1c, r=matthiaskrgr
Rollup of 9 pull requests

Successful merges:

 - #119592 (resolve: Unload speculatively resolved crates before freezing cstore)
 - #120103 (Make it so that async-fn-in-trait is compatible with a concrete future in implementation)
 - #120206 (hir: Make sure all `HirId`s have corresponding HIR `Node`s)
 - #120214 (match lowering: consistently lower bindings deepest-first)
 - #120688 (GVN: also turn moves into copies with projections)
 - #120702 (docs: also check the inline stmt during redundant link check)
 - #120727 (exhaustiveness: Prefer "`0..MAX` not covered" to "`_` not covered")
 - #120734 (Add `SubdiagnosticMessageOp` as a trait alias.)
 - #120739 (improve pretty printing for associated items in trait objects)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-08 12:14:19 +00:00
Oli Scherer
1fcd04ed49 inline a function that is only used in clippy 2024-02-08 07:37:02 +00:00
Vadim Petrochenkov
3e8c8d8d34 hir: Add some FIXMEs for future work 2024-02-07 09:59:15 +03:00
Vadim Petrochenkov
a61019b290 hir: Remove fn opt_hir_id and fn opt_span 2024-02-07 09:38:24 +03:00
Vadim Petrochenkov
363b098245 hir: Make sure all HirIds have corresponding HIR Nodes 2024-02-07 09:38:24 +03:00
Michael Goulet
a82bae2172 Teach typeck/borrowck/solvers how to deal with async closures 2024-02-06 02:22:58 +00:00
Michael Goulet
c567eddec2 Add CoroutineClosure to TyKind, AggregateKind, UpvarArgs 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
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
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
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
bors
69db514ed9 Auto merge of #119968 - clubby789:unused-feature, r=compiler-errors
Remove unused/unnecessary features

~~The bulk of the actual code changes here is replacing try blocks with equivalent closures. I'm not entirely sure that's a good idea since it may have perf impact, happy to revert if that's the case/the change is unwanted.~~

I also removed a lot of `recursion_limit = "256"` since everything seems to build fine without that and most don't have any comment justifying it.
2024-01-26 03:18:34 +00:00
bors
dd2559e08e Auto merge of #116167 - RalfJung:structural-eq, r=lcnr
remove StructuralEq trait

The documentation given for the trait is outdated: *all* function pointers implement `PartialEq` and `Eq` these days. So the `StructuralEq` trait doesn't really seem to have any reason to exist any more.

One side-effect of this PR is that we allow matching on some consts that do not implement `Eq`. However, we already allowed matching on floats and consts containing floats, so this is not new, it is just allowed in more cases now. IMO it makes no sense at all to allow float matching but also sometimes require an `Eq` instance. If we want to require `Eq` we should adjust https://github.com/rust-lang/rust/pull/115893 to check for `Eq`, and rule out float matching for good.

Fixes https://github.com/rust-lang/rust/issues/115881
2024-01-26 00:17:00 +00:00
clubby789
fd29f74ff8 Remove unused features 2024-01-25 14:01:33 +00:00
Matthias Krüger
8c6cf3c934
Rollup merge of #119305 - compiler-errors:async-fn-traits, r=oli-obk
Add `AsyncFn` family of traits

I'm proposing to add a new family of `async`hronous `Fn`-like traits to the standard library for experimentation purposes.

## Why do we need new traits?

On the user side, it is useful to be able to express `AsyncFn` trait bounds natively via the parenthesized sugar syntax, i.e. `x: impl AsyncFn(&str) -> String` when experimenting with async-closure code.

This also does not preclude `AsyncFn` becoming something else like a trait alias if a more fundamental desugaring (which can take many[^1] different[^2] forms) comes around. I think we should be able to play around with `AsyncFn` well before that, though.

I'm also not proposing stabilization of these trait names any time soon (we may even want to instead express them via new syntax, like `async Fn() -> ..`), but I also don't think we need to introduce an obtuse bikeshedding name, since `AsyncFn` just makes sense.

## The lending problem: why not add a more fundamental primitive of `LendingFn`/`LendingFnMut`?

Firstly, for `async` closures to be as flexible as possible, they must be allowed to return futures which borrow from the async closure's captures. This can be done by introducing `LendingFn`/`LendingFnMut` traits, or (equivalently) by adding a new generic associated type to `FnMut` which allows the return type to capture lifetimes from the `&mut self` argument of the trait. This was proposed in one of [Niko's blog posts](https://smallcultfollowing.com/babysteps/blog/2023/05/09/giving-lending-and-async-closures/).

Upon further experimentation, for the purposes of closure type- and borrow-checking, I've come to the conclusion that it's significantly harder to teach the compiler how to handle *general* lending closures which may borrow from their captures. This is, because unlike `Fn`/`FnMut`, the `LendingFn`/`LendingFnMut` traits don't form a simple "inheritance" hierarchy whose top trait is `FnOnce`.

```mermaid
flowchart LR
    Fn
    FnMut
    FnOnce
    LendingFn
    LendingFnMut

    Fn -- isa --> FnMut
    FnMut -- isa --> FnOnce

    LendingFn -- isa --> LendingFnMut

    Fn -- isa --> LendingFn
    FnMut -- isa --> LendingFnMut
```

For example:

```
fn main() {
  let s = String::from("hello, world");
  let f = move || &s;
  let x = f(); // This borrows `f` for some lifetime `'1` and returns `&'1 String`.
```

That trait hierarchy means that in general for "lending" closures, like `f` above, there's not really a meaningful return type for `<typeof(f) as FnOnce>::Output` -- it can't return `&'static str`, for example.

### Special-casing this problem:

By splitting out these traits manually, and making sure that each trait has its own associated future type, we side-step the issue of having to answer the questions of a general `LendingFn`/`LendingFnMut` implementation, since the compiler knows how to generate built-in implementations for first-class constructs like async closures, including the required future types for the (by-move) `AsyncFnOnce` and (by-ref) `AsyncFnMut`/`AsyncFn` trait implementations.

[^1]: For example, with trait transformers, we may eventually be able to write: `trait AsyncFn = async Fn;`
[^2]: For example, via the introduction of a more fundamental "`LendingFn`" trait, plus a [special desugaring with augmented trait aliases](https://rust-lang.zulipchat.com/#narrow/stream/213817-t-lang/topic/Lending.20closures.20and.20Fn*.28.29.20-.3E.20impl.20Trait/near/408471480).
2024-01-25 08:39:41 +01:00
Ralf Jung
0df7810734 remove StructuralEq trait 2024-01-24 07:56:23 +01:00
Matthias Krüger
221115cbd6
Rollup merge of #120143 - compiler-errors:consolidate-instance-resolve-for-coroutines, r=oli-obk
Consolidate logic around resolving built-in coroutine trait impls

Deduplicates a lot of code. Requires defining a new lang item for `Coroutine::resume` for consistency, but it seems not harmful at worst, and potentially later useful at best.

r? oli-obk
2024-01-22 22:12:08 +01:00
bors
867d39cdf6 Auto merge of #120100 - oli-obk:astconv_lifetimes, r=BoxyUwU
Don't forget that the lifetime on hir types is `'tcx`

This PR just tracks the `'tcx` lifetime to wherever the original objects actually have that lifetime. This code is needed for https://github.com/rust-lang/rust/pull/107606 (now #120131) so that `ast_ty_to_ty` can invoke `lit_to_const` on an argument passed to it. Currently the argument is `&hir::Ty<'_>`, but after this PR it is `&'tcx hir::Ty<'tcx>`.
2024-01-21 00:33:43 +00:00
Michael Goulet
f2ef88ba06 Consolidate logic around resolving built-in coroutine trait impls 2024-01-19 21:28:37 +00: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
Oli Scherer
e532b0dd7e Don't forget that the lifetime on hir types is 'tcx 2024-01-18 16:07:10 +00: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
Camille GILLOT
b99c3ae6d6 Get rid of the hir_owner query. 2024-01-16 23:49:38 +00:00
bors
8847bda592 Auto merge of #119361 - sjwang05:issue-119352, r=WaffleLapkin
Fix ICE when suggesting dereferencing binop operands

Fixes #119352
2024-01-14 09:39:03 +00:00
sjwang05
c36b5d5353
Fix ICE when suggesting dereferencing binop operands 2024-01-12 17:49:37 -08:00
Bryanskiy
d69cd6473c Delegation implementation: step 1 2024-01-12 14:11:16 +03:00
Oli Scherer
972c95a6e2 Turn some free functions into methods 2024-01-10 08:52:44 +00:00
bors
dc641039d2 Auto merge of #117703 - compiler-errors:recursive-async, r=lcnr
Support async recursive calls (as long as they have indirection)

Before #101692, we stored coroutine witness types directly inside of the coroutine. That means that a coroutine could not contain itself (as a witness field) without creating a cycle in the type representation of the coroutine, which we detected with the `OpaqueTypeExpander`, which is used to detect cycles when expanding opaque types after that are inferred to contain themselves.

After `-Zdrop-tracking-mir` was stabilized, we no longer store these generator witness fields directly, but instead behind a def-id based query. That means there is no technical obstacle in the compiler preventing coroutines from containing themselves per se, other than the fact that for a coroutine to have a non-infinite layout, it must contain itself wrapped in a layer of allocation indirection (like a `Box`).

This means that it should be valid for this code to work:

```
async fn async_fibonacci(i: u32) -> u32 {
    if i == 0 || i == 1 {
        i
    } else {
        Box::pin(async_fibonacci(i - 1)).await
          + Box::pin(async_fibonacci(i - 2)).await
    }
}
```

Whereas previously, you'd need to coerce the future to `Pin<Box<dyn Future<Output = ...>>` before `await`ing it, to prevent the async's desugared coroutine from containing itself across as await point.

This PR does two things:
1. Only report an error if an opaque expansion cycle is detected *not* through coroutine witness fields.
    * Instead, if we find an opaque cycle through coroutine witness fields, we compute the layout of the coroutine. If that results in a cycle error, we report it as a recursive async fn.
4. Reworks the way we report layout errors having to do with coroutines, to make up for the diagnostic regressions introduced by (1.). We actually do even better now, pointing out the call sites of the recursion!
2024-01-09 07:20:50 +00:00
Matthias Krüger
5efa69d979
Rollup merge of #119704 - chenyukang:yukang-fix-let_underscore, r=Nilstrieb
Fix two variable binding issues in lint let_underscore

Fixes #119696
Fixes #119697
2024-01-09 00:19:35 +01:00
Michael Goulet
82a2215481 Don't check for recursion in generator witness fields 2024-01-08 20:30:21 +00:00
yukang
75df38e816 Fix 2 variable binding issues in let_underscore 2024-01-08 16:50:14 +08: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
León Orell Valerian Liehr
893b6f6538
Rollup merge of #119239 - compiler-errors:yield-coercion, r=davidtwco
Remove unnecessary arm in `check_expr_yield`

We always set up the `resume_yield_tys` for async blocks and fns, so this arm was unreachable.
2024-01-03 16:08:24 +01:00
bors
dc450f9dcb Auto merge of #119259 - cjgillot:single-crate-id, r=Mark-Simulacrum
Only store StableCrateId once in DefPathTable.

https://github.com/rust-lang/rust/pull/119238 made me think of this.

cc `@Mark-Simulacrum`
2023-12-29 14:37:40 +00:00
León Orell Valerian Liehr
3eb48a35c8
Introduce const Trait (always-const trait bounds) 2023-12-27 12:51:32 +01:00
Michael Goulet
3320c09eab Only regular coroutines have movability 2023-12-25 21:13:41 +00:00
Michael Goulet
17b433351d select AsyncFn traits during overloaded call op 2023-12-25 20:31:28 +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
Camille GILLOT
821920b2a3 Do not store stable crate id in on-disk hash map. 2023-12-24 17:22:48 +00:00
Camille GILLOT
75ad81ce93 Do not store stable_crate_id again in Definitions. 2023-12-24 17:22:48 +00:00