Switch to `EarlyBinder` for `explicit_item_bounds`
Part of the work to finish https://github.com/rust-lang/rust/issues/105779.
This PR adds `EarlyBinder` to the return type of the `explicit_item_bounds` query and removes `bound_explicit_item_bounds`.
r? `@compiler-errors` (hope it's okay to request you, since you reviewed #110299 and #110498😃)
Run various queries from other queries instead of explicitly in phases
These are just legacy leftovers from when rustc didn't have a query system. While there are more cleanups of this sort that can be done here, I want to land them in smaller steps.
This phased order of query invocations was already a lie, as any query that looks at types (e.g. the wf checks run before) can invoke e.g. const eval which invokes borrowck, which invokes typeck, ...
Evaluate place expression in `PlaceMention`
https://github.com/rust-lang/rust/pull/102256 introduces a `PlaceMention(place)` MIR statement which keep trace of `let _ = place` statements from surface rust, but without semantics.
This PR proposes to change the behaviour of `let _ =` patterns with respect to the borrow-checker to verify that the bound place is live.
Specifically, consider this code:
```rust
let _ = {
let a = 5;
&a
};
```
This passes borrowck without error on stable. Meanwhile, replacing `_` by `_: _` or `_p` errors with "error[E0597]: `a` does not live long enough", [see playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c448d25a7c205dc95a0967fe96bccce8).
This PR *does not* change how `_` patterns behave with respect to initializedness: it remains ok to bind a moved-from place to `_`.
The relevant test is `tests/ui/borrowck/let_underscore_temporary.rs`. Crater check found no regression.
For consistency, this PR changes miri to evaluate the place found in `PlaceMention`, and report eventual dangling pointers found within it.
r? `@RalfJung`
Add offset_of! macro (RFC 3308)
Implements https://github.com/rust-lang/rfcs/pull/3308 (tracking issue #106655) by adding the built in macro `core::mem::offset_of`. Two of the future possibilities are also implemented:
* Nested field accesses (without array indexing)
* DST support (for `Sized` fields)
I wrote this a few months ago, before the RFC merged. Now that it's merged, I decided to rebase and finish it.
cc `@thomcc` (RFC author)
Allow to feed a value in another query's cache and remove `WithOptConstParam`
I used it to remove `WithOptConstParam` queries, as an example.
The idea is that a query (here `typeck(function)`) can write into another query's cache (here `type_of(anon const)`). The dependency node for `type_of` would depend on all the current dependencies of `typeck`.
There is still an issue with cycles: if `type_of(anon const)` is accessed before `typeck(function)`, we will still have the usual cycle. The way around this issue is to `ensure` that `typeck(function)` is called before accessing `type_of(anon const)`.
When replayed, we may the following cases:
- `typeck` is green, in that case `type_of` is green too, and all is right;
- `type_of` is green, `typeck` may still be marked as red (it depends on strictly more things than `type_of`) -> we verify that the saved value and the re-computed value of `type_of` have the same hash;
- `type_of` is red, then `typeck` is red -> it's the caller responsibility to ensure `typeck` is recomputed *before* `type_of`.
As `anon consts` have their own `DefPathData`, it's not possible to have the def-id of the anon-const point to something outside the original function, but the general case may have to be resolved before using this device more broadly.
There is an open question about loading from the on-disk cache. If `typeck` is loaded from the on-disk cache, the side-effect does not happen. The regular `type_of` implementation can go and fetch the correct value from the decoded `typeck` results, and the dep-graph will check that the hashes match, but I'm not sure we want to rely on this behaviour.
I specifically allowed to feed the value to `type_of` from inside a call to `type_of`. In that case, the dep-graph will check that the fingerprints of both values match.
This implementation is still very sensitive to cycles, and requires that we call `typeck(function)` before `typeck(anon const)`. The reason is that `typeck(anon const)` calls `type_of(anon const)`, which calls `typeck(function)`, which feeds `type_of(anon const)`, and needs to build the MIR so needs `typeck(anon const)`. The latter call would not cycle, since `type_of(anon const)` has been set, but I'd rather not remove the cycle check.
Enable flatten-format-args by default.
Part of https://github.com/rust-lang/rust/issues/99012.
This enables the `flatten-format-args` feature that was added by https://github.com/rust-lang/rust/pull/106824:
> This change inlines string literals, integer literals and nested format_args!() into format_args!() during ast lowering, making all of the following pairs result in equivalent hir:
>
> ```rust
> println!("Hello, {}!", "World");
> println!("Hello, World!");
> ```
>
> ```rust
> println!("[info] {}", format_args!("error"));
> println!("[info] error");
> ```
>
> ```rust
> println!("[{}] {}", status, format_args!("error: {}", msg));
> println!("[{}] error: {}", status, msg);
> ```
>
> ```rust
> println!("{} + {} = {}", 1, 2, 1 + 2);
> println!("1 + 2 = {}", 1 + 2);
> ```
>
> And so on.
>
> This is useful for macros. E.g. a `log::info!()` macro could just pass the tokens from the user directly into a `format_args!()` that gets efficiently flattened/inlined into a `format_args!("info: {}")`.
>
> It also means that `dbg!(x)` will have its file, line, and expression name inlined:
>
> ```rust
> eprintln!("[{}:{}] {} = {:#?}", file!(), line!(), stringify!(x), x); // before
> eprintln!("[example.rs:1] x = {:#?}", x); // after
> ```
>
> Which can be nice in some cases, but also means a lot more unique static strings than before if dbg!() is used a lot.
This is mostly an optimization, except that it will be visible through [`fmt::Arguments::as_str()`](https://doc.rust-lang.org/nightly/std/fmt/struct.Arguments.html#method.as_str).
In https://github.com/rust-lang/rust/pull/106823, there was already a libs-api FCP about the documentation of `fmt::Arguments::as_str()` to allow it to give `Some` rather than `None` depending on optimizations like this. That was just a documentation update though. This PR is the one that actually makes the user visible change:
```rust
assert_eq!(format_args!("abc").as_str(), Some("abc")); // Unchanged.
assert_eq!(format_args!("ab{}", "c").as_str(), Some("abc")); // Was `None` before!
```
Don't transmute `&List<GenericArg>` <-> `&List<Ty>`
In #93505 we allowed safely transmuting between `&List<GenericArg<'_>>` and `&List<Ty<'_>>`. This was possible because `GenericArg` is a tagged pointer and the tag for types is `0b00`, such that a `GenericArg` with a type inside has the same layout as `Ty`.
While this was meant as an optimization, it doesn't look like it was actually any perf or max-rss win (see https://github.com/rust-lang/rust/pull/94799#issuecomment-1064340003, https://github.com/rust-lang/rust/pull/94841, https://github.com/rust-lang/rust/pull/110496#issuecomment-1513799140).
Additionally the way it was done is quite fragile — `unsafe` code was not properly documented or contained in a module, types were not marked as `repr(C)` (making the transmutes possibly unsound). All of this makes the code maintenance harder and blocks other possible optimizations (as an example I've found out about these `transmutes` when my change caused them to sigsegv compiler).
Thus, I think we can safely (pun intended) remove those transmutes, making maintenance easier, optimizations possible, code less cursed, etc.
r? `@compiler-errors`
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.
resolve: Pre-compute non-reexport module children
Instead of repeating the same logic by walking HIR during metadata encoding.
The only difference is that we are no longer encoding `macro_rules` items, but we never currently need them as a part of this list. They can be encoded separately if this need ever arises.
`module_reexports` is also un-querified, because I don't see any reasons to make it a query, only overhead.
Instead of repeating the same logic by walking HIR during metadata encoding.
The only difference is that we are no longer encoding `macro_rules` items, but we never currently need them as a part of this list.
They can be encoded separately if this need ever arises.
`module_reexports` is also un-querified, because I don't see any reasons to make it a query, only overhead.
Make elaboration generic over input
Combines all the `elaborate_*` family of functions into just one, which is an iterator over the same type that you pass in (e.g. elaborating `Predicate` gives `Predicate`s, elaborating `Obligation`s gives `Obligation`s, etc.)
Initial support for return type notation (RTN)
See: https://smallcultfollowing.com/babysteps/blog/2023/02/13/return-type-notation-send-bounds-part-2/
1. Only supports `T: Trait<method(): Send>` style bounds, not `<T as Trait>::method(): Send`. Checking validity and injecting an implicit binder for all of the late-bound method generics is harder to do for the latter.
* I'd add this in a follow-up.
3. ~Doesn't support RTN in general type position, i.e. no `let x: <T as Trait>::method() = ...`~
* I don't think we actually want this.
5. Doesn't add syntax for "eliding" the function args -- i.e. for now, we write `method(): Send` instead of `method(..): Send`.
* May be a hazard if we try to add it in the future. I'll probably add it in a follow-up later, with a structured suggestion to change `method()` to `method(..)` once we add it.
7. ~I'm not in love with the feature gate name 😺~
* I renamed it to `return_type_notation` ✔️
Follow-up PRs will probably add support for `where T::method(): Send` bounds. I'm not sure if we ever want to support return-type-notation in arbitrary type positions. I may also make the bounds require `..` in the args list later.
r? `@ghost`
Insert alignment checks for pointer dereferences when debug assertions are enabled
Closes https://github.com/rust-lang/rust/issues/54915
- [x] Jake tells me this sounds like a place to use `MirPatch`, but I can't figure out how to insert a new basic block with a new terminator in the middle of an existing basic block, using `MirPatch`. (if nobody else backs up this point I'm checking this as "not actually a good idea" because the code looks pretty clean to me after rearranging it a bit)
- [x] Using `CastKind::PointerExposeAddress` is definitely wrong, we don't want to expose. Calling a function to get the pointer address seems quite excessive. ~I'll see if I can add a new `CastKind`.~ `CastKind::Transmute` to the rescue!
- [x] Implement a more helpful panic message like slice bounds checking.
r? `@oli-obk`
Clarify the 'use a constant in a pattern' error message
```rs
use std::borrow::Cow;
const ERROR_CODE: Cow<'_, str> = Cow::Borrowed("23505");
fn main() {
let x = Cow::from("23505");
match x {
ERROR_CODE => {}
}
}
```
```
error: to use a constant of type `Cow` in a pattern, `Cow` must be annotated with `#[derive(PartialEq, Eq)]`
--> src/main.rs:9:9
|
9 | ERROR_CODE => {}
| ^^^^^^^^^^
error: could not compile `playground` due to previous error
```
It seems helpful to link to StructuralEq in this message. I was a little confused, because `Cow<'_, str>` implements PartialEq and Eq, but they're not derived, which I learned is necessary for structural equality and using constants in patterns (thanks to the Rust community Discord server)
For tests, should I update every occurrence of this message? I see tests where this is still a warning and I'm not sure if I should update those.
Remove the `NodeId` of `ast::ExprKind::Async`
This is a followup to https://github.com/rust-lang/rust/pull/104833#pullrequestreview-1314537416.
In my original attempt, I was using `LoweringContext::expr`, which was not correct as it creates a fresh `DefId`.
It now uses the correct `DefId` for the wrapping `Expr`, and also makes forwarding `#[track_caller]` attributes more explicit.