check `mut`-restriction when tuple constructor is used as a value
this fixes a bug where tuple struct constructors could bypass `mut` field restrictions when used as function values instead of being called directly. right now `CheckMutRestriction` only checks struct expressions like `Wrapper(5)`. but referencing `inner::Wrapper` as a value was allowed, which let outsiders construct structs with restricted fields.
Fixesrust-lang/rust#160891
* check mut restriction when tuple ctor is used as a value
* add missing stderr file for mut-restriction ctor value test
* simplify def_kind matching in tuple ctor mut restriction check
Match the DefKind::Ctor directly on the result of tcx.def_kind instead of binding it to a local first. Extend the ctor-value ui test with additional enum variants covering plain and crate-restricted fields.
* test: exercise new ctor variants
* address review: drop shell.nix, add tests
mir: prohibit projection into scalable vec
Fixesrust-lang/rust#160580. Preventing projections into scalable vectors is an oversight from the initial implementation and something we should fix.
I'm surprised it caused a stdarch CI failure as reported by rust-lang/rust#160580, as nothing in rustc or stdarch seems to have changed that would have caused that to start happening as far as I can tell. This likely won't fix that stdarch CI failure if it keeps happening, because if there is a projection coming from somewhere then that needs to be fixed - nevertheless, preventing them as in this patch is the right thing to do.
I've tested this against the stdarch CI locally.
Remove `analysis` arg from `ResultsVisitor` methods
It's not needed: if a visitor needs access to the analysis it can just hold a reference itself. Details in individual commits.
r? @cjgillot
`Collector` is a `ResultsVisitor` that needs access to
`ConstAnalysis::map`. Currently it accesses the map using the `analysis`
args to the visitor methods, and passing a map reference to some
methods, and storing a reference in the shorter-lived `OperandCollector`
struct.
This commit simplifies things by just storing a map reference directly
in `Collector` so it's always available.
Fix FutureDropPoll shim for by-move async closures
Related rust-lang/rust#142559
When the coroutine is coroutine-closures, `build_adrop_for_coroutine_shim` used the the ref of the coroutine body.
This PR uses `coroutine_by_move_body_def_id` to fetch the by-move body.
(matching the existing `DropGlue` behavior in `shim.rs`)
Do not promote extern statics
We already reject thread-local statics during promotion, so extend that check to extern statics as well.
fixesrust-lang/rust#143174
Optimize handling of solver errors
- Check for the empty case in `collect_remaining_errors()`.
- Instead of representing trait errors as `Vec<Error>`, use a special type
This has multiple advantages:
- Performance. The new type is 1/3 the size of `Vec` (being equivalent in layout to `Option<ThinVec>`) and can be kept in a register.
- Type safety. We mark the type `#[must_use]`, and thinks requiring errors take `ThinVec`, which requires unwrapping the type and verifying there is indeed an error. We still provide conversions to slices, `ThinVec`, and iteration, because some code needs this and I saw no benefit in changing it, but we deliberately do not provide `Deref<Target = [E]>` or things like that.
Split `apply_primary_terminator_effect`
It currently does two distinct things, and it's a bit nicer it they are separated. Details in individual commits.
r? @cjgillot
This has multiple advantages:
- Performance. The new type is 1/3 the size of `Vec` (being equivalent in layout to `Option<ThinVec>`) and can be kept in a register.
- Type safety. We mark the type `#[must_use]`, and thinks requiring errors take `ThinVec`, which requires unwrapping the type and verifying there is indeed an error. We still provide conversions to slices, `ThinVec`, and iteration, because some code needs this and I saw no benefit in changing it, but we deliberately do not provide `Deref<Target = [E]>` or things like that.
This method currently does two things: it applies the effect, and also
computes the edges. However:
- Three of the four call sites don't use the edges.
- Most analyses just return `terminator.edges()` unconditionally.
This commit separates the edge computation into a new method,
`get_terminator_edges()`. It defaults to `terminator.edges()`, which
means that most analyses don't need to define it. And now edges are only
obtained when they are needed (in `Forward::apply_effects_in_block`).
It only has one call site; might as well just use `visit_results`.
Also, clarify that the blocks passed to `visit_results` must be
reachable; this is something I didn't realize, probably because the name
`visit_reachable_results` made `visit_results` sound like its blocks
*don't* need to be reachable.
`StorageConflictVisitor::apply_state` currently returns early for any
location within a block that ends with an `Unreachable` terminator.
Instead of checking while visiting, we can instead pre-filter these
blocks in the block iterator given to `visit_results`. This removes the
need for the `body` field and the `'tcx` lifetime.
Next steps for FnDef binder changes (instantiate most FnDef binders)
This change is a part of the ongoing effort to clean up binder/turbofishing behavior in the compiler (https://github.com/rust-lang/rust/issues/156581).
This PR instantiates binders that were previously created via `ty::Binder::dummy()` with meaningfully bound vars.
r? oli-obk
> Call me Turbofishmael.
Some years ago- never mind how long precisely-
having little or no money in my purse,
and nothing particular to interest me in C++,
I thought I would sail about a little and see the rusty part of the world.
remove InterpError::map_err_info
That would let us replace the backtrace attached to this interpreter error, which we don't want to allow. We also don't need it, all uses of `map_err_info` can be covered by a `inspect_err_info` instead if we reorganize the helper methods around debug-printing interpreter errors a bit.
Drop elaboration: Only create a reset block if there are flags to reset.
Follow-up to https://github.com/rust-lang/rust/pull/157491
I'm not totally convinced this is worth the effort. The generated pattern is trivially cleaned-up by SimplifyCfg, so we should not need to bother.
r? @saethlin since you reviewed the earlier PR
miri: ensure validity of references and pointers we dereference and cast
Conceptually, when we evaluate the place expression `*place`, there are two steps that happen:
- perform a (typed) load from `place`, which yields a value of pointer/ref type
- construct a new place from that value
Since this is a typed load, we have to ensure that the value satisfies the validity invariant. We forgot to do that, which led to Miri missing a bunch of UB. This PR fixes that by adding the missing checks.
Triggering this UB is a bit non-trivial: you cannot just store an invalid value into `place` using regular assignment (that would already be caught as part of the assignment). However, you can take a raw pointer to `place` and then use that to mutate the contents of `place` in a way that its validity invariant no longer holds. For example:
```rust
fn main() {
let mut x = &();
// Overwrite `x` with null.
unsafe { (&raw mut x).cast::<usize>().write(0) };
let _val = *x; //~ERROR: null reference
}
```
This program clearly (IMO) should have UB, and has UB in MiniRust, but Miri accepted that program before this PR. The same applies to references that are invalid because they are unaligned (even if we end up only accessing a 1-aligned field, i.e. the rest of the place expression evaluates just fine), and to references that are invalid because they are not dereferenceable (even if we end up projecting to a zero-sized field, i.e., the rest of the place expression evaluates just fine).
Even raw pointers have this problem: a raw pointer can be invalid if its vtable pointer is wrong, and we did not check that.
And finally, this also affects `Box`, and this is where things get tricky. `Box` derefs are not even present any more in the MIR Miri sees; they have been replaced by derefs of the underlying raw pointer. But that means we have no way to know that we should check all those things. So to fix that I adjusted the ElaborateBoxDerefs to emit a new special kind of cast that's almost a transmute but also checks `Box` validity.
Fixes https://github.com/rust-lang/miri/issues/5226
Fixes https://github.com/rust-lang/unsafe-code-guidelines/issues/617
Cc @rust-lang/opsem
Refactor: shrink region ext traits
- Removes `RegionUtilitiesExt`.
- Ports, where trivially simple, methods from the extension traits to `rustc_type_ir`.
- Cleans up imported crates where possible.
It seems `EarlyParamRegion` could possibly move to `rust_type_ir`?
r? @lcnr
Simplify `MaybeRequiresStorage`
It currently contains a `MaybeBorrowedLocals` cursor. The cursor is within a `RefCell` because cursor traversal requires mutation. The cursor is used in the `MaybeRequiresStorage::check_for_move` operation.
Instead of using this cursor within `MaybeRequiresStorage` it's possible to do a pre-traversal of `MaybeBorrowedLocals` to extract the necessary information and then give that (immutably) to `MaybeRequiresStorage`.
This commit makes that change. The extracted information is in the new `KillableLocals` type, which is computed by the `KillableLocalsVisitor` type within `MaybeRequiresStorage::new`. `MaybeRequiresStorage` no longer needs lifetimes. `MoveVisitor` is no longer needed. And the complicated `locals_live_across_suspend_points` gets a little simpler.
r? @cjgillot
It currently contains a `MaybeBorrowedLocals` cursor. The cursor is
within a `RefCell` because cursor traversal requires mutation. The
cursor is used in the `MaybeRequiresStorage::check_for_move` operation.
Instead of using this cursor within `MaybeRequiresStorage` it's possible
to do a pre-traversal of `MaybeBorrowedLocals` to extract the necessary
information and then give that (immutably) to `MaybeRequiresStorage`.
This commit makes that change. The extracted information is in the new
`KillableLocals` type, which is computed by the `KillableLocalsVisitor`
type within `MaybeRequiresStorage::new`. `MaybeRequiresStorage` no
longer needs lifetimes. `MoveVisitor` is no longer needed. And the
complicated `locals_live_across_suspend_points` gets a little simpler.
refactor(mir-transform): Calculate optimization status inside `run_passes_inner`
The `Optimizations` enum represents whether `#[optimize(none)]` has been applied to a function. Currently, `run_passes` takes an `Optimizations` which is confusing (https://github.com/rust-lang/rust/pull/160015#discussion_r3663238318).
Calculate this in `run_passes_inner` instead (which also means `#[optimize(none)]` is applied more consistently.
r? @RalfJung
Replace most `Ty::new_fn_def` calls with `type_of` queries directly
This is so we can reduce the amount of code and changes in rust-lang/rust#159403. It should stand on its own, but really it's meant as an extended part of 159403.
This allows getting the right `ty::FnDef` even cross-crate, as the `type_of` query results are stored in metadata, in contrast to the queries for computing the binder for various declarations. These binders are already cached via `fn_sig`, but using that is somewhat overkill and can cause cycle errors in some cases.
Many "predicate"-to-"clause" renamings
Lots of names weren't changed to account for the introduction of the `Clause` type as a specialized form of `Predicate`, presumably because it was tedious. This commit converts as many of them as I could find. It's mostly very tedious renamings of types, functions, variables, and queries. The more interesting ones are a couple of files (`predicates_of.rs`, `impossible_predicates.rs`) and a MIR pass (`ImpossiblePredicates`).
r? @oli-obk
Don't optimize across storage markers in SimplifyComparisonIntegral
This PR rejects `SimplifyComparisonIntegral` candidates when either `StorageLive` or `StorageDead` for the compared local occurs between the comparison and the terminator.
Since those candidates are rejected, the pass no longer relocates `StorageDead` into switch successors. This conservatively leaves one comparison in `issue_59352` unoptimized, so its MIR snapshots are updated.
Resolvesrust-lang/rust#158231.
r? @hanna-kruppe
Lint against iterator functions that panic when `N` is zero
This PR extends the deny-by-default `unconditional_panic` lint, by linting on iterator functions that panics when `N` (chunks/windows size) is zero[^attr].
Those methods are [documented](https://doc.rust-lang.org/std/primitive.slice.html#panics-11) to panic if `N` is zero.
```
error: this operation will panic at runtime
--> $DIR/const-n-is-zero.rs:11:13
|
LL | let _ = s.array_windows::<0>();
| ^^^^^^^^^^^^^^^^^^^^^^ const parameter `N` is zero
|
= note: `#[deny(unconditional_panic)]` on by default
```
cc @rust-lang/libs-api
[^attr]: this is done by introducing a new internal attribute on the const parameter: `#[rustc_panics_when_zero]`
Lots of names weren't changed to account for the introduction of the
`Clause` type as a specialized form of `Predicate`, presumably because
it was tedious. This commit converts as many of them as I could find.
It's mostly very tedious renamings of types, functions, variables, and
queries. The more interesting ones are a couple of files
(`predicates_of.rs`, `impossible_predicates.rs`) and a MIR pass
(`ImpossiblePredicates`).