Terminals supporting the OSC8 Hyperlink Extension can support inline
anchors where the text is user defineable but clicking on it opens a
browser to a specified URLs, just like `<a href="URL">` does in HTML.
https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
correctly update goals in the cache
we may want to actually write the response for our goal into the provisional or global cache instead of simply using the result from the last iteration '^^
r? ```@rust-lang/initiative-trait-system-refactor```
Now that the compiler accepts "-Z instrument-xray" option only when
targeting one of the supported targets, make sure to not run the
codegen tests where the compiler will fail.
Like with other compiletests, we don't have access to internals,
so simply hardcode a list of supported architectures here.
This is somewhat important because LLVM enables the pass based on
target architecture, but support by the target OS also matters.
For example, XRay attributes are processed by codegen for macOS
targets, but Apple linker fails to process relocations in XRay
data sections, so the feature as a whole is not supported there
for the time being.
Make `derive_const` derive properly const-if-const impls
Fixes#107774Fixes#107666
Also fixes rendering of const-if-const bounds in pretty printing.
r? ```@oli-obk``` or ```@fee1-dead```
Remove astconv usage in diagnostic
Fixes#107775
Location of the test sucks, I know, but I needed to put it somewhere 😓
The issue here is that the root cause of the issue has nothing to do with what's being tested, so I couldn't really give it a better name. Oh well.
Rename `PointerSized` to `PointerLike`
The old name was unnecessarily vague. This PR renames a nightly language feature that I added, so I don't think it needs any additional approval, though anyone can feel free to speak up if you dislike the rename.
It's still unsatisfying that we don't the user which of {size, alignment} is wrong, but this trait really is just a stepping stone for a more generalized mechanism to create `dyn*`, just meant for nightly testing, so I don't think it really deserves additional diagnostic machinery for now.
Fixes#107696, cc ``@RalfJung``
r? ``@eholk``
Rollup of 8 pull requests
Successful merges:
- #100599 (Add compiler error E0523 long description and test)
- #107471 (rustdoc: do not include empty default-settings tag in HTML)
- #107555 (Modify existing bounds if they exist)
- #107662 (Turn projections into copies in CopyProp.)
- #107695 (Add test for Future inflating arg size to 3x )
- #107700 (Run the tools builder on all PRs)
- #107706 (Mark 'atomic_mut_ptr' methods const)
- #107709 (Fix problem noticed in PR106859 with char -> u8 suggestion)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Fix problem noticed in PR106859 with char -> u8 suggestion
HN reader `@ayosec` noticed that my #106859 a few weeks back, malfunctions if you have a Unicode escape, the code suggested b'\u{0}' if you tried to use '\u{0}' where a byte should be, when of course b'\u{0}' is not a byte literal, regardless of the codepoint you can't write Unicode escapes in a byte literal at all.
My proposed fix here just checks that the "character" you wrote is fewer than 5 bytes, thus allowing \x7F and similar escapes but conveniently forbidding even the smallest Unicode escape \u{0} before offering the suggestion as before.
I have provided an updated test which includes examples which do and don't work because of this additional rule.
Modify existing bounds if they exist
Fixes#107335.
This implementation is kinda gross but I don't really see a better way to do it.
This primarily does two things: Modifies `suggest_constraining_type_param` to accept a new parameter that indicates a span to be replaced instead of added, if presented, and limit the additive suggestions to either suggest a new bound on an existing bound (see newly added unit test) or add the generics argument if a generics argument wasn't found.
The former change is required to retain the capability to add an entirely new bounds if it was entirely omitted.
r? ``@compiler-errors``
Fix suggestions rendering when the diff span is multiline
Fixes#92741
cc `@estebank`
I think, I finally fixed. I still want to go back and try to clean up the code a bit. I'm open to suggestions.
Some examples of the new suggestions:
```
help: consider removing the borrow
|
2 - &
|
```
```
help: consider removing the borrow
|
2 - &
3 - mut
|
```
```
help: consider removing the borrow
|
2 - &
3 - mut if true { true } else { false }
2 + if true { true } else { false }
|
```
Should we add a test to ensure this behavior doesn't disappear in the future?
This adds one more test that should track improvements to generator
layout, like #62958 and #62575.
In particular, this test highlights suboptimal layout, as the storage
for the argument future is not being reused across its usage as `upvar`,
`local` and `awaitee` (being polled to completion).
Sort Generator `print-type-sizes` according to their yield points
Especially when trying to diagnose runaway future sizes, it might be more intuitive to sort the variants according to the control flow (aka their yield points) rather than the size of the variants.
Refine error spans for "The trait bound `T: Trait` is not satisfied" when passing literal structs/tuples
This PR adds a new heuristic which refines the error span reported for "`T: Trait` is not satisfied" errors, by "drilling down" into individual fields of structs/enums/tuples to point to the "problematic" value.
Here's a self-contained example of the difference in error span:
```rs
struct Burrito<Filling> {
filling: Filling,
}
impl <Filling: Delicious> Delicious for Burrito<Filling> {}
fn eat_delicious_food<Food: Delicious>(food: Food) {}
fn will_type_error() {
eat_delicious_food(Burrito { filling: Kale });
// ^~~~~~~~~~~~~~~~~~~~~~~~~ (before) The trait bound `Kale: Delicious` is not satisfied
// ^~~~ (after) The trait bound `Kale: Delicious` is not satisfied
}
```
(kale is fine, this is just a silly food-based example)
Before this PR, the error span is identified as the entire argument to the generic function `eat_delicious_food`. However, since only `Kale` is the "problematic" part, we can point at it specifically. In particular, the primary error message itself mentions the missing `Kale: Delicious` trait bound, so it's much clearer if this part is called out explicitly.
---
The _existing_ heuristic tries to label the right function argument in `point_at_arg_if_possible`. It goes something like this:
- Look at the broken base trait `Food: Delicious` and find which generics it mentions (in this case, only `Food`)
- Look at the parameter type definitions and find which of them mention `Filling` (in this case, only `food`)
- If there is exactly one relevant parameter, label the corresponding argument with the error span, instead of the entire call
This PR extends this heuristic by further refining the resulting expression span in the new `point_at_specific_expr_if_possible` function. For each `impl` in the (broken) chain, we apply the following strategy:
The strategy to determine this span involves connecting information about our generic `impl`
with information about our (struct) type and the (struct) literal expression:
- Find the `impl` (`impl <Filling: Delicious> Delicious for Burrito<Filling>`)
that links our obligation (`Kale: Delicious`) with the parent obligation (`Burrito<Kale>: Delicious`)
- Find the "original" predicate constraint in the impl (`Filling: Delicious`) which produced our obligation.
- Find all of the generics that are mentioned in the predicate (`Filling`).
- Examine the `Self` type in the `impl`, and see which of its type argument(s) mention any of those generics.
- Examing the definition for the `Self` type, and identify (for each of its variants) if there's a unique field
which uses those generic arguments.
- If there is a unique field mentioning the "blameable" arguments, use that field for the error span.
Before we do any of this logic, we recursively call `point_at_specific_expr_if_possible` on the parent
obligation. Hence we refine the `expr` "outwards-in" and bail at the first kind of expression/impl we don't recognize.
This function returns a `Result<&Expr, &Expr>` - either way, it returns the `Expr` whose span should be
reported as an error. If it is `Ok`, then it means it refined successfull. If it is `Err`, then it may be
only a partial success - but it cannot be refined even further.
---
I added a new test file which exercises this new behavior. A few existing tests were affected, since their error spans are now different. In one case, this leads to a different code suggestion for the autofix - although the new suggestion isn't _wrong_, it is different from what used to be.
This change doesn't create any new errors or remove any existing ones, it just adjusts the spans where they're presented.
---
Some considerations: right now, this check occurs in addition to some similar logic in `adjust_fulfillment_error_for_expr_obligation` function, which tidies up various kinds of error spans (not just trait-fulfillment error). It's possible that this new code would be better integrated into that function (or another one) - but I haven't looked into this yet.
Although this code only occurs when there's a type error, it's definitely not as efficient as possible. In particular, there are definitely some cases where it degrades to quadratic performance (e.g. for a trait `impl` with 100+ generic parameters or 100 levels deep nesting of generic types). I'm not sure if these are realistic enough to worry about optimizing yet.
There's also still a lot of repetition in some of the logic, where the behavior for different types (namely, `struct` vs `enum` variant) is _similar_ but not the same.
---
I think the biggest win here is better targeting for tuples; in particular, if you're using tuples + traits to express variadic-like functions, the compiler can't tell you which part of a tuple has the wrong type, since the span will cover the entire argument. This change allows the individual field in the tuple to be highlighted, as in this example:
```
// NEW
LL | want(Wrapper { value: (3, q) });
| ---- ^ the trait `T3` is not implemented for `Q`
// OLD
LL | want(Wrapper { value: (3, q) });
| ---- ^~~~~~~~~~~~~~~~~~~~~~~~~ the trait `T3` is not implemented for `Q`
```
Especially with large tuples, the existing error spans are not very effective at quickly narrowing down the source of the problem.
Rollup of 5 pull requests
Successful merges:
- #107553 (Suggest std::ptr::null if literal 0 is given to a raw pointer function argument)
- #107580 (Recover from lifetimes with default lifetimes in generic args)
- #107669 (rustdoc: combine duplicate rules in ayu CSS)
- #107685 (Suggest adding a return type for async functions)
- #107687 (Adapt SROA MIR opt for aggregated MIR)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Suggest std::ptr::null if literal 0 is given to a raw pointer function argument
Implementation feels a little sus (we're parsing the span for a `0`) but it seems to fall in line the string-expected-found-char condition right above this check, so I think it's fine.
Feedback appreciated on help text? I think it's consistent but it does sound a little awkward maybe?
Fixes#107517
Adds the extended error documentation for E0523 to indicate that the
error is no longer produced by the compiler.
Update the E0464 documentation to include example code that produces the
error.
Remove the error message E0523 from the compiler and replace it with an
internal compiler error.
don't point at nonexisting code beyond EOF when warning about delims
Previously we would show this:
```
warning: unnecessary braces around block return value
--> /tmp/bad.rs:1:8
|
1 | fn a(){{{
| ^ ^
|
= note: `#[warn(unused_braces)]` on by default
help: remove these braces
|
1 - fn a(){{{
1 + fn a(){{
|
```
which is now hidden in this case.
We would create a span spanning between the pair of redundant {}s but there is only EOF instead of the `}` so we would previously point at nothing. This would cause the debug assertion ice to trigger. I would have loved to just only point at the second delim and say "you can remove that" but I'm not sure how to do that without refactoring the entire diagnostic which seems tricky. :( But given that this does not seem to regress any other tests we have, I think this edge-casey enough be acceptable.
Fixes https://github.com/rust-lang/rust/issues/107423
r? `@compiler-errors`
Especially when trying to diagnose runaway future sizes, it might be
more intuitive to sort the variants according to the control flow
(aka their yield points) rather than the size of the variants.
Previously we would show this:
```
warning: unnecessary braces around block return value
--> /tmp/bad.rs:1:8
|
1 | fn a(){{{
| ^ ^
|
= note: `#[warn(unused_braces)]` on by default
help: remove these braces
|
1 - fn a(){{{
1 + fn a(){{
|
```
which is now hidden in this case.
We would create a span spanning between the pair of redundant {}s but there is only EOF instead of the `}` so we would previously point at nothing.
This would cause the debug assertion ice to trigger.
I would have loved to just only point at the second delim and say "you can remove that" but I'm not sure how to do that without refactoring the entire diagnostic which seems tricky. :(
But given that this does not seem to regress any other tests we have, I think this edge-casey enough be acceptable.
Fixes https://github.com/rust-lang/rust/issues/107423
r? @compiler-errors
Fix suggestion for coercing Option<&String> to Option<&str>
Fixes#107604
This also makes the diagnostic `MachineApplicable`, and runs `rustfix` to check we're not producing incorrect code.
``@rustbot`` label +A-diagnostics
Don't cause a cycle when formatting query description that references a FnDef
When a function returns `-> _`, we use typeck to compute what the resulting type of the body _should_ be. If we call another query inside of typeck and hit a cycle error, we attempt to report the cycle error which requires us to compute all of the query descriptions for the stack.
However, if one of the queries in that cycle has a query description that references this function as a FnDef type, we'll cause a *second* cycle error from within the cycle error reporting code, since rendering a FnDef requires us to compute its signature. This causes an unwrap to ICE, since during the *second* cycle reporting code, we try to look for a job that isn't in the active jobs list.
We can avoid this by using `with_no_queries!` when computing these query descriptions.
Fixes#107089
The only drawback is that the rendering of opaque types in cycles regresses a bit :| I'm open to alternate suggestions about how we may handle this...
Emit warnings on unused parens in index expressions
Fixes: #96606.
I am not sure what the best term for "index expression" is. Is there a better term we could use?
Don't generate unecessary `&&self.field` in deriving Debug
Since unsized fields may only be the last one in a struct, we only need to generate a double reference (`&&self.field`) for the final one.
cc `@nnethercote`
Suggest `{var:?}` when finding `{?:var}` in inline format strings
Link to issue: https://github.com/rust-lang/rust/issues/106572
This is my first PR to this project, so hopefully I can get some good pointers with me from the first PR.
Currently my idea was to test out whether or not this is the correct solution to this issue and then hopefully expand upon the idea to not only work for Debug formatting but for all of them. If this is a valid solution, I will create a new issue to give a better error message to a broader range of wrong-order formatting.
Erase regions before doing uninhabited check in borrowck
~Also, fingerprint query keys/values when debug assertions are enabled. This should make it easier to check for issues like this without `-Cincremental`, and make UI tests a bit cleaner.~ edit: moving that to a separate PR
Fixes#107505
Improve diagnostic for missing space in range pattern
Improves the diagnostic in #107425 by turning it into a note explaining the parsing issue.
r? `@compiler-errors`
Revert "Teach parser to understand fake anonymous enum syntax" and related commits
anonymous enum types are currently ambiguous in positions like:
* `|` operator: `a as fn() -> B | C`
* closure args: `|_: as fn() -> A | B`
I first tried to thread around `RecoverAnonEnum` into all these positions, but the resulting complexity in the compiler is IMO not worth it, or at least worth a bit more thinking time. In the mean time, let's revert this syntax for now, so we can go back to the drawing board.
Fixes#107461
cc: `@estebank` `@cjgillot` #106960
---
### Squashed revert commits:
Revert "review comment: Remove AST AnonTy"
This reverts commit 020cca8d36.
Revert "Ensure macros are not affected"
This reverts commit 12d18e4031.
Revert "Emit fewer errors on patterns with possible type ascription"
This reverts commit c847a01a3b.
Revert "Teach parser to understand fake anonymous enum syntax"
This reverts commit 2d82420665.
Revert "review comment: Remove AST AnonTy"
This reverts commit 020cca8d36.
Revert "Ensure macros are not affected"
This reverts commit 12d18e4031.
Revert "Emit fewer errors on patterns with possible type ascription"
This reverts commit c847a01a3b.
Revert "Teach parser to understand fake anonymous enum syntax"
This reverts commit 2d82420665.
Add proc-macro boilerplate to crt-static test
I was seeing this failure when running ui tests with with a `-Cpanic=abort` stdlib targeting fuchsia:
```
---- [ui] tests/ui/proc-macro/crt-static.rs stdout ----
normalized stderr:
warning: building proc macro crate with `panic=abort` may crash the compiler should the proc-macro panic
warning: 1 warning emitted
The actual stderr differed from the expected stderr.
```
`force-host` was enough to stop it from running/failing, not sure if I should also add `needs-unwind`?
Fix syntax in `-Zunpretty-expanded` output for derived `PartialEq`.
If you do `derive(PartialEq)` on a packed struct, the output shown by `-Zunpretty=expanded` includes expressions like this:
```
{ self.x } == { other.x }
```
This is invalid syntax. This doesn't break compilation, because the AST nodes are constructed within the compiler. But it does mean anyone using `-Zunpretty=expanded` output as a guide for hand-written impls could get a nasty surprise.
This commit fixes things by instead using this form:
```
({ self.x }) == ({ other.x })
```
r? ``@RalfJung``
Remove confusing 'while checking' note from opaque future type mismatches
Maybe I'm just misinterpreting the wording of the note. The only value I can see in this note is that it points out where the async's opaque future is coming from, but the way it's doing it is misleading IMO.
For example:
```rust
note: while checking the return type of the `async fn`
--> $DIR/dont-suggest-missing-await.rs:7:24
|
LL | async fn make_u32() -> u32 {
| ^^^ checked the `Output` of this `async fn`, found opaque type
```
We point at the type `u32` in the HIR, but then say "found opaque type". We also say "while checking"... but we're typechecking a totally different function when we get this type mismatch!
r? ``@estebank`` but feel free to reassign and/or take your time reviewing this. I'd be inclined to also discuss reworking the presentation of this type mismatch to restore some of these labels in a way that makes it more clear what it's trying to point out.
The check previously matched this, and suggested adding a missing
`struct`:
pub Foo(...):
It was probably intended to match this instead (semicolon instead of
colon):
pub Foo(...);
Strengthen validation of FFI attributes
Previously, `codegen_attrs` validated the attributes `#[ffi_pure]`, `#[ffi_const]`, and `#[ffi_returns_twice]` to make sure that they were only used on foreign functions. However, this validation was insufficient in two ways:
1. `codegen_attrs` only sees items for which code must be generated, so it was unable to raise errors when the attribute was incorrectly applied to macros and the like.
2. the validation code only checked that the item with the attr was foreign, but not that it was a foreign function, allowing these attributes to be applied to foreign statics as well.
This PR moves the validation to `check_attr`, which sees all items. It additionally changes the validation to ensure that the attribute's target is `Target::ForeignFunction`, only allowing the attributes on foreign functions and not foreign statics. Because these attributes are unstable, there is no risk for backwards compatibility. The changes also ending up making the code much easier to read.
This PR is best reviewed commit by commit. Additionally, I was considering moving the tests to the `attribute` subdirectory, to get them out of the general UI directory. I could do that as part of this PR or a follow-up, as the reviewer prefers.
CC: #58328, #58329
Do not depend on Generator trait when deducing closure signature
1. Do not depend on `Generator` trait when deducing closure signature.
2. Compare the name of the `Generator::Return` associated item, rather than its order in the trait. Seems more stable this way.
Fixing confusion between mod and remainder
Like many programming languages, rust too confuses remainder and modulus. The `%` operator and the associated `Rem` trait is (as the trait name suggests) the remainder, but since most people are linguistically more familiar with the modulus the documentation sometimes claims otherwise. This PR tries to fix this problem in rustc.
If you do `derive(PartialEq)` on a packed struct, the output shown by
`-Zunpretty=expanded` includes expressions like this:
```
{ self.x } == { other.x }
```
This is invalid syntax. This doesn't break compilation, because the AST
nodes are constructed within the compiler. But it does mean anyone using
`-Zunpretty=expanded` output as a guide for hand-written impls could get
a nasty surprise.
This commit fixes things by instead using this form:
```
({ self.x }) == ({ other.x })
```
Modify primary span label for E0308
Looking at the reactions to https://hachyderm.io/`@ekuber/109622160673605438,` a lot of people seem to have trouble understanding the current output, where the primary span label on type errors talks about the specific types that diverged, but these can be deeply nested type parameters. Because of that we could see "expected i32, found u32" in the label while the note said "expected Vec<i32>, found Vec<u32>". This understandably confuses people. I believe that once people learn to read these errors it starts to make more sense, but this PR changes the output to be more in line with what people might expect, without sacrificing terseness.
Fix#68220.
Use `ObligationCtxt::new_in_snapshot` in `satisfied_from_param_env`
We can evaluate nested `ConstEvaluatable` obligations in an evaluation probe, which will ICE if we use `ObligationCtxt::new`.
Fixes#107474Fixes#106666
r? `@BoxyUwU` but feel free to reassign
cc `@JulianKnodt` who i think added this assertion code
Not sure if the rustdoc test is needed, but can't hurt. They're the same root cause, though.
Implement unsizing in the new trait solver
This makes hello world compile! Ignore the first commit, that's just #107146 which is waiting on merge.
I'll leave some comments inline about design choices that might be debatable.
r? `@lcnr` (until we have a new trait solver reviewer group...)
Fix invalid float literal suggestions when recovering an integer
Only suggest adding a zero to integers with a preceding dot when the change will result in a valid floating point literal.
For example, `.0x0` should not be turned into `0.0x0`.
r? nnethercote
Only suggest adding a zero to integers with a preceding dot when the change will
result in a valid floating point literal.
For example, `.0x0` should not be turned into `0.0x0`.
The original tweet in the chain linked to, and thus the through line of links back to Anna's tweet where she named the turbofish (https://web.archive.org/web/20210911061514/https://twitter.com/whoisaldeka/status/914914008225816576) are lost as the user whoisaldeka has deleted their twitter account.
Switching to an archive link preserves this through line, allowing someone to browse back to see the point at which Anna created the turbofish, as was the original intent of including this context.
Don't re-export private/unstable ArgumentV1 from `alloc`.
The `alloc::fmt::ArgumentV1` re-export was marked as `#[stable]` even though the original `core::fmt::ArgumentV1` is `#[unstable]` (and `#[doc(hidden)]`).
(It wasn't usable though:
```
error[E0658]: use of unstable library feature 'fmt_internals': internal to format_args!
--> src/main.rs:4:12
|
4 | let _: alloc::fmt::ArgumentV1 = todo!();
| ^^^^^^^^^^^^^^^^^^^^^^
|
= help: add `#![feature(fmt_internals)]` to the crate attributes to enable
```
)
Part of #99012
Currently, deriving on packed structs has some non-trivial limitations,
related to the fact that taking references on unaligned fields is UB.
The current approach to field accesses in derived code:
- Normal case: `&self.0`
- In a packed struct that derives `Copy`: `&{self.0}`
- In a packed struct that doesn't derive `Copy`: `&self.0`
Plus, we disallow deriving any builtin traits other than `Default` for any
packed generic type, because it's possible that there might be
misaligned fields. This is a fairly broad restriction.
Plus, we disallow deriving any builtin traits other than `Default` for most
packed types that don't derive `Copy`. (The exceptions are those where the
alignments inherently satisfy the packing, e.g. in a type with
`repr(packed(N))` where all the fields have alignments of `N` or less
anyway. Such types are pretty strange, because the `packed` attribute is
not having any effect.)
This commit introduces a new, simpler approach to field accesses:
- Normal case: `&self.0`
- In a packed struct: `&{self.0}`
In the latter case, this requires that all fields impl `Copy`, which is
a new restriction. This means that the following example compiles under
the old approach and doesn't compile under the new approach.
```
#[derive(Debug)]
struct NonCopy(u8);
#[derive(Debug)
#[repr(packed)]
struct MyType(NonCopy);
```
(Note that the old approach's support for cases like this was brittle.
Changing the `u8` to a `u16` would be enough to stop it working. So not
much capability is lost here.)
However, the other constraints from the old rules are removed. We can now
derive builtin traits for packed generic structs like this:
```
trait Trait { type A; }
#[derive(Hash)]
#[repr(packed)]
pub struct Foo<T: Trait>(T, T::A);
```
To allow this, we add a `T: Copy` bound in the derived impl and a `T::A:
Copy` bound in where clauses. So `T` and `T::A` must impl `Copy`.
We can now also derive builtin traits for packed structs that don't derive
`Copy`, so long as the fields impl `Copy`:
```
#[derive(Hash)]
#[repr(packed)]
pub struct Foo(u32);
```
This includes types that hand-impl `Copy` rather than deriving it, such as the
following, that show up in winapi-0.2:
```
#[derive(Clone)]
#[repr(packed)]
struct MyType(i32);
impl Copy for MyType {}
```
The new approach is simpler to understand and implement, and it avoids
the need for the `unsafe_derive_on_repr_packed` check.
One exception is required for backwards-compatibility: we allow `[u8]`
fields for now. There is a new lint for this,
`byte_slice_in_packed_struct_with_derive`.
Output tree representation on thir-tree
The current output of `-Zunpretty=thir-tree` is really cumbersome to work with, using an actual tree representation should make it easier to see what the thir looks like.
Insert whitespace to avoid ident concatenation in suggestion
This PR tweaks the suggestion of removing misplaced parentheses around trait bounds so as to avoid concatenating two identifiers. Although subtle, this should make outputs less surprising especially when applying the `MachineApplicable` suggestions automatically.
Skip possible where_clause_object_safety lints when checking `multiple_supertrait_upcastable`
Fix#106247
To achieve this, I lifted the `WhereClauseReferencesSelf` out from `object_safety_violations` and move it into `is_object_safe` (which is changed to a new query).
cc `@dtolnay`
r? `@compiler-errors`
Rollup of 8 pull requests
Successful merges:
- #106618 (Disable `linux_ext` in wasm32 and fortanix rustdoc builds.)
- #107097 (Fix def-use dominance check)
- #107154 (library/std/sys_common: Define MIN_ALIGN for m68k-unknown-linux-gnu)
- #107397 (Gracefully exit if --keep-stage flag is used on a clean source tree)
- #107401 (remove the usize field from CandidateSource::AliasBound)
- #107413 (make more pleasant to read)
- #107422 (Also erase substs for new infcx in pin move error)
- #107425 (Check for missing space between fat arrow and range pattern)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Check for missing space between fat arrow and range pattern
Fixes#107420
Ideally we wouldn't emit an error about expecting `=>` etc., but I'm not sure how to recover from this.
`@rustbot` label +A-diagnostics
Also erase substs for new infcx in pin move error
The code originally correctly erased the regions of the type it passed to the newly created infcx. But after the `fn_sig` query was made to return an `EarlyBinder<T>`, some substs that were around were substituted there without erasing their regions. They were then passed into the newly cerated infcx, which caused the ICE.
Fixes#107419
r? compiler-errors who reviewed the original PR adding this diagnostic
Fix def-use dominance check
A definition does not dominate a use in the same statement. For example
in MIR generated for compound assignment x += a (when overflow checks
are disabled).
Use stable metric for const eval limit instead of current terminator-based logic
This patch adds a `MirPass` that inserts a new MIR instruction `ConstEvalCounter` to any loops and function calls in the CFG. This instruction is used during Const Eval to count against the `const_eval_limit`, and emit the `StepLimitReached` error, replacing the current logic which uses Terminators only.
The new method of counting loops and function calls should be more stable across compiler versions (i.e., not cause crates that compiled successfully before, to no longer compile when changes to the MIR generation/optimization are made).
Also see: #103877
Special-case deriving `PartialOrd` for enums with dataless variants
I was able to get slightly better codegen by flipping the derived `PartialOrd` logic for two-variant enums. I also tried to document the implementation of the derive macro to make the special-case logic a little clearer.
```rs
#[derive(PartialEq, PartialOrd)]
pub enum A<T> {
A,
B(T)
}
```
```diff
impl<T: ::core::cmp::PartialOrd> ::core::cmp::PartialOrd for A<T> {
#[inline]
fn partial_cmp(
&self,
other: &A<T>,
) -> ::core::option::Option<::core::cmp::Ordering> {
let __self_tag = ::core::intrinsics::discriminant_value(self);
let __arg1_tag = ::core::intrinsics::discriminant_value(other);
- match ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag) {
- ::core::option::Option::Some(::core::cmp::Ordering::Equal) => {
- match (self, other) {
- (A::B(__self_0), A::B(__arg1_0)) => {
- ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0)
- }
- _ => ::core::option::Option::Some(::core::cmp::Ordering::Equal),
- }
+ match (self, other) {
+ (A::B(__self_0), A::B(__arg1_0)) => {
+ ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0)
}
- cmp => cmp,
+ _ => ::core::cmp::PartialOrd::partial_cmp(&__self_tag, &__arg1_tag),
}
}
}
```
Godbolt: [Current](https://godbolt.org/z/GYjEzG1T8), [New](https://godbolt.org/z/GoK78qx15)
I'm not sure how common a case comparing two enums like this (such as `Option`) is, and if it's worth the slowdown of adding a special case to the derive. If it causes overall regressions it might be worth just manually implementing this for `Option`.
The code originally correctly erased the regions of the type it passed
to the newly created infcx. But after the `fn_sig` query was made to
return an `EarlyBinder<T>`, some substs that were around were
substituted there without erasing their regions. They were then passed
into the newly cerated infcx, which caused the ICE.
Improve unexpected close and mismatch delimiter hint in TokenTreesReader
Fixes#103882Fixes#68987Fixes#69259
The inner indentation mismatching will be covered by outer block, the new added function `report_error_prone_delim_block` will find out the error prone candidates for reporting.
Remove overlapping parts of multipart suggestions
This PR adds a debug assertion that the parts of a single substitution cannot overlap, fixes a overlapping substitution from the testsuite, and fixes https://github.com/rust-lang/rust/issues/106870.
Note that a single suggestion can still have multiple overlapping substitutions / possible edits, we just don't suggest overlapping replacements in a single edit anymore.
I've also included a fix for an unrelated bug where rustfix for `explicit_outlives_requirements` would produce multiple trailing commas for a where clause.
internally change regions to be covariant
Surprisingly, we consider the reference type `&'a T` to be contravaraint in its lifetime parameter. This is confusing and conflicts with the documentation we have in the reference, rustnomicon, and rustc-dev-guide. This also arguably not the correct use of terminology since we can use `&'static u8` in a place where `&' a u8` is expected, this implies that `&'static u8 <: &' a u8` and consequently `'static <: ' a`, hence covariance.
Because of this, when relating two types, we used to switch the argument positions in a confusing way:
`Subtype(&'a u8 <: &'b u8) => Subtype('b <: 'a) => Outlives('a: 'b) => RegionSubRegion('b <= 'a)`
The reason for the current behavior is probably that we wanted `Subtype('b <: 'a)` and `RegionSubRegion('b <= 'a)` to be equivalent, but I don' t think this is a good reason since these relations are sufficiently different in that the first is a relation in the subtyping lattice and is intrinsic to the type-systems, while the the second relation is an implementation detail of regionck.
This PR changes this behavior to use covariance, so..
`Subtype(&'a u8 <: &'b u8) => Subtype('a <: 'b) => Outlives('a: 'b) => RegionSubRegion('b <= 'a) `
Resolves#103676
r? `@lcnr`
Correct suggestions for closure arguments that need a borrow
Fixes#107301 by dealing with binders correctly
Fixes another issue where we were suggesting adding just `&` when we expected `&mut _` in a closure arg
Recover from more const arguments that are not wrapped in curly braces
Recover from some array, borrow, tuple & arithmetic expressions in const argument positions that lack curly braces and provide a suggestion to fix the issue continuing where #92884 left off. Examples of such expressions: `[]`, `[0]`, `[1, 2]`, `[0; 0xff]`, `&9`, `("", 0)` and `(1 + 2) * 3` (we previously did not recover from them).
I am not entirely happy with my current solution because the code that recovers from `[0]` (coinciding with a malformed slice type) and `[0; 0]` (coinciding with a malformed array type) is quite fragile as the aforementioned snippets are actually successfully parsed as types by `parse_ty` since it itself already recovers from them (returning `[⟨error⟩]` and `[⟨error⟩; 0]` respectively) meaning I have to manually look for `TyKind::Err`s and construct a separate diagnostic for the suggestion to attach to (thereby emitting two diagnostics in total).
Fixes#81698.
`@rustbot` label A-diagnostics
r? diagnostics
A definition does not dominate a use in the same statement. For example
in MIR generated for compound assignment x += a (when overflow checks
are disabled).
make `output_filenames` a real query
part of #105462
This may be a perf regression and is not obviously the right way forward. We may store this information in the resolver after freezing it for example.
Rollup of 8 pull requests
Successful merges:
- #106904 (Preserve split DWARF files when building archives.)
- #106971 (Handle diagnostics customization on the fluent side (for one specific diagnostic))
- #106978 (Migrate mir_build's borrow conflicts)
- #107150 (`ty::tls` cleanups)
- #107168 (Use a type-alias-impl-trait in `ObligationForest`)
- #107189 (Encode info for Adt in a single place.)
- #107322 (Custom mir: Add support for some remaining, easy to support constructs)
- #107323 (Disable ConstGoto opt in cleanup blocks)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Migrate mir_build's borrow conflicts
This also changes the error message slightly, for two reasons:
- I'm not a fan of saying "value borrowed, by `x`, here"
- it simplifies the error implementation significantly.
Move format_args!() into AST (and expand it during AST lowering)
Implements https://github.com/rust-lang/compiler-team/issues/541
This moves FormatArgs from rustc_builtin_macros to rustc_ast_lowering. For now, the end result is the same. But this allows for future changes to do smarter things with format_args!(). It also allows Clippy to directly access the ast::FormatArgs, making things a lot easier.
This change turns the format args types into lang items. The builtin macro used to refer to them by their path. After this change, the path is no longer relevant, making it easier to make changes in `core`.
This updates clippy to use the new language items, but this doesn't yet make clippy use the ast::FormatArgs structure that's now available. That should be done after this is merged.
Use `can_eq` to compare types for default assoc type error
This correctly handles inference variables like `{integer}`. I had to move all of this `note_and_explain` code to `rustc_infer`, it made no sense for it to be in `rustc_middle` anyways.
The commits are reviewed separately.
Fixes#106968
impl DispatchFromDyn for Cell and UnsafeCell
After some fruitful discussion on [Internals](https://internals.rust-lang.org/t/impl-dispatchfromdyn-for-cell-2/16520) here's my first PR to rust-lang/rust 🎉
Please let me know if there's something I missed.
This adds `DispatchFromDyn` impls for `Cell`, `UnsafeCell` and `SyncUnsafeCell`.
An existing test is also expanded to test the `Cell` impl (which requires the `UnsafeCell` impl)
The different `RefCell` types can not implement `DispatchFromDyn` since they have more than one (non ZST) field.
**Edit:**
### What:
These changes allow one to make types like `MyRc`(code below), to be object safe method receivers after implementing `DispatchFromDyn` and `Deref` for them.
This allows for code like this:
```rust
struct MyRc<T: ?Sized>(Cell<NonNull<RcBox<T>>>);
/* impls for DispatchFromDyn, CoerceUnsized and Deref for MyRc*/
trait Trait {
fn foo(self: MyRc<Self>);
}
let impls_trait = ...;
let rc = MyRc::new(impls_trait) as MyRc<dyn Trait>;
rc.foo();
```
Note: `Cell` and `UnsafeCell` won't directly become valid method receivers since they don't implement `Deref`. Making use of these changes requires a wrapper type and nightly features.
### Why:
A custom pointer type with interior mutability allows one to store extra information in the pointer itself.
These changes allow for such a type to be a method receiver.
### Examples:
My use case is a cycle aware custom `Rc` implementation that when dropping a cycle marks some references dangling.
On the [forum](https://internals.rust-lang.org/t/impl-dispatchfromdyn-for-cell/14762/8) andersk mentioned that they track if a `Gc` reference is rooted with an extra bit in the reference itself.
Fix escaping inference var ICE in `point_at_expr_source_of_inferred_type`
Fixes#107158
`point_at_expr_source_of_inferred_type` uses `lookup_probe` to adjust the self type of a method receiver -- but that method returns inference variables from inside a probe. That means that the ty vars are no longer valid, so we can't use any infcx methods on them.
Also, pass some extra span info to hack a quick solution to bad labels, resulting in this diagnostic improvement:
```rust
fn example2() {
let mut x = vec![1];
x.push("");
}
```
```diff
error[E0308]: mismatched types
--> src/main.rs:5:12
|
5 | x.push("");
| ---- ^^
| | |
| | expected integer, found `&str`
- | | this is of type `&'static str`, which causes `x` to be inferred as `Vec<{integer}>`
| arguments to this method are incorrect
```
(since that "which causes `x` to be inferred as `Vec<{integer}>` part is wrong)
r? `@estebank`
(we really should make this code better in general, cc #106590, but that's a bit bigger issue that needs some more thinking about)
Teach parser to understand fake anonymous enum syntax
Parse `Ty | OtherTy` in function argument and return types.
Parse type ascription in top level patterns.
Minimally address #100741.
Suggest using a lock for `*Cell: Sync` bounds
I mostly did this for `OnceCell<T>` at first because users will be confused to see that the `OnceCell<T>` in `std` isn't `Sync` but then extended it to `Cell<T>` and `RefCell<T>` as well.
Add hint for missing lifetime bound on trait object when type alias is used
Fix issue #103582.
The problem: When a type alias is used to specify the return type of the method in a trait impl, the suggestion for fixing the problem of "missing lifetime bound on trait object" of the trait impl will not be created. The issue caused by the code which searches for the return trait objects when constructing the hint suggestion is not able to find the trait objects since they are specified in the type alias path instead of the return path of the trait impl.
The solution: Trace the trait objects in the type alias path and provide them along with the alias span to generate the suggestion in case the type alias is used in return type of the method in the trait impl.
Add suggestion to remove if in let..else block
Adds an additional hint to failures where we encounter an else keyword while we're parsing an if-let expression.
This is likely that the user has accidentally mixed if-let and let..else together.
Fixes#103791.
- On compiler-error's suggestion of moving this lower down the stack,
along the path of `report_mismatched_types()`, which is used
by `rustc_hir_analysis` and `rustc_hir_typeck`.
- update ui tests, add test
- add suggestions for references to fn pointers
- modify `TypeErrCtxt::same_type_modulo_infer` to take `T: relate::Relate` instead of `Ty`
Adds an additional hint to failures where we encounter an else keyword
while we're parsing an if-let block.
This is likely that the user has accidentally mixed if-let and let...else
together.
remove error code from `E0789`, add UI test/docs
`E0789` shouldn't have an error code, it's explicitly internal-only and is tiny in scope. (I wonder if we can tighten the standard for this in the RFC?) I also added a UI test and error docs (done like `E0208`, they are "no longer emitted").
r? `@GuillaumeGomez` (shouldn't need a compiler review, it's pretty minor)
Consider doc(alias) when providing typo suggestions
This means that
```rust
impl Foo {
#[doc(alias = "quux")]
fn bar(&self) {}
}
fn main() {
(Foo {}).quux();
}
```
will suggest `bar`. This currently uses the "there is a method with a similar name" help text, because the point where we choose and emit a suggestion is different from where we gather the suggestions. Changes have mainly been made to the latter.
The selection code will now fall back to aliased candidates, but generally only if there is no candidate that matches based on the existing Levenshtein methodology.
Fixes#83968.
This means that
```rust
impl Foo {
#[doc(alias = "quux")]
fn bar(&self) {}
}
fn main() {
(Foo {}).quux();
}
```
will suggest `bar`. This currently uses the "there is a method with a
similar name" help text, because the point where we choose and emit a
suggestion is different from where we gather the suggestions. Changes
have mainly been made to the latter.
The selection code will now fall back to aliased candidates, but
generally only if there is no candidate that matches based on the
existing Levenshtein methodology.
Fixes#83968.
Rollup of 8 pull requests
Successful merges:
- #103418 (Add `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` to future-incompat report)
- #106113 (llvm-wrapper: adapt for LLVM API change)
- #106144 (Improve the documentation of `black_box`)
- #106578 (Label closure captures/generator locals that make opaque types recursive)
- #106749 (Update cc to 1.0.77)
- #106935 (Fix `SingleUseLifetime` ICE)
- #107015 (Re-enable building rust-analyzer on riscv64)
- #107029 (Add new bootstrap members to triagebot.toml)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Add `SEMICOLON_IN_EXPRESSIONS_FROM_MACROS` to future-incompat report
See https://github.com/rust-lang/rust/issues/79813 for a discussion of this lint. This has been warn-by-default for over a year, so adding it to the future-incompat report should help to find libraries that haven't yet updated.
Revert "Make PROC_MACRO_DERIVE_RESOLUTION_FALLBACK a hard error"
This reverts commit 7d82cadd97 aka PR #84022
I am doing this to buy us some time with respect to issue #106337 w.r.t. the 1.67 release.