Move lint level source explanation to the bottom
So, uhhhhh
r? `@estebank`
## User-facing change
"note: `#[warn(...)]` on by default" and such are moved to the bottom of the diagnostic:
```diff
- = note: `#[warn(unsupported_calling_conventions)]` on by default
= warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
= note: for more information, see issue #87678 <https://github.com/rust-lang/rust/issues/87678>
+ = note: `#[warn(unsupported_calling_conventions)]` on by default
```
Why warning is enabled is the least important thing, so it shouldn't be the first note the user reads, IMO.
## Developer-facing change
`struct_span_lint` and similar methods have a different signature.
Before: `..., impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>)`
After: `..., impl Into<DiagnosticMessage>, impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>) -> &'b mut DiagnosticBuilder<'a, ()>`
The reason for this is that `struct_span_lint` needs to edit the diagnostic _after_ `decorate` closure is called. This also makes lint code a little bit nicer in my opinion.
Another option is to use `impl for<'a> FnOnce(LintDiagnosticBuilder<'a, ()>) -> DiagnosticBuilder<'a, ()>` altough I don't _really_ see reasons to do `let lint = lint.build(message)` everywhere.
## Subtle problem
By moving the message outside of the closure (that may not be called if the lint is disabled) `format!(...)` is executed earlier, possibly formatting `Ty` which may call a query that trims paths that crashes the compiler if there were no warnings...
I don't think it's that big of a deal, considering that we move from `format!(...)` to `fluent` (which is lazy by-default) anyway, however this required adding a workaround which is unfortunate.
## P.S.
I'm sorry, I do not how to make this PR smaller/easier to review. Changes to the lint API affect SO MUCH 😢
Group together more size assertions.
Also add a few more assertions for some relevant token-related types.
And fix an erroneous comment in `rustc_errors`.
r? `@lqd`
Flush delayed bugs before codegen
Sometimes it can happen that invalid code like a TyKind::Error makes its way through the compiler without triggering any errors (this is always a bug in rustc but bugs do happen sometimes :)). These ICEs will manifest in the backend like as cg_llvm not being able to get the layout of `[type error]`, which makes it hard to debug. By flushing before codegen, we display all the delayed bugs, making it easier to trace it to the root of the problem.
I tried this on #102366 and it showed tons of of delayed bugs and no error in cg_llvm, so it seems to be working.
remove the unused :: between trait and type to give user correct diag…
…nostic information
modified: compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs
new file: src/test/ui/type/issue-101866.rs
new file: src/test/ui/type/issue-101866.stderr
Manually order `DefId` on 64-bit big-endian
`DefId` uses different field orders on 64-bit big-endian vs. others, in
order to optimize its `Hash` implementation. However, that also made it
derive different lexical ordering for `PartialOrd` and `Ord`. That
caused spurious differences wherever `DefId`s are sorted, like the
candidate sources list in `report_method_error`.
Now we manually implement `PartialOrd` and `Ord` on 64-bit big-endian to
match the same lexical ordering as other targets, fixing at least one
test, `src/test/ui/methods/method-ambig-two-traits-cross-crate.rs`.
Adjust the s390x data layout for LLVM 16
LLVM [D131158] changed the SystemZ data layout to always set 64-bit
vector alignment, which used to be conditional on the "vector" feature.
[D131158]: https://reviews.llvm.org/D131158
r? `@nikic`
Improve errors for incomplete functions in struct definitions
Given the following code:
```rust
fn main() {}
struct Foo {
fn
}
```
[playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=29139f870511f6918324be5ddc26c345)
The current output is:
```
Compiling playground v0.0.1 (/playground)
error: functions are not allowed in struct definitions
--> src/main.rs:4:5
|
4 | fn
| ^^
|
= help: unlike in C++, Java, and C#, functions are declared in `impl` blocks
= help: see https://doc.rust-lang.org/book/ch05-03-method-syntax.html for more information
error: could not compile `playground` due to previous error
```
In this case, rustc should suggest escaping `fn` to use it as an identifier.
Migrate rustc_codegen_gcc to SessionDiagnostics
As part of #100717 this pr migrates diagnostics to `SessionDiagnostics` for the `rustc_codegen_gcc` crate.
``@rustbot`` label +A-translation
remove outdated coherence hack
we have a more precise detection for downstream conflicts in candidate assembly: the `is_knowable` check in `candidate_from_obligation_no_cache`.
r? types cc `@nikomatsakis`
LLVM [D131158] changed the SystemZ data layout to always set 64-bit
vector alignment, which used to be conditional on the "vector" feature.
[D131158]: https://reviews.llvm.org/D131158
From talking with @abrown, we aren't planning to have hosts call these
`__tls_*` functions; instead, TLS initialization will be handled
transparently within libc. Consequently, these functions don't need to
be exported.
Leave them exported on wasm32-unknown-unknown though, as wasm-bindgen
does call them.
modified: compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs
new file: src/test/ui/type/issue-101866.rs
new file: src/test/ui/type/issue-101866.stderr
Rollup of 7 pull requests
Successful merges:
- #102214 (Fix span of byte-escaped left format args brace)
- #102426 (Don't export `__wasm_init_memory` on WebAssembly.)
- #102437 (rustdoc: cut margin-top from first header in docblock)
- #102442 (rustdoc: remove bad CSS font-weight on `.impl`, `.method`, etc)
- #102447 (rustdoc: add method spacing to trait methods)
- #102468 (tidy: make rustc dependency error less confusing)
- #102476 (Split out the error reporting logic into a separate function)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Split out the error reporting logic into a separate function
I was trying to read the function and got distracted by the huge block of code in the middle of it. Turns out it only reports diagnostics and all paths within it end in an error. The main function is now more readable imo.
Don't export `__wasm_init_memory` on WebAssembly.
Since #72889, the Rust wasm target doesn't use --passive-segments, so remove the `--export=__wasm_init_memory`.
As documented in the [tool-conventions Linking convention], `__wasm_init_memory` is not intended to be exported.
[tool-conventions Linking convention]: 7c064f3048/Linking.md (shared-memory-and-passive-segments)
Fix span of byte-escaped left format args brace
Fix#102057 (see issue for example).
Previously, the use of escaped left braces (`\x7B`) in format args resulted in an incorrectly offset span. This patch fixes that by considering any escaped characters within the string instead of using a constant offset.
Fix perf regression from TypeVisitor changes
Regression occurred in https://github.com/rust-lang/rust/pull/101858#issuecomment-1248732579
Instead of just reverting, we only fixed part of the regression. The main regression was due to actually correctly visiting a type that contains types and consts and should therefor be visited. This is not actually observable (yet?), but we should still do it correctly instead of risking major bugs in the future.
Don't export `__heap_base` and `__data_end` on wasm32-wasi.
`__heap_base` and `__data_end` are exported for use by wasm-bindgen, which uses the wasm32-unknown-unknown target. On wasm32-wasi, as a step toward implementing the Canonical ABI, and as an aid to building speicalized WASI API polyfill wrappers, don't export `__heap_base` and `__data_end` on wasm32-wasi.
Fix associated type bindings with anon const in GAT position
The first commit formats `type_of.rs`, which is really hard to maintain since it uses a bunch of features like `let`-chains and `if let` match arm bindings. Best if you just review the second two diffs.
Fixes#102333
Enable inline stack probes on PowerPC and SystemZ
The LLVM PowerPC and SystemZ targets have both supported `"probe-stack"="inline-asm"` for longer than our current minimum LLVM 13 requirement, so we can turn this on for all `powerpc`, `powerpc64`, `powerpc64le`, and `s390x` targets in Rust. These are all tier-2 or lower, so CI does not run their tests, but I have confirmed that their `linux-gnu` variants do pass on RHEL.
cc #43241
`Res::SelfTy` currently has two `Option`s. When the second one is `Some`
the first one is never consulted. So we can split it into two variants,
`Res::SelfTyParam` and `Res::SelfTyAlias`, reducing the size of `Res`
from 24 bytes to 12. This then shrinks `hir::Path` and
`hir::PathSegment`, which are the HIR types that take up the most space.
Add `#[rustc_safe_intrinsic]`
This PR adds the `#[rustc_safe_intrinsic]` attribute as mentionned on Zulip. The goal of this attribute is to avoid keeping a list of symbols as the source for stable intrinsics, and instead rely on an attribute. This is similar to `#[rustc_const_stable]` and `#[rustc_const_unstable]`, which among other things, are used to mark the constness of intrinsic functions.
Since #72889, the Rust wasm target doesn't use --passive-segments, so
remove the `--export=__wasm_init_memory`.
As documented in the [tool-conventions Linking convention],
`__wasm_init_memory` is not intended to be exported.
[tool-conventions Linking convention]: 7c064f3048/Linking.md (shared-memory-and-passive-segments)
On targets with `default_hidden_visibility` set, which is currrently
just WebAssembly, declare the generated `main` function with visibility
hidden. This makes it consistent with clang's WebAssembly target, where
`main` is just a user function that gets the same visibility as any
other user function, which is hidden on WebAssembly unless explicitly
overridden.
This will help simplify use cases which in the future may want to
automatically wasm-export all visibility-"default" symbols. `main` isn't
intended to be wasm-exported, and marking it hidden prevents it from
being wasm-exported in that scenario.
Do not overwrite lifetime binders for another HirId.
This PR makes higher-ranked bounds in where clauses a bit more principled.
We used to conflate `for<'a> T: Trait` with `(for<'a> T): Trait`.
This PR separates both binders.
This caused issued with fn types, which have their own binder, causing us to overwrite the predicates's binders with `fn`'s binders, ICEing.
Fixes https://github.com/rust-lang/rust/issues/98594
Migrate more of rustc_parse to SessionDiagnostic
Still far from complete, but I thought I'd add a checkpoint here because rebasing was starting to get annoying.
Rollup of 8 pull requests
Successful merges:
- #100747 (Add long description and test for E0311)
- #102232 (Stabilize bench_black_box)
- #102288 (Suggest unwrapping `???<T>` if a method cannot be found on it but is present on `T`.)
- #102338 (Deny associated type bindings within associated type bindings)
- #102347 (Unescaping cleanups)
- #102348 (Tweak `FulfillProcessor`.)
- #102378 (Use already resolved `self_ty` in `confirm_fn_pointer_candidate`)
- #102380 (rustdoc: remove redundant mobile `.source > .sidebar` CSS)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Deny associated type bindings within associated type bindings
Fixes#102335
This was made worse by #100865, which unified the way we generate substs for GATs and non-generic associated types. However, the issue was not _caused_ by #100865, evidenced by the test I added for GATs:
```rust
trait T {
type A: S<C<(), i32 = ()> = ()>;
//~^ ERROR associated type bindings are not allowed here
}
trait Q {}
trait S {
type C<T>: Q;
}
fn main() {}
```
^ which passes on beta (where GATs are stable) and presumably ever since GATs support was added to `create_substs_for_associated_item` in astconv.
Suggest unwrapping `???<T>` if a method cannot be found on it but is present on `T`.
This suggests various ways to get inside wrapper types if the method cannot be found on the wrapper type, but is present on the wrappee.
For this PR, those wrapper types include `Localkey`, `MaybeUninit`, `RefCell`, `RwLock` and `Mutex`.
Stabilize bench_black_box
This PR stabilize `feature(bench_black_box)`.
```rust
pub fn black_box<T>(dummy: T) -> T;
```
The FCP was completed in https://github.com/rust-lang/rust/issues/64102.
`@rustbot` label +T-libs-api -T-libs
Rewrite and refactor format_args!() builtin macro.
This is a near complete rewrite of `compiler/rustc_builtin_macros/src/format.rs`.
This gets rid of the massive unmaintanable [`Context` struct](76531befc4/compiler/rustc_builtin_macros/src/format.rs (L176-L263)), and splits the macro expansion into three parts:
1. First, `parse_args` will parse the `(literal, arg, arg, name=arg, name=arg)` syntax, but doesn't parse the template (the literal) itself.
2. Second, `make_format_args` will parse the template, the format options, resolve argument references, produce diagnostics, and turn the whole thing into a `FormatArgs` structure.
3. Finally, `expand_parsed_format_args` will turn that `FormatArgs` structure into the expression that the macro expands to.
In other words, the `format_args` builtin macro used to be a hard-to-maintain 'single pass compiler', which I've split into a three phase compiler with a parser/tokenizer (step 1), semantic analysis (step 2), and backend (step 3). (It's compilers all the way down. ^^)
This can serve as a great starting point for https://github.com/rust-lang/rust/issues/99012, which will only need to change the implementation of 3, while leaving step 1 and 2 unchanged.
It also makes https://github.com/rust-lang/compiler-team/issues/541 easier, which could then upgrade the new `FormatArgs` struct to an `ast` node and remove step 3, moving that step to later in the compilation process.
It also fixes a few diagnostics bugs.
This also [significantly reduces](https://gist.github.com/m-ou-se/b67b2d54172c4837a5ab1b26fa3e5284) the amount of generated code for cases with arguments in non-default order without formatting options, like `"{1} {0}"` or `"{a} {}"`, etc.
`__heap_base` and `__data_end` are exported for use by wasm-bindgen, which
uses the wasm32-unknown-unknown target. On wasm32-wasi, as a step toward
implementing the Canonical ABI, and as an aid to building speicalized WASI
API polyfill wrappers, don't export `__heap_base` and `__data_end` on
wasm32-wasi.
- Rename `unescape_raw_str_or_raw_byte_str` as
`unescape_raw_str_or_byte_str`, which is more accurate.
- Remove the unused `Mode::in_single_quotes` method.
- Make some assertions more precise, and add a missing one to
`unescape_char_or_byte`.
- Change all the assertions to `debug_assert!`, because this code is
reasonably hot, and the assertions aren't required for memory safety,
and any violations are likely to be sufficiently obvious that normal
tests will trigger them.
`DefId` uses different field orders on 64-bit big-endian vs. others, in
order to optimize its `Hash` implementation. However, that also made it
derive different lexical ordering for `PartialOrd` and `Ord`. That
caused spurious differences wherever `DefId`s are sorted, like the
candidate sources list in `report_method_error`.
Now we manually implement `PartialOrd` and `Ord` on 64-bit big-endian to
match the same lexical ordering as other targets, fixing at least one
test, `src/test/ui/methods/method-ambig-two-traits-cross-crate.rs`.
session: remove now-unnecessary lint `#[allow]`s
In #101230, the internal diagnostic migration lints - `diagnostic_outside_of_impl` and `untranslatable_diagnostic` - were modified so that they wouldn't trigger on functions annotated with `#[rustc_lint_diagnostics]`. However, this change has to make it into the bootstrap compiler before the `#[allow]` annotations that it aims to remove can be removed, which is possible now that #102051 has landed.
Avoid LLVM-deprecated `Optional::hasValue`
LLVM 15 added `Optional::has_value`, and LLVM `main` (16) has deprecated
`hasValue`. However, its `explicit operator bool` does the same thing,
and was added long ago, so we can use that across our full LLVM range of
compatibility.
Sometimes it can happen that invalid code like a TyKind::Error makes
its way through the compiler without triggering any errors (this is
always a bug in rustc but bugs do happen sometimes :)). These ICEs
will manifest in the backend like as cg_llvm not being able to get
the layout of `[type error]`, which makes it hard to debug. By flushing
before codegen, we display all the delayed bugs, making it easier to
trace it to the root of the problem.
In #101230, the internal diagnostic migration lints -
`diagnostic_outside_of_impl` and `untranslatable_diagnostic` - were
modified so that they wouldn't trigger on functions annotated with
`#[rustc_lint_diagnostics]`. However, this change has to make it into
the bootstrap compiler before the `#[allow]` annotations that it aims to
remove can be removed, which is possible now that #102051 has landed.
Signed-off-by: David Wood <david.wood@huawei.com>
macros: diagnostic derive on enums
Part of #100717.
Extends `#[derive(Diagnostic)]` to work on enums too where each variant acts like a distinct diagnostic - being able to represent diagnostics this way can be quite a bit simpler for some parts of the compiler.
r? `@compiler-errors`
cc `@Xiretza`
LLVM 15 added `Optional::has_value`, and LLVM `main` (16) has deprecated
`hasValue`. However, its `explicit operator bool` does the same thing,
and was added long ago, so we can use that across our full LLVM range of
compatibility.
Rollup of 5 pull requests
Successful merges:
- #101875 (Allow more `!Copy` impls)
- #101996 (Don't duplicate region names for late-bound regions in print of Binder)
- #102181 (Add regression test)
- #102273 (Allow `~const` bounds on non-const functions)
- #102286 (Recover some items that expect braces and don't take semicolons)
Failed merges:
- #102314 (Add a label to struct/enum/union ident name)
r? `@ghost`
`@rustbot` modify labels: rollup
Allow more `!Copy` impls
You can already implement `!Copy` for a lot of types (with `#![feature(negative_impls)]`). However, before this PR you could not implement `!Copy` for ADTs whose fields don't implement `Copy` which didn't make any sense. Further, you couldn't implement `!Copy` for types impl'ing `Drop` (equally nonsensical).
``@rustbot`` label T-types F-negative_impls
Fixes#101836.
r? types
Fix lint scoping for let-else.
The scoping for let-else is inconsistent with HIR nesting. This creates cases, in `ui/let-else/let-else-allow-unused.rs` for instance, where an `allow` lint attribute does not apply to the bindings created by `let-else`.
This PR is an attempt to correct this.
As there is no lint that currently relies on this, the test for this behaviour is https://github.com/rust-lang/rust/pull/101500.
cc `@dingxiangfei2009` as you filed https://github.com/rust-lang/rust/pull/101894
Update bootstrap compiler to 1.65.0
This PR updates the bootstrap compiler to Rust 1.65.0, removing the various `cfg(bootstrap)`s.
r? `@Mark-Simulacrum`
Rollup of 5 pull requests
Successful merges:
- #102143 (Recover from struct nested in struct)
- #102178 (bootstrap: the backtrace feature is stable, no need to allow it any more)
- #102197 (Stabilize const `BTree{Map,Set}::new`)
- #102267 (Don't set RUSTC in the bootstrap build script)
- #102270 (Remove benches from `rustc_middle`)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Remove benches from `rustc_middle`
These benches benchmark rust langauge features and not the compiler, so they seem to be in the wrong place here. They also all take <1ns, making them pretty useless. Looking at their git history, they just seem to have been carried around for many, many years. This commit ends their journey.
Stabilize const `BTree{Map,Set}::new`
The FCP was completed in #71835.
Since `len` and `is_empty` are not const stable yet, this also creates a new feature for them since they previously used the same `const_btree_new` feature.
`Cursor` keeps track of the position within the current token. But it
uses confusing names that don't make it clear that the "length consumed"
is just within the current token.
This commit renames things to make this clearer.
`Cursor` is currently hidden, and the main tokenization path uses
`rustc_lexer::first_token` which involves constructing a new `Cursor`
for every single token, which is weird. Also, `first_token` also can't
handle empty input, so callers have to check for that first.
This commit makes `Cursor` public, so `StringReader` can contain a
`Cursor`, which results in a simpler structure. The commit also changes
`StringReader::advance_token` so it returns an `Option<Token>`,
simplifying the the empty input case.
`TokenTreesReader` wraps a `StringReader`, but the `into_token_trees`
function obscures this. This commit moves to a more straightforward
control flow.