Desugaring of drop and replace at MIR build
This commit desugars the drop and replace deriving from an
assignment at MIR build, avoiding the construction of the
`DropAndReplace` terminator (which will be removed in a following PR).
In order to retain the same error messages for replaces a new
`DesugaringKind::Replace` variant is introduced.
The changes in the borrowck are also useful for future work in moving drop elaboration
before borrowck, as no `DropAndReplace` would be present there anymore.
Notes on test diffs:
* `tests/ui/borrowck/issue-58776-borrowck-scans-children`: the assignment deriving from the desugaring kills the borrow.
* `tests/ui/async-await/async-fn-size-uninit-locals.rs`, `tests/mir-opt/issue_41110.test.ElaborateDrops.after.mir`, `tests/mir-opt/issue_41888.main.ElaborateDrops.after.mir`: drop elaboration generates (or reads from) a useless drop flag due to an issue with the dataflow analysis. Will be fixed independently by https://github.com/rust-lang/rust/pull/106430.
See https://github.com/rust-lang/rust/pull/104488 for more context
Make compressed rmeta contain compressed data length after header
Fixes#90056, which is caused by link.exe introducing padding to the `.rustc` section, since it assumes this will have no effect besides allowing it to possibly use the extra space in future links.
Don't call `temporary_scope` twice.
`mirror_expr_inner` calls `temporary_scope`. It then calls `make_mirror_unadjusted` which makes an identical call to `temporary_scope`.
This commit changes the `mirror_expr_inner` to get the `temp_lifetime` out of the expression produced by `make_mirror_unadjusted`, similar to how it currently gets the type.
r? `@cjgillot`
rustc_expand: make proc-macro derive error translatable
kept this tiny so as to point to it as an example in rustc-dev-guide
`@rustbot` label +A-translation
Remove `NormalizationError::ConstantKind`
No longer in use by `TryNormalizeAfterErasingRegionsFolder` (as of #102355 / e8150fa60c it seems). It's making `LayoutError`, etc. kinda large -- that was noticed by `@zoxc.`
Use `Option::as_slice` where applicable
After #105871 introduced `Option::as_slice`, this PR uses it within the compiler. I found it interesting that all cases where `as_slice` could be used were done with different code before; so it seems the new API also has the benefit of being "the obvious solution" where before there was a mix of options, none clearly better than the rest.
Label opaque type for 'captures lifetime' error message
Providing more information may help make this somewhat opaque (lol) error message a bit clearer.
Fix another ICE in `point_at_expr_source_of_inferred_type`
Types coming from method probes must only be investigated *structurally*, since they often contain escaping infer variables from generalization and autoderef. We already have a hack in this PR that erases variables from types, so just use that.
Fixes#108664
The note attached to this error is pretty bad:
```
here the type of `primes` is inferred to be `[_]`
```
But that's unrelated to the PR.
---
Side-note: This is a pretty easy to trigger beta regression, so I've nominated it. Alternatively, I'm slightly inclined to remove this code altogether until it can be reformulated to be more accurate and less ICEy.
Remove legacy PM leftovers
This drops two leftovers of legacy PM usage:
* We don't need to initialize passes anymore.
* The pass listing was still using legacy PM passes. Replace it with the corresponding new PM listing.
Deny capturing late-bound non-lifetime param in anon const
Introduce a new AnonConstBoundary so we can detect when we capture a late-bound non-lifetime param with `non_lifetime_binders` enabled.
In the future, we could technically do something like introduce an early-bound parameter on the anon const, and stick the late-bound param in its substs (kinda like how we turn late-bound lifetimes in opaques into early-bound ones). But for now, just deny it so we don't ICE.
Fixes#108191
This commit desugars the drop and replace deriving from an
assignment at MIR build, avoiding the construction of the
DropAndReplace terminator (which will be removed in a followign PR)
In order to retain the same error messages for replaces a new
DesugaringKind::Replace variant is introduced.
`mirror_expr_inner` calls `temporary_scope`. It then calls
`make_mirror_unadjusted` which makes an identical call to
`temporary_scope`.
This commit changes the `mirror_expr_inner` to get the `temp_lifetime`
out of the expression produced by `make_mirror_unadjusted`, similar to
how it currently gets the type.
Feed queries on impl side for RPITITs when using lower_impl_trait_in_trait_to_assoc_ty
I've added a test for traits that were already working and what I think is probably the last bit of infrastructure work needed.
In following PRs I'm going to start adding things TDD style, tests and code that make it work.
r? `@compiler-errors`
Make `ExprKind` the first field in `thir::Expr`
This makes its `Debug` impl print it first which is useful, as it's the most important part when looking at an expr.
Explain compile-time vs run-time difference in env!() error message
This PR is clarifying error message of `env!()` based on this user question: https://users.rust-lang.org/t/environment-variable-out-dir-is-undefined/90067
It makes it clear that `env!()` is for env variables defined at compile-time. There's special-case help text for common Cargo build script variables.
I've also rearranged the code to avoid allocating error message on the happy path when the env var is defined.
Point error span at Some constructor argument when trait resolution fails
This is a follow up to #108254 and #106477 which extends error span refinement to handle a case which I mistakenly believed was handled in #106477. The goal is to refine the error span depicted below:
```rs
trait Fancy {}
impl <T> Fancy for Option<T> where T: Iterator {}
fn want_fancy<F>(f: F) where F: Fancy {}
fn example() {
want_fancy(Some(5));
// (BEFORE) ^^^^^^^ `{integer}` is not an iterator
// (AFTER) ^ `{integer}` is not an iterator
}
```
I had used a (slightly more complex) example as an illustrative example in #108254 , but hadn't actually turned it into a test, because I had (incorrectly) believed at the time it was covered by existing behavior. It turns out that `Some` is slightly "special" in that it resolves differently from the other `enum` constructors I had tried, and therefore this test was actually broken.
I've now updated the tests to include this example, and fixed the code to correctly resolve the `Some` constructor so that the span of the error is reduced.
Support allocations with non-Box<[u8]> bytes
This is prep work for allowing miri to support passing pointers to C code, which will require `Allocation`s to be correctly aligned. Currently, it just makes `Allocation` generic and plumbs the necessary changes through the right places.
The follow-up to this will be adding a type in the miri interpreter which correctly aligns the bytes, using that for the Miri engine, then allowing Miri to pass pointers into these allocations to C calls.
Based off of #100467, credit to ```@emarteca``` for the code
Revert stabilization of `#![feature(target_feature_11)]`
This reverts #99767 due to the presence of bugs #108645 and #108646.
cc `@joshtriplett`
cc tracking issue #69098
r? `@ghost`
Highlight whole expression for E0599
Fixes#108603
This adds a secondary label to highlight the whole expression leading to the error. It also prevents empty labels being recognised as 'unexpected' by compiletest - otherwise, tests with NOTE annotations would pick up empty labels.
`@rustbot` label +A-diagnostics
Restrict `#[rustc_box]` to `Box::new` calls
Currently, `#[rustc_box]` can be applied to any call expression with a single argument. This PR only allows it to be applied to calls to `Box::new`
Rollup of 7 pull requests
Successful merges:
- #108143 (rustdoc: search by macro when query ends with `!`)
- #108394 (Make `x doc --open` work on every book)
- #108427 (Recover from for-else and while-else)
- #108462 (Fix `VecDeque::append` capacity overflow for ZSTs)
- #108568 (Make associated_item_def_ids for traits use an unstable option to also return associated types for RPITITs)
- #108604 (Add regression test for #107280)
- #108605 (Add regression test for #105821)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Name LLVM anonymous constants by a hash of their contents
This makes the names stable between different versions of a crate unlike the `AllocId` naming, making LLVM IR comparisons with `llvm-diff` more practical.
Fix a race in the query system
This fixes an issue where in between the `job` removal and `complete` call the query neither has a job nor a result, allowing another thread to start executing it again.
r? ``@cjgillot``
Only look for param in item's generics if it actually comes from generics
Record whether a `hir::GenericParam` comes from an item's generics, or from a `for<...>` binder. Then, only look for the param in `object_lifetime_default` if it actually comes from the item's generics.
Fixes#108177
Stabilize `#![feature(target_feature_11)]`
## Stabilization report
### Summary
Allows for safe functions to be marked with `#[target_feature]` attributes.
Functions marked with `#[target_feature]` are generally considered as unsafe functions: they are unsafe to call, cannot be assigned to safe function pointers, and don't implement the `Fn*` traits.
However, calling them from other `#[target_feature]` functions with a superset of features is safe.
```rust
// Demonstration function
#[target_feature(enable = "avx2")]
fn avx2() {}
fn foo() {
// Calling `avx2` here is unsafe, as we must ensure
// that AVX is available first.
unsafe {
avx2();
}
}
#[target_feature(enable = "avx2")]
fn bar() {
// Calling `avx2` here is safe.
avx2();
}
```
### Test cases
Tests for this feature can be found in [`src/test/ui/rfcs/rfc-2396-target_feature-11/`](b67ba9ba20/src/test/ui/rfcs/rfc-2396-target_feature-11/).
### Edge cases
- https://github.com/rust-lang/rust/issues/73631
Closures defined inside functions marked with `#[target_feature]` inherit the target features of their parent function. They can still be assigned to safe function pointers and implement the appropriate `Fn*` traits.
```rust
#[target_feature(enable = "avx2")]
fn qux() {
let my_closure = || avx2(); // this call to `avx2` is safe
let f: fn() = my_closure;
}
```
This means that in order to call a function with `#[target_feature]`, you must show that the target-feature is available while the function executes *and* for as long as whatever may escape from that function lives.
### Documentation
- Reference: https://github.com/rust-lang/reference/pull/1181
---
cc tracking issue #69098
r? `@ghost`
Avoid invoking typeck from borrowck
This PR attempts to reduce direct dependencies between typeck and MIR-related queries. The goal is to have all the information transit either through THIR or through dedicated queries that avoid depending on the whole `TypeckResults`.
In a first commit, we store the type information that MIR building requires into THIR. This avoids edges between mir_built and typeck.
In the second and third commit, we wrap informations around closures (upvars, kind origin and user-provided signature) to avoid borrowck depending on typeck information.
There should be a single remaining borrowck -> typeck edge in the good path, due to inline consts.
Rollup of 8 pull requests
Successful merges:
- #104265 (Move IpAddr, SocketAddr and V4+V6 related types to `core`)
- #107110 ([stdio][windows] Use MBTWC and WCTMB)
- #108308 (Allow building serde and serde_derive in parallel)
- #108363 (Move the unused extern crate check back to the resolver.)
- #108519 (Bages for easy access links to Rust community)
- #108522 (Commit some new solver tests)
- #108523 (Avoid `&str` to `String` conversions)
- #108533 (diagnostics: avoid querying `associated_item` in the resolver)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Move THIR printing to rustc_mir_build.
https://github.com/rust-lang/rust/pull/107451 increased the compilation time of `rustc_middle` by 10% = 3s.
As https://github.com/rust-lang/rust/pull/107006 adds quite a lot of code to rustc_middle, I suspect it to be the cause.
This PR moves the THIR printing code to `rustc_mir_build`, where the query provider lives, in order to benefit from higher parallelism when compiling rustc.
MIR-Validate StorageLive.
`StorageLive` statements on a local which already has storage is banned by miri.
This check is easy enough, and can detect bugs in MIR opts.
Unify validity checks into a single query
Previously, there were two queries to check whether a type allows the 0x01 or zeroed bitpattern.
I am planning on adding a further initness to check in #100423, truly uninit for MaybeUninit, which would make this three queries. This seems overkill for such a small feature, so this PR unifies them into one.
I am not entirely happy with the naming and key type and open for improvements.
r? oli-obk
Don't project specializable RPITIT projection
This effective rejects specialization + RPITIT/AFIT (usages of `impl Trait` in traits) because the implementation is significantly complicated over making regular "default" trait method bodies work.
I have another PR that experimentally fixes all this, but the code may not be worth investing in.
Emit the enum discriminant separately for the Encodable macro
This changes the `Encodable` proc macro to first emit the discriminant with a separate `match` statement, then emit the fields. LLVM can optimize down the first `match` to just a read of the enum discriminant. This avoids generating a `emit_usize` call per variant and enums with no fields now optimize down to just a single `emit_usize` call.
The no variant case is special cased to avoid warnings about unreachable code.
<table><tr><td rowspan="2">Benchmark</td><td colspan="1"><b>Before</b></th><td colspan="2"><b>After</b></th></tr><tr><td align="right">Time</td><td align="right">Time</td><td align="right">%</th></tr><tr><td>🟣 <b>clap</b>:check:unchanged</td><td align="right">0.4676s</td><td align="right">0.4640s</td><td align="right"> -0.78%</td></tr><tr><td>🟣 <b>hyper</b>:check:unchanged</td><td align="right">0.1348s</td><td align="right">0.1338s</td><td align="right"> -0.75%</td></tr><tr><td>🟣 <b>regex</b>:check:unchanged</td><td align="right">0.3370s</td><td align="right">0.3352s</td><td align="right"> -0.54%</td></tr><tr><td>🟣 <b>syn</b>:check:unchanged</td><td align="right">0.6326s</td><td align="right">0.6281s</td><td align="right"> -0.71%</td></tr><tr><td>🟣 <b>syntex_syntax</b>:check:unchanged</td><td align="right">1.8561s</td><td align="right">1.8589s</td><td align="right"> 0.15%</td></tr><tr><td>Total</td><td align="right">3.4282s</td><td align="right">3.4200s</td><td align="right"> -0.24%</td></tr><tr><td>Summary</td><td align="right">1.0000s</td><td align="right">0.9947s</td><td align="right"> -0.53%</td></tr></table>
Upgrade to ena-0.14.1.
It avoids some inlining within its `inlined_probe_value` function, which seems to result in better codegen for the very large `process_obligations` function within rustc. It might also help with reducing the bimodal perf results we see for the `keccak` and `cranelift-codegen-0.82.1` benchmarks.
r? `@ghost`
Remove `from` lang item
It was probably a leftover from the old `?` desugaring but anyways, it's unused now except for clippy, which can just use a diagnostics item.
statically guarantee that current error codes are documented
Closes#61137 (that's right!)
Pretty simple refactor (often just a change from `Result<Option<&str>>` to `Result<&str>`)
r? `@GuillaumeGomez` (could you specially look at 53044158eff0d64673a6100f701c57b484232aca? I believe you wrote that in the first place, just want to make sure you're happy with the change)
rustc_infer: Consolidate obligation elaboration de-duplication
# Explanation
The obligations `Elaborator` is doing de-duplication of obligations in 3 different locations. 1 off which has a comment.
This PR consolidates the functionality and comment to a single function.
Replace parse_[sth]_expr with parse_expr_[sth] function names
This resolves an inconsistency in naming style for functions on the parser, where:
* functions parsing specific kinds of items are named `parse_item_[sth]` and
* functions parsing specific kinds of *expressions* are named `parse_[sth]_expr`
favoring the style used by functions for items. There are multiple advantages of that style:
* functions of both categories are collected in the same place in the [rustdoc output](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_parse/parser/struct.Parser.html).
* it helps with autocompletion, as you can narrow down your search for a function to those about expressions.
* it mirrors rust's path syntax where less specific things come first, then it gets more specific, i.e. `std::collections::hash_map::Entry`.
The disadvantage is that it doesn't "read like a sentence" any more. But I think the advantages weigh more greatly.
This change was mostly application of this command:
```
sed -i -E 's/(fn |\.)parse_([[:alnum:]_]+)_expr/\1parse_expr_\2/' compiler/rustc_parse/src/parser/*.rs
```
Plus very minor fixes outside of `rustc_parse`, and an invocation of `x fmt`.
Add `ErrorGuaranteed` to `hir::{Expr,Ty}Kind::Err` variants
First step in making the `Err` variants of `ExprKind` and `TyKind` require an `ErrorGuaranteed` during parsing. Making the corresponding AST versions require `ErrorGuaranteed` is a bit harder, whereas it was pretty easy to do this for HIR, so let's do that first.
The only weird thing about this PR is that `ErrorGuaranteed` is moved to `rustc_span`. This is *certainly* not the right place to put it, but `rustc_hir` cannot depend on `rustc_error` because the latter already depends on the former. Should I just pull out some of the error machinery from `rustc_error` into an even more minimal crate that `rustc_hir` can depend on? Advice would be appreciated.
Treat `str` as containing `[u8]` for auto trait purposes
Wanted to gauge ``@rust-lang/lang`` and ``@rust-lang/types`` teams' thoughts on treating `str` as "containing" a `[u8]` slice for auto-trait purposes.
``@dtolnay`` brought this up in https://github.com/rust-lang/rust/issues/13231#issuecomment-1399386472 as a blocker for future `str` type librarification, and I think it's both a valid concern and very easy to fix. I'm interested in actually doing that `str` type librarification (#107939), but this probably should be considered in the mean time regardless of that PR.
r? types for the impl, though this definitely needs an FCP.
Rollup of 8 pull requests
Successful merges:
- #107062 (Do some cleanup of doc/index.md)
- #107890 (Lint against `Iterator::map` receiving a callable that returns `()`)
- #108431 (Add regression test for #107918)
- #108432 (test: drop unused deps)
- #108436 (make "proc macro panicked" translatable)
- #108444 (docs/test: add UI test and docs for `E0476`)
- #108449 (Do not lint ineffective unstable trait impl for unresolved trait)
- #108456 (Complete migrating `ast_passes` to derive diagnostics)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
docs/test: add UI test and docs for `E0476`
Final undocumented error code. Not entirely sure about wording in the docs.
Part of https://github.com/rust-lang/rust/issues/61137.
r? ```@compiler-errors```
cc ```@compiler-errors```
Implement -Zlink-directives=yes/no
`-Zlink-directives=no` will ignored `#[link]` directives while compiling a crate, so nothing is emitted into the crate's metadata. The assumption is that the build system already knows about the crate's native dependencies and can provide them at link time without these directives.
This is another way to address issue # #70093, which is currently addressed by `-Zlink-native-libraries` (implemented in #70095). The latter is implemented at link time, which has the effect of ignoring `#[link]` in *every* crate. This makes it a very large hammer as it requires all native dependencies to be known to the build system to be at all usable, including those in sysroot libraries. I think this means its effectively unused, and definitely under-used.
Being able to control this on a crate-by-crate basis should make it much easier to apply when needed.
I'm not sure if we need both mechanisms, but we can decide that later.
cc `@pcwalton` `@cramertj`
[breaking change] Remove a rustdoc back compat warning
This warning was introduced in https://github.com/rust-lang/rust/pull/62855 for users who use `rustdoc` directly on proc macro crates (instead of using `cargo doc`) without passing `--crate-type proc-macro` (which `cargo doc` passed automatically).