Avoid some redundant work in GVN
The first 2 commits are about reducing the perf effect.
Third commit avoids doing redundant work: is a local is SSA, it already has been simplified, and the resulting value is in `self.locals`. No need to call any code on it.
The last commit avoids removing some storage statements.
r? wg-mir-opt
Some of these tests use non-standard formatting that we can simulate by
strategically adding `//` line comments.
One contains `where` clauses that would be split across multiple lines, which
we can keep on one line by moving the bounds to the generic type instead.
These tests deliberately use non-standard formatting, so that the line
execution counts reported by `llvm-cov` reveal additional information about
where code regions begin and end.
never patterns: Check bindings wrt never patterns
Never patterns:
- Shouldn't contain bindings since they never match anything;
- Don't count when checking that or-patterns have consistent bindings.
r? `@compiler-errors`
Tune the inlinability of `unwrap`
Fixes#115463
cc `@thomcc`
This tweaks `unwrap` on ~~`Option` &~~ `Result` to be two parts:
- `#[inline(always)]` for checking the discriminant
- `#[cold]` for actually panicking
The idea here is that checking the discriminant on a `Result` ~~or `Option`~~ should always be trivial enough to be worth inlining, even in `opt-level=z`, especially compared to passing it to a function.
As seen in the issue and codegen test, this will hopefully help particularly for things like `.try_into().unwrap()`s that are actually infallible, but in a way that's only visible with the inlining.
EDIT: I've restricted this to `Result` to avoid combining effects
Fix `allow_internal_unstable` for `(min_)specialization`
Fixes#119950
Blocked on #119949 (comment doesn't make sense until that merges)
I'd like to follow this up and look for more instances of not properly checking spans for features but I wanted to fix the motivating issue.
Silence some follow-up errors [3/x]
this is one piece of the requested cleanups from https://github.com/rust-lang/rust/pull/117449
Keep error types around, even in obligations.
These help silence follow-up errors, as we now figure out that some types (most notably inference variables) are equal to an error type.
But it also allows figuring out more types in the presence of errors, possibly causing more errors.
Don't ICE when noting GAT bounds in `report_no_match_method_error`
We can encounter `BindingObligation`s from GATs that we should handle in `report_no_match_method_error`. I assume we can encounter them from methods, though I didn't really feel like wasting my time creating a repro.
Fixes#119942
Make `InferCtxtExt::could_impl_trait` more precise, less ICEy
The implementation for `InferCtxtExt::could_impl_trait` was very wrong. Along with being pretty poorly named, way too specific to ADTs, it was also doing impl substitution wrong -- this caused an ICE (#119915).
This PR generalizes that code, gives it a clearer name, makes it stop using the new trait solver (lol), and fixes some fallout bad suggestions that are made worse with the code fix.
Fixes#119915
store the segment name when resolution fails
Fixes#112672
The `find_cfg_stripped` does indeed get executed within `smart_resolve_report_errors`. However, this error is not reported as it is subsequently overridden by `parent_err`. (See: https://github.com/rust-lang/rust/blob/master/compiler/rustc_resolve/src/late.rs#L3760)
This PR changes `last_segment` to `segment`, which stores the name of the failed resolution, and ensures that the result of `find_cfg_stripped` is also included in `parent_err`.
r? ```@Nilstrieb```
Suggest Upgrading Compiler for Gated Features
This PR addresses #117318
I have a few questions:
1. Do we want to specify the current version and release date of the compiler? I have added this in via environment variables, which I found in the code for the rustc cli where it handles the `--version` flag
a. How can I handle the changing message in the tests?
3. Do we want to only show this message when the compiler is old?
a. How can we determine when the compiler is old?
I'll wait until we figure out the message to bless the tests
Move platform modules into `sys::pal`
This is the initial step of #117276. `sys` just re-exports everything from the current `sys` for now, I'll move the implementations for the individual features one-by-one after this PR merges.
Taint `_` placeholder types in trait impl method signatures
We report an error right below for them, but that kind of broken type can cause subsequent ICEs.
fixes#119867
Allow `~const` on associated type bounds again
This follows from [this Zulip discussion](https://rust-lang.zulipchat.com/#narrow/stream/419616-t-compiler.2Fproject-const-traits/topic/projections.20on.20.28~.29const.20Trait.20.26.20.28~.29const.20assoc.20ty.20bounds).
Basically in my opinion, it makes sense to allow `~const` on associated type bounds again since they're quite useful even though we haven't implemented the proposed syntax `<Ty as ~const Trait>::Proj`/`<Ty as const Trait>::Proj` yet; that can happen as a follow-up.
This already allows more code to compile since `T::Assoc` where `T` is a type parameter and where the predicate `<T as ~const Trait>` is in the environment gets elaborated to (pseudo) `<T as ~const Trait>::Assoc`.
```rs
#[const_trait]
trait Trait {
type Assoc: ~const Trait;
fn func() -> i32;
}
const fn function<T: ~const Trait>() -> i32 {
T::Assoc::func()
}
```
`~const` associated type bounds also work together with `const` bounds:
```rs
struct Type<const N: i32>;
fn procedure<T: const Trait>() -> Type<{ T::Assoc::func() }> { // `Trait` comes from above
Type
}
```
NB: This PR also starts allowing `~const` bounds in the generics and the where-clause of trait associated types since it's trivial to support them. However, I don't know if those bounds are actually useful. Maybe we should continue to reject them?
For reference, it wouldn't make any sense to allow `~const Trait` in GACs (generic associated constants, `generic_const_items`) because they'd be absolutely useless (contrary to `const Trait`).
~~[``@]rustbot`` ping project-const-traits~~
r? project-const-traits
Varargs support for system ABI
This PR allows functions with the `system` ABI to be variadic (under the `extended_varargs_abi_support` feature tracked in #100189). On x86 windows, the `system` ABI is equivalent to `C` for variadic functions. On other platforms, `system` is already equivalent to `C`.
Fixes#110505
Overhaul `-Ztreat-err-as-bug`
It's current behaviour is surprising, in a bad way. This also makes the implementation more complex than it needs to be.
r? `@oli-obk`
Add explicit `none()` value variant in check-cfg
This PR adds an explicit none value variant in check-cfg values: `values(none())`.
Currently the only way to define the none variant is with an empty `values()` which means that if someone has a cfg that takes none and strings they need to use two invocations: `--check-cfg=cfg(foo) --check-cfg=cfg(foo, values("bar"))`.
Which would now be `--check-cfg=cfg(foo, values(none(),"bar"))`, this is simpler and easier to understand.
`--check-cfg=cfg(foo)`, `--check-cfg=cfg(foo, values())` and `--check-cfg=cfg(foo, values(none()))` would be equivalent.
*Another motivation for doing this is to make empty `values()` actually means no-values, but this is orthogonal to this PR and adding `none()` is sufficient in it-self.*
`@rustbot` label +F-check-cfg
r? `@petrochenkov`
`-Ztreat-err-as-bug` treats normal errors and delayed bugs equally,
which can lead to some really surprising results.
This commit changes `-Ztreat-err-as-bug` so it ignores delayed bugs,
unless they get promoted to proper bugs and are printed.
This feels to me much simpler and more logical. And it simplifies the
implementation:
- The `-Ztreat-err-as-bug` check is removed from in
`DiagCtxt::{delayed_bug,span_delayed_bug}`.
- `treat_err_as_bug` doesn't need to count delayed bugs.
- The `-Ztreat-err-as-bug` panic message is simpler, because it doesn't
have to mention delayed bugs.
Output of delayed bugs is now more consistent. They're always printed
the same way. Previously when they triggered `-Ztreat-err-as-bug` they
would be printed slightly differently, via `span_bug` in
`span_delayed_bug` or `delayed_bug`.
A minor behaviour change: the "no errors encountered even though
`span_delayed_bug` issued" printed before delayed bugs is now a note
rather than a bug. This is done so it doesn't get counted as an error
that might trigger `-Ztreat-err-as-bug`, which would be silly.
This means that if you use `-Ztreat-err-as-bug=1` and there are no
normal errors but there are delayed bugs, the first delayed bug will be
shown (and the panic will happen after it's printed).
Also, I have added a second note saying "those delayed bugs will now be
shown as internal compiler errors". I think this makes it clearer what
is happening, because the whole concept of delayed bugs is non-obvious.
There are some test changes.
- equality-in-canonical-query.rs: Minor output changes, and the error
count reduces by one because the "no errors encountered even though
`span_delayed_bug` issued" message is no longer counted as an error.
- rpit_tait_equality_in_canonical_query.rs: Ditto.
- storage-live.rs: The query stack disappears because these delayed bugs
are now printed at the end, rather than when they are created.
- storage-return.rs, span_delayed_bug.rs: now need
`-Zeagerly-emit-delayed-bugs` because they need the delayed bugs
emitted immediately to preserve behaviour.
Fix unused_parens issue when cast is followed LT
Fixes#117142
The original check only checks `a as (i32) < 0`, this fix extends it to handle `b + a as (i32) < 0`.
A better way is maybe we suggest `(a as i32) < 0` instead of suppressing the warning, maybe following PR could improve it.
Give me a way to emit all the delayed bugs as errors (add `-Zeagerly-emit-delayed-bugs`)
This is probably a *better* way to inspect all the delayed bugs in a program that what exists currently (and therefore makes it very easy to choose the right number `N` with `-Zemit-err-as-bug=N`, though I guess the naming is a bit ironic when you pair both of the flags together, but that feels like naming bikeshed more than anything).
This pacifies my only concern with https://github.com/rust-lang/rust/pull/119871#issuecomment-1888170259, because (afaict?) that PR doesn't allow you to intercept a delayed bug's stack trace anymore, which as someone who debugs the compiler a lot, is something that I can *promise* that I do.
r? `@nnethercote` or `@oli-obk`
Remove special-casing around `AliasKind::Opaque` when structurally resolving in new solver
This fixes a few inconsistencies around where we don't eagerly resolve opaques to their (locally-defined) hidden types in the new solver. It essentially allows this code to work:
```rust
fn main() {
type Tait = impl Sized;
struct S {
i: i32,
}
let x: Tait = S { i: 0 };
println!("{}", x.i);
}
```
Since `Tait` is defined in `main`, we are able to poke through the type of `x` with deref.
r? lcnr
Exhaustiveness: track overlapping ranges precisely
The `overlapping_range_endpoints` lint has false positives, e.g. https://github.com/rust-lang/rust/issues/117648. I expected that removing these false positives would have too much of a perf impact but never measured it. This PR is an experiment to see if the perf loss is manageable.
r? `@ghost`
Register even erroneous impls
Otherwise the specialization graph fails to pick it up, even though other code assumes that all impl blocks have an entry in the specialization graph.
also includes an unrelated cleanup of the specialization graph query
fixes #119827
next solver: provisional cache
this adds the cache removed in #115843. However, it should now correctly track whether a provisional result depends on an inductive or coinductive stack.
While working on this, I was using the following doc: https://hackmd.io/VsQPjW3wSTGUSlmgwrDKOA. I don't think it's too helpful to understanding this, but am somewhat hopeful that the inline comments are more useful.
There are quite a few future perf improvements here. Given that this is already very involved I don't believe it is worth it (for now). While working on this PR one of my few attempts to significantly improve perf ended up being unsound again because I was not careful enough ✨
r? `@compiler-errors`
By making it an `EscapeError` instead of a `LitError`. This makes it
like the other errors produced when checking string literals contents,
e.g. for invalid escape sequences or bare CR chars.
NOTE: this means these errors are issued earlier, before expansion,
which changes behaviour. It will be possible to move the check back to
the later point if desired. If that happens, it's likely that all the
string literal contents checks will be delayed together.
One nice thing about this: the old approach had some code in
`report_lit_error` to calculate the span of the nul char from a range.
This code used a hardwired `+2` to account for the `c"` at the start of
a C string literal, but this should have changed to a `+3` for raw C
string literals to account for the `cr"`, which meant that the caret in
`cr"` nul error messages was one short of where it should have been. The
new approach doesn't need any of this and avoids the off-by-one error.
libtest: Fix padding of benchmarks run as tests
### Summary
The first commit adds regression tests for libtest padding.
The second commit fixes padding for benches run as tests and updates the blessed output of the regression tests to make it clear what effect the fix has on padding.
Closes#104092 which is **E-help-wanted** and **regression-from-stable-to-stable**
### More details
Before this fix we applied padding _before_ manually doing what `convert_benchmarks_to_tests()` does which affects padding calculations. Instead use `convert_benchmarks_to_tests()` first if applicable and then apply padding afterwards so it becomes correct.
Benches should only be padded when run as benches to make it easy to compare the benchmark numbers. Not when run as tests.
r? `@ghost` until CI passes.
coverage: Add enums to accommodate other kinds of coverage mappings
Extracted from #118305.
LLVM supports several different kinds of coverage mapping regions, but currently we only ever emit ordinary “code” regions. This PR performs the plumbing required to add other kinds of regions as enum variants, but does not add any specific variants other than `Code`.
The main motivation for this change is branch coverage, but it will also allow separate experimentation with gap regions and skipped regions, which might help in producing more accurate and useful coverage reports.
---
``@rustbot`` label +A-code-coverage
Remove `DiagnosticBuilder::buffer`
`DiagnosticBuilder::buffer` doesn't do much, and part of what it does (for `-Ztreat-err-as-bug`) it shouldn't.
This PR strips it back, replaces its uses, and finally removes it, making a few cleanups in the vicinity along the way.
r? ``@oli-obk``
Silence some follow-up errors [2/x]
this is one piece of the requested cleanups from https://github.com/rust-lang/rust/pull/117449
the `type_of` query frequently uses astconv to convert a `hir::Ty` to a `ty::Ty`. This process is infallible, but may produce errors as it goes. All the error reporting sites that had access to the `ItemCtxt` are now tainting it, causing `type_of` to return a `ty::Error` instead of anything else.
Stop mentioning internal lang items in no_std binary errors
When writing a no_std binary, you'll be greeted with nonsensical errors mentioning lang items like eh_personality and start. That's pretty bad because it makes you think that you need to define them somewhere! But oh no, now you're getting the `internal_features` lint telling you that you shouldn't use them! But you need a no_std binary! What now?
No problem! Writing a no_std binary is super easy. Just use panic=abort and supply your own platform specific entrypoint symbol (like `main`) and you're good to go. Would be nice if the compiler told you that, right?
This makes it so that it does do that.
I don't _love_ the new messages yet, but they're decent I think. They can probably be improved, please suggest improvements.
Errors in `DiagCtxtInner::emit_diagnostic` are never set to
`Level::Bug`, because the condition never succeeds, because
`self.treat_err_as_bug()` is called *before* the error counts are
incremented.
This commit switches to `self.treat_next_err_as_bug()`, fixing the
problem. This changes the error message output to actually say "internal
compiler error".
Reorder early post-inlining passes.
`RemoveZsts`, `RemoveUnneededDrops` and `UninhabitedEnumBranching` only depend on types, so they should be executed together early after MIR inlining introduces those types.
This does not change the end-result, but this makes the pipeline a bit more consistent.
Silence some follow-up errors [1/x]
this is one piece of the requested cleanups from https://github.com/rust-lang/rust/pull/117449
When we use `-> impl SomeTrait<_>` as a return type, we are both using the "infer return type suggestion" code path, and the infer opaque type code path within the same function. That can lead to confusing diagnostics, so silence all opaque type diagnostics in that case.
When writing a no_std binary, you'll be greeted with nonsensical errors
mentioning lang items like eh_personality and start. That's pretty bad
because it makes you think that you need to define them somewhere! But
oh no, now you're getting the `internal_features` lint telling you that
you shouldn't use them! But you need a no_std binary! What now?
No problem! Writing a no_std binary is super easy. Just use panic=abort
and supply your own platform specific entrypoint symbol (like `main`)
and you're good to go. Would be nice if the compiler told you that,
right?
This makes it so that it does do that.
rustdoc: offset generic args of cross-crate trait object types when cleaning
Fixes#119529.
This PR contains several refactorings apart from the bug fix.
Best reviewed commit by commit.
r? GuillaumeGomez
Avoid silencing relevant follow-up errors
r? `@matthewjasper`
This PR only adds new errors to tests that are already failing and fixes one ICE.
Several tests were changed to not emit new errors. I believe all of them were faulty tests, and not explicitly testing for the code that had new errors.
`~const` trait and projection bounds do not imply their non-const counterparts
This PR removes the hack where we install a non-const trait and projection bound for every `const_trait` and `~const` projection bound we have in the AST. It ends up messing up more things than it fixes, see words below.
Fixes#119718
cc `@fmease` `@fee1-dead` `@oli-obk`
r? fee1-dead or one of y'all i don't care
---
My understanding is that this hack was added to support the following code:
```rust
pub trait Owo<X = <Self as Uwu>::T> {}
#[const_trait]
pub trait Uwu: Owo {}
```
Which is concretely lifted from in the `FromResidual` and `Try` traits. Since within the param-env of `trait Uwu`, we only know that `Self: ~const Uwu` and not `Self: Uwu`, the projection `<Self as Uwu>::T` is not satsifyable.
This causes problems such as #119718, since instantiations of `FnDef` types coming from `const fn` really do **only** implement one of `FnOnce` or `const FnOnce`!
---
In the long-term, I believe that such code should really look something more like:
```rust
#[const_trait]
pub trait Owo<X = <Self as ~const Uwu>::T> {}
#[const_trait]
pub trait Uwu: Owo {}
```
... and that we should introduce some sort of `<T as ~const Foo>::Bar` bound syntax, since due to the fact that `~const` bounds can be present in item bounds, e.g.
```rust
#[const_trait] trait Foo { type Bar: ~const Destruct; }
```
It's easy to see that `<T as Foo>::Bar` and `<T as ~const Foo>::Bar` (or `<T as const Foo>::Bar`) can be distinct types with distinct item bounds!
**Admission**: I know I've said before that I don't like `~const` projection syntax, I do at this point believe they're necessary to fully express bounds and types in a maybe-const world.
Merge dead bb pruning and unreachable bb deduplication.
Both routines share the same basic structure: iterate on all bbs to identify work, and then renumber bbs.
We can do both at once.
unify query canonicalization mode
Exclude from canonicalization only the static lifetimes that appear in the param env because of #118965 . Any other occurrence can be canonicalized safely AFAICT.
r? `@lcnr`
Support async recursive calls (as long as they have indirection)
Before #101692, we stored coroutine witness types directly inside of the coroutine. That means that a coroutine could not contain itself (as a witness field) without creating a cycle in the type representation of the coroutine, which we detected with the `OpaqueTypeExpander`, which is used to detect cycles when expanding opaque types after that are inferred to contain themselves.
After `-Zdrop-tracking-mir` was stabilized, we no longer store these generator witness fields directly, but instead behind a def-id based query. That means there is no technical obstacle in the compiler preventing coroutines from containing themselves per se, other than the fact that for a coroutine to have a non-infinite layout, it must contain itself wrapped in a layer of allocation indirection (like a `Box`).
This means that it should be valid for this code to work:
```
async fn async_fibonacci(i: u32) -> u32 {
if i == 0 || i == 1 {
i
} else {
Box::pin(async_fibonacci(i - 1)).await
+ Box::pin(async_fibonacci(i - 2)).await
}
}
```
Whereas previously, you'd need to coerce the future to `Pin<Box<dyn Future<Output = ...>>` before `await`ing it, to prevent the async's desugared coroutine from containing itself across as await point.
This PR does two things:
1. Only report an error if an opaque expansion cycle is detected *not* through coroutine witness fields.
* Instead, if we find an opaque cycle through coroutine witness fields, we compute the layout of the coroutine. If that results in a cycle error, we report it as a recursive async fn.
4. Reworks the way we report layout errors having to do with coroutines, to make up for the diagnostic regressions introduced by (1.). We actually do even better now, pointing out the call sites of the recursion!
Adding alignment to the cases to test for specific error messages.
Adding alignment to the list of cases to test for specific error message. Covers `>`, `^` and `<`.
Pinging people who chimed in last time ( https://github.com/rust-lang/rust/pull/106805 ): ``@estebank`` , ``@compiler-errors`` and ``@Nilstrieb``
tests: Normalize `\r\n` to `\n` in some run-make tests
The output is produced by printf from C code in these cases, and printf prints in text mode, which means `\n` will be printed as `\r\n` on Windows.
In --bless mode the new output with `\r\n` will replace expected output in `tests/run-make/raw-dylib-*\output.txt` files, which use \n, always resulting in dirty files in the repo.
remove an unnecessary stderr-per-bitwidth
also update some regexp, `a(lloc)?` would no longer match now that we have compiletest itself do alloc ID normalization.
r? ````@oli-obk````
coverage: `llvm-cov` expects column numbers to be bytes, not code points
Normally the compiler emits column numbers as a 1-based number of Unicode code points.
But when we embed coverage mappings for `-Cinstrument-coverage`, those mappings will ultimately be read by the `llvm-cov` tool. That tool assumes that column numbers are 1-based numbers of *bytes*, and relies on that assumption when slicing up source code to apply highlighting (in HTML reports, and in text-based reports with colour).
For the very common case of all-ASCII source code, bytes and code points are the same, so the difference isn't noticeable. But for code that contains non-ASCII characters, emitting column numbers as code points will result in `llvm-cov` slicing strings in the wrong places, producing mangled output or fatal errors.
(See https://github.com/taiki-e/cargo-llvm-cov/issues/275 as an example of what can go wrong.)
Improved support of collapse_debuginfo attribute for macros.
Added walk_chain_collapsed function to consider collapse_debuginfo attribute in parent macros in call chain.
Fixed collapse_debuginfo attribute processing for cranelift (there was if/else branches error swap).
cc https://github.com/rust-lang/rust/issues/100758
Unions are not `PointerLike`
I introduced the `PointerLike` trait to enforce `dyn*` coercions only from types that share the same ABI as a pointer. On top of needing to be scalar, they also should not be unions, since CTFE chokes on scalar reads for union types.
Fixes#119695
Impl trait diagnostic tweaks
1. Tweak some names for `impl Trait` being used in the wrong position
2. Remove two helper functions that are no longer needed since RPITIT is stable, and which causes matches to be a bit obtuse.
3. Split and fix the part where the error notes that it's "only allowed in XX"
Fixes#119629
Rewrite `pin` module documentation to clarify usage and invariants
The documentation of `pin` today does not give a complete treatment of pinning from first principles, nor does it adequately help build intuition and understanding for how the different elements of the pinning story fit together.
This rewrite attempts to address these in a way that makes the concept more approachable while also making the documentation more normative.
This PR picks up where `@mcy` left off in #88500 (thanks to him for the original work and `@Manishearth` for mentioning it such that I originally found it). I've directly incorporated much of the feedback left on the original PR and have rewritten and changed some of the main conceits of the prose to better adhere to the feedback from the reviewers on that PR or just explain something in (hopefully) a better way.
Run Miri and mir-opt tests without a target linker
Normally, we need a linker for the target to build the standard library. That's only because `std` declares crate-type lib and dylib; building the dylib is what creates a need for the linker.
But for mir-opt tests (and for Miri) we do not need to build a `libstd.so`. So with this PR, when we build the standard library for mir-opt tests, instead of `cargo build` we run `cargo rustc --crate-type=lib` which overrides the configured crate types in `std`'s manifest.
I've also swapped in what seems to me a better hack than `BOOTSTRAP_SKIP_TARGET_SANITY` to prevent cross-interpreting with Miri from checking for a target linker and expanded it to mir-opt tests too. Whether it's actually better is up to a reviewer.
The output is produced by printf from C code in these cases, and printf prints in text mode, which means `\n` will be printed as `\r\n` on Windows.
In --bless mode the new output with `\r\n` will replace expected output in `tests/run-make/raw-dylib-*\output.txt` files, which use \n, always resulting in dirty files in the repo.
Remove ignore-stage1 that was added when changing error count msg
The bootstrap bump has happened, so the bootstrap compiler now contains the new diagnostic.
this was added in #118138
rustc_span: More consistent span combination operations
Also add more tests for using `tt` in addition to `ident`, and some other minor tweaks, see individual commits.
This is a part of https://github.com/rust-lang/rust/pull/119412 that doesn't yet add side tables for metavariable spans.
rustc_mir_transform: Make DestinationPropagation stable for queries
By using `FxIndexMap` instead of `FxHashMap`, so that the order of visiting of locals is deterministic.
We also need to bless
`copy_propagation_arg.foo.DestinationPropagation.panic*.diff`. Do not review the diff of the diff. Instead look at the diff files before and after this commit. Both before and after this commit, 3 statements are replaced with nop. It's just that due to change in ordering, different statements are replaced. But the net result is the same. In other words, compare this diff (before fix):
* 090d5eac72/tests/mir-opt/dest-prop/copy_propagation_arg.foo.DestinationPropagation.panic-unwind.diff
With this diff (after fix):
* f603babd63/tests/mir-opt/dest-prop/copy_propagation_arg.foo.DestinationPropagation.panic-unwind.diff
and you can see that both before and after the fix, we replace 3 statements with `nop`s.
I find it _slightly_ surprising that the test this PR affects did not previously fail spuriously due to the indeterminism of `FxHashMap`, but I guess in can be explained with the predictability of small `FxHashMap`s with `usize` (`Local`) keys, or something along those lines.
This should fix [this](https://github.com/rust-lang/rust/pull/119252#discussion_r1436101791) comment, but I wanted to make a separate PR for this fix for a simpler development and review process.
Part of https://github.com/rust-lang/rust/issues/84447 which is E-help-wanted.
r? `@cjgillot` who is reviewer for the highly related PR https://github.com/rust-lang/rust/pull/119252.
merge core_panic feature into panic_internals
I don't know why those are two separate features, but it does not seem intentional. This merge is useful because with https://github.com/rust-lang/rust/pull/118123, panic_internals is recognized as an internal feature, but core_panic is not -- but core_panic definitely should be internal.
rustdoc: search for tuples and unit by type with `()`
This feature extends rustdoc to support the syntax that most users will naturally attempt to use to search for tuples. Part of https://github.com/rust-lang/rust/issues/60485
Function signature searches already support tuples and unit. The explicit name `primitive:tuple` and `primitive:unit` can be used to match a tuple or unit, while `()` will match either one. It also follows the direction set by the actual language for parens as a group, so `(u8,)` will only match a tuple, while `(u8)` will match a plain, unwrapped byte—thanks to loose search semantics, it will also match the tuple.
## Preview
* [`option<t>, option<u> -> (t, u)`](<https://notriddle.com/rustdoc-html-demo-5/tuple-unit/std/index.html?search=option%3Ct%3E%2C option%3Cu%3E -%3E (t%2C u)>)
* [`[t] -> (t,)`](<https://notriddle.com/rustdoc-html-demo-5/tuple-unit/std/index.html?search=[t] -%3E (t%2C)>)
* [`(ipaddr,) -> socketaddr`](<https://notriddle.com/rustdoc-html-demo-5/tuple-unit/std/index.html?search=(ipaddr%2C) -%3E socketaddr>)
## Motivation
When type-based search was first landed, it was directly [described as incomplete][a comment].
[a comment]: https://github.com/rust-lang/rust/pull/23289#issuecomment-79437386
Filling out the missing functionality is going to mean adding support for more of Rust's [type expression] syntax, such as tuples (in this PR), references, raw pointers, function pointers, and closures.
[type expression]: https://doc.rust-lang.org/reference/types.html#type-expressions
There does seem to be demand for this sort of thing, such as [this Discord message](https://discord.com/channels/442252698964721669/443150878111694848/1042145740065099796) expressing regret at rustdoc not supporting tuples in search queries.
## Reference description (from the Rustdoc book)
<table>
<thead>
<tr>
<th>Shorthand</th>
<th>Explicit names</th>
</tr>
</thead>
<tbody>
<tr><td colspan="2">Before this PR</td></tr>
<tr>
<td><code>[]</code></td>
<td><code>primitive:slice</code> and/or <code>primitive:array</code></td>
</tr>
<tr>
<td><code>[T]</code></td>
<td><code>primitive:slice<T></code> and/or <code>primitive:array<T></code></td>
</tr>
<tr>
<td><code>!</code></td>
<td><code>primitive:never</code></td>
</tr>
<tr><td colspan="2">After this PR</td></tr>
<tr>
<td><code>()</code></td>
<td><code>primitive:unit</code> and/or <code>primitive:tuple</code></td>
</tr>
<tr>
<td><code>(T)</code></td>
<td><code>T</code></td>
</tr>
<tr>
<td><code>(T,)</code></td>
<td><code>primitive:tuple<T></code></td>
</tr>
</tbody>
</table>
A single type expression wrapped in parens is the same as that type expression, since parens act as the grouping operator. If they're empty, though, they will match both `unit` and `tuple`, and if there's more than one type (or a trailing or leading comma) it is the same as `primitive:tuple<...>`.
However, since items can be left out of the query, `(T)` will still return results for types that match tuples, even though it also matches the type on its own. That is, `(u32)` matches `(u32,)` for the exact same reason that it also matches `Result<u32, Error>`.
## Future direction
The [type expression grammar](https://doc.rust-lang.org/reference/types.html#type-expressions) from the Reference is given below:
<pre><code>Syntax
Type :
TypeNoBounds
| <a href="https://doc.rust-lang.org/reference/types/impl-trait.html">ImplTraitType</a>
| <a href="https://doc.rust-lang.org/reference/types/trait-object.html">TraitObjectType</a>
<br>
TypeNoBounds :
<a href="https://doc.rust-lang.org/reference/types.html#parenthesized-types">ParenthesizedType</a>
| <a href="https://doc.rust-lang.org/reference/types/impl-trait.html">ImplTraitTypeOneBound</a>
| <a href="https://doc.rust-lang.org/reference/types/trait-object.html">TraitObjectTypeOneBound</a>
| <a href="https://doc.rust-lang.org/reference/paths.html#paths-in-types">TypePath</a>
| <a href="https://doc.rust-lang.org/reference/types/tuple.html#tuple-types">TupleType</a>
| <a href="https://doc.rust-lang.org/reference/types/never.html">NeverType</a>
| <a href="https://doc.rust-lang.org/reference/types/pointer.html#raw-pointers-const-and-mut">RawPointerType</a>
| <a href="https://doc.rust-lang.org/reference/types/pointer.html#shared-references-">ReferenceType</a>
| <a href="https://doc.rust-lang.org/reference/types/array.html">ArrayType</a>
| <a href="https://doc.rust-lang.org/reference/types/slice.html">SliceType</a>
| <a href="https://doc.rust-lang.org/reference/types/inferred.html">InferredType</a>
| <a href="https://doc.rust-lang.org/reference/paths.html#qualified-paths">QualifiedPathInType</a>
| <a href="https://doc.rust-lang.org/reference/types/function-pointer.html">BareFunctionType</a>
| <a href="https://doc.rust-lang.org/reference/macros.html#macro-invocation">MacroInvocation</a>
</code></pre>
ImplTraitType and TraitObjectType (and ImplTraitTypeOneBound and TraitObjectTypeOneBound) are not yet implemented. They would mostly desugar to `trait:`, similarly to how `!` desugars to `primitive:never`.
ParenthesizedType and TuplePath are added in this PR.
TypePath is already implemented (except const generics, which is not planned, and function-like trait syntax, which is planned as part of closure support).
NeverType is already implemented.
RawPointerType and ReferenceType require parsing and fixes to the search index to store this information, but otherwise their behavior seems simple enough. Just like tuples and slices, `&T` would be equivalent to `primitive:reference<T>`, `&mut T` would be equivalent to `primitive:reference<keyword:mut, T>`, `*T` would be equivalent to `primitive:pointer<T>`, `*mut T` would be equivalent to `primitive:pointer<keyword:mut, T>`, and `*const T` would be equivalent to `primitive:pointer<keyword:const, T>`. Lifetime generics support is not planned, because lifetime subtyping seems too complicated.
ArrayType is subsumed by SliceType right now. Implementing const generics is not planned, because it seems like it would require a lot of implementation complexity for not much gain.
InferredType isn't really covered right now. Its semantics in a search context are not obvious.
QualifiedPathInType is not implemented, and it is not planned. I would need a use case to justify it, and act as a guide for what the exact semantics should be.
BareFunctionType is not implemented. Along with function-like trait syntax, which is formally considered a TypePath, it's the biggest missing feature to be able to do structured searches over generic APIs like `Option`.
MacroInvocation is not parsed (macro names are, but they don't mean the same thing here at all). Those are gone by the time Rustdoc sees the source code.
Avoid specialization in the metadata serialization code
With the exception of a perf-only specialization for byte slices and byte vectors.
This uses the same trick of introducing a new trait and having the Encodable and Decodable derives add a bound to it as used for TyEncoder/TyDecoder. The new code is clearer about which encoder/decoder uses which impl and it reduces the dependency of rustc on specialization, making it easier to remove support for specialization entirely or turn it into a construct that is only allowed for perf optimizations if we decide to do this.
fix cyle error when suggesting to use associated function instead of constructor
Fixes https://github.com/rust-lang/rust/issues/119625.
The first commit fixes the infinite recursion and makes the cycle error actually show up. We do this by making the `Display` for `ty::Instance` impl respect `with_no_queries` so that it can be used in query descriptions.
The second commit fixes the cycle error `resolver_for_lowering` -> `normalize` -> `resolve_instance` (for evaluating const) -> `lang_items` (for `drop_in_place`) -> `resolver_for_lowering` (for collecting lang items). We do this by simply skipping the suggestion when encountering an unnormalized type.
remove duplicate test
This was added in ace6fc3646 where overflowing-rsh-6 differed from overflowing-rsh-5 in a feature gate, but the feature has since been stabilized, making the tests 100% identical.
Most of these tests in numbers-arithmetic could be put into one file rather than having so many files that all test the same lint... but it doesn't seem worth the effort. After https://github.com/rust-lang/rust/pull/119432 we might be able to remove most of them entirely as they will be covered by the new tests added there.
Use diagnostic namespace in stdlib
This required a minor fix to have the diagnostics shown in third party crates when the `diagnostic_namespace` feature is not enabled. See 5d63f5d8d1 for details. I've opted for having a single PR for both changes as it's really not that much code. If it is required it should be easy to split up the change into several PR's.
r? `@compiler-errors`
coverage: Hoist some complex code out of the main span refinement loop
The span refinement loop in `spans.rs` takes the spans that have been extracted from MIR, and modifies them to produce more helpful output in coverage reports.
It is also one of the most complicated pieces of code in the coverage instrumentor. It has an abundance of moving pieces that make it difficult to understand, and most attempts to modify it end up accidentally changing its behaviour in unacceptable ways.
This PR nevertheless tries to make a dent in it by hoisting two pieces of special-case logic out of the main loop, and into separate preprocessing passes. Coverage tests show that the resulting mappings are *almost* identical, with all known differences being unimportant.
This should hopefully unlock further simplifications to the refinement loop, since it now has fewer edge cases to worry about.
By using FxIndexMap instead of FxHashMap, so that the order of visiting
of locals is deterministic.
We also need to bless
copy_propagation_arg.foo.DestinationPropagation.panic*.diff. Do not
review the diff of the diff. Instead look at the diff file before and
after this commit. Both before and after this commit, 3 statements are
replaced with nop. It's just that due to change in ordering, different
statements are replaced. But the net result is the same.
never patterns: Document behavior of never patterns with macros-by-example
`never_patterns` makes `!` parse as a pattern so I was worried about breaking macros-by-example matching. Turns out we're fine because the cases that now match `$p:pat` used to error in the past. The only tricky case is `!` by itself, which backwards-compatibly doesn't match `$p:pat`. I have no idea why tho, I didn't think of that when I was implementing parsing 😅.
This adds tests so we don't regress the current behavior.
r? `@compiler-errors`
Check yield terminator's resume type in borrowck
In borrowck, we didn't check that the lifetimes of the `TerminatorKind::Yield`'s `resume_place` were actually compatible with the coroutine's signature. That means that the lifetimes were totally going unchecked. Whoops!
This PR implements this checking.
Fixes#119564
r? types
Fix scoping for let chains in match guards
If let guards were previously represented as a different type of guard in HIR and THIR. This meant that let chains in match guards were not handled correctly because they were treated exactly like normal guards.
- Remove `hir::Guard` and `thir::Guard`.
- Make the scoping different between normal guards and if let guards also check for let chains.
closes#118593
Use `resolutions(()).effective_visiblities` to avoid cycle errors in `report_object_error`
Inside of `report_object_error`, using the `effective_visibilities` query causes cycles since it calls `type_of`, which itself may call `typeck`, which may end up reporting its own object-safety errors.
Fixes#119346Fixes#119502
Hide foreign `#[doc(hidden)]` paths in import suggestions
Stops the compiler from suggesting to import foreign `#[doc(hidden)]` paths.
```@rustbot``` label A-suggestion-diagnostics
[rustdoc] Fix invalid handling for static method calls in jump to definition feature
I realized when working on a clippy lint that static method calls on `Self` could not give me the method `Res`. For that, we need to use `typeck` and so that's what I did in here.
It fixes the linking to static method calls.
r? ````@notriddle````
Migrate memory overlap check from validator to lint
The check attempts to identify potential undefined behaviour, rather
than whether MIR is well-formed. It belongs in the lint not validator.
Follow up to changes from #119077.
Remove `-Zdump-mir-spanview`
The `-Zdump-mir-spanview` flag was added back in #76074, as a development/debugging aid for the initial work on what would eventually become `-Cinstrument-coverage`. It causes the compiler to emit an HTML file containing a function's source code, with various spans highlighted based on the contents of MIR.
When the suggestion was made to [triage and remove unnecessary `-Z` flags (Zulip)](https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/.60-Z.60.20option.20triage), I noted that this flag could potentially be worth removing, but I wanted to keep it around to see whether I found it useful for my own coverage work.
But when I actually tried to use it, I ran into various issues (e.g. it crashes on `tests/coverage/closure.rs`). If I can't trust it to work properly without a full overhaul, then instead of diving down a rabbit hole of trying to fix arcane span-handling bugs, it seems better to just remove this obscure old code entirely.
---
````@rustbot```` label +A-code-coverage
Tweak suggestions for bare trait used as a type
```
error[E0782]: trait objects must include the `dyn` keyword
--> $DIR/not-on-bare-trait-2021.rs:11:11
|
LL | fn bar(x: Foo) -> Foo {
| ^^^
|
help: use a generic type parameter, constrained by the trait `Foo`
|
LL | fn bar<T: Foo>(x: T) -> Foo {
| ++++++++ ~
help: you can also use `impl Foo`, but users won't be able to specify the type paramer when calling the `fn`, having to rely exclusively on type inference
|
LL | fn bar(x: impl Foo) -> Foo {
| ++++
help: alternatively, use a trait object to accept any type that implements `Foo`, accessing its methods at runtime using dynamic dispatch
|
LL | fn bar(x: &dyn Foo) -> Foo {
| ++++
error[E0782]: trait objects must include the `dyn` keyword
--> $DIR/not-on-bare-trait-2021.rs:11:19
|
LL | fn bar(x: Foo) -> Foo {
| ^^^
|
help: use `impl Foo` to return an opaque type, as long as you return a single underlying type
|
LL | fn bar(x: Foo) -> impl Foo {
| ++++
help: alternatively, you can return an owned trait object
|
LL | fn bar(x: Foo) -> Box<dyn Foo> {
| +++++++ +
```
Fix#119525:
```
error[E0038]: the trait `Ord` cannot be made into an object
--> $DIR/bare-trait-dont-suggest-dyn.rs:3:33
|
LL | fn ord_prefer_dot(s: String) -> Ord {
| ^^^ `Ord` cannot be made into an object
|
note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
--> $SRC_DIR/core/src/cmp.rs:LL:COL
|
= note: the trait cannot be made into an object because it uses `Self` as a type parameter
::: $SRC_DIR/core/src/cmp.rs:LL:COL
|
= note: the trait cannot be made into an object because it uses `Self` as a type parameter
help: consider using an opaque type instead
|
LL | fn ord_prefer_dot(s: String) -> impl Ord {
| ++++
```
Allow coverage tests to ignore test modes, and to enable color in coverage reports
This PR adds two new header directives to compiletest, intended for use by coverage tests (and by #119033 in particular).
The new headers are:
- `// ignore-mode-{mode}` causes a test to not be run in a particular compiletest mode (e.g. `ignore-mode-coverage-run`).
- This can theoretically be used by any test, but coverage tests are currently the only ones that automatically run in multiple modes, so it's not very useful for other kinds of test.
- `// llvm-cov-flags: --use-color` makes `coverage-run` tests pass the flag `--use-color` when generating coverage reports.
- For most tests, non-coloured reports are easier to read and more portable across platforms. But for #119033 specifically, we want to test that `llvm-cov` slices up source text correctly, which only happens when colour output is enabled.
Separate immediate and in-memory ScalarPair representation
Currently, we assume that ScalarPair is always represented using a two-element struct, both as an immediate value and when stored in memory.
This currently works fairly well, but runs into problems with https://github.com/rust-lang/rust/pull/116672, where a ScalarPair involving an i128 type can no longer be represented as a two-element struct in memory. For example, the tuple `(i32, i128)` needs to be represented in-memory as `{ i32, [3 x i32], i128 }` to satisfy alignment requirements. Using `{ i32, i128 }` instead will result in the second element being stored at the wrong offset (prior to LLVM 18).
Resolve this issue by no longer requiring that the immediate and in-memory type for ScalarPair are the same. The in-memory type will now look the same as for normal struct types (and will include padding filler and similar), while the immediate type stays a simple two-element struct type. This also means that booleans in immediate ScalarPair are now represented as i1 rather than i8, just like we do everywhere else.
The core change here is to llvm_type (which now treats ScalarPair as a normal struct) and immediate_llvm_type (which returns the two-element struct that llvm_type used to produce). The rest is fixing things up to no longer assume these are the same. In particular, this switches places that try to get pointers to the ScalarPair elements to use byte-geps instead of struct-geps.
`#[diagnostic::on_unimplemented]`
This commit replaces those `#[rustc_on_unimplemented]` attributes with
their equivalent `#[diagnostic::on_unimplemented]` where this is
supported (So no filter or any extended option)
Stabilize THIR unsafeck
- Removes `-Zthir-unsafeck`, stabilizing the behaviour of `-Zthir-unsafeck=on`.
- Removes MIR unsafeck.
- Union patterns are now unsafe unless the field is matched to a wildcard pattern.
Opening for a crater run in case we need a compatibility lint.
Match guards with an if let guard or an if let chain guard should have a
temporary scope of the whole arm. This is to allow ref bindings to
temporaries to borrow check.
PR #82639 changed UI tests so `-Z unstable-options` aren't passed to UI
tests by default. This completely broke `use_suggestion_json.rs`, which
uses the unstable `--error-format=pretty-json` option. The expected
output went from 400 lines of pretty JSON error messages to a single
JSON error saying "`--error-format=pretty-json` is unstable"!
This commit adds `-Z unstable-options` back and reinstates the old
expected output, with some minor changes to account for shifted spans
and slightly JSON output changes since then.
Normally, each test in `tests/coverage` is automatically run in both
`coverage-map` mode and `coverage-run` mode.
This new family of directives allows an individual test to specify that it
should not be run in a particular mode.
Reorder check_item_type diagnostics so they occur next to the corresponding `check_well_formed` diagnostics
The first commit is just a cleanup.
The second commit moves most checks from `check_mod_item_types` into `check_well_formed`, invoking the checks in lockstep per-item instead of iterating over all items twice.
Reevaluate `body.should_skip()` after updating the MIR phase to ensure
that injected MIR is processed correctly.
Update a few custom MIR tests that were ill-formed for the injected
phase.
Rollup of 10 pull requests
Successful merges:
- #118521 (Enable address sanitizer for MSVC targets using INFERASANLIBS linker flag)
- #119026 (std::net::bind using -1 for openbsd which in turn sets it to somaxconn.)
- #119195 (Make named_asm_labels lint not trigger on unicode and trigger on format args)
- #119204 (macro_rules: Less hacky heuristic for using `tt` metavariable spans)
- #119362 (Make `derive(Trait)` suggestion more accurate)
- #119397 (Recover parentheses in range patterns)
- #119417 (Uplift some miscellaneous coroutine-specific machinery into `check_closure`)
- #119539 (Fix typos)
- #119540 (Don't synthesize host effect args inside trait object types)
- #119555 (Add codegen test for RVO on MaybeUninit)
r? `@ghost`
`@rustbot` modify labels: rollup
Make offset_of field parsing use metavariable which handles any spacing
As discussed at and around comments https://github.com/rust-lang/rust/issues/106655#issuecomment-1793485081 and https://github.com/rust-lang/rust/issues/106655#issuecomment-1793774183, the current arguments to offset_of do not accept all the whitespace combinations: `0. 1.1.1` and `0.1.1. 1` are currently treated specially in `tests/ui/offset-of/offset-of-tuple-nested.rs`.
They also do not allow [forwarding individual fields as in](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=444cdf0ec02b99e8fd5fd8d8ecb312ca)
```rust
macro_rules! off {
($a:expr) => {
offset_of!(m::S, 0. $a)
}
}
```
This PR replaces the macro arguments with `($Container:ty, $($fields:expr)+ $(,)?)` which does allow any arrangement of whitespace that I could come up with and the forwarding of fields example above.
This also allows for array indexing in the future, which I think is the last future extension to the syntax suggested in the offset_of RFC.
Tracking issue for offset_of: #106655
``@rustbot`` label F-offset_of
``@est31``
Support reg_addr register class in s390x inline assembly
In s390x, `r0` cannot be used as an address register (it is evaluated as zero in an address context).
Therefore, currently, in assemblies involving memory accesses, `r0` must be [marked as clobbered](1a1155653a/src/arch/s390x.rs (L58)) or [explicitly used to a non-address](1a1155653a/src/arch/s390x.rs (L135)) or explicitly use an address register to prevent `r0` from being allocated to a register for the address.
This patch adds a register class for allocating general-purpose registers, except `r0`, to make it easier to use address registers. (powerpc already has a register class (reg_nonzero) for a similar purpose.)
This is identical to the `a` constraint in LLVM and GCC:
https://llvm.org/docs/LangRef.html#supported-constraint-code-list
> a: A 32, 64, or 128-bit integer address register (excludes R0, which in an address context evaluates as zero).
https://gcc.gnu.org/onlinedocs/gcc/Machine-Constraints.html
> a
> Address register (general purpose register except r0)
cc ``@uweigand``
r? ``@Amanieu``
custom mir: make it clear what the return block is
Custom MIR recently got support for specifying the "unwind action", so now there's two things coming after the actual call part of `Call` terminators. That's not very self-explaining so I propose we change the syntax to imitate keyword arguments:
```
Call(popped = Vec::pop(v), ReturnTo(drop), UnwindContinue())
```
Also fix some outdated docs and add some docs to `Call` and `Drop`.
Switch from using `//~ERROR` annotations with `--error-format` to `error-pattern`
Fixes#118752
As noticed by ```@jyn514``` while working on a patch, tests failed due to `//~ERROR` annotations used in combination with the older `--error-format` which is now `error-pattern`.
Don't synthesize host effect args inside trait object types
While we were indeed emitting an error for `~const` & `const` trait bounds in trait object types, we were still synthesizing host effect args for them.
Since we don't record the original trait bound modifiers for dyn-Trait in `hir::TyKind::TraitObject` (unlike we do for let's say impl-Trait, `hir::TyKind::OpaqueTy`), AstConv just assumes `ty::BoundConstness::NotConst` in `conv_object_ty_poly_trait_ref` which given `<host> dyn ~const NonConstTrait` resulted in us not realizing that `~const` was used on a non-const trait which lead to a failed assertion in the end.
Instead of updating `hir::TyKind::TraitObject` to track this kind of information, just strip the user-provided constness (similar to #119505).
Fixes#119524.
Uplift some miscellaneous coroutine-specific machinery into `check_closure`
This PR uplifts some of the logic in `check_fn` that is specific to checking coroutines, which always flows through `check_closure`.
This is just some miscellaneous clean up that I've wanted to do, especially because I'm poking around this code to make it work for async closures.
Recover parentheses in range patterns
Before:
```rs
match n {
(0).. => (),
_ => ()
}
```
```
error: expected one of `=>`, `if`, or `|`, found `..`
--> src/lib.rs:3:12
|
3 | (0).. => (),
| ^^ expected one of `=>`, `if`, or `|`
```
After:
```
error: range pattern bounds cannot have parentheses
--> main.rs:3:5
|
3 | (0).. => (),
| ^ ^
|
help: remove these parentheses
|
3 - (0).. => (),
3 + 0.. => (),
|
```
This sets the groundwork for #118625, which will extend the recovery to expressions like `(0 + 1)..` where users may tend to add parentheses to avoid dealing with precedence.
---
```@rustbot``` label +A-parser +A-patterns +A-diagnostics
Make `derive(Trait)` suggestion more accurate
Only suggest `derive(PartialEq)` when both LHS and RHS types are the same, otherwise the suggestion is not useful.
macro_rules: Less hacky heuristic for using `tt` metavariable spans
See the big comment on `fn maybe_use_metavar_location` for a more detailed description.
Make named_asm_labels lint not trigger on unicode and trigger on format args
Someone showed me some cursed code that used format args to create named labels, and rustc wasn't linting on that. Additionally while fixing that, I noticed that Unicode alphabetic characters were being used as part of labels, when they are not actually permitted in labels.
r? ```@Amanieu```
Note the parentheses in the last suggestion:
```
error[E0277]: the size for values of type `(dyn Foo + Send + 'static)` cannot be known at compilation time
--> $DIR/not-on-bare-trait.rs:7:8
|
LL | fn foo(_x: Foo + Send) {
| ^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `(dyn Foo + Send + 'static)`
= help: unsized fn params are gated as an unstable feature
help: you can use `impl Trait` as the argument type
|
LL | fn foo(_x: impl Foo + Send) {
| ++++
help: function arguments must have a statically known size, borrowed types always have a known size
|
LL | fn foo(_x: &(Foo + Send)) {
| ++ +
```
Add the following suggestions:
```
error[E0782]: trait objects must include the `dyn` keyword
--> $DIR/not-on-bare-trait-2021.rs:11:11
|
LL | fn bar(x: Foo) -> Foo {
| ^^^
|
help: use a generic type parameter, constrained by the trait `Foo`
|
LL | fn bar<T: Foo>(x: T) -> Foo {
| ++++++++ ~
help: you can also use `impl Foo`, but users won't be able to specify the type paramer when calling the `fn`, having to rely exclusively on type inference
|
LL | fn bar(x: impl Foo) -> Foo {
| ++++
help: alternatively, use a trait object to accept any type that implements `Foo`, accessing its methods at runtime using dynamic dispatch
|
LL | fn bar(x: &dyn Foo) -> Foo {
| ++++
error[E0782]: trait objects must include the `dyn` keyword
--> $DIR/not-on-bare-trait-2021.rs:11:19
|
LL | fn bar(x: Foo) -> Foo {
| ^^^
|
help: use `impl Foo` to return an opaque type, as long as you return a single underlying type
|
LL | fn bar(x: Foo) -> impl Foo {
| ++++
help: alternatively, you can return an owned trait object
|
LL | fn bar(x: Foo) -> Box<dyn Foo> {
| +++++++ +
```