Previously some code paths would fail to evaluate the rvalue, while
incorrectly indicating success with `Ok`. As a result the previous value
of lhs could have been incorrectly const propagated.
Suggest to specify a target triple when lang item is missing
It is very common for newbies to embedded to hit this confusing error when forgetting to specify the target.
Source: me googling this error many times.
## Possible changes
* We could possibly restrict the note+help to only be included on eh_personality lang item if that helped reduce false positives, but its also possible doing so would just increase false negatives
* Open to any suggestions on rewriting the messages
* We could possibly remove the `.cargo/config` alternative to avoid the message getting too noisy but I think its valuable to have as its the correct approach for most embedded projects so that `cargo build` just works.
r? rust-lang/diagnostics
manually implement `Hash` for `DefId`
This might speed up hashing for hashers that can work on individual u64s. Just as an experiment, suggested in a reddit thread on `FxHasher`. cc `@nnethercote`
Note that this should not be merged as is without cfg-ing the code path for 64 bits.
This crate actually had a typo `'ctx` in one of its functions:
```diff
-pub fn same_type_modulo_infer(a: Ty<'tcx>, b: Ty<'ctx>) -> bool {
+pub fn same_type_modulo_infer<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
```
This reverts commit b376f5621b, which is
the main part of #90499, because it turns out that this causes a good
amount of breakage in crates relying on the old behavior.
Fixes#91372.
GATs outlives lint: Try to prove bounds
Fixes#91036Fixes#90888Fixes#91348 (better error + documentation to be added to linked issue)
Instead of checking for bounds directly, try to prove them in the associated type environment.
Also, add a bit of extra information to the error, including a link to the relevant discussion issue (#87479). That should be edited to include a brief summary of the current state of the outlives lint, including a brief background. It also might or might not be worth it to bump this to a full error code at some point.
r? ``@nikomatsakis``
Use module inline assembly to embed bitcode
In LLVM 14, our current method of setting section flags to avoid
embedding the `.llvmbc` section into final compilation artifacts
will no longer work, see issue #90326. The upstream recommendation
is to instead embed the entire bitcode using module-level inline
assembly, which is what this change does.
I've kept the existing code for platforms where we do not need to
set section flags, but possibly we should always be using the
inline asm approach (which would have to look a bit different for MachO).
r? `@nagisa`
The resulting profile will include the crate name and will be stored in
the `--out-dir` directory.
This implementation makes it convenient to use LLVM time trace together
with cargo, in the contrast to the previous implementation which would
overwrite profiles or store them in `.cargo/registry/..`.
replace dynamic library module with libloading
This PR deletes the `rustc_metadata::dynamic_lib` module in favor of the popular and better tested [`libloading` crate](https://github.com/nagisa/rust_libloading/).
We don't benefit from `libloading`'s symbol lifetimes since we end up leaking the loaded library in all cases, but the call-sites look much nicer by improving error handling and abstracting away some transmutes. We also can remove `rustc_metadata`'s direct dependencies on `libc` and `winapi`.
This PR also adds an exception for `libloading` (and its license) to tidy, so this will need sign-off from the compiler team.
Stabilise `feature(const_generics_defaults)`
`feature(const_generics_defaults)` is complete implementation wise and has a pretty extensive test suite so I think is ready for stabilisation.
needs stabilisation report and maybe an RFC 😅
r? `@lcnr`
cc `@rust-lang/project-const-generics`
They are also removed from the prelude as per the decision in
https://github.com/rust-lang/rust/issues/87228.
stdarch and compiler-builtins are updated to work with the new, stable
asm! and global_asm! macros.
Slightly optimize hash map stable hashing
I was profiling some of the `rustc-perf` benchmarks locally and noticed that quite some time is spent inside the stable hash of hashmaps. I tried to use a `SmallVec` instead of a `Vec` there, which helped very slightly.
Then I tried to remove the sorting, which was a bottleneck, and replaced it with insertion into a binary heap. Locally, it yielded nice improvements in instruction counts and RSS in several benchmarks for incremental builds. The implementation could probably be much nicer and possibly extended to other stable hashes, but first I wanted to test the perf impact properly.
Can I ask someone to do a perf run? Thank you!
I think it's helpful to know what type was unused when looking at these
warnings. The type will likely determine whether the result *should* be
used, or whether it should just be ignored.
Including the type also matches the behavior of the `must_use` lint:
unused `SomeType` that must be used.
Rollup of 8 pull requests
Successful merges:
- #90081 (Make `intrinsics::write_bytes` const)
- #91643 (asm: Allow using r9 (ARM) and x18 (AArch64) if they are not reserved by the current target)
- #91737 (Make certain panicky stdlib functions behave better under panic_immediate_abort)
- #91750 (rustdoc: Add regression test for Iterator as notable trait on &T)
- #91764 (Do not ICE when suggesting elided lifetimes on non-existent spans.)
- #91780 (Remove hir::Node::hir_id.)
- #91797 (Fix zero-sized reference to deallocated memory)
- #91806 (Make `Unique`s methods `const`)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
asm: Allow using r9 (ARM) and x18 (AArch64) if they are not reserved by the current target
This supersedes https://github.com/rust-lang/rust/pull/88879.
cc `@Skirmisher`
r? `@joshtriplett`
Tweak assoc type obligation spans
* Point at RHS of associated type in obligation span
* Point at `impl` assoc type on projection error
* Reduce verbosity of recursive obligations
* Point at source of binding lifetime obligation
* Tweak "required bound" note
* Tweak "expected... found opaque (return) type" labels
* Point at set type in impl assoc type WF errors
r? `@oli-obk`
This is a(n uncontroversial) subset of #85799.
Point at capture points for non-`'static` reference crossing a `yield` point
```
error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> $DIR/issue-72312.rs:10:24
|
LL | pub async fn start(&self) {
| ^^^^^ this data with an anonymous lifetime `'_`...
...
LL | require_static(async move {
| -------------- ...is required to live as long as `'static` here...
LL | &self;
| ----- ...and is captured here
|
note: `'static` lifetime requirement introduced by this trait bound
--> $DIR/issue-72312.rs:2:22
|
LL | fn require_static<T: 'static>(val: T) -> T {
| ^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0759`.
```
Fix#72312.
Suggest using a temporary variable to fix borrowck errors
Fixes#77834.
In Rust, nesting method calls with both require `&mut` access to `self`
produces a borrow-check error:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/lib.rs:7:14
|
7 | self.foo(self.bar());
| ---------^^^^^^^^^^-
| | | |
| | | second mutable borrow occurs here
| | first borrow later used by call
| first mutable borrow occurs here
That's because Rust has a left-to-right evaluation order, and the method
receiver is passed first. Thus, the argument to the method cannot then
mutate `self`.
There's an easy solution to this error: just extract a local variable
for the inner argument:
let tmp = self.bar();
self.foo(tmp);
However, the error doesn't give any suggestion of how to solve the
problem. As a result, new users may assume that it's impossible to
express their code correctly and get stuck.
This commit adds a (non-structured) suggestion to extract a local
variable for the inner argument to solve the error. The suggestion uses
heuristics that eliminate most false positives, though there are a few
false negatives (cases where the suggestion should be emitted but is
not). Those other cases can be implemented in a future change.
Improve the readability of `List<T>`.
This commit does the following.
- Expands on some of the things already mentioned in comments.
- Describes the uniqueness assumption, which is critical but wasn't
mentioned at all.
- Rewrites `empty()` into a clearer form, as provided by Daniel
Henry-Mantilla on Zulip.
- Reorders things slightly so that more important things
are higher up, and incidental things are lower down, which makes
reading the code easier.
r? ````@lcnr````
* Point at RHS of associated type in obligation span
* Point at `impl` assoc type on projection error
* Reduce verbosity of recursive obligations
* Point at source of binding lifetime obligation
* Tweak "required bound" note
* Tweak "expected... found opaque (return) type" labels
* Point at set type in impl assoc type WF errors
Bump rmeta version to fix rustc_serialize ICE
#91407 changed the serialization format which leads to ICEs for nightly users such as #91663 and linked issues. The issue can be solved by running `cargo clean`. But bumping the metadata version should lead to the cached files being discarded, avoiding the issue entirely.
In Rust, nesting method calls with both require `&mut` access to `self`
produces a borrow-check error:
error[E0499]: cannot borrow `*self` as mutable more than once at a time
--> src/lib.rs:7:14
|
7 | self.foo(self.bar());
| ---------^^^^^^^^^^-
| | | |
| | | second mutable borrow occurs here
| | first borrow later used by call
| first mutable borrow occurs here
That's because Rust has a left-to-right evaluation order, and the method
receiver is passed first. Thus, the argument to the method cannot then
mutate `self`.
There's an easy solution to this error: just extract a local variable
for the inner argument:
let tmp = self.bar();
self.foo(tmp);
However, the error doesn't give any suggestion of how to solve the
problem. As a result, new users may assume that it's impossible to
express their code correctly and get stuck.
This commit adds a (non-structured) suggestion to extract a local
variable for the inner argument to solve the error. The suggestion uses
heuristics that eliminate most false positives, though there are a few
false negatives (cases where the suggestion should be emitted but is
not). Those other cases can be implemented in a future change.
Fix ICE on format string of macro with secondary-label
This generalizes the fix#86104 to also correctly skip `Span::from_inner` for the `secondary_label` of a format macro parsing error as well.
We can alternatively skip the `span_label` diagnostic call for the secondary label as well, since that label probably only makes sense when the _proper_ span is computed.
Fixes#91556
code-cov: generate dead functions with private/default linkage
As discovered in #85461, the MSVC linker treats weak symbols slightly
differently than unix-y linkers do. This causes link.exe to fail with
LNK1227 "conflicting weak extern definition" where as other targets are
able to link successfully.
This changes the dead functions from being generated as weak/hidden to
private/default which, as the LLVM reference says:
> Global values with “private” linkage are only directly accessible by
objects in the current module. In particular, linking code into a module
with a private global value may cause the private to be renamed as
necessary to avoid collisions. Because the symbol is private to the
module, all references can be updated. This doesn’t show up in any
symbol table in the object file.
This fixes the conflicting weak symbols but doesn't address the reason
*why* we have conflicting symbols for these dead functions. The test
cases added in this commit contain a minimal repro of the fundamental
issue which is that the logic used to decide what dead code functions
should be codegen'd in the current CGU doesn't take into account that
functions can be duplicated across multiple CGUs (for instance, in the
case of `#[inline(always)]` functions).
Fixing that is likely to be a more complex change (see
https://github.com/rust-lang/rust/issues/85461#issuecomment-985005805).
Fixes#85461
```
error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> $DIR/issue-72312.rs:10:24
|
LL | pub async fn start(&self) {
| ^^^^^ this data with an anonymous lifetime `'_`...
...
LL | require_static(async move {
| -------------- ...is required to live as long as `'static` here...
LL | &self;
| ----- ...and is captured here
|
note: `'static` lifetime requirement introduced by this trait bound
--> $DIR/issue-72312.rs:2:22
|
LL | fn require_static<T: 'static>(val: T) -> T {
| ^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0759`.
```
Fix#72312.
This also reorders the fields to reduce the assembly operations for hashing
and changes two UI tests that depended on the former ordering because of
hashmap iteration order.
#91407 changed the serialization format which leads to ICEs for nightly users such as #91663 and linked issue.
Bumping the metadata version should lead to the cached files being discarded instead.
Rollup of 6 pull requests
Successful merges:
- #87599 (Implement concat_bytes!)
- #89999 (Update std::env::temp_dir to use GetTempPath2 on Windows when available.)
- #90796 (Remove the reg_thumb register class for asm! on ARM)
- #91042 (Use Vec extend instead of repeated pushes on several places)
- #91634 (Do not attempt to suggest help for overly malformed struct/function call)
- #91685 (Install llvm tools to sysroot when assembling local toolchain)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
This commit does the following.
- Expands on some of the things already mentioned in comments.
- Describes the uniqueness assumption, which is critical but wasn't
mentioned at all.
- Rewrites `empty()` into a clearer form, as provided by Daniel
Henry-Mantilla on Zulip.
- Reorders things slightly so that more important things
are higher up, and incidental things are lower down, which makes
reading the code easier.
Use Vec extend instead of repeated pushes on several places
Inspired by https://github.com/rust-lang/rust/pull/90813, I tried to use a simple regex (`for .*in.*\{\n.*push\(.*\);\n\s+}`) to search for more places that would use `Vec::push` in a loop and replace them with `Vec::extend`.
These probably won't have as much perf. impact as the original PR (if any), but it would probably be better to do a perf run to see if there are not any regressions.
Remove the reg_thumb register class for asm! on ARM
Also restricts r8-r14 from being used on Thumb1 targets as per #90736.
cc ``@Lokathor``
r? ``@joshtriplett``
Implement concat_bytes!
This implements the unstable `concat_bytes!` macro, which has tracking issue #87555. It can be used like:
```rust
#![feature(concat_bytes)]
fn main() {
assert_eq!(concat_bytes!(), &[]);
assert_eq!(concat_bytes!(b'A', b"BC", [68, b'E', 70]), b"ABCDEF");
}
```
If strings or characters are used where byte strings or byte characters are required, it suggests adding a `b` prefix. If a number is used outside of an array it suggests arrayifying it. If a boolean is used it suggests replacing it with the numeric value of that number. Doubly nested arrays of bytes are disallowed.
suggest casting between i/u32 and char
As discussed in https://github.com/rust-lang/rust/issues/91063 , this adds a suggestion for converting between i32/u32 <-> char with `as`, and a short explanation for why this is safe
Rollup of 7 pull requests
Successful merges:
- #90709 (Only shown relevant type params in E0283 label)
- #91551 (Allow for failure of subst_normalize_erasing_regions in const_eval)
- #91570 (Evaluate inline const pat early and report error if too generic)
- #91571 (Remove unneeded access to pretty printer's `s` field in favor of deref)
- #91610 (Link to rustdoc_json_types docs instead of rustdoc-json RFC)
- #91619 (Update cargo)
- #91630 (Add missing whitespace before disabled HTML attribute)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Remove unneeded access to pretty printer's `s` field in favor of deref
I found it taxing in some of my recent PRs touching the pretty printer to maintain consistency with the surrounding code, since the current code is all over the place about whether it uses `self.s.…()` or `self.…()` for invoking methods of `rustc_ast_pretty::pp::Printer`.
This PR standardizes on `self.…()` — relying on the `Deref` and `DerefMut` impls introduced by [#62532](cab453250a).
Allow for failure of subst_normalize_erasing_regions in const_eval
Fixes https://github.com/rust-lang/rust/issues/72845
Using associated types that cannot be normalized previously resulted in an ICE. We now allow for normalization failure and return a "TooGeneric" error in that case.
r? ```@RalfJung``` maybe?
Only shown relevant type params in E0283 label
When we point at a binding to suggest giving it a type, erase all the
type for ADTs that have been resolved, leaving only the ones that could
not be inferred. For small shallow types this is not a problem, but for
big nested types with lots of params, this can otherwise cause a lot of
unnecessary visual output.
Use object crate for .rustc metadata generation
We already use the object crate for generating uncompressed .rmeta
metadata object files. This switches the generation of compressed
.rustc object files to use the object crate as well. These have
slightly different requirements in that .rmeta should be completely
excluded from any final compilation artifacts, while .rustc should
be part of shared objects, but not loaded into memory.
The primary motivation for this change is #90326: In LLVM 14, the
current way of setting section flags (and in particular, preventing
the setting of SHF_ALLOC) will no longer work. There are other ways
we could work around this, but switching to the object crate seems
like the most elegant, as we already use it for .rmeta, and as it
makes this independent of the codegen backend. In particular, we
don't need separate handling in codegen_llvm and codegen_gcc.
codegen_cranelift should be able to reuse the implementation as
well, though I have omitted that here, as it is not based on
codegen_ssa.
This change mostly extracts the existing code for .rmeta handling
to allow using it for .rustc as well, and adjusts the codegen
infrastructure to handle the metadata object file separately: We
no longer create a backend-specific module for it, and directly
produce the compiled module instead.
This does not `fix` #90326 by itself yet, as .llvmbc will need to be
handled separately.
r? `@nagisa`
Remove `in_band_lifetimes` from `rustc_mir_transform`
Like #91580, this was inspired by the conversation in #44524 about possibly removing the feature from the compiler. This crate is a heavy `'tcx` user, so is a nice case study.
r? ``@petrochenkov``
Three interesting ones:
This one had the `'tcx` declared on the function, despite the trait taking a `'tcx`:
```diff
-impl Visitor<'_> for UsedLocals {
+impl<'tcx> Visitor<'tcx> for UsedLocals {
fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
```
This one use in-band for one, and underscore for the other:
```diff
-pub fn remove_dead_blocks(tcx: TyCtxt<'tcx>, body: &mut Body<'_>) {
+pub fn remove_dead_blocks<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
```
A spurious name, since there's no single-use-lifetime warning:
```diff
-pub fn run_passes(tcx: TyCtxt<'tcx>, body: &'mir mut Body<'tcx>, passes: &[&dyn MirPass<'tcx>]) {
+pub fn run_passes<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>, passes: &[&dyn MirPass<'tcx>]) {
```
Address some FIXMEs left over from #91475
This shouldn't change behavior, only clarify what we're currently doing. I filed #91576 to see if the treatment of generator drop shims is intentional.
cc #91475
Do not add `;` to expected tokens list when it's wrong
There's a few spots where semicolons are checked for to do error recovery, and should not be suggested (or checked for other stuff).
Fixes#87647
Deprecate crate_type and crate_name nested inside #![cfg_attr]
This implements the proposal in https://github.com/rust-lang/rust/pull/83676#issuecomment-811213956, with a future compatibility lint imposed on usage of crate_type/crate_name inside cfg's.
This is a compromise between removing `#![crate_type]` and `#![crate_name]` completely and keeping them as a whole, which requires somewhat of a hack in rustc and is impossible to support by gcc-rust. By only removing `#![crate_type]` and `#![crate_name]` nested inside `#![cfg_attr]` it becomes possible to parse them before a big chunk of the compiler has started.
Replaces https://github.com/rust-lang/rust/pull/83676
```rust
#![crate_type = "lib"] // remains working
#![cfg_attr(foo, crate_type = "bin")] // will stop working
```
# Rationale
As it currently is it is possible to try to access the stable crate id before it is actually set, which will panic. The fact that the Session contains mutable state beyond debugging things also doesn't completely sit well with me. Especially once parallel rustc becomes the default.
I think there is currently also a cyclic dependency where you need to set the stable crate id to be able to load crates, but you need to load crates to expand proc macro attributes that may define #![crate_name] or #![crate_type]. Currently crate level proc macro attributes are unstable or completely unsupported (can't remember which), so this is not a problem, but it may become an issue in the future.
Finally if we want to add incremental compilation to macro expansion or even parsing, we need the StableCrateId to be created together with the Session or even earlier as incremental compilation determines the incremental compilation session dir based on the StableCrateId.
In LLVM 14, our current method of setting section flags to avoid
embedding the `.llvmbc` section into final compilation artifacts
will no longer work, see issue #90326. The upstream recommendation
is to instead embed the entire bitcode using module-level inline
assembly, which is what this change does.
I've kept the existing code for platforms where we do not need to
set section flags, but possibly we should always be using the
inline asm approach.
This one is a heavy `'tcx` user.
Two interesting ones:
This one had the `'tcx` declared on the function, despite the trait taking a `'tcx`:
```diff
-impl Visitor<'_> for UsedLocals {
+impl<'tcx> Visitor<'tcx> for UsedLocals {
fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
```
This one use in-band for one, and underscore for the other:
```diff
-pub fn remove_dead_blocks(tcx: TyCtxt<'tcx>, body: &mut Body<'_>) {
+pub fn remove_dead_blocks<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
```
Avoid string validation in rustc_serialize, check a marker byte instead
Since the serialization format isn't self-describing we need a way to detect when encoder and decoder don't match up. But for strings it doesn't have to be utf8 validation, which currently does cost a few percent of performance.
Instead we can use a marker byte at the end to be reasonably sure that we're dealing with a string and it wasn't overwritten in some way.
Support AVR for inline asm!
A first pass at support for the AVR platform in inline `asm!`. Passes the initial compiler tests, have not yet done more complete verification.
In particular, the register classes could use a lot more fleshing out, this draft PR so far only includes the most basic.
cc `@Amanieu` `@dylanmckay`
Remove a dead code path.
It is neither documented nor can I see any way it could ever be reached.
Also, no tests fail when turning that arm into an ICE
Fix AnonConst ICE
I am not sure if this is even the correct place to fix this issue, but i went down the path where the generic args came from and i wasn't able to find a clear cause for this down there. But if anybody has a suggestion what i should do, just tell me.
This fixes: https://github.com/rust-lang/rust/issues/91267
We already use the object crate for generating uncompressed .rmeta
metadata object files. This switches the generation of compressed
.rustc object files to use the object crate as well. These have
slightly different requirements in that .rmeta should be completely
excluded from any final compilation artifacts, while .rustc should
be part of shared objects, but not loaded into memory.
The primary motivation for this change is #90326: In LLVM 14, the
current way of setting section flags (and in particular, preventing
the setting of SHF_ALLOC) will no longer work. There are other ways
we could work around this, but switching to the object crate seems
like the most elegant, as we already use it for .rmeta, and as it
makes this independent of the codegen backend. In particular, we
don't need separate handling in codegen_llvm and codegen_gcc.
codegen_cranelift should be able to reuse the implementation as
well, though I have omitted that here, as it is not based on
codegen_ssa.
This change mostly extracts the existing code for .rmeta handling
to allow using it for .rustc as well, and adjust the codegen
infrastructure to handle the metadata object file separately: We
no longer create a backend-specific module for it, and directly
produce the compiled module instead.
This does not fix#90326 by itself yet, as .llvmbc will need to be
handled separately.
When we point at a binding to suggest giving it a type, erase all the
type for ADTs that have been resolved, leaving only the ones that could
not be inferred. For small shallow types this is not a problem, but for
big nested types with lots of params, this can otherwise cause a lot of
unnecessary visual output.
This largely avoids remapping from and to the 'real' indices, with the exception
of predecessor lookup and the final merge back, and is conceptually better.
As the paper indicates, the unprocessed vertices in the DFS tree and processed
vertices are disjoint, and we can use them in the same space, tracking only the index
of the split.
This replaces the previous implementation with the simple variant of
Lengauer-Tarjan, which performs better in the general case. Performance on the
keccak benchmark is about equivalent between the two, but we don't see
regressions (and indeed see improvements) on other benchmarks, even on a
partially optimized implementation.
The implementation here follows that of the pseudocode in "Linear-Time
Algorithms for Dominators and Related Problems" thesis by Loukas Georgiadis. The
next few commits will optimize the implementation as suggested in the thesis.
Several related works are cited in the comments within the implementation, as
well.
Implement the simple Lengauer-Tarjan algorithm
This replaces the previous implementation (from #34169), which has not been
optimized since, with the simple variant of Lengauer-Tarjan which performs
better in the general case. A previous attempt -- not kept in commit history --
attempted a replacement with a bitset-based implementation, but this led to
regressions on perf.rust-lang.org benchmarks and equivalent wins for the keccak
benchmark, so was rejected.
The implementation here follows that of the pseudocode in "Linear-Time
Algorithms for Dominators and Related Problems" thesis by Loukas Georgiadis. The
next few commits will optimize the implementation as suggested in the thesis.
Several related works are cited in the comments within the implementation, as
well.
On the keccak benchmark, we were previously spending 15% of our cycles computing
the NCA / intersect function; this function is quite expensive, especially on
modern CPUs, as it chases pointers on every iteration in a tight loop. With this
commit, we spend ~0.05% of our time in dominator computation.
Also add a test case for inserting a semicolon on extern fns.
Without this fix, we got an error like this:
error: expected one of `->`, `where`, or `{`, found `}`
--> chk.rs:3:1
|
2 | fn foo()
| --- - expected one of `->`, `where`, or `{`
| |
| while parsing this `fn`
3 | }
| ^ unexpected token
Since this is inside an extern block, you're required to write function
prototypes with no body. This fixes a regression, and adds a test case
for it.
since the serialization format isn't self-describing we need a way to detect
when encoder and decoder don't match up. but that doesn't have to
be utf8 validation for strings, which does cost a few % of performance.
Instead we can use a marker byte at the end to be reasonably
sure that we're dealing with a string and it wasn't overwritten in some
way.
Stop enabling `in_band_lifetimes` in rustc_data_structures
There's a conversation started in the tracking issue about possibly unaccepting `in_band_lifetimes`, but it's used heavily in the compiler, and thus there'd need to be a bunch of PRs like this if that were to happen.
So here's one to see how much of an impact it has. For this crate, at least, it doesn't seem like in-band was a big win -- about half the places that were using it didn't even need a named lifetime.
(Oh, and I removed `nll` while I was here too, since it didn't seem needed. Let me know if I should put that back.)
r? `@petrochenkov`
Delete duplicated helpers from HIR printer
These functions (`cbox`, `nbsp`, `word_nbsp`, `head`, `bopen`, `space_if_not_bol`, `break_offset_if_not_bol`, `synth_comment`, `maybe_print_trailing_comment`, `print_remaining_comments`) are duplicated with identical behavior across the AST printer and HIR printer, but are not specific to AST or HIR data structures.
There's a conversation in the tracking issue about possibly unaccepting `in_band_lifetimes`, but it's used heavily in the compiler, and thus there'd need to be a bunch of PRs like this if that were to happen.
So here's one to see how much of an impact it has.
(Oh, and I removed `nll` while I was here too, since it didn't seem needed. Let me know if I should put that back.)
Add support for riscv64gc-unknown-freebsd
For https://doc.rust-lang.org/nightly/rustc/target-tier-policy.html#tier-3-target-policy:
* A tier 3 target must have a designated developer or developers (the "target maintainers") on record to be CCed when issues arise regarding the target. (The mechanism to track and CC such developers may evolve over time.)
For all Rust targets on FreeBSD, it's [rust@FreeBSD.org](mailto:rust@FreeBSD.org).
* Targets must use naming consistent with any existing targets; for instance, a target for the same CPU or OS as an existing Rust target should use the same name for that CPU or OS. Targets should normally use the same names and naming conventions as used elsewhere in the broader ecosystem beyond Rust (such as in other toolchains), unless they have a very good reason to diverge. Changing the name of a target can be highly disruptive, especially once the target reaches a higher tier, so getting the name right is important even for a tier 3 target.
Done.
* Target names should not introduce undue confusion or ambiguity unless absolutely necessary to maintain ecosystem compatibility. For example, if the name of the target makes people extremely likely to form incorrect beliefs about what it targets, the name should be changed or augmented to disambiguate it.
Done
* Tier 3 targets may have unusual requirements to build or use, but must not create legal issues or impose onerous legal terms for the Rust project or for Rust developers or users.
Done.
* The target must not introduce license incompatibilities.
Done.
* Anything added to the Rust repository must be under the standard Rust license (MIT OR Apache-2.0).
Fine with me.
* The target must not cause the Rust tools or libraries built for any other host (even when supporting cross-compilation to the target) to depend on any new dependency less permissive than the Rust licensing policy. This applies whether the dependency is a Rust crate that would require adding new license exceptions (as specified by the tidy tool in the rust-lang/rust repository), or whether the dependency is a native library or binary. In other words, the introduction of the target must not cause a user installing or running a version of Rust or the Rust tools to be subject to any new license requirements.
Done.
* If the target supports building host tools (such as rustc or cargo), those host tools must not depend on proprietary (non-FOSS) libraries, other than ordinary runtime libraries supplied by the platform and commonly used by other binaries built for the target. For instance, rustc built for the target may depend on a common proprietary C runtime library or console output library, but must not depend on a proprietary code generation library or code optimization library. Rust's license permits such combinations, but the Rust project has no interest in maintaining such combinations within the scope of Rust itself, even at tier 3.
Done.
* Targets should not require proprietary (non-FOSS) components to link a functional binary or library.
Done.
* "onerous" here is an intentionally subjective term. At a minimum, "onerous" legal/licensing terms include but are not limited to: non-disclosure requirements, non-compete requirements, contributor license agreements (CLAs) or equivalent, "non-commercial"/"research-only"/etc terms, requirements conditional on the employer or employment of any particular Rust developers, revocable terms, any requirements that create liability for the Rust project or its developers or users, or any requirements that adversely affect the livelihood or prospects of the Rust project or its developers or users.
Fine with me.
* Neither this policy nor any decisions made regarding targets shall create any binding agreement or estoppel by any party. If any member of an approving Rust team serves as one of the maintainers of a target, or has any legal or employment requirement (explicit or implicit) that might affect their decisions regarding a target, they must recuse themselves from any approval decisions regarding the target's tier status, though they may otherwise participate in discussions.
Ok.
* This requirement does not prevent part or all of this policy from being cited in an explicit contract or work agreement (e.g. to implement or maintain support for a target). This requirement exists to ensure that a developer or team responsible for reviewing and approving a target does not face any legal threats or obligations that would prevent them from freely exercising their judgment in such approval, even if such judgment involves subjective matters or goes beyond the letter of these requirements.
Ok.
* Tier 3 targets should attempt to implement as much of the standard libraries as possible and appropriate (core for most targets, alloc for targets that can support dynamic memory allocation, std for targets with an operating system or equivalent layer of system-provided functionality), but may leave some code unimplemented (either unavailable or stubbed out as appropriate), whether because the target makes it impossible to implement or challenging to implement. The authors of pull requests are not obligated to avoid calling any portions of the standard library on the basis of a tier 3 target not implementing those portions.
std is implemented.
* The target must provide documentation for the Rust community explaining how to build for the target, using cross-compilation if possible. If the target supports running tests (even if they do not pass), the documentation must explain how to run tests for the target, using emulation if possible or dedicated hardware if necessary.
Building is possible the same way as other Rust on FreeBSD targets.
* Tier 3 targets must not impose burden on the authors of pull requests, or other developers in the community, to maintain the target. In particular, do not post comments (automated or manual) on a PR that derail or suggest a block on the PR based on a tier 3 target. Do not send automated messages or notifications (via any medium, including via `@)` to a PR author or others involved with a PR regarding a tier 3 target, unless they have opted into such messages.
Ok.
* Backlinks such as those generated by the issue/PR tracker when linking to an issue or PR are not considered a violation of this policy, within reason. However, such messages (even on a separate repository) must not generate notifications to anyone involved with a PR who has not requested such notifications.
Ok.
* Patches adding or updating tier 3 targets must not break any existing tier 2 or tier 1 target, and must not knowingly break another tier 3 target without approval of either the compiler team or the maintainers of the other tier 3 target.
Ok.
* In particular, this may come up when working on closely related targets, such as variations of the same architecture with different features. Avoid introducing unconditional uses of features that another variation of the target may not have; use conditional compilation or runtime detection, as appropriate, to let each target run code supported by that target.
Ok.
compiler/rustc_target: make m68k-unknown-linux-gnu use the gnu base
This makes the m68k arch match the other GNU/Linux based targets by setting the environment to gnu.
...because alignment is always nonzero.
This helps eliminate redundant runtime alignment checks, when a DST
is a field of a struct whose remaining fields have alignment 1.
Don't suggest types whose inner type is erroneous
Currently, we check if the returned type equals to `tcx.ty_error()` not to emit
erroneous types, but this has a pitfall; for example,
`Option<[type error]> != tcx.ty_error()` holds.
Fixes#91371.
Pretty print empty blocks as {}
**Example:**
```rust
macro_rules! p {
($e:expr) => {
println!("{}", stringify!($e));
};
($i:item) => {
println!("{}", stringify!($i));
};
}
fn main() {
p!(if true {});
p!(struct S {});
}
```
**Before:**
```console
if true { }
struct S {
}
```
**After:**
```console
if true {}
struct S {}
```
This affects [`dbg!`](https://doc.rust-lang.org/std/macro.dbg.html), as well as ecosystem uses of stringify such as in [`anyhow::ensure!`](https://docs.rs/anyhow/1/anyhow/macro.ensure.html). Printing a `{ }` in today's heavily rustfmt'd world comes out looking jarring/sloppy.
Skip reborrows in AbstractConstBuilder
Fixes https://github.com/rust-lang/rust/issues/90455
Temporary fix to prevent confusing diagnostics that refer to implicit borrows and derefs until we allow borrows and derefs on constant expressions.
r? `@oli-obk`
Add a MIR pass manager (Taylor's Version)
The final draft of #91386 and #77665.
While the compile-time constraints in #91386 are cool, I decided on a more minimal approach for now. I want to explore phase constraints and maybe relative-ordering constraints in the future, though. This should preserve existing behavior **exactly** (please let me know if it doesn't) while making the following changes to the way we organize things today:
- Each `MirPhase` now corresponds to a single MIR pass. `run_passes` is not responsible for listing the correct MIR phase.
- `run_passes` no longer silently skips passes if the declared MIR phase is greater than or equal to the body's. This has bitten me multiple times. If you want this behavior, you can always branch on `body.phase` yourself.
- If your pass is solely to emit errors, you can use the `MirLint` interface instead, which gets a shared reference to `Body` instead of a mutable one. By differentiating the two, I hope to make it clearer in the short term where lints belong in the pipeline. In the long term perhaps we could enforce this at compile-time?
- MIR is no longer dumped for passes that aren't enabled, or for lints.
I tried to check that `-Zvalidate` still works correctly, since the MIR phase is now updated as soon as the associated pass is done, instead of at the end of all the passes in `run_passes`. However, it looks like `-Zvalidate` is broken with current nightlies anyways 😢 (it spits out a bunch of errors).
cc `@oli-obk` `@wesleywiser`
r? rust-lang/wg-mir-opt
std: Stabilize the `thread_local_const_init` feature
This commit is intended to follow the stabilization disposition of the
FCP that has now finished in #84223. This stabilizes the ability to flag
thread local initializers as `const` expressions which enables the macro
to generate more efficient code for accessing it, notably removing
runtime checks for initialization.
More information can also be found in #84223 as well as the tests where
the feature usage was removed in this PR.
Closes#84223