Remove `NtIdent` and `NtLifetime`
This is one part of the bigger "remove `Nonterminal` and `TokenKind::Interpolated`" change drafted in #114647. More details in the individual commit messages.
r? `@petrochenkov`
Split out `ty::AliasTerm` from `ty::AliasTy`
Splitting out `AliasTerm` (for use in project and normalizes goals) and `AliasTy` (for use in `ty::Alias`)
r? lcnr
The extra span is now recorded in the new `TokenKind::NtIdent` and
`TokenKind::NtLifetime`. These both consist of a single token, and so
there's no operator precedence problems with inserting them directly
into the token stream.
The other way to do this would be to wrap the ident/lifetime in invisible
delimiters, but there's a lot of code that assumes an interpolated
ident/lifetime fits in a single token, and changing all that code to work with
invisible delimiters would have been a pain. (Maybe it could be done in a
follow-up.)
This change might not seem like much of a win, but it's a first step toward the
much bigger and long-desired removal of `Nonterminal` and
`TokenKind::Interpolated`. That change is big and complex enough that it's
worth doing this piece separately. (Indeed, this commit is based on part of a
late commit in #114647, a prior attempt at that big and complex change.)
This commit adds a new nonterminal `expr_2021` in macro patterns, and
`expr_fragment_specifier_2024` feature flag. For now, `expr` and
`expr_2021` are treated the same, but in future PRs we will update
`expr` to match to new grammar.
Co-authored-by: Vincezo Palazzo <vincenzopalazzodev@gmail.com>
Subtree sync for rustc_codegen_cranelift
A variety of bug fixes, added support for naked functions, a couple more vendor intrinsics implemented.
r? `@ghost`
`@rustbot` label +A-codegen +A-cranelift +T-compiler
Unify `Rvalue::Aggregate` paths in cg_ssa
In #123840 and #123886 I added two different codepaths for `Rvalue::Aggregate` in `cg_ssa`.
This merges them into one, since raw pointers are also immediates that can be built from the immediates of their "fields".
Avoid clone in `Comments::next`
`Comments::next`, in `rustc_ast_pretty`, has this comment:
```
// FIXME: This shouldn't probably clone lmao
```
The obvious thing to try is to return `Option<&Comment>` instead of `Option<Comment>`. But that leads to multiple borrows all over the place, because `Comments` must be borrowed from `PrintState` and then processed by `&mut self` methods within `PrintState`.
This PR instead rearranges things so that comments are consumed as they are used, preserving the `Option<Comment>` return type without requiring any cloning.
r? `@compiler-errors`
This span records the declaration of the metavariable in the LHS of the macro.
It's used in a couple of error messages. Unfortunately, it gets in the way of
the long-term goal of removing `TokenKind::Interpolated`. So this commit
removes it, which degrades a couple of (obscure) error messages but makes
things simpler and enables the next commit.
Remove `#[macro_use] extern crate rustc middle` from numerous crates
Because explicit importing of macros via `use` items is nicer (more standard and readable) than implicit importing via `#[macro_use]`. This PR mops up some cases I didn't get to in #124511.
r? `@saethlin`
The current way of stepping through each comment in `Comments` is a bit
weird. There is a `Vec<Comments>` and a `current` index, which is fine.
The `Comments::next` method clones the current comment but doesn't
advance `current`; the advancing instead happens in `print_comment`,
which is where each cloned comment is actually finally used (or not, in
some cases, if the comment fails to satisfy a predicate).
This commit makes things more iterator-like:
- `Comments::next` now advances `current` instead of `print_comment`.
- `Comments::peek` is added so you can inspect a comment and check a
predicate without consuming it.
- This requires splitting `PrintState::comments` into immutable and
mutable versions. The commit also moves the ref inside the `Option` of
the return type, to save callers from having to use `as_ref`/`as_mut`.
- It also requires adding `PrintState::peek_comment` alongside the
existing `PrintState::next_comment`. (The lifetimes in the signature
of `peek_comment` ended up more complex than I expected.)
We now have a neat separation between consuming (`next`) and
non-consuming (`peek`) uses of each comment. As well as being clearer,
this will facilitate the next commit that avoids unnecessary cloning.
Pretty-print let-else with added parenthesization when needed
Rustc used to produce invalid syntax for the following code, which is problematic because it means we cannot apply rustfmt to the output of `-Zunpretty=expanded`.
```rust
macro_rules! expr {
($e:expr) => { $e };
}
fn main() {
let _ = expr!(loop {}) else { return; };
}
```
```console
$ rustc repro.rs -Zunpretty=expanded | rustfmt
error: `loop...else` loops are not supported
--> <stdin>:9:29
|
9 | fn main() { let _ = loop {} else { return; }; }
| ---- ^^^^^^^^^^^^^^^^
| |
| `else` is attached to this loop
|
= note: consider moving this `else` clause to a separate `if` statement and use a `bool` variable to control if it should run
```
Unfortunately, we can't always offer a machine-applicable suggestion when there are subpatterns from macro expansion.
Co-Authored-By: Guillaume Boisseau <Nadrieril@users.noreply.github.com>
solve: all "non-structural" logging to trace
This enables us to start with `RUSTC_LOG=rustc_trait_selection::solve=debug` to figure out *where* something went wrong, to then separately use `trace` to get to the details.
r? ``@compiler-errors``
Fix, document, and test parser and pretty-printer edge cases related to braced macro calls
_Review note: this is a deceptively small PR because it comes with 145 lines of docs and 196 lines of tests, and only 25 lines of compiler code changed. However, I recommend reviewing it 1 commit at a time because much of the effect of the code changes is non-local i.e. affecting code that is not visible in the final state of the PR. I have paid attention that reviewing the PR one commit at a time is as easy as I can make it. All of the code you need to know about is touched in those commits, even if some of those changes disappear by the end of the stack._
This is a follow-up to https://github.com/rust-lang/rust/pull/119105. One case that is not relevant to `-Zunpretty=expanded`, but which came up as I'm porting #119105 and #118726 into `syn`'s printer and `prettyplease`'s printer where it **is** relevant, and is also relevant to rustc's `stringify!`, is statement boundaries in the vicinity of braced macro calls.
Rustc's AST pretty-printer produces invalid syntax for statements that begin with a braced macro call:
```rust
macro_rules! stringify_item {
($i:item) => {
stringify!($i)
};
}
macro_rules! repro {
($e:expr) => {
stringify_item!(fn main() { $e + 1; })
};
}
fn main() {
println!("{}", repro!(m! {}));
}
```
**Before this PR:** output is not valid Rust syntax.
```console
fn main() { m! {} + 1; }
```
```console
error: leading `+` is not supported
--> <anon>:1:19
|
1 | fn main() { m! {} + 1; }
| ^ unexpected `+`
|
help: try removing the `+`
|
1 - fn main() { m! {} + 1; }
1 + fn main() { m! {} 1; }
|
```
**After this PR:** valid syntax.
```console
fn main() { (m! {}) + 1; }
```
Uplift various `*Predicate` types into `rustc_type_ir`
Uplifts `ProjectionPredicate`, `ExistentialTraitRef`, `ExistentialProjection`, `TraitPredicate`, `NormalizesTo`, `CoercePredicate`, and `SubtypePredicate`.
Adds `rustc_type_ir_macros`, which semi-duplicates the derive for `TypeVisitable`, `TypeFoldable`, and `Lift`, but in a way that is interner-agnostic.
Moves `rustc_type_ir::trait_ref` to `rustc_type_ir::predicate`. The specific placement of all these structs doesn't matter b/c of glob imports, tho.
Refactoring after the `PlaceValue` addition
I added [`PlaceValue`](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_codegen_ssa/mir/place/struct.PlaceValue.html) in #123775, but kept that one line-by-line simple because it touched so many places.
This goes through to add more helpers & docs, and change some `PlaceRef` to `PlaceValue` where the type didn't need to be included.
No behaviour changes -- the codegen is exactly the same.
It is impossible for expr here to be a braced macro call. Expr comes
from `parse_stmt_without_recovery`, in which macro calls are parsed by
`parse_stmt_mac`. See this part:
let kind = if (style == MacStmtStyle::Braces
&& self.token != token::Dot
&& self.token != token::Question)
|| self.token == token::Semi
|| self.token == token::Eof
{
StmtKind::MacCall(P(MacCallStmt { mac, style, attrs, tokens: None }))
} else {
// Since none of the above applied, this is an expression statement macro.
let e = self.mk_expr(lo.to(hi), ExprKind::MacCall(mac));
let e = self.maybe_recover_from_bad_qpath(e)?;
let e = self.parse_expr_dot_or_call_with(e, lo, attrs)?;
let e = self.parse_expr_assoc_with(
0,
LhsExpr::AlreadyParsed { expr: e, starts_statement: false },
)?;
StmtKind::Expr(e)
};
A braced macro call at the head of a statement is always either extended
into ExprKind::Field / MethodCall / Await / Try / Binary, or else
returned as StmtKind::MacCall. We can never get a StmtKind::Expr
containing ExprKind::MacCall containing brace delimiter.
The change to the test is a little goofy because the compiler was
guessing "correctly" before that `falsy! {}` is the condition as opposed
to the else body. But I believe this change is fundamentally correct.
Braced macro invocations in statement position are most often item-like
(`thread_local! {...}`) as opposed to parenthesized macro invocations
which are condition-like (`cfg!(...)`).
I didn't figure out how to reach this condition with `expr` containing
`ExprKind::MacCall`. All the approaches I tried ended up with the macro
call ending up in the `StmtKind::MacCall` case below instead.
In any case, from visual inspection this is a bugfix. If we do end up
with a `StmtKind::Expr` containing `ExprKind::MacCall` with brace
delimiter, it would not need ";" printed after it.
This commit by itself is supposed to have no effect on behavior. All of
the call sites are updated to preserve their previous behavior.
The behavior changes are in the commits that follow.
For each of these, we need to decide whether they need to be using
`expr_requires_semi_to_be_stmt`, or `expr_requires_comma_to_be_match_arm`,
which are supposed to be 2 different behaviors. Previously they were
conflated into one, causing either too much or too little
parenthesization.
Refactor Apple `target_abi`
This was bundled together with `Arch`, which complicated a few code paths and meant we had to do more string matching than necessary.
CC `@BlackHoleFox` as you've worked on the Apple target spec before
Related: Is there a reason why `Target`/`TargetOptions` use `StaticCow` for so many things, instead of an enum with defined values (and perhaps a catch-all case for custom target json files)? Tagging `@Nilstrieb,` as you might know?
Update ena to 0.14.3
Includes https://github.com/rust-lang/ena/pull/53, which removes a trivial `Self: Sized` bound that prevents `ena` from building on the new solver.
I added `PlaceValue` in 123775, but kept that one line-by-line simple because it touched so many places.
This goes through to add more helpers & docs, and change some `PlaceRef` to `PlaceValue` where the type didn't need to be included.
No behaviour changes.
Rollup of 5 pull requests
Successful merges:
- #124233 (Add `-lmingwex` second time in `mingw_libs`)
- #124318 (ignore generics args in attribute paths)
- #124899 (bootstrap: add comments for the automatic dry run)
- #124904 (reachable computation: extend explanation of what this does, and why)
- #124930 (Make sure we consume a generic arg when checking mistyped turbofish)
r? `@ghost`
`@rustbot` modify labels: rollup
Make sure we consume a generic arg when checking mistyped turbofish
When recovering un-turbofish-ed args in expr position (e.g. `let x = a<T, U>();` in `check_mistyped_turbofish_with_multiple_type_params`, we used `parse_seq_to_before_end` to parse the fake generic args; however, it used `parse_generic_arg` which *optionally* parses a generic arg. If it doesn't end up parsing an arg, it returns `Ok(None)` and consumes no tokens. If we don't find a delimiter after this (`,`), we try parsing *another* element. In this case, we just infinitely loop looking for a subsequent element.
We can fix this by making sure that we either parse a generic arg or error in `parse_seq_to_before_end`'s callback.
Fixes#124897
reachable computation: extend explanation of what this does, and why
Follow-up to https://github.com/rust-lang/rust/pull/122769. I had the time to think about this some more, in particular in the context of https://github.com/rust-lang/rust/issues/119214, so I felt it was worth extending these comments some more.
I also gave up on the context of "externally reachable" as it is not called that way anywhere else in the compiler.
Cc `@tmiasko` `@saethlin`
ignore generics args in attribute paths
Fixes#97006Fixes#123911Fixes#123912
This patch ensures that we no longer have to handle invalid generic arguments in attribute paths.
r? `@petrochenkov`
Add `-lmingwex` second time in `mingw_libs`
Upcoming mingw-w64 releases will contain small math functions refactor which moved implementation around. As a result functions like `lgamma`
now depend on libraries in this order:
`libmingwex.a` -> `libmsvcrt.a` -> `libmingwex.a`.
Fixes#124221
Avoid `alloca`s in codegen for simple `mir::Aggregate` statements
The core idea here is to remove the abstraction penalty of simple newtypes in codegen.
Even something simple like constructing a
```rust
#[repr(transparent)] struct Foo(u32);
```
forces an `alloca` to be generated in nightly right now.
Certainly LLVM can optimize that away, but it would be nice if it didn't have to.
Quick example:
```rust
#[repr(transparent)]
pub struct Transparent32(u32);
#[no_mangle]
pub fn make_transparent(x: u32) -> Transparent32 {
let a = Transparent32(x);
a
}
```
on nightly we produce <https://rust.godbolt.org/z/zcvoM79ae>
```llvm
define noundef i32 `@make_transparent(i32` noundef %x) unnamed_addr #0 {
%a = alloca i32, align 4
store i32 %x, ptr %a, align 4
%0 = load i32, ptr %a, align 4, !noundef !3
ret i32 %0
}
```
but after this PR we produce
```llvm
define noundef i32 `@make_transparent(i32` noundef %x) unnamed_addr #0 {
start:
ret i32 %x
}
```
(even before the optimizer runs).
Rename some `FulfillmentErrorCode`/`ObligationCauseCode` variants to be less redundant
1. Rename some `FulfillmentErrorCode` variants.
2. Always use `ObligationCauseCode::` to prefix a code, rather than using a glob import and naming them through `traits::`.
3. Rename some `ObligationCauseCode` variants -- I wasn't particularly thorough with thinking of a new names for these, so could workshop them if necessary.
4. Misc stuff from renaming.
r? lcnr
Rollup of 5 pull requests
Successful merges:
- #124615 (coverage: Further simplify extraction of mapping info from MIR)
- #124778 (Fix parse error message for meta items)
- #124797 (Refactor float `Primitive`s to a separate `Float` type)
- #124888 (Migrate `run-make/rustdoc-output-path` to rmake)
- #124957 (Make `Ty::builtin_deref` just return a `Ty`)
r? `@ghost`
`@rustbot` modify labels: rollup
Refactor float `Primitive`s to a separate `Float` type
Now there are 4 of them, it makes sense to refactor `F16`, `F32`, `F64` and `F128` out of `Primitive` and into a separate `Float` type (like integers already are). This allows patterns like `F16 | F32 | F64 | F128` to be simplified into `Float(_)`, and is consistent with `ty::FloatTy`.
As a side effect, this PR also makes the `Ty::primitive_size` method work with `f16` and `f128`.
Tracking issue: #116909
`@rustbot` label +F-f16_and_f128
Fix parse error message for meta items
Addresses https://github.com/rust-lang/rust/issues/122796#issuecomment-2010803906, cc [``@]Thomasdezeeuw.``
For attrs inside of a macro like `#[doc(alias = $ident)]` or `#[cfg(feature = $ident)]` where `$ident` is a macro metavariable of fragment kind `ident`, we used to say the following when expanded (with `$ident` ⟼ `ident`):
```
error: expected unsuffixed literal or identifier, found `ident`
--> weird.rs:6:19
|
6 | #[cfg(feature = $ident)]
| ^^^^^^
...
11 | m!(id);
| ------ in this macro invocation
|
= note: this error originates in the macro `m` (in Nightly builds, run with -Z macro-backtrace for more info)
```
This was incorrect and caused confusion, justifiably so (see #122796).
In this position, we only accept/expect *unsuffixed literals* which consist of numeric & string literals as well as the boolean literals / the keywords / the reserved identifiers `false` & `true` **but not** arbitrary identifiers.
Furthermore, we used to suggest garbage when encountering unexpected non-identifier tokens:
```
error: expected unsuffixed literal, found `-`
--> weird.rs:16:17
|
16 | #[cfg(feature = -1)]
| ^
|
help: surround the identifier with quotation marks to parse it as a string
|
16 | #[cfg(feature =" "-1)]
| + +
```
Now we no longer do.
coverage: Further simplify extraction of mapping info from MIR
This is another round of rearrangement and simplification that builds on top of the changes made to mapping-extraction by #124603.
The overall theme is to take the computation of `bcb_has_mappings` and `test_vector_bitmap_bytes` out of the main body of `generate_coverage_spans`, which then lets us perform a few other small changes that had previously been held up by the need to work around those computations.
codegen: memmove/memset cannot be non-temporal
non-temporal memset is not a thing.
And for memmove, since the LLVM backend doesn't support this, surely we don't need it in the GCC backend.
Some minor (English only) heroics are performed to print error messages
like "5th rule of macro `m` is never used". The form "rule #5 of macro
`m` is never used" is just as good and much simpler to implement.
Eliminate some `FIXME(lcnr)` comments
In some cases this involved changing code. In some cases the comment was able to removed or replaced.
r? ``@lcnr``
Rename `Generics::params` to `Generics::own_params`
I hope this makes it slightly more obvious that `generics.own_params` is insufficient when considering nested items. I didn't actually audit any of the usages, for the record.
r? lcnr
`InferCtxt::next_{ty,const}_var*` all take an origin, but the
`param_def_id` is almost always `None`. This commit changes them to just
take a `Span` and build the origin within the method, and adds new
methods for the rare cases where `param_def_id` might not be `None`.
This avoids a lot of tedious origin building.
Specifically:
- next_ty_var{,_id_in_universe,_in_universe}: now take `Span` instead of
`TypeVariableOrigin`
- next_ty_var_with_origin: added
- next_const_var{,_in_universe}: takes Span instead of ConstVariableOrigin
- next_const_var_with_origin: added
- next_region_var, next_region_var_in_universe: these are unchanged,
still take RegionVariableOrigin
The API inconsistency (ty/const vs region) seems worth it for the
large conciseness improvements.
`InferCtxt::next_{ty,const,int,float}_var_id` each have a single call
site, in `InferCtt::next_{ty,const,int,float}_var` respectively.
The only remaining method that creates a var_id is
`InferCtxt::next_ty_var_id_in_universe`, which has one use outside the
crate.
Make `#![feature]` suggestion MaybeIncorrect
Fixes https://github.com/rust-lang/rust-clippy/issues/12784
The `unstable_name_collisions` lint uses `disabled_nightly_features` to mention the feature name, but accepting the suggestion would result in an ambiguity error
There are other calls where accepting the feature gate would fix code when ran with `cargo fix --broken-code`, though it's not always desirable to add a feature gate even if the user is currently on nightly so MaybeIncorrect seems appropriate
Add `ErrorGuaranteed` to `Recovered::Yes` and use it more.
The starting point for this was identical comments on two different fields, in `ast::VariantData::Struct` and `hir::VariantData::Struct`:
```
// FIXME: investigate making this a `Option<ErrorGuaranteed>`
recovered: bool
```
I tried that, and then found that I needed to add an `ErrorGuaranteed` to `Recovered::Yes`. Then I ended up using `Recovered` instead of `Option<ErrorGuaranteed>` for these two places and elsewhere, which required moving `ErrorGuaranteed` from `rustc_parse` to `rustc_ast`.
This makes things more consistent, because `Recovered` is used in more places, and there are fewer uses of `bool` and
`Option<ErrorGuaranteed>`. And safer, because it's difficult/impossible to set `recovered` to `Recovered::Yes` without having emitted an error.
r? `@oli-obk`
Fix#124819, where a if-less block causes a wrong output. It is
caused by get_return_block in get_fn_decl. In get_return_block,
when a else-less if expression is the tail expression, the check
for next_node will keep iterating. So it is necessary to make a
early return in the check.
The comment mentions that `ReBound` and `ReVar` aren't expected here.
Experimentation with the full test suite indicates this is true, and
that `ReErased` also doesn't occur. So the commit introduces `bug!` for
those cases. (If any of them show up later on, at least we'll have a
test case.)
The commit also remove the first sentence in the comment.
`RePlaceholder` is now handled in the match arm above this comment and
nothing is printed for it, so that sentence is just wrong. Furthermore,
issue #13998 was closed some time ago.
The starting point for this was identical comments on two different
fields, in `ast::VariantData::Struct` and `hir::VariantData::Struct`:
```
// FIXME: investigate making this a `Option<ErrorGuaranteed>`
recovered: bool
```
I tried that, and then found that I needed to add an `ErrorGuaranteed`
to `Recovered::Yes`. Then I ended up using `Recovered` instead of
`Option<ErrorGuaranteed>` for these two places and elsewhere, which
required moving `ErrorGuaranteed` from `rustc_parse` to `rustc_ast`.
This makes things more consistent, because `Recovered` is used in more
places, and there are fewer uses of `bool` and
`Option<ErrorGuaranteed>`. And safer, because it's difficult/impossible
to set `recovered` to `Recovered::Yes` without having emitted an error.
Do not add leading asterisk in the `PartialEq`
I think we should address this issue, however I am not exactly sure, if this is the right way to do it. It is related to the #123056.
Imagine the simplified code:
```rust
trait MyTrait {}
impl PartialEq for dyn MyTrait {
fn eq(&self, _other: &Self) -> bool {
true
}
}
#[derive(PartialEq)]
enum Bar {
Foo(Box<dyn MyTrait>),
}
```
On the nightly compiler, the `derive` produces invalid code with the weird error message:
```
error[E0507]: cannot move out of `*__arg1_0` which is behind a shared reference
--> src/main.rs:11:9
|
9 | #[derive(PartialEq)]
| --------- in this derive macro expansion
10 | enum Things {
11 | Foo(Box<dyn MyTrait>),
| ^^^^^^^^^^^^^^^^ move occurs because `*__arg1_0` has type `Box<dyn MyTrait>`, which does not implement the `Copy` trait
|
= note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info)
```
It may be related to the perfect derive problem, although requiring the _type_ to be `Copy` seems unfortunate because it is not necessary. Besides, we are adding the extra dereference only for the diagnostics?
Handle field projections like slice indexing in invalid_reference_casting
r? `@Urgau`
I saw the implementation in https://github.com/rust-lang/rust/pull/124761, and I was wondering if we also need to handle field access. We do. Without this PR, we get this errant diagnostic:
```
error: casting references to a bigger memory layout than the backing allocation is undefined behavior, even if the reference is unused
--> /home/ben/rust/tests/ui/lint/reference_casting.rs:262:18
|
LL | let r = &mut v.0;
| --- backing allocation comes from here
LL | let ptr = r as *mut i32 as *mut Vec3<i32>;
| ------------------------------- casting happend here
LL | unsafe { *ptr = Vec3(0, 0, 0) }
| ^^^^^^^^^^^^^^^^^^^^
|
= note: casting from `i32` (4 bytes) to `Vec3<i32>` (12 bytes)
```
Fix more ICEs in `diagnostic::on_unimplemented`
There were 8 other calls to `expect_local` left in `on_unimplemented.rs` -- all of which (afaict) could be turned into ICEs.
I would really like to see validation of `on_unimplemented` separated from parsing, so we only emit errors here:
a60f077c38/compiler/rustc_hir_analysis/src/check/check.rs (L836-L839)
...And gracefully fail instead when emitting trait predicate failures, not *ever* even trying to emit an error or a lint. But that's left for a separate PR.
r? `@estebank`
Fix Error Messages for `break` Inside Coroutines
Fixes#124495
Previously, `break` inside `gen` blocks and functions
were incorrectly identified to be enclosed by a closure.
This PR fixes it by displaying an appropriate error message
for async blocks, async closures, async functions, gen blocks,
gen closures, gen functions, async gen blocks, async gen closures
and async gen functions.
Note: gen closure and async gen closure are not supported by the
compiler yet but I have added an error message here assuming that
they might be implemented in the future.
~~Also, fixes grammar in a few places by replacing
`inside of a $coroutine` with `inside a $coroutine`.~~
It's a macro that just creates an enum with a `from_u32` method. It has
two arms. One is unused and the other has a single use.
This commit inlines that single use and removes the whole macro. This
increases readability because we don't have two different macros
interacting (`enum_from_u32` and `language_item_table`).
It provides a way to effectively embed a linked list within an
`IndexVec` and also iterate over that list. It's written in a very
generic way, involving two traits `Links` and `LinkElem`. But the
`Links` trait is only impl'd for `IndexVec` and `&IndexVec`, and the
whole thing is only used in one module within `rustc_borrowck`. So I
think it's over-engineered and hard to read. Plus it has no comments.
This commit removes it, and adds a (non-generic) local iterator for the
use within `rustc_borrowck`. Much simpler.
It is optimized for lists with a single element, avoiding the need for
an allocation in that case. But `SmallVec<[T; 1]>` also avoids the
allocation, and is better in general: more standard, log2 number of
allocations if the list exceeds one item, and a much more capable API.
This commit removes `TinyList` and converts the two uses to
`SmallVec<[T; 1]>`. It also reorders the `use` items in the relevant
file so they are in just two sections (`pub` and non-`pub`), ordered
alphabetically, instead of many sections. (This is a relevant part of
the change because I had to decide where to add a `use` item for
`SmallVec`.)
And move the `repr` line after the `derive` line, where it's harder to
overlook. (I overlooked it initially, and didn't understand how this
type worked.)
Simplify `use crate::rustc_foo::bar` occurrences.
They can just be written as `use rustc_foo::bar`, which is far more standard. (I didn't even know that a `crate::` prefix was valid.)
r? ``@eholk``
Remove braces when fixing a nested use tree into a single item
[Back in 2019](https://github.com/rust-lang/rust/pull/56645) I added rustfix support for the `unused_imports` lint, to automatically remove them when running `cargo fix`. For the most part this worked great, but when removing all but one childs of a nested use tree it turned `use foo::{Unused, Used}` into `use foo::{Used}`. This is slightly annoying, because it then requires you to run `rustfmt` to get `use foo::Used`.
This PR automatically removes braces and the surrouding whitespace when all but one child of a nested use tree are unused. To get it done I had to add the span of the nested use tree to the AST, and refactor a bit the code I wrote back then.
A thing I noticed is, there doesn't seem to be any `//@ run-rustfix` test for fixing the `unused_imports` lint. I created a test in `tests/suggestions` (is that the right directory?) that for now tests just what I added in the PR. I can followup in a separate PR to add more tests for fixing `unused_lints`.
This PR is best reviewed commit-by-commit.
Previously, `break` inside `gen` blocks and functions
were incorrectly identified to be enclosed by a closure.
This PR fixes it by displaying an appropriate error message
for async blocks, async closures, async functions, gen blocks,
gen closures, gen functions, async gen blocks, async gen closures
and async gen functions.
Note: gen closure and async gen closure are not supported by the
compiler yet but I have added an error message here assuming that
they might be implemented in the future.
Also, fixes grammar in a few places by replacing
`inside of a $coroutine` with `inside a $coroutine`.
Fix insufficient logic when searching for the underlying allocation
This PR fixes the logic inside the `invalid_reference_casting` lint, when trying to lint on bigger memory layout casts.
More specifically when looking for the "underlying allocation" we were wrongly assuming that when we got `&mut slice[index]` that `slice[index]` was the allocation, but it's not.
Fixes https://github.com/rust-lang/rust/issues/124685
Handle normalization failure in `struct_tail_erasing_lifetimes`
Fixes#113272
The ICE occurred because the struct being normalized had an error. This PR adds some defensive code to guard against that.
rustc: Some small changes for the wasm32-wasip2 target
This commit has a few changes for the wasm32-wasip2 target. The first two are aimed at improving the compatibility of using `clang` as an external linker driver on this target. The default target to LLVM is updated to match the Rust target and additionally the `-fuse-ld=lld` argument is dropped since that otherwise interferes with clang's own linker detection. The only linker on wasm targets is LLD but on the wasip2 target a wrapper around LLD, `wasm-component-ld`, is used to drive the process and perform steps necessary for componentization.
The final commit changes the output of all objects on the wasip2 target to being PIC by default. This improves compatibilty with shared libaries but notably does not mean that there's a turnkey solution for shared libraries. The hope is that by having the standard libray work both with and without dynamic libraries will make experimentation easier.
Improve `rustc_parse::Parser`'s debuggability
The main event is the final commit where I add `Parser::debug_lookahead`. Everything else was basically cleaning up things that bugged me (debugging, as it were) until I felt comfortable enough to actually work on it.
The motivation is that it's annoying as hell to try to figure out how the debug infra works in rustc without having basic queries like `debug!(?parser);` come up "empty". However, Parser has a lot of fields that are mostly irrelevant for most debugging, like the entire ParseSess. I think `Parser::debug_lookahead` with a capped lookahead might be fine as a general-purpose Debug impl, but this adapter version was suggested to allow more choice, and admittedly, it's a refined version of what I was already handrolling just to get some insight going.
I tried debugging a parser-related issue but found it annoying to not be
able to easily peek into the Parser's token stream.
Add a convenience fn that offers an opinionated view into the parser,
but one that is useful for answering basic questions about parser state.
coverage: Branch coverage support for let-else and if-let
This PR adds branch coverage instrumentation for let-else and if-let, including let-chains.
This lifts two of the limitations listed at #124118.
This commit changes the new `wasm32-wasip2` target to being PIC by
default rather than the previous non-PIC by default. This change is
intended to make it easier for the standard library to be used in a
shared object in its precompiled form. This comes with a hypothetical
modest slowdown but it's expected that this is quite minor in most use
cases or otherwise wasm compilers and/or optimizing runtimes can elide
the cost.