This patch adds two methods to `Duration`. The first, `Duration::zero`,
provides a `const` constructor for getting an zero-length duration. This
is also what `Default` provides (this was clarified in the docs), though
`default` is not `const`.
The second, `Duration::is_zero`, returns true if a `Duration` spans no
time (i.e., because its components are all zero). Previously, the way to
do this was either to compare both `as_secs` and `subsec_nanos` to 0, to
compare against `Duration::new(0, 0)`, or to use the `u128` method
`as_nanos`, none of which were particularly elegant.
Rollup of 16 pull requests
Successful merges:
- #71420 (Specialization is unsound)
- #71899 (Refactor `try_find` a little)
- #72689 (add str to common types)
- #72791 (update coerce docs and unify relevant tests)
- #72934 (forbid mutable references in all constant contexts except for const-fns)
- #73027 (Make `need_type_info_err` more conservative)
- #73347 (Diagnose use of incompatible sanitizers)
- #73359 (shim.rs: avoid creating `Call` terminators calling `Self`)
- #73399 (Clean up E0668 explanation)
- #73436 (Clean up E0670 explanation)
- #73440 (Add src/librustdoc as an alias for src/tools/rustdoc)
- #73442 (pretty/mir: const value enums with no variants)
- #73452 (Unify region variables when projecting associated types)
- #73458 (Use alloc::Layout in DroplessArena API)
- #73484 (Update the doc for std::prelude to the correct behavior)
- #73506 (Bump Rustfmt and RLS)
Failed merges:
r? @ghost
Update the doc for std::prelude to the correct behavior
Fixes#64686.
One line change to ensure the docs are correct about the behavior of the compiler when inserting`std::prelude::v1`.
I don't think examples are necessary but I can add some (especially those from the original issue) if needed.
Unify region variables when projecting associated types
This is required to avoid cycles when evaluating auto trait predicates.
Notably, this is required to be able add Chalk types to `CtxtInterners` for `cfg(parallel_compiler)`.
r? @nikomatsakis
pretty/mir: const value enums with no variants
Fixes#72181.
This PR modifies the pretty printer and const eval in the MIR so that `destructure_const` (used in `pretty_print_const_value`) can handle enums with no variants (or types containing enums with no variants).
I'm not convinced that this is the correct approach, folks more familiar with `destructure_const` would be able to say - happy to adjust the PR. Looking through `destructure_const` and the functions that it invokes, it didn't seem like it was written to handle zero-variant-enums - I assume that case is handled earlier in some way so `destructure_const` doesn't need to under normal circumstances. It didn't seem like it would be straightforward to make `destructure_const` handle this case in a first-class-feeling way (e.g. adding a `Variants::None` variant), so this PR makes some minimal changes to avoid ICEs.
Diagnose use of incompatible sanitizers
Emit an error when incompatible sanitizer are configured through command
line options. Previously the last one configured prevailed and others
were silently ignored.
Additionally use a set to represent configured sanitizers, making it
possible to enable multiple sanitizers at once. At least in principle,
since currently all of them are considered to be incompatible with
others.
Make `need_type_info_err` more conservative
Makes sure arg patterns we are going to suggest on are actually contained within the span of the obligation that caused the inference error (credit to @lcnr for suggesting this fix).
There's a subtle trade-off regarding the handling of local patterns which I've left a comment about.
Resolves#72690
update coerce docs and unify relevant tests
Merges `test/ui/coerce` with `test/ui/coercion`.
Updates the documentation of `librustc_typeck/check/coercion.rs`.
Adds 2 new coercion tests.
add str to common types
I already expected this to be the case and it may slightly improve perf.
Afaict if we ever want to change str into a lang item this would have to get reverted.
As that would be fairly simple I don't believe this to cause any problems in the future.
Refactor `try_find` a little
~~This works like `find_map`, but mapping to a `Try` type. It stops when `Ok` is `Some(value)`, with an additional short-circuit on `Try::Error`. This is similar to the unstable `try_find`, but has the advantage of being able to directly return the user's `R: Try` type directly, rather than converting to `Result`.~~
(removed -- `try_find_map` was declined in review)
This PR also refactors `try_find` a little to match style. The `E` type parameter was unnecessary, so it's now removed. The folding closure now has reduced parametricity on just `T = Self::Item`, rather
than the whole `Self` iterator type. There's otherwise no functional change in this.
Specialization is unsound
As discussed in https://github.com/rust-lang/rust/issues/31844#issuecomment-617013949, it might be a good idea to warn users of specialization that the feature they are using is unsound.
I also expanded the "incomplete feature" warning to link the user to the tracking issue.
Rollup of 13 pull requests
Successful merges:
- #71568 (Document unsafety in slice/sort.rs)
- #72709 (`#[deny(unsafe_op_in_unsafe_fn)]` in liballoc)
- #73214 (Add asm!() support for hexagon)
- #73248 (save_analysis: improve handling of enum struct variant)
- #73257 (ty: projections in `transparent_newtype_field`)
- #73261 (Suggest `?Sized` when applicable for ADTs)
- #73300 (Implement crate-level-only lints checking.)
- #73334 (Note numeric literals that can never fit in an expected type)
- #73357 (Use `LocalDefId` for import IDs in trait map)
- #73364 (asm: Allow multiple template string arguments; interpret them as newline-separated)
- #73382 (Only display other method receiver candidates if they actually apply)
- #73465 (Add specialization of `ToString for char`)
- #73489 (Refactor hir::Place)
Failed merges:
r? @ghost
The `E` type parameter was unnecessary, so it's now removed. The folding
closure now has reduced parametricity on just `T = Self::Item`, rather
than the whole `Self` iterator type. There's otherwise no functional
change in this.
ty: projections in `transparent_newtype_field`
Fixes#73249.
This PR modifies `transparent_newtype_field` so that it handles
projections with generic parameters, where `normalize_erasing_regions`
would ICE.
Refactor hir::Place
For the following code
```rust
let c = || bar(foo.x, foo.x)
```
We generate two different `hir::Place`s for both `foo.x`.
Handling this adds overhead for analysis we need to do for RFC 2229.
We also want to store type information at each Projection to support
analysis as part of the RFC. This resembles what we have for
`mir::Place`
This commit modifies the Place as follows:
- Rename to `PlaceWithHirId`, where there `hir_id` is that of the
expressioin.
- Move any other information that describes the access out to another
struct now called `Place`.
- Removed `Span`, it can be accessed using the [hir
API](https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/hir/map/struct.Map.html#method.span)
- Modify `Projection` to be a strucutre of its own, that currently only
contains the `ProjectionKind`.
Adding type information to projections wil be completed as part of https://github.com/rust-lang/project-rfc-2229/issues/5
Closes https://github.com/rust-lang/project-rfc-2229/issues/3
Only display other method receiver candidates if they actually apply
Previously, we would suggest `Box<Self>` as a valid receiver, even if
method resolution only succeeded due to an autoderef (e.g. to `&self`)
asm: Allow multiple template string arguments; interpret them as newline-separated
Allow the `asm!` macro to accept a series of template arguments, and interpret them as if they were concatenated with a '\n' between them. This allows writing an `asm!` where each line of assembly appears in a separate template string argument.
This syntax makes it possible for rustfmt to reliably format and indent each line of assembly, without risking changes to the inside of a template string. It also avoids the complexity of having the user carefully format and indent a multi-line string (including where to put the surrounding quotes), and avoids the extra indentation and lines of a call to `concat!`.
For example, rewriting the second example from the [blog post on the new inline assembly syntax](https://blog.rust-lang.org/inside-rust/2020/06/08/new-inline-asm.html) using multiple template strings:
```rust
fn main() {
let mut bits = [0u8; 64];
for value in 0..=1024u64 {
let popcnt;
unsafe {
asm!(
" popcnt {popcnt}, {v}",
"2:",
" blsi rax, {v}",
" jz 1f",
" xor {v}, rax",
" tzcnt rax, rax",
" stosb",
" jmp 2b",
"1:",
v = inout(reg) value => _,
popcnt = out(reg) popcnt,
out("rax") _, // scratch
inout("rdi") bits.as_mut_ptr() => _,
);
}
println!("bits of {}: {:?}", value, &bits[0..popcnt]);
}
}
```
Note that all the template strings must appear before all other arguments; you cannot, for instance, provide a series of template strings intermixed with the corresponding operands.
Note numeric literals that can never fit in an expected type
re https://github.com/rust-lang/rust/pull/72380#discussion_r438289385
Given the toy code
```rust
fn is_positive(n: usize) {
n > -1_isize;
}
```
We currently get a type mismatch error like the following:
```
error[E0308]: mismatched types
--> src/main.rs:2:9
|
2 | n > -1_isize;
| ^^^^^^^^ expected `usize`, found `isize`
|
help: you can convert an `isize` to `usize` and panic if the converted value wouldn't fit
|
2 | n > (-1_isize).try_into().unwrap();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
But clearly, `-1` can never fit into a `usize`, so the suggestion will
always panic. A more useful message would tell the user that the value
can never fit in the expected type:
```
error[E0308]: mismatched types
--> test.rs:2:9
|
2 | n > -1_isize;
| ^^^^^^^^ expected `usize`, found `isize`
|
note: `-1_isize` can never fit into `usize`
--> test.rs:2:9
|
2 | n > -1_isize;
| ^^^^^^^^
```
Which is what this commit implements.
I only added this check for negative literals because
- Currently we can only perform such a check for literals (constant
value propagation is outside the scope of the typechecker at this
point)
- A lint error for out-of-range numeric literals is already emitted
IMO it makes more sense to put this check in librustc_lint, but as far
as I can tell the typecheck pass happens before the lint pass, so I've
added it here.
r? @estebank
Implement crate-level-only lints checking.
This implements a crate_level_only flag on lints, and when it is true, it becomes an error when user tries to specify this flag upon nodes other than crate node.
This also turns on this flag for all non_ascii_ident lints.
ty: projections in `transparent_newtype_field`
Fixes#73249.
This PR modifies `transparent_newtype_field` so that it handles
projections with generic parameters, where `normalize_erasing_regions`
would ICE.
`#[deny(unsafe_op_in_unsafe_fn)]` in liballoc
This PR proposes to make use of the new `unsafe_op_in_unsafe_fn` lint, i.e. no longer consider the body of an unsafe function as an unsafe block and require explicit unsafe block to perform unsafe operations.
This has been first (partly) suggested by @Mark-Simulacrum in https://github.com/rust-lang/rust/pull/69245#issuecomment-587817065
Tracking issue for the feature: #71668.
~~Blocked on #71862.~~
r? @Mark-Simulacrum cc @nikomatsakis can you confirm that those changes are desirable? Should I restrict it to only BTree for the moment?
Document unsafety in slice/sort.rs
Let me know if these documentations are accurate c:
I don't think I am capable enough to document the safety of `partition_blocks`, however.
Related issue #66219
This commit modifies the pretty printer and const eval in the MIR so
that `destructure_const` (used in `pretty_print_const_value`) can handle
enums with no variants (or types containing enums with no variants).
Signed-off-by: David Wood <david@davidtw.co>
Speed up bootstrap a little.
The bootstrap script was calling `cargo metadata` 3 times (or 6 with `-v`). This is a very expensive operation, and this attempts to avoid the extra calls. On my system, a simple command like `./x.py test -h -v` goes from about 3 seconds to 0.4.
An overview of the changes:
- Call `cargo metadata` only once with `--no-deps`. Optional dependencies are filtered in `in_tree_crates` (handling `profiler_builtins` and `rustc_codegen_llvm` which are driven by the config).
- Remove a duplicate call to `metadata::build` when using `-v`. I'm not sure why it was there, it looks like a mistake or vestigial from previous behavior.
- Remove check for `_shim`, I believe all the `_shim` crates are now gone.
- Remove check for `rustc_` and `*san` for `test::Crate::should_run`, these are no longer dependencies in the `test` tree.
- Use relative paths in `./x.py test -h -v` output.
- Some code cleanup (remove unnecessary `find_compiler_crates`, etc.).
- Show suite paths (`src/test/ui/...`) in `./x.py test -h -v` output.
- Some doc comments.
bootstrap/install.rs: support a nonexistent `prefix` in `x.py install`
PR #49778 introduced fs::canonicalize() which fails for a nonexistent path.
This is a surprise for someone used to GNU Autotools' configure which can create any necessary intermediate directories in prefix.
This change makes it run fs::create_dir_all() before canonicalize().
bootstrap: read config from $RUST_BOOTSTRAP_CONFIG
This PR modifies bootstrap so that `config.toml` is read first from `RUST_BOOTSTRAP_CONFIG`, then `--config` and finally `config.toml` in the current directory.
This is a subjective change, intended to improve the ergnomics when using "development shells" for rustc development (for example, using tools such as Nix) which set environment variables to ensure a reproducible environment (these development shells can then be version controlled, e.g. [my rustc shell](6b74a5c170/nix/shells/rustc.nix)). By optionally reading `config.toml` from an environment variable, a `config.toml` can be defined in the development shell and a path to it exposed in the `RUST_BOOTSTRAP_CONFIG` environment variable - avoiding the need to manually symlink the contents of this file to `config.toml` in the working directory.
Change how compiler-builtins gets many CGUs
This commit intends to fix an accidental regression from #70846. The
goal of #70846 was to build compiler-builtins with a maximal number of
CGUs to ensure that each module in the source corresponds to an object
file. This high degree of control for compiler-builtins is desirable to
ensure that there's at most one exported symbol per CGU, ideally
enabling compiler-builtins to not conflict with the system libgcc as
often.
In #70846, however, only part of the compiler understands that
compiler-builtins is built with many CGUs. The rest of the compiler
thinks it's building with `sess.codegen_units()`. Notably the
calculation of `sess.lto()` consults `sess.codegen_units()`, which when
there's only one CGU it disables ThinLTO. This means that
compiler-builtins is built without ThinLTO, which is quite harmful to
performance! This is the root of the cause from #73135 where intrinsics
were found to not be inlining trivial functions.
The fix applied in this commit is to remove the special-casing of
compiler-builtins in the compiler. Instead the build system is now
responsible for special-casing compiler-builtins. It doesn't know
exactly how many CGUs will be needed but it passes a large number that
is assumed to be much greater than the number of source-level modules
needed. After reading the various locations in the compiler source, this
seemed like the best solution rather than adding more and more special
casing in the compiler for compiler-builtins.
Closes#73135