coverage: Avoid creating malformed macro name spans
This is a workaround for #117788. It detects a particular scenario where we would create malformed coverage spans that might cause `llvm-cov` to immediately exit with an error, preventing the user from processing coverage reports.
The patch has been kept as simple as possible so that it's trivial to backport to beta (or stable) if desired.
---
The `maybe_push_macro_name_span` method is trying to detect macro invocations, so that it can split a span into two parts just after the `!` of the invocation.
Under some circumstances (probably involving nested macros), it gets confused and produces a span that is larger than the original span, and possibly extends outside its enclosing function and even into an adjacent file.
In extreme cases, that can result in malformed coverage mappings that cause `llvm-cov` to fail. For now, we at least want to detect these egregious cases and avoid them, so that coverage reports can still be produced.
The included measurements have varied over the years. At one point there
were quite a few more, but #49558 deleted a lot that were no longer
used. Today there's just four, and it's a motley collection that doesn't
seem particularly valuable.
I think it has been well and truly subsumed by self-profiling, which
collects way more data.
This method is trying to detect macro invocations, so that it can split a span
into two parts just after the `!` of the invocation.
Under some circumstances (probably involving nested macros), it gets confused
and produces a span that is larger than the original span, and possibly extends
outside its enclosing function and even into an adjacent file.
In extreme cases, that can result in malformed coverage mappings that cause
`llvm-cov` to fail. For now, we at least want to detect these egregious cases
and avoid them, so that coverage reports can still be produced.
Deny more `~const` trait bounds
thereby fixing a family of ICEs (delayed bugs) for `feature(const_trait_impl, effects)` code.
As discussed
r? `@fee1-dead`
Allow adding values to the `!llvm.module.flags` metadata for a generated
module. The syntax is
`-Z llvm_module_flag=<name>:<type>:<value>:<behavior>`
Currently only u32 values are supported but the type is required to be
specified for forward compatibility. The `behavior` element must match
one of the named LLVM metadata behaviors.viors.
This flag is expected to be perma-unstable.
Add `std:#️⃣:{DefaultHasher, RandomState}` exports (needs FCP)
This implements rust-lang/libs-team#267 to move the libstd hasher types to `std::hash` where they belong, instead of `std::collections::hash_map`.
<details><summary>The below no longer applies, but is kept for clarity.</summary>
This is a small refactor for #27242, which moves the definitions of `RandomState` and `DefaultHasher` into `std::hash`, but in a way that won't be noticed in the public API.
I've opened rust-lang/libs-team#267 as a formal ACP to move these directly into the root of `std::hash`, but for now, they're at least separated out from the collections code in a way that will make moving that around easier.
I decided to simply copy the rustdoc for `std::hash` from `core::hash` since I think it would be ideal for the two to diverge longer-term, especially if the ACP is accepted. However, I would be willing to factor them out into a common markdown document if that's preferred.
</details>
Partial removal of storage statements for a local is incorrect, so a
decision to optimize cannot be make independently for each statement.
Avoid the issue by performing the transformation completely or not at
all.
On method chain expression failure, look for missing method in earlier segments of the chain
This PR tries to fix the issue: https://github.com/rust-lang/rust/issues/115222
As suggested by `@estebank` , I did the following:
1. Add new test `tests/ui/structs/method-chain-expression-failure.rs`
2. In `compiler/rusct_hir_tycheck/src/method/suggest.rs`
walking up the method chain and calling `probe_for_name` with the method name. But the call fails to return `Ok`.
It's not clear to me (klinvill) that UserTypeProjections are produced
anymore with the removal of type ascriptions as per
https://github.com/rust-lang/rfcs/pull/3307. Furthermore, it's not clear
to me which variants of ProjectionElem could appear in such projections.
For these reasons, I'm reverting projections in UserTypeProjections to
simple strings until I can get more clarity on UserTypeProjections.
This commit includes richer projections for both Places and
UserTypeProjections. However, the tests only touch on Places. There are
also outstanding TODOs regarding how projections should be resolved to
produce Place types, and regarding if UserTypeProjections should just
contain ProjectionElem<(),()> objects as in MIR.
It was added way back in #28585 under the name `-Zkeep-mtwt-tables`. The
justification was:
> This is so that the resolution results can be used after analysis,
> potentially for tool support.
There are no uses of significance in the code base, and various Google
searches for both option names (and variants) found nothing of interest.
@petrochenkov says removing this part (and it's only part) of the
hygiene data is dubious. It doesn't seem that big, so let's just keep it
around.
It currently has the syntax
`current_rustc_version!(env!("CFG_RELEASE"))` where the
`env!("CFG_RELEASE")` part looks like a normal expression but it is
actually parsed and processed by the `current_rustc_version` macro.
The documented rationale for this is that you'll find it if you grep for
`env!("CFG_RELEASE")`. But I think that's of very little use -- I would
personally grep for just "CFG_RELEASE" -- and it complicates the macro,
requiring the use of `syn`.
This commit simplifies the macro.
Emit #[inline] on derive(Debug)
While working on https://github.com/rust-lang/rust/pull/116583 I noticed that the `cross_crate_inlinable` query identifies a lot of derived `Debug` impls as a MIR body that's little more than a call, which suggests they may be a good candidate for `#[inline]`. So here I've implemented that change specifically.
It seems to provide a nice improvement to build times.
generator layout: ignore fake borrows
fixes#117059
We emit fake shallow borrows in case the scrutinee place uses a `Deref` and there is a match guard. This is necessary to prevent the match guard from mutating the scrutinee: fab1054e17/compiler/rustc_mir_build/src/build/matches/mod.rs (L1250-L1265)
These fake borrows end up impacting the generator witness computation in `mir_generator_witnesses`, which causes the issue in #117059. This PR now completely ignores fake borrows during this computation. This is sound as thse are always removed after analysis and the actual computation of the generator layout happens afterwards.
Only the second commit impacts behavior, and could be backported by itself.
r? types
Remove `-Z strip`.
It was stabilized as `-C strip` in November 2021. The unstable option was kept around as a temporary measure to ease the transition. Two years is more than enough!
r? `@tmandry`
Update ICU4X
This updates all ICU4X crates and regenerates rustc_baked_icu_data.
Since the new unicode license under which they are licensed does not have an SPDX identifier yet, we define some exceptions. The license has to be reviewed to make sure it is still fine to use here, but I assume that is the case.
I also added an exception for rustc_icu_data to the unexplained ignore doctest tidy lint. This is a bit hacky but the whole style.rs in tidy is a mess so I didn't want to touch it more than this small hack.
part of #112865
r? `@davidtwco` `@wesleywiser` `@Manishearth`
Extend builtin/auto trait args with error when they have >1 argument
Reuse `extend_with_error` to add error args to any auto trait (or built-in trait like `Copy` that is defined incorrectly) that has additional non-`Self` args.
Fixes#117628
Make `FatalErrorMarker` lower priority than other panics
This makes `FatalErrorMarker` lower priority than other panics in a parallel sections. If any other panics occur, they will be unwound instead of `FatalErrorMarker`. This ensures `rustc` will exit with the correct error code on ICEs.
This fixes https://github.com/rust-lang/rust/issues/116659.
It was stabilized as `-C strip` in November 2021. The unstable option
was kept around as a temporary measure to ease the transition. Two years
is more than enough!
patterns: reject raw pointers that are not just integers
Matching against `0 as *const i32` is fine, matching against `&42 as *const i32` is not.
This extends the existing check against function pointers and wide pointers: we now uniformly reject all these pointer types during valtree construction, and then later lint because of that. See [here](https://github.com/rust-lang/rust/pull/116930#issuecomment-1784654073) for some more explanation and context.
Also fixes https://github.com/rust-lang/rust/issues/116929.
Cc `@oli-obk` `@lcnr`
Rollup of 5 pull requests
Successful merges:
- #117263 (handle the case when the change-id isn't found)
- #117282 (Recover from incorrectly ordered/duplicated function keywords)
- #117679 (tests/rustdoc-json: Avoid needless use of `no_core` and `lang_items`)
- #117702 (target: move base and target specifications)
- #117713 (Add test for reexported hidden item with `--document-hidden-items`)
r? `@ghost`
`@rustbot` modify labels: rollup
target: move base and target specifications
Follow-up to #116004.
In anticipation of later PRs where we'll want to add tidy checks to ensure that, for each target, we have a test or a platform support document or something like that, this PR moves target specifications into a directory on their own so that we can just list the files in this directory to get a list of all targets.
- Base specifications are moved to `rustc_target::spec::base`.
- Target specifications are moved to `rustc_target::spec::targets`.
- All the other source files containing types used in the target specs remain in `rustc_target::spec`.
- `rustc_target/src/spec/abi.rs` is moved to `rustc_target/src/spec/abi/mod.rs` (where there was already a `tests.rs`) for uniformity.
r? ``@petrochenkov``
Compute polonius loan scopes over the region graph
In issue #117146 a loan flows into an SCC containing a placeholder, and whose representative is an existential region. Since we currently compute loan scopes by looking at SCCs and their representatives only, polonius would compute kill points for this loan here whereas NLLs would not of course.
There are a few ways to fix this:
- don't try to be efficient by doing the computation over SCCs, and simply look for free regions and placeholders in the successors of the issuing region.
- change how the SCC representatives are picked, biasing towards placeholders over existential regions. They *shouldn't* matter much, but some downstream code may subtly depend on the current scheme (though no tests fail if we do such a change). This is for unrelated reasons also the way #116891 changes the representative computation. So that PR would also fix issue #117146.
- try to remove placeholders from the main path, and contain them to a pre-pass + a post-pass kind of polonius leak check. If possible, it would fix this issue by turning an outlives constraints to a placeholder into a constraint to 'static. This should also fix the issue, as the representative would be the free region in the SCC. We want to prototype this change to see if it's possible to try to simplify the borrowck main path from having to deal with placeholders and higher-ranked subtyping 🤞.
I'd like to take advantage of fuzzing and a crater run sooner rather than later, so that we grow more confidence that the 2 models are indeed equivalent empirically. Therefore this PR implements option 1 to fix the issue now.
We can take care of efficiency later after validation, and once we implement option 3 (which could also impact option 2 and that associated PR, maybe the lack of placeholders could remove the need to change the representative computation) to traverse SCCs and their representative again.
(Or we maybe will have some kind of naive position-dependent outlives propagation by then and this code would have been changed)
Fixes#117146.
r? `@matthewjasper`
Add -Zcross-crate-inline-threshold=yes
``@thomcc`` says this would be useful for
> seeing if it makes a difference in some code if i do it when building the sysroot, since -Zbuild-std + lto helps more than it seems like it should
And I've changed the possible values as a reference to ``@Manishearth`` saying
> LLVM's inlining heuristic is "yes".
Only use `normalize_param_env` when normalizing predicate in `check_item_bounds`
Only use the `normalize_param_env` when normalizing the item bound predicate in `check_item_bounds`, instead of using it when processing this obligation as well. This causes <BUG> to reoccur, but hopefully with better caching in the future, we can fix this would having such bad effects on perf.
This PR also fixes#117598. It turns out that the GAT predicate that we install is actually wrong -- given code like:
```
impl<'r> HasValueRef<'r> for Any {
type Database = Any;
}
```
We currently generate a predicate that looks like `<Any as HasValueRef<'r>>::Database = Any`, where `'r` is an early-bound variable. Really this GAT assumption should be universally quantified over the impl's args, i.e. `for<'r> <Any as HasValueRef<'r>>::Database = Any`, but then we'd need the binder to also include all the WC of the impl as well, which we don't support yet, lol.
To avoid `!matches!(...)`, which is hard to think about. Instead every
case now uses direct pattern matching and returns true or false.
Also add a couple of cases to the `stringify.rs` test that currently
print badly.
Method suggestion code tweaks
I was rummaging around the method suggestion code after https://github.com/rust-lang/rust/pull/117006#discussion_r1384153722 and saw a few things to simplify.
This is two unrelated commits, both in the same file. Review them separately, if you'd like.
r? estebank
Fix some clippy perf lints
`@matthiaskrgr` gave me the output of a clippy run with perf lints enabled. This PR fixes ones that I thought were worth fixing.
r? `@cuviper`
llvm-wrapper: Remove include of non-existant Vectorize.h
LLVM recently removed the header: 2400c54c37
It only contained a declaration of `createLoadStoreVectorizerPass()`, which Rust doesn't reference.
warn when using an unstable feature with -Ctarget-feature
Setting or unsetting the wrong target features can cause ABI incompatibility (https://github.com/rust-lang/rust/issues/116344, https://github.com/rust-lang/rust/issues/116558). We need to carefully audit features for their ABI impact before stabilization. I just learned that we currently accept arbitrary unstable features on stable and if they are in the list of Rust target features, even unstable, then we don't even warn about that!1 That doesn't seem great, so I propose we introduce a warning here.
This has an obvious loophole via `-Ctarget-cpu`. I'm not sure how to best deal with that, but it seems better to fix what we can and think about the other cases later, maybe once we have a better idea for how to resolve the general mess that are ABI-affecting target features.
Give a better diagnostic for missing parens in Fn* bounds
Fixes#108109
It would be nice to try and recover here, but I'm not sure it's worth the effort, especially as the bounds on the recovered function would be incorrect.
Thir unsafeck fixes
- Recognise thread local statics in THIR unsafeck
- Add suggestion for unsafe_op_in_unsafe_fn
- Fix unsafe checking of let expressions
Only instantiate binder during dyn's built-in trait candidate probe once
See UI test for demonstration of the issue.
This was "caused" by #117131, but only because we're using the `normalize_param_env` (which has been augmented with a projection clause used to normalize GATs) which features non-lifetime bound vars in it.
Fixes#117602 technically, though that's also fixed by #117542.
r? types
Build a better MIR body when errors are encountered
Doesn't really have much of an effect on its own, but it does lead to a less confusing phony MIR body being generated when an error is detected during THIR/MIR/match building. This was quite confusing when I hacked `-Zunpretty=mir` to emit `mir_built` rather than `instance_mir`.
This coincidentually also fixes#117413, but not as generally as #117416.
cc `@Nadrieril`
When not finding assoc fn on type, look for builder fn
When we have a resolution error when looking at a fully qualified path on a type, look for all associated functions on inherent impls that return `Self` and mention them to the user.
```
error[E0599]: no function or associated item named `new` found for struct `TcpStream` in the current scope
--> tests/ui/resolve/fn-new-doesnt-exist.rs:4:28
|
4 | let stream = TcpStream::new();
| ^^^ function or associated item not found in `TcpStream`
|
note: if you're trying to build a new `TcpStream` consider using one of the following associated functions:
TcpStream::connect
TcpStream::connect_timeout
--> /home/gh-estebank/rust/library/std/src/net/tcp.rs:156:5
|
156 | pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
...
172 | pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpStream> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
Fix#69512.
When we have a resolution error when looking at a fully qualified path
on a type, look for all associated functions on inherent impls that
return `Self` and mention them to the user.
Fix#69512.
Emit explanatory note for move errors in packed struct derives
Derive expansions for packed structs with non-`Copy` fields cause move errors because they prefer copying over borrowing since borrowing the fields of a packed struct can result in unaligned access.
This underlying cause of the errors, however, is not apparent to the user. This PR adds a diagnostic note to make it clear to the user (the new note is on the second last line):
```
tests/ui/derives/deriving-with-repr-packed-move-errors.rs:13:16
|
12 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Default)]
| ----- in this derive macro expansion
13 | struct StructA(String);
| ^^^^^^ move occurs because `self.0` has type `String`, which does not implement the `Copy` trait
|
= note: `#[derive(Debug)]` triggers a move because taking references to the fields of a packed struct is undefined behaviour
= note: this error originates in the derive macro `Debug` (in Nightly builds, run with -Z macro-backtrace for more info)
```
Fixes#117406
Partially addresses #110777