Rollup of 4 pull requests
Successful merges:
- #91169 (Change cg_ssa's get_param to borrow the builder mutably)
- #91176 (If the thread does not get the lock in the short term, yield the CPU)
- #91212 (Fix ICE due to out-of-bounds statement index when reporting borrowck error)
- #91225 (Fix invalid scrollbar display on source code page)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Fix ICE due to out-of-bounds statement index when reporting borrowck error
Replace an `[index]` with a `.get` when `statement_index` points to a basic-block terminator (and is therefore out-of-bounds in the statements list).
Fixes#91206
Cc ``@camsteffen``
r? ``@oli-obk``
Change cg_ssa's get_param to borrow the builder mutably
This is a small change to make `get_param` more flexible for codegens that may need to modify things when retrieving function parameters.
This will currently only be used by [rustc_codegen_nvvm](https://github.com/Rust-GPU/Rust-CUDA) (my own project), but may be useful to more codegens in the future.
This is needed because cg_nvvm needs to remap certain types to libnvvm-friendly types, such as `i128` -> `<2 x i64>`. Because cg_ssa does not give mutable access to the builder, i resorted to using a mutex:
```rs
fn get_param(&self, index: usize) -> Self::Value {
let val = llvm::get_param(self.llfn(), index as c_uint);
trace!("Get param `{:?}`", val);
unsafe {
let llfnty = LLVMRustGetFunctionType(self.llfn());
let map = self.remapped_integer_args.borrow();
if let Some((_, key)) = map.get(llfnty) {
if let Some((_, new_ty)) = key.iter().find(|t| t.0 == index) {
trace!("Casting irregular param {:?} to {:?}", val, new_ty);
return transmute_llval(
*self.llbuilder.lock().unwrap(),
&self.cx,
val,
*new_ty,
);
}
}
val
}
}
```
However, i predict this is pretty bad for performance, considering how much builders are called during codegen, so i would greatly appreciate having a more flexible API for this.
Fix stack overflow in `usefulness.rs`
Fix#88747
Applied the suggestion from `@nbdd0121,` not sure if this has any drawbacks. The first call to `ensure_sufficient_stack` is not needed to fix the test case, but I added it to be safe.
Visit `param_env` field in Obligation's `TypeFoldable` impl
This oversight appears to have gone unnoticed for a long time
without causing issues, but it should still be fixed.
Diagnostic tweaks
* On type mismatch caused by assignment, point at the source of the expectation
* Hide redundant errors
* Suggest `while let` when `let` is missing in some cases
* Do not emit unnecessary E0308 after E0070
* Show fewer errors on `while let` missing `let`
* Hide redundant E0308 on `while let` missing `let`
* Point at binding definition when possible on invalid assignment
* do not point at closure twice
* do not suggest `if let` for literals in lhs
* account for parameter types
Do not visit attributes in `ItemLowerer`.
By default, AST visitors visit expressions that appear in key-value attributes.
Those expressions should not be lowered to HIR, as they do not correspond to actually compiled code.
Since an attribute cannot produce meaningful HIR, just skip them altogether.
Fixes https://github.com/rust-lang/rust/issues/81886
Fixes https://github.com/rust-lang/rust/issues/90873
r? `@michaelwoerister`
Print associated types on opaque `impl Trait` types
This PR generalizes #91021, printing associated types for all opaque `impl Trait` types instead of just special-casing for future.
before:
```
error[E0271]: type mismatch resolving `<impl Iterator as Iterator>::Item == u32`
```
after:
```
error[E0271]: type mismatch resolving `<impl Iterator<Item = usize> as Iterator>::Item == u32`
```
---
Questions:
1. I'm kinda lost in binders hell with this one. Is all of the `rebind`ing necessary?
2. Is there a map collection type that will give me a stable iteration order? Doesn't seem like TraitRef is Ord, so I can't just sort later..
3. I removed the logic that suppresses printing generator projection types. It creates outputs like this [gist](https://gist.github.com/compiler-errors/d6f12fb30079feb1ad1d5f1ab39a3a8d). Should I put that back?
4. I also added spaces between traits, `impl A+B` -> `impl A + B`. I quite like this change, but is there a good reason to keep it like that?
r? ````@estebank````
Link with default MACOSX_DEPLOYMENT_TARGET if not otherwise specified.
This PR sets the MACOSX_DEPLOYMENT_TARGET environment variable during the linking stage to our default, if it is not specified. This way it matches the deployment target we pass to llvm. If not set the the linker uses Xcode or Xcode commandline tools default which varies by version.
Fixes#90342, #91082.
Drive-by fixes to make Rust behave more like clang:
* Default to 11.0 deployment target for ARM64 which is the earliest version that had support for it.
* Set the llvm target to `arm64-apple-macosx<deployment target>` instead of `aarch64-apple-macosx<deployment target>`.
Various fixes for const_trait_impl
A few problems I found while making `Iterator` easier to const-implement.
1. More generous `~const Drop` check.
We check for nested fields with caller bounds.
For example, an ADT type with fields of types `A`, `B`, `C`, check if all of them are either:
- Bounded (`A: ~const Drop`, `B: Copy`)
- Known to be able to destruct at compile time (`C = i32`, `struct C(i32)`, `C = some_fn`)
2. Don't treat trait functions marked with `#[default_method_body_is_const]` as stable const fns when checking `const_for` and `const_try` feature gates.
I think anyone can review this, so no r? this time.
Tokenize emoji as if they were valid identifiers
In the lexer, consider emojis to be valid identifiers and reject
them later to avoid knock down parse errors.
Partially address #86102.
Restrict aarch64 outline atomics to glibc for now.
The introduced dependency on `getauxval` causes linking problems with musl, making compiling any binaries for `aarch64-unknown-linux-musl` impossible without workarounds such as using lld or adding liblibc.rlib again to the linker invocation, see #89626.
This is a workaround until libc>0.2.108 is merged.
Optimize live point computation
This refactors the live-point computation to lower per-MIR-instruction costs by operating on a largely per-block level. This doesn't fundamentally change the number of operations necessary, but it greatly improves the practical performance by aggregating bit manipulation into ranges rather than single-bit; this scales much better with larger blocks.
On the benchmark provided in #90445, with 100,000 array elements, walltime for a check build is improved from 143 seconds to 15.
I consider the tiny losses here acceptable given the many small wins on real world benchmarks and large wins on stress tests. The new code scales much better, but on some subset of inputs the slightly higher constant overheads decrease performance somewhat. Overall though, this is expected to be a big win for pathological cases (as illustrated by the test case motivating this work) and largely not material for non-pathological cases. I consider the new code somewhat easier to follow, too.
fix(doctest): detect extern crate items in statement doctests
This partially reverts #91026, because rustdoc needs to detect the extern statements, even when they appear inside implicit `main()`. It does not entirely revert it, so the old bug is still fixed, by duplicating some of the logic from `parse_mod` instead of trying to use it directly.
Fixes#91134
By default, AST visitors visit expressions that appear in key-value attributes.
Those expressions should not be lowered to HIR, as they do not correspond to actually compiled code.
Since an attribute cannot produce meaningful HIR, just skip them altogether.
Rollup of 6 pull requests
Successful merges:
- #90856 (Suggestion to wrap inner types using 'allocator_api' in tuple)
- #91103 (Inhibit clicks on summary's children)
- #91137 (Give people a single link they can click in the contributing guide)
- #91140 (Split inline const to two feature gates and mark expression position inline const complete)
- #91148 (Use `derive_default_enum` in the compiler)
- #91153 (kernel_copy: avoid panic on unexpected OS error)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Split inline const to two feature gates and mark expression position inline const complete
This PR splits inline const in pattern position into its own `#![feature(inline_const_pat)]` feature gate, and make the usage in expression position complete.
I think I have resolved most outstanding issues related to `inline_const` with #89561 and other PRs. The only thing left that I am aware of is #90150 and the lack of lifetime checks when inline const is used in pattern position (FIXME in #89561). Implementation-wise when used in pattern position it has to be lowered during MIR building while in expression position it's evaluated only when monomorphizing (just like normal consts), so it makes some sense to separate it into two feature gates so one can progress without being blocked by another.
``@rustbot`` label: T-compiler F-inline_const
Suggestion to wrap inner types using 'allocator_api' in tuple
This PR provides a suggestion to wrap the inner types in tuple when being along with 'allocator_api'.
Closes https://github.com/rust-lang/rust/issues/83250
```rust
fn main() {
let _vec: Vec<u8, _> = vec![]; //~ ERROR use of unstable library feature 'allocator_api'
}
```
```diff
error[E0658]: use of unstable library feature 'allocator_api'
--> $DIR/suggest-vec-allocator-api.rs:2:23
|
LL | let _vec: Vec<u8, _> = vec![];
- | ^
+ | ----^
+ | |
+ | help: consider wrapping the inner types in tuple: `(u8, _)`
|
= note: see issue #32838 <https://github.com/rust-lang/rust/issues/32838> for more information
= help: add `#![feature(allocator_api)]` to the crate attributes to enable
```
Mark places as initialized when mutably borrowed
Fixes the example in #90752, but does not handle some corner cases involving raw pointers and unsafe. See [this comment](https://github.com/rust-lang/rust/issues/90752#issuecomment-965822895) for more information, or the second test.
Although I talked about both `MaybeUninitializedPlaces` and `MaybeInitializedPlaces` in #90752, this PR only changes the latter. That's because "maybe uninitialized" is the conservative choice, and marking them as definitely initialized (`!maybe_uninitialized`) when a mutable borrow is created could lead to problems if `addr_of_mut` to an uninitialized local is allowed. Additionally, places cannot become uninitialized via a mutable reference, so if a place is definitely initialized, taking a mutable reference to it should not change that.
I think it's correct to ignore interior mutability as nbdd0121 suggests below. Their analysis doesn't work inside of `core::cell`, which *does* have access to `UnsafeCell`'s field, but that won't be an issue unless we explicitly instantiate one with an `enum` within that module.
r? `@wesleywiser`
Avoid generating empty closures for fieldless enum variants
For many enums, this avoids generating lots of tiny stubs that need to be codegen'd and then inlined and removed by LLVM. perf shows this to be a fairly small, but significant, win on rustc bootstrap time -- with minimal impact on runtime performance (which is at times even positive).
Manually outline error on incremental_verify_ich
This reduces codegen for rustc_query_impl by 169k lines of LLVM IR, representing
a 1.2% improvement. This code should be fairly cold, so hopefully this has minimal
performance impact.
This partially reverts #91026, because rustdoc needs to detect the extern statements,
even when they appear inside implicit `main()`. It does not entirely revert it,
so the old bug is still fixed, by duplicating some of the logic from `parse_mod`
instead of trying to use it directly.
Fixes#91134
LLVM has built-in heuristics for adding stack canaries to functions. These
heuristics can be selected with LLVM function attributes. This patch adds a
rustc option `-Z stack-protector={none,basic,strong,all}` which controls the use
of these attributes. This gives rustc the same stack smash protection support as
clang offers through options `-fno-stack-protector`, `-fstack-protector`,
`-fstack-protector-strong`, and `-fstack-protector-all`. The protection this can
offer is demonstrated in test/ui/abi/stack-protector.rs. This fills a gap in the
current list of rustc exploit
mitigations (https://doc.rust-lang.org/rustc/exploit-mitigations.html),
originally discussed in #15179.
Stack smash protection adds runtime overhead and is therefore still off by
default, but now users have the option to trade performance for security as they
see fit. An example use case is adding Rust code in an existing C/C++ code base
compiled with stack smash protection. Without the ability to add stack smash
protection to the Rust code, the code base artifacts could be exploitable in
ways not possible if the code base remained pure C/C++.
Stack smash protection support is present in LLVM for almost all the current
tier 1/tier 2 targets: see
test/assembly/stack-protector/stack-protector-target-support.rs. The one
exception is nvptx64-nvidia-cuda. This patch follows clang's example, and adds a
warning message printed if stack smash protection is used with this target (see
test/ui/stack-protector/warn-stack-protector-unsupported.rs). Support for tier 3
targets has not been checked.
Since the heuristics are applied at the LLVM level, the heuristics are expected
to add stack smash protection to a fraction of functions comparable to C/C++.
Some experiments demonstrating how Rust code is affected by the different
heuristics can be found in
test/assembly/stack-protector/stack-protector-heuristics-effect.rs. There is
potential for better heuristics using Rust-specific safety information. For
example it might be reasonable to skip stack smash protection in functions which
transitively only use safe Rust code, or which uses only a subset of functions
the user declares safe (such as anything under `std.*`). Such alternative
heuristics could be added at a later point.
LLVM also offers a "safestack" sanitizer as an alternative way to guard against
stack smashing (see #26612). This could possibly also be included as a
stack-protection heuristic. An alternative is to add it as a sanitizer (#39699).
This is what clang does: safestack is exposed with option
`-fsanitize=safe-stack`.
The options are only supported by the LLVM backend, but as with other codegen
options it is visible in the main codegen option help menu. The heuristic names
"basic", "strong", and "all" are hopefully sufficiently generic to be usable in
other backends as well.
Reviewed-by: Nikita Popov <nikic@php.net>
Extra commits during review:
- [address-review] make the stack-protector option unstable
- [address-review] reduce detail level of stack-protector option help text
- [address-review] correct grammar in comment
- [address-review] use compiler flag to avoid merging functions in test
- [address-review] specify min LLVM version in fortanix stack-protector test
Only for Fortanix test, since this target specifically requests the
`--x86-experimental-lvi-inline-asm-hardening` flag.
- [address-review] specify required LLVM components in stack-protector tests
- move stack protector option enum closer to other similar option enums
- rustc_interface/tests: sort debug option list in tracking hash test
- add an explicit `none` stack-protector option
Revert "set LLVM requirements for all stack protector support test revisions"
This reverts commit a49b74f92a4e7d701d6f6cf63d207a8aff2e0f68.
Check for duplicate attributes.
This adds some checks for duplicate attributes. In many cases, the duplicates were being ignored without error or warning. This adds several kinds of checks (see `AttributeDuplicates` enum).
The motivation here is to issue unused warnings with similar reasoning for any unused lint, and to error for cases where there are conflicts.
This also adds a check for empty attribute lists in a few attributes where this causes the attribute to be ignored.
Closes#55112.
Rollup of 4 pull requests
Successful merges:
- #91008 (Adds IEEE 754-2019 minimun and maximum functions for f32/f64)
- #91070 (Make `LLVMRustGetOrInsertGlobal` always return a `GlobalVariable`)
- #91097 (Add spaces in opaque `impl Trait` with more than one trait)
- #91098 (Don't suggest certain fixups (`.field`, `.await`, etc) when reporting errors while matching on arrays )
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Don't suggest certain fixups (`.field`, `.await`, etc) when reporting errors while matching on arrays
When we have a type mismatch with a `cause.code` that is an `ObligationCauseCode::Pattern`, skip suggesting fixes like adding `.await` or accessing a struct's `.field` if the pattern's `root_ty` differs from the `expected` ty. This occurs in situations like this:
```rust
struct S(());
fn main() {
let array = [S(())];
match array {
[()] => {}
_ => {}
}
}
```
I think what's happening here is a layer of `[_; N]` is peeled off of both types and we end up seeing the mismatch between just `S` and `()`, but when we suggest a fixup, that applies to the expression with type `root_ty`.
---
Questions:
1. Should this check live here, above all of the suggestions, or should I push this down into every suggestion when we match `ObligationCauseCode`?
2. Any other `ObligationCauseCode`s to check here?
3. Am I overlooking an easier way to get to this same conclusion without pattern matching on `ObligationCauseCode` and comparing `root_ty`?
Fixes#91058
Make `LLVMRustGetOrInsertGlobal` always return a `GlobalVariable`
`Module::getOrInsertGlobal` returns a `Constant*`, which is a super
class of `GlobalVariable`, but if the given type doesn't match an
existing declaration, it returns a bitcast of that global instead.
This causes UB when we pass that to `LLVMGetVisibility` which
unconditionally casts the opaque argument to a `GlobalValue*`.
Instead, we can do our own get-or-insert without worrying whether
existing types match exactly. It's not relevant when we're just trying
to get/set the linkage and visibility, and if types are needed we can
bitcast or error nicely from `rustc_codegen_llvm` instead.
Fixes#91050, fixes#87933, fixes#87813.
Point at source of trait bound obligations in more places
Be more thorough in using `ItemObligation` and `BindingObligation` when
evaluating obligations so that we can point at trait bounds that
introduced unfulfilled obligations. We no longer incorrectly point at
unrelated trait bounds (`substs-ppaux.verbose.stderr`).
In particular, we now point at trait bounds on method calls.
We no longer point at "obvious" obligation sources (we no longer have a
note pointing at `Trait` saying "required by a bound in `Trait`", like
in `associated-types-no-suitable-supertrait*`).
We no longer point at associated items (`ImplObligation`), as they didn't
add any user actionable information, they just added noise.
Address part of #89418.
Suggest `await` in more situations where infer types are involved
Currently we use `TyS::same_type` in diagnostics that suggest adding `.await` to opaque future types.
This change makes the suggestion slightly more general, when we're comparing types like `Result<T, E>` and `Result<_, _>` which happens sometimes in places like `match` patterns or `let` statements with partially-elaborated types.
----
Question:
1. Is this change worthwhile? Totally fine if it doesn't make sense adding.
2. Should `same_type_modulo_infer` live in `rustc_infer::infer::error_reporting` or alongside the other method in `rustc_middle::ty::util`?
3. Should we generalize this change? I wanted to change all usages, but I don't want erroneous suggestions when adding `.field_name`...
Be more thorough in using `ItemObligation` and `BindingObligation` when
evaluating obligations so that we can point at trait bounds that
introduced unfulfilled obligations. We no longer incorrectly point at
unrelated trait bounds (`substs-ppaux.verbose.stderr`).
In particular, we now point at trait bounds on method calls.
We no longer point at "obvious" obligation sources (we no longer have a
note pointing at `Trait` saying "required by a bound in `Trait`", like
in `associated-types-no-suitable-supertrait*`).
Address part of #89418.
Elaborate `Future::Output` when printing opaque `impl Future` type
I would love to see the `Output =` type when printing type errors involving opaque `impl Future`.
[Test code](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=a800b481edd31575fbcaf5771a9c3678)
Before (cut relevant part of output):
```
note: while checking the return type of the `async fn`
--> /home/michael/test.rs:5:19
|
5 | async fn bar() -> usize {
| ^^^^^ checked the `Output` of this `async fn`, found opaque type
= note: expected type `usize`
found opaque type `impl Future`
```
After:
```
note: while checking the return type of the `async fn`
--> /home/michael/test.rs:5:19
|
5 | async fn bar() -> usize {
| ^^^^^ checked the `Output` of this `async fn`, found opaque type
= note: expected type `usize`
found opaque type `impl Future<Output = usize>`
```
Note the "found opaque type `impl Future<Output = usize>`" in the new output.
----
Questions:
1. We skip printing the output type when it's a projection, since I have been seeing some types like `impl Future<Output = <[static generator@/home/michael/test.rs:2:11: 2:21] as Generator<ResumeTy>>::Return>` which are not particularly helpful and leak implementation detail.
* Am I able to normalize this type within `rustc_middle::ty::print::pretty`? Alternatively, can we normalize it when creating the diagnostic? Otherwise, I'm fine with skipping it and falling back to the old output.
* Should I suppress any other types? I didn't encounter anything other than this generator projection type.
2. Not sure what the formatting of this should be. Do I include spaces in `Output = `?
Fix `non-constant value` ICE (#90878)
This also fixes the same suggestion, which was kind of broken, because it just searched for the last occurence of `const` to replace with a `let`. This works great in some cases, but when there is no const and a leading space to the file, it doesn't work and panic with overflow because it thought that it had found a const.
I also changed the suggestion to only trigger if the `const` and the non-constant value are on the same line, because if they aren't, the suggestion is very likely to be wrong.
Also don't trigger the suggestion if the found `const` is on line 0, because that triggers the ICE.
Asking Esteban to review since he was the last one to change the relevant code.
r? ``@estebank``
Fixes#90878
Clarify error messages caused by re-exporting `pub(crate)` visibility to outside
This PR clarifies error messages and suggestions caused by re-exporting pub(crate) visibility outside the crate.
Here is a small example ([Rust Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=e2cd0bd4422d4f20e6522dcbad167d3b)):
```rust
mod m {
pub(crate) enum E {}
}
pub use m::E;
fn main() {}
```
This code is compiled to:
```
error[E0365]: `E` is private, and cannot be re-exported
--> prog.rs:4:9
|
4 | pub use m::E;
| ^^^^ re-export of private `E`
|
= note: consider declaring type or module `E` with `pub`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0365`.
```
However, enum `E` is actually public to the crate, not private totally—nevertheless, rustc treats `pub(crate)` and private visibility as the same on the error messages. They are not clear and should be segmented distinctly.
By applying changes in this PR, the error message below will be the following message that would be clearer:
```
error[E0365]: `E` is only public to inside of the crate, and cannot be re-exported outside
--> prog.rs:4:9
|
4 | pub use m::E;
| ^^^^ re-export of crate public `E`
|
= note: consider declaring type or module `E` with `pub`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0365`.
```
Implement `clone_from` for `State`
Data flow engine uses `clone_from` for domain values. Providing an
implementation of `clone_from` will avoid some intermediate memory
allocations.
Extracted from #90413.
r? `@oli-obk`
`Module::getOrInsertGlobal` returns a `Constant*`, which is a super
class of `GlobalVariable`, but if the given type doesn't match an
existing declaration, it returns a bitcast of that global instead.
This causes UB when we pass that to `LLVMGetVisibility` which
unconditionally casts the opaque argument to a `GlobalValue*`.
Instead, we can do our own get-or-insert without worrying whether
existing types match exactly. It's not relevant when we're just trying
to get/set the linkage and visibility, and if types are needed we can
bitcast or error nicely from `rustc_codegen_llvm` instead.
fix CTFE/Miri simd_insert/extract on array-style repr(simd) types
The changed test would previously fail since `place_index` would just return the only field of `f32x4`, i.e., the array -- rather than *indexing into* the array which is what we have to do.
The new helper methods will also be needed for https://github.com/rust-lang/miri/issues/1912.
r? ``````@oli-obk``````
Rollup of 8 pull requests
Successful merges:
- #89258 (Make char conversion functions unstably const)
- #90578 (add const generics test)
- #90633 (Refactor single variant `Candidate` enum into a struct)
- #90800 (bootstap: create .cargo/config only if not present)
- #90942 (windows: Return the "Not Found" error when a path is empty)
- #90947 (Move some tests to more reasonable directories - 9.5)
- #90961 (Suggest removal of arguments for unit variant, not replacement)
- #90990 (Arenas cleanup)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Refactor single variant `Candidate` enum into a struct
`Candidate` enum has only a single `Ref` variant. Refactor it into a
struct and reduce overall indentation of the code by two levels.
No functional changes.
Try all stable method candidates first before trying unstable ones
Currently we try methods in this order in each step:
* Stable by value
* Unstable by value
* Stable autoref
* Unstable autoref
* ...
This PR changes it to first try pick methods without any unstable candidates, and if none is found, try again to pick unstable ones.
Fix#90320
CC #88971, hopefully would allow us to rename the "unstable_*" methods for integer impls back.
`@rustbot` label T-compiler T-libs-api
Rollup of 8 pull requests
Successful merges:
- #90386 (Add `-Zassert-incr-state` to assert state of incremental cache)
- #90438 (Clean up mess for --show-coverage documentation)
- #90480 (Mention `Vec::remove` in `Vec::swap_remove`'s docs)
- #90607 (Make slice->str conversion and related functions `const`)
- #90750 (rustdoc: Replace where-bounded Clean impl with simple function)
- #90895 (require full validity when determining the discriminant of a value)
- #90989 (Avoid suggesting literal formatting that turns into member access)
- #91002 (rustc: Remove `#[rustc_synthetic]`)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
require full validity when determining the discriminant of a value
This resolves (for now) the semantic question that came up in https://github.com/rust-lang/rust/pull/89764: arguably, reading the discriminant of a value is 'using' that value, so we are in our right to demand full validity. Reading a discriminant is somewhat special in that it works for values of *arbitrary* type; all the other primitive MIR operations work on specific types (e.g. `bool` or an integer) and basically implicitly require validity as part of just "doing their job".
The alternative would be to just require that the discriminant itself is valid, if any -- but then what do we do for types that do not have a discriminant, which kind of validity do we check? [This code](81117ff930/compiler/rustc_codegen_ssa/src/mir/place.rs (L206-L215)) means we have to at least reject uninhabited types, but I would rather not special case that.
I don't think this can be tested in CTFE (since validity is not enforced there), I will add a compile-fail test to Miri:
```rust
#[allow(enum_intrinsics_non_enums)]
fn main() {
let i = 2u8;
std::mem::discriminant(unsafe { &*(&i as *const _ as *const bool) }); // UB
}
```
(I tried running the check even on the CTFE machines, but then it runs during ConstProp and that causes all sorts of problems. We could run it for ConstEval but not ConstProp, but that simply does not seem worth the effort currently.)
r? ``@oli-obk``
std: Get the standard library compiling for wasm64
This commit goes through and updates various `#[cfg]` as appropriate to
get the wasm64-unknown-unknown target behaving similarly to the
wasm32-unknown-unknown target. Most of this is just updating various
conditions for `target_arch = "wasm32"` to also account for `target_arch
= "wasm64"` where appropriate. This commit also lists `wasm64` as an
allow-listed architecture to not have the `restricted_std` feature
enabled, enabling experimentation with `-Z build-std` externally.
The main goal of this commit is to enable playing around with
`wasm64-unknown-unknown` externally via `-Z build-std` in a way that's
similar to the `wasm32-unknown-unknown` target. These targets are
effectively the same and only differ in their pointer size, but wasm64
is much newer and has much less ecosystem/library support so it'll still
take time to get wasm64 fully-fledged.
This function parameter attribute was introduced in https://github.com/rust-lang/rust/pull/44866 as an intermediate step in implementing `impl Trait`, it's not necessary or used anywhere by itself.
Improve ManuallyDrop suggestion
closes https://github.com/rust-lang/rust/issues/90585
* Fixes the recommended change to use ManuallyDrop as per the issue
* Changes the note to a help
* improves the span so it only points at the type.
Remove workaround for the forward progress handling in LLVM
this workaround was only needed for LLVM < 12 and the minimum LLVM version was updated to 12 in #90175
Fix span for non-satisfied trivial trait bounds
The spans for "trait bound not satisfied" errors in trivial trait bounds referenced the entire item (fn, impl, struct) before.
Now they only reference the obligation itself (`String: Copy`)
Address #90869
Print escaped string if char literal has multiple characters, but only one printable character
Fixes#90857
I'm not sure about the error message here, it could get rather long and *maybe* using the names of characters would be better? That wouldn't help the length any, though.
Improve diagnostics when a static lifetime is expected
Makes progress towards https://github.com/rust-lang/rust/issues/90600
The diagnostics here were previously entirely removed due to giving a misleading suggestion but if we instead provide an informative label in that same location it should better help the user understand the situation.
I included the example from the issue as it demonstrates an area where the diagnostics are still lacking.
Happy to remove that if its just adding noise atm.
warn on must_use use on async fn's
As referenced in #78149
This only works on `async` fn's for now, I can also look into if I can get `Box<dyn Future>` and `impl Future` working at this level (hir)
Alphabetize language features
This should significantly reduce the frequency of merge conflicts.
r? ````@joshtriplett````
````@rustbot```` label: +A-contributor-roadblock +S-waiting-on-review
Fix await suggestion on non-future type
Remove a match block that would suggest to add `.await` in the case where the expected type's `Future::Output` equals the found type. We only want to suggest `.await`ing in the opposite case (the found type's `Future::Output` equals the expected type).
The code sample is here: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=6ba6b83d4dddda263553b79dca9f6bcb
Before:
```
➜ ~ rustc --edition=2021 --crate-type=lib test.rs
error[E0308]: `match` arms have incompatible types
--> test.rs:4:14
|
2 | let x = match 1 {
| _____________-
3 | | 1 => other(),
| | ------- this is found to be of type `impl Future`
4 | | 2 => other().await,
| | ^^^^^^^^^^^^^ expected opaque type, found enum `Result`
5 | | };
| |_____- `match` arms have incompatible types
|
= note: expected type `impl Future`
found enum `Result<(), ()>`
help: consider `await`ing on the `Future`
|
4 | 2 => other().await.await,
| ++++++
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
```
After:
```
➜ ~ rustc +stage1 --edition=2021 --crate-type=lib test.rs
error[E0308]: `match` arms have incompatible types
--> test.rs:4:14
|
2 | let x = match 1 {
| _____________-
3 | | 1 => other(),
| | ------- this is found to be of type `impl Future`
4 | | 2 => other().await,
| | ^^^^^^^^^^^^^ expected opaque type, found enum `Result`
5 | | };
| |_____- `match` arms have incompatible types
|
= note: expected type `impl Future`
found enum `Result<(), ()>`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
```
Fixes#90931
Because it's always `'tcx`. In fact, some of them use a mixture of
passed-in `$tcx` and hard-coded `'tcx`, so no other lifetime would even
work.
This makes the code easier to read.
Remove `DropArena`.
Most arena-allocate types that impl `Drop` get their own `TypedArena`, but a
few infrequently used ones share a `DropArena`. This sharing adds complexity
but doesn't help performance or memory usage. Perhaps it was more effective in
the past prior to some other improvements to arenas.
This commit removes `DropArena` and the sharing of arenas via the `few`
attribute of the `arena_types` macro. This change removes over 100 lines of
code and nine uses of `unsafe` (one of which affects the parallel compiler) and
makes the remaining code easier to read.
Rollup of 8 pull requests
Successful merges:
- #86455 (check where-clause for explicit `Sized` before suggesting `?Sized`)
- #90801 (Normalize both arguments of `equate_normalized_input_or_output`)
- #90803 (Suggest `&str.chars()` on attempt to `&str.iter()`)
- #90819 (Fixes incorrect handling of TraitRefs when emitting suggestions.)
- #90910 (fix getting the discriminant of a zero-variant enum)
- #90925 (rustc_mir_build: reorder bindings)
- #90928 (Use a different server for checking clock drift)
- #90936 (Add a regression test for #80772)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
The default diagnostic handler considers all remarks to be disabled by
default unless configured otherwise through LLVM internal flags:
`-pass-remarks`, `-pass-remarks-missed`, and `-pass-remarks-analysis`.
This behaviour makes `-Cremark` ineffective on its own.
Fix this by configuring a custom diagnostic handler that enables
optimization remarks based on the value of `-Cremark` option. With
`-Cremark=all` enabling all remarks.
rustc_mir_build: reorder bindings
No functional changes intended.
I'm playing around with building compiler components using nightly rust
(2021-11-02) in a non-standard way. I encountered the following error while
trying to build rustc_mir_build:
```
error[E0597]: `wildcard` does not live long enough
--> rust/src/nightly/compiler/rustc_mir_build/src/build/matches/mod.rs:1767:82
|
1767 | let mut otherwise_candidate = Candidate::new(expr_place_builder.clone(), &wildcard, false);
| ^^^^^^^^^ borrowed value does not live long enough
...
1799 | }
| -
| |
| `wildcard` dropped here while still borrowed
| borrow might be used here, when `guard_candidate` is dropped and runs the destructor for type `Candidate<'_, '_>`
|
= note: values in a scope are dropped in the opposite order they are defined
```
I believe this flags an issue that may become an error in the future.
Swapping the order of `wildcard` and `guard_candidate` resolves it.
Fixes incorrect handling of TraitRefs when emitting suggestions.
Closes#90804 , although there were more issues here that were hidden by the thing that caused this ICE.
Underlying problem was that substitutions were being thrown out, which not only leads to an ICE but also incorrect diagnostics. On top of that, in some cases the self types from the root obligations were being mixed in with those from derived obligations.
This makes a couple diagnostics arguable worse ("`B<C>` does not implement `Copy`" instead of "`C` does not implement `Copy`") but the worse diagnostics are at least still correct and that downside is in my opinion clearly outweighed by the benefits of fixing the ICE and unambiguously wrong diagnostics.
check where-clause for explicit `Sized` before suggesting `?Sized`
Fixes#85945.
Based on #86454.
``@rustbot`` label +A-diagnostics +A-traits +A-typesystem +D-papercut +T-compiler
Address performance regression introduced by #90218
As part of the changes in #90218 , the `adt_drop_tys` and friends code stopped recursing through the query system, meaning that intermediate computations did not get cached. This change adds the recursions back in without re-introducing any of the old issues.
On local benchmarks this fixes the 5% regressions in #90504 ; the wg-grammar regressions didn't seem to move too much. I may take some time later to look into those.
Not sure who to request for review here, so will leave it up to whoever gets it.
Android is not GNU
For a long time, the Android targets had `target_env=""`, but this changed to `"gnu"` in Rust 1.49.0. I tracked this down to #77729 which started setting `"gnu"` in the `linux_base` target options, and this was inherited by `android_base`. Then #78929 split the env into `linux_gnu_base`, but `android_base` was also changed to follow that. Android was not specifically mentioned in either pull request, so I believe this was an accident. Moving it back to `linux_base` will use an empty `env` again.
r? ````@Mark-Simulacrum````
cc ````@petrochenkov````
Assoc item cleanup Part 2
- Remove `AssocItem` from `RegionVariableOrigin::AutoRef`
- Use the `associated_item_def_ids` query instead of the `associated_items` query when possible
The change to `ObligationCauseCode` from #90639 is omitted because it caused a perf regression.
r? `@cjgillot`
This also fixes the same suggestion, which was kind of broken, because it just searched for the last occurence of `const` to replace with a `let`. This works great in some cases, but when there is no const and a leading space to the file, it doesn't work and panic with overflow because it thought that it had found a const.
I also changed the suggestion to only trigger if the `const` and the non-constant value are on the same line, because if they aren't, the suggestion is very likely to be wrong.
Also don't trigger the suggestion if the found `const` is on line 0, because that triggers the ICE.
stabilize format args capture
Works as expected, and there are widespread reports of success with it, as well as interest in it.
RFC: rust-lang/rfcs#2795
Tracking issue: https://github.com/rust-lang/rust/issues/67984
Addressing items from the tracking issue:
- We don't support capturing arguments from a non-literal format string like `format_args!(concat!(...))`. We could add that in a future enhancement, or we can decide that it isn't supported (as suggested in https://github.com/rust-lang/rust/issues/67984#issuecomment-801394736 ).
- I've updated the documentation.
- `panic!` now supports capture as well.
- There are potentially opportunities to further improve diagnostics for invalid usage, such as if it looks like the user tried to use an expression rather than a variable. However, such cases are all already caught and provide reasonable syntax errors now, and we can always provided even friendlier diagnostics in the future.
No functional changes intended.
I'm playing around with building compiler components using nightly rust
(2021-11-02) in a non-standard way. I encountered the following error while
trying to build rustc_mir_build:
```
error[E0597]: `wildcard` does not live long enough
--> rust/src/nightly/compiler/rustc_mir_build/src/build/matches/mod.rs:1767:82
|
1767 | let mut otherwise_candidate = Candidate::new(expr_place_builder.clone(), &wildcard, false);
| ^^^^^^^^^ borrowed value does not live long enough
...
1799 | }
| -
| |
| `wildcard` dropped here while still borrowed
| borrow might be used here, when `guard_candidate` is dropped and runs the destructor for type `Candidate<'_, '_>`
|
= note: values in a scope are dropped in the opposite order they are defined
```
I believe this flags an issue that may become an error in the future.
Swapping the order of `wildcard` and `guard_candidate` resolves it.
Fix ld64 flags
- The `-exported_symbols_list` argument appears to be malformed for `ld64` (if you are not going through `clang`).
- The `-dynamiclib` argument isn't support for `ld64`. It should be guarded behind a compiler flag.
These problems are fixed by these changes. I have also refactored the way linker arguments are generated to be ld/compiler agnostic and therefore less error prone.
These changes are necessary to support cross-compilation to darwin targets.
Leave -Z strip available temporarily as an alias, to avoid breaking
cargo until cargo transitions to using -C strip. (If the user passes
both, the -C version wins.)
Tweak the `options!` macro to allow for -Z and -C options with the same
name without generating conflicting internal parsing functions.
Split out of the commit stabilizing -Z strip as -C strip.
Most arena-allocate types that impl `Drop` get their own `TypedArena`, but a
few infrequently used ones share a `DropArena`. This sharing adds complexity
but doesn't help performance or memory usage. Perhaps it was more effective in
the past prior to some other improvements to arenas.
This commit removes `DropArena` and the sharing of arenas via the `few`
attribute of the `arena_types` macro. This change removes over 100 lines of
code and nine uses of `unsafe` (one of which affects the parallel compiler) and
makes the remaining code easier to read.
Implement diagnostic for String conversion
This is my first real contribution to rustc, any feedback is highly appreciated.
This should fix https://github.com/rust-lang/rust/issues/89856
Thanks to `@estebank` for guiding me.
check if `String` or `&String` or `&str`
Update compiler/rustc_typeck/src/check/method/suggest.rs
Co-authored-by: Esteban Kuber <estebank@users.noreply.github.com>
remove some trailing whitespace
selection deduplicates obligations through a hashset at some point, computing the hashes for ObligationCauseCode
appears to dominate the hashing cost. bodyid + span + discriminant hash hopefully will sufficiently unique
unique enough.
Generate documentation in rustc `rustc_index::newtype_index` macro
The macro now documents all generated items. Documentation notes possible panics and unsafety.
The spans for "trait bound not satisfied" errors in trivial trait bounds referenced the entire item (fn, impl, struct) before.
Now they only reference the obligation itself (`String: Copy`)
Address #90869
This commit refactors linker argument generation to leverage a helper
function that abstracts away details governing how these arguments are
transformed and provided to the linker.
This fixes the misuse of the `-exported_symbols_list` when an ld-like
linker is used rather than a compiler. A compiler would expect
`-Wl,-exported_symbols_list,path` but ld would expect
`-exported_symbols_list` and `path` as two seperate arguments. Prior
to this change, an ld-like linker was given
`-exported_symbols_list,path`.
Linker arguments must transformed when Rust is interacting with the
linker through a compiler. This commit introduces a helper function
that abstracts away details of this transformation.
Fix trait object error code
closes#90768
I `grep`:d and changed the occurrences that seemed relevant. Please let me know what you think and if anything is missing!
When suggesting references, substitutions were being forgotten and some types were misused. This led to at
least one ICE and other incorrectly emitted diagnostics. This has been fixed; in some cases this leads to
diagnostics changing, and tests have been adjusted.
Stabilize `const_raw_ptr_deref` for `*const T`
This stabilizes dereferencing immutable raw pointers in const contexts.
It does not stabilize `*mut T` dereferencing. This is behind the
same feature gate as mutable references.
closes https://github.com/rust-lang/rust/issues/51911
proc_macro: Add an expand_expr method to TokenStream
This feature is aimed at giving proc macros access to powers similar to those used by builtin macros such as `format_args!` or `concat!`. These macros are able to accept macros in place of string literal parameters, such as the format string, as they perform recursive macro expansion while being expanded.
This can be especially useful in many cases thanks to helper macros like `concat!`, `stringify!` and `include_str!` which are often used to construct string literals at compile-time in user code.
For now, this method only allows expanding macros which produce literals, although more expressions will be supported before the method is stabilized.
In earlier versions of this PR, this method exclusively returned `Literal`, and spans on returned literals were stripped of expansion context before being returned to be as conservative as possible about permission leakage. The method's naming has been generalized to eventually support arbitrary expressions, and the context stripping has been removed (https://github.com/rust-lang/rust/pull/87264#discussion_r674863279), which should allow for more general APIs like "format_args_implicits" (https://github.com/rust-lang/rust/issues/67984) to be supported as well.
## API Surface
```rust
impl TokenStream {
pub fn expand_expr(&self) -> Result<TokenStream, ExpandError>;
}
#[non_exhaustive]
pub struct ExpandError;
impl Debug for ExpandError { ... }
impl Display for ExpandError { ... }
impl Error for ExpandError {}
impl !Send for ExpandError {}
impl !Sync for ExpandError {}
```
This feature is aimed at giving proc macros access to powers similar to
those used by builtin macros such as `format_args!` or `concat!`. These
macros are able to accept macros in place of string literal parameters,
such as the format string, as they perform recursive macro expansion
while being expanded.
This can be especially useful in many cases thanks to helper macros like
`concat!`, `stringify!` and `include_str!` which are often used to
construct string literals at compile-time in user code.
For now, this method only allows expanding macros which produce
literals, although more expresisons will be supported before the method
is stabilized.
Shorten Span of unused macro lints
The span has been reduced to the actual ident of the macro, instead of linting the
*whole* macro.
Closes#90745
r? ``@estebank``
Optimize pattern matching
These commits speed up the `match-stress-enum` benchmark, which is very artificial, but the changes are simple enough that it's probably worth doing.
r? `@Nadrieril`
Added the --temps-dir option
Fixes#10971.
The new `--temps-dir` option puts intermediate files in a user-specified directory. This provides a fix for the issue where parallel invocations of rustc would overwrite each other's intermediate files.
No files are kept in the intermediate directory unless `-C save-temps=yes`.
If additional files are specifically requested using `--emit asm,llvm-bc,llvm-ir,obj,metadata,link,dep-info,mir`, these will be put in the output directory rather than the intermediate directory.
This is a backward-compatible change, i.e. if `--temps-dir` is not specified, the behavior is the same as before.
Use computed visibility in rustdoc
This PR changes `librustdoc` to use computed visibility instead of syntactic visibility. It was initially part of #88019, but was separated due to concerns that it might cause a regression somewhere we couldn't predict.
r? `@jyn514`
cc `@cjgillot` `@petrochenkov`
* Add wasm64 variants for inline assembly along the same lines as wasm32
* Update a few directives in libtest to check for `target_family`
instead of `target_arch`
* Update some rustc codegen and typechecks specialized for wasm32 to
also work for wasm64.
This commit works around a crash in LLVM when the
`-generate-arange-section` argument is passed to LLVM. An LLVM bug is
opened for this and the code in question is also set to continue passing
this flag with LLVM 14, assuming that this is fixed by the time LLVM 14
comes out. Otherwise this should work around debuginfo crashes on LLVM
13.
This commit goes through and updates various `#[cfg]` as appropriate to
get the wasm64-unknown-unknown target behaving similarly to the
wasm32-unknown-unknown target. Most of this is just updating various
conditions for `target_arch = "wasm32"` to also account for `target_arch
= "wasm64"` where appropriate. This commit also lists `wasm64` as an
allow-listed architecture to not have the `restricted_std` feature
enabled, enabling experimentation with `-Z build-std` externally.
The main goal of this commit is to enable playing around with
`wasm64-unknown-unknown` externally via `-Z build-std` in a way that's
similar to the `wasm32-unknown-unknown` target. These targets are
effectively the same and only differ in their pointer size, but wasm64
is much newer and has much less ecosystem/library support so it'll still
take time to get wasm64 fully-fledged.