check where-clause for explicit `Sized` before suggesting `?Sized`
Fixes#85945.
Based on #86454.
``@rustbot`` label +A-diagnostics +A-traits +A-typesystem +D-papercut +T-compiler
MIRI says `reverse` is UB, so replace it with something LLVM can vectorize
For small types with padding, the current implementation is UB because it does integer operations on uninit values.
```
error: Undefined Behavior: using uninitialized data, but this operation requires initialized memory
--> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/num/mod.rs:836:5
|
836 | / uint_impl! { u32, u32, i32, 32, 4294967295, 8, "0x10000b3", "0xb301", "0x12345678",
837 | | "0x78563412", "0x1e6a2c48", "[0x78, 0x56, 0x34, 0x12]", "[0x12, 0x34, 0x56, 0x78]", "", "" }
| |________________________________________________________________________________________________^ using uninitialized data, but this operation requires initialized memory
|
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
= note: inside `core::num::<impl u32>::rotate_left` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/num/uint_macros.rs:211:13
= note: inside `core::slice::<impl [Foo]>::reverse` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/slice/mod.rs:701:58
```
<https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=340739f22ca5b457e1da6f361768edc6>
But LLVM has gotten smarter since I wrote the previous implementation in 2017, so this PR removes all the manual magic and just writes it in such a way that LLVM will vectorize. This code is much simpler and has very little `unsafe`, and is actually faster to boot!
If you're curious to see the codegen: <https://rust.godbolt.org/z/Pcn13Y9E3>
Before:
```
running 7 tests
test slice::reverse_simd_f64x4 ... bench: 17,940 ns/iter (+/- 481) = 58448 MB/s
test slice::reverse_u128 ... bench: 17,758 ns/iter (+/- 205) = 59048 MB/s
test slice::reverse_u16 ... bench: 158,234 ns/iter (+/- 6,876) = 6626 MB/s
test slice::reverse_u32 ... bench: 62,047 ns/iter (+/- 1,117) = 16899 MB/s
test slice::reverse_u64 ... bench: 31,582 ns/iter (+/- 552) = 33201 MB/s
test slice::reverse_u8 ... bench: 81,253 ns/iter (+/- 1,510) = 12905 MB/s
test slice::reverse_u8x3 ... bench: 270,615 ns/iter (+/- 11,463) = 3874 MB/s
```
After:
```
running 7 tests
test slice::reverse_simd_f64x4 ... bench: 17,731 ns/iter (+/- 306) = 59137 MB/s
test slice::reverse_u128 ... bench: 17,919 ns/iter (+/- 239) = 58517 MB/s
test slice::reverse_u16 ... bench: 43,160 ns/iter (+/- 607) = 24295 MB/s
test slice::reverse_u32 ... bench: 21,065 ns/iter (+/- 371) = 49778 MB/s
test slice::reverse_u64 ... bench: 21,118 ns/iter (+/- 482) = 49653 MB/s
test slice::reverse_u8 ... bench: 76,878 ns/iter (+/- 1,688) = 13639 MB/s
test slice::reverse_u8x3 ... bench: 264,723 ns/iter (+/- 5,544) = 3961 MB/s
```
Those are the existing benches, <14a2fd640e/library/alloc/benches/slice.rs (L322-L346)>
This also fixes the same suggestion, which was kind of broken, because it just searched for the last occurence of `const` to replace with a `let`. This works great in some cases, but when there is no const and a leading space to the file, it doesn't work and panic with overflow because it thought that it had found a const.
I also changed the suggestion to only trigger if the `const` and the non-constant value are on the same line, because if they aren't, the suggestion is very likely to be wrong.
Also don't trigger the suggestion if the found `const` is on line 0, because that triggers the ICE.
stabilize format args capture
Works as expected, and there are widespread reports of success with it, as well as interest in it.
RFC: rust-lang/rfcs#2795
Tracking issue: https://github.com/rust-lang/rust/issues/67984
Addressing items from the tracking issue:
- We don't support capturing arguments from a non-literal format string like `format_args!(concat!(...))`. We could add that in a future enhancement, or we can decide that it isn't supported (as suggested in https://github.com/rust-lang/rust/issues/67984#issuecomment-801394736 ).
- I've updated the documentation.
- `panic!` now supports capture as well.
- There are potentially opportunities to further improve diagnostics for invalid usage, such as if it looks like the user tried to use an expression rather than a variable. However, such cases are all already caught and provide reasonable syntax errors now, and we can always provided even friendlier diagnostics in the future.
Implement diagnostic for String conversion
This is my first real contribution to rustc, any feedback is highly appreciated.
This should fix https://github.com/rust-lang/rust/issues/89856
Thanks to `@estebank` for guiding me.
check if `String` or `&String` or `&str`
Update compiler/rustc_typeck/src/check/method/suggest.rs
Co-authored-by: Esteban Kuber <estebank@users.noreply.github.com>
remove some trailing whitespace
The spans for "trait bound not satisfied" errors in trivial trait bounds referenced the entire item (fn, impl, struct) before.
Now they only reference the obligation itself (`String: Copy`)
Address #90869
Fix trait object error code
closes#90768
I `grep`:d and changed the occurrences that seemed relevant. Please let me know what you think and if anything is missing!
When suggesting references, substitutions were being forgotten and some types were misused. This led to at
least one ICE and other incorrectly emitted diagnostics. This has been fixed; in some cases this leads to
diagnostics changing, and tests have been adjusted.
Stabilize `const_raw_ptr_deref` for `*const T`
This stabilizes dereferencing immutable raw pointers in const contexts.
It does not stabilize `*mut T` dereferencing. This is behind the
same feature gate as mutable references.
closes https://github.com/rust-lang/rust/issues/51911
proc_macro: Add an expand_expr method to TokenStream
This feature is aimed at giving proc macros access to powers similar to those used by builtin macros such as `format_args!` or `concat!`. These macros are able to accept macros in place of string literal parameters, such as the format string, as they perform recursive macro expansion while being expanded.
This can be especially useful in many cases thanks to helper macros like `concat!`, `stringify!` and `include_str!` which are often used to construct string literals at compile-time in user code.
For now, this method only allows expanding macros which produce literals, although more expressions will be supported before the method is stabilized.
In earlier versions of this PR, this method exclusively returned `Literal`, and spans on returned literals were stripped of expansion context before being returned to be as conservative as possible about permission leakage. The method's naming has been generalized to eventually support arbitrary expressions, and the context stripping has been removed (https://github.com/rust-lang/rust/pull/87264#discussion_r674863279), which should allow for more general APIs like "format_args_implicits" (https://github.com/rust-lang/rust/issues/67984) to be supported as well.
## API Surface
```rust
impl TokenStream {
pub fn expand_expr(&self) -> Result<TokenStream, ExpandError>;
}
#[non_exhaustive]
pub struct ExpandError;
impl Debug for ExpandError { ... }
impl Display for ExpandError { ... }
impl Error for ExpandError {}
impl !Send for ExpandError {}
impl !Sync for ExpandError {}
```
pub use core::simd;
A portable abstraction over SIMD has been a major pursuit in recent years for several programming languages. In Rust, `std::arch` offers explicit SIMD acceleration via compiler intrinsics, but it does so at the cost of having to individually maintain each and every single such API, and is almost completely `unsafe` to use. `core::simd` offers safe abstractions that are resolved to the appropriate SIMD instructions by LLVM during compilation, including scalar instructions if that is all that is available.
`core::simd` is enabled by the `#![portable_simd]` nightly feature tracked in https://github.com/rust-lang/rust/issues/86656 and is introduced here by pulling in the https://github.com/rust-lang/portable-simd repository as a subtree. We built the repository out-of-tree to allow faster compilation and a stochastic test suite backed by the proptest crate to verify that different targets, features, and optimizations produce the same result, so that using this library does not introduce any surprises. As these tests are technically non-deterministic, and thus can introduce overly interesting Heisenbugs if included in the rustc CI, they are visible in the commit history of the subtree but do nothing here. Some tests **are** introduced via the documentation, but these use deterministic asserts.
There are multiple unsolved problems with the library at the current moment, including a want for better documentation, technical issues with LLVM scalarizing and lowering to libm, room for improvement for the APIs, and so far I have not added the necessary plumbing for allowing the more experimental or libm-dependent APIs to be used. However, I thought it would be prudent to open this for review in its current condition, as it is both usable and it is likely I am going to learn something else needs to be fixed when bors tries this out.
The major types are
- `core::simd::Simd<T, N>`
- `core::simd::Mask<T, N>`
There is also the `LaneCount` struct, which, together with the SimdElement and SupportedLaneCount traits, limit the implementation's maximum support to vectors we know will actually compile and provide supporting logic for bitmasks. I'm hoping to simplify at least some of these out of the way as the compiler and library evolve.
These tests just verify some basic APIs of core::simd function, and
guarantees that attempting to access the wrong things doesn't work.
The majority of tests are stochastic, and so remain upstream, but
a few deterministic tests arrive in the subtree as doc tests.
This enables programmers to use a safe alternative to the current
`extern "platform-intrinsics"` API for writing portable SIMD code.
This is `#![feature(portable_simd)]` as tracked in #86656
This feature is aimed at giving proc macros access to powers similar to
those used by builtin macros such as `format_args!` or `concat!`. These
macros are able to accept macros in place of string literal parameters,
such as the format string, as they perform recursive macro expansion
while being expanded.
This can be especially useful in many cases thanks to helper macros like
`concat!`, `stringify!` and `include_str!` which are often used to
construct string literals at compile-time in user code.
For now, this method only allows expanding macros which produce
literals, although more expresisons will be supported before the method
is stabilized.
Shorten Span of unused macro lints
The span has been reduced to the actual ident of the macro, instead of linting the
*whole* macro.
Closes#90745
r? ``@estebank``
For small types with padding, the current implementation is UB because it does integer operations on uninit values. But LLVM has gotten smarter since I wrote the previous implementation in 2017, so remove all the manual magic and just write it in such a way that LLVM will vectorize. This code is much simpler (albeit nuanced) and has very little `unsafe`, and is actually faster to boot!
Added the --temps-dir option
Fixes#10971.
The new `--temps-dir` option puts intermediate files in a user-specified directory. This provides a fix for the issue where parallel invocations of rustc would overwrite each other's intermediate files.
No files are kept in the intermediate directory unless `-C save-temps=yes`.
If additional files are specifically requested using `--emit asm,llvm-bc,llvm-ir,obj,metadata,link,dep-info,mir`, these will be put in the output directory rather than the intermediate directory.
This is a backward-compatible change, i.e. if `--temps-dir` is not specified, the behavior is the same as before.
Only use `clone3` when needed for pidfd
In #89522 we learned that `clone3` is interacting poorly with Gentoo's
`sandbox` tool. We only need that for the unstable pidfd extensions, so
otherwise avoid that and use a normal `fork`.
This is a re-application of beta #89924, now that we're aware that we need
more than just a temporary release fix. I also reverted 12fbabd27f, as
that was just fallout from using `clone3` instead of `fork`.
r? `@Mark-Simulacrum`
cc `@joshtriplett`
Because after PR 86041, the optimizer no longer load-merges at the LLVM IR level, which might be part of the perf loss. (I'll run perf and see if this makes a difference.)
Also I added a codegen test so this hopefully won't regress in future -- it passes on stable and with my change here, but not on the 2021-11-09 nightly.
Rollup of 7 pull requests
Successful merges:
- #89561 (Type inference for inline consts)
- #90035 (implement rfc-2528 type_changing-struct-update)
- #90613 (Allow to run a specific rustdoc-js* test)
- #90683 (Make `compiler-docs` only control the default instead of being a hard off-switch)
- #90685 (x.py: remove fixme by deleting code)
- #90701 (Record more artifact sizes during self-profiling.)
- #90723 (Better document `Box` and `alloc::alloc::box_free` connection)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
implement rfc-2528 type_changing-struct-update
This PR implement rfc2528-type_changing-struct-update.
The main change process is as follows:
1. Move the processing part of `base_expr` into `check_expr_struct_fields` to avoid returning `remaining_fields` (a relatively complex hash table)
2. Before performing the type consistency check(`check_expr_has_type_or_error`), if the `type_changing_struct_update` feature is set, enter a different processing flow, otherwise keep the original flow
3. In the case of the same structure definition, check each field in `remaining_fields`. If the field in `base_expr` is not the suptype of the field in `adt_ty`, an error(`FeildMisMatch`) will be reported.
The MIR part does not need to be changed, because only the items contained in `remaining_fields` will be extracted from `base_expr` when MIR is generated. This means that fields with different types in `base_expr` will not be used
Updates #86618
cc `@nikomatsakis`
Type inference for inline consts
Fixes#78132Fixes#78174Fixes#81857Fixes#89964
Perform type checking/inference of inline consts in the same context as the outer def, similar to what is currently done to closure.
Doing so would require `closure_base_def_id` of the inline const to return the outer def, and since `closure_base_def_id` can be called on non-local crate (and thus have no HIR available), a new `DefKind` is created for inline consts.
The type of the generated anon const can capture lifetime of outer def, so we couldn't just use the typeck result as the type of the inline const's def. Closure has a similar issue, and it uses extra type params `CK, CS, U` to capture closure kind, input/output signature and upvars. I use a similar approach for inline consts, letting it have an extra type param `R`, and then `typeof(InlineConst<[paremt generics], R>)` would just be `R`. In borrowck region requirements are also propagated to the outer MIR body just like it's currently done for closure.
With this PR, inline consts in expression position are quitely usable now; however the usage in pattern position is still incomplete -- since those does not remain in the MIR borrowck couldn't verify the lifetime there. I have left an ignored test as a FIXME.
Some disucssions can be found on [this Zulip thread](https://rust-lang.zulipchat.com/#narrow/stream/260443-project-const-generics/topic/inline.20consts.20typeck).
cc `````@spastorino````` `````@lcnr`````
r? `````@nikomatsakis`````
`````@rustbot````` label A-inference F-inline_const T-compiler
treat illumos like solaris in failing ui tests which need it
Just adding the right cfg target for tests which fail because they don't know illumos is a thing.
(cc `````@jclulow)`````
Don't abort compilation after giving a lint error
The only reason to use `abort_if_errors` is when the program is so broken that either:
1. later passes get confused and ICE
2. any diagnostics from later passes would be noise
This is never the case for lints, because the compiler has to be able to deal with `allow`-ed lints.
So it can continue to lint and compile even if there are lint errors.
Closes https://github.com/rust-lang/rust/issues/82761. This is a WIP because I have a feeling it will exit with 0 even if there were lint errors; I don't have a computer that can build rustc locally at the moment.
Don't destructure args tuple in format_args!
This allows Clippy to parse the HIR more simply since `arg0` is changed to `_args.0`. (cc rust-lang/rust-clippy#7843). From rustc's perspective, I think this is something between a lateral move and a tiny improvement since there are fewer bindings.
r? `@m-ou-se`
Fix bug with `#[doc]` string single-character last lines
Fixes#90618.
This is because `.iter().all(|c| c == '*')` returns `true` if there is no character checked. And in case the last line has only one character, it simply returns `true`, making the last line behind removed.
The only reason to use `abort_if_errors` is when the program is so broken that either:
1. later passes get confused and ICE
2. any diagnostics from later passes would be noise
This is never the case for lints, because the compiler has to be able to deal with `allow`-ed lints.
So it can continue to lint and compile even if there are lint errors.
Improve error when an .rlib can't be parsed
This usually describes either an error in the compiler itself or some
sort of IO error. Either way, we should report it to the user rather
than just saying "crate not found".
This only gives an error if the crate couldn't be loaded at all - if the
compiler finds another .rlib or .rmeta file which was valid, it will
continue to compile the crate.
Example output:
```
error[E0785]: found invalid metadata files for crate `foo`
--> bar.rs:3:24
|
3 | println!("{}", foo::FOO_11_49[0]);
| ^^^
|
= warning: failed to parse rlib '/home/joshua/test-rustdoc/libfoo.rlib': Invalid archive extended name offset
```
cc `@ehuss`
This usually describes either an error in the compiler itself or some
sort of IO error. Either way, we should report it to the user rather
than just saying "crate not found".
This only gives an error if the crate couldn't be loaded at all - if the
compiler finds another .rlib or .rmeta file which was valid, it will
continue to compile the crate.
Example output:
```
error[E0785]: found invalid metadata files for crate `foo`
--> bar.rs:3:24
|
3 | println!("{}", foo::FOO_11_49[0]);
| ^^^
|
= warning: failed to parse rlib '/home/joshua/test-rustdoc/libfoo.rlib': Invalid archive extended name offset
```
TraitKind -> Trait
TyAliasKind -> TyAlias
ImplKind -> Impl
FnKind -> Fn
All `*Kind`s in AST are supposed to be enums.
Tuple structs are converted to braced structs for the types above, and fields are reordered in syntactic order.
Also, mutable AST visitor now correctly visit spans in defaultness, unsafety, impl polarity and constness.
Add features gates for experimental asm features
This PR splits off parts of `asm!` into separate features because they are not ready for stabilization.
Specifically this adds:
- `asm_const` for `const` operands.
- `asm_sym` for `sym` operands.
- `asm_experimental_arch` for architectures other than x86, x86_64, arm, aarch64 and riscv.
r? `@nagisa`
type error go brrrrrrrr
Fixes#90444
when we relate something like:
`fn(fn((), (), u32))` with `fn(fn((), (), ()))`
we relate the inner fn ptrs:
`fn((), (), u32)` with `fn((), (), ())`
yielding a `TypeError::ArgumentSorts(_, 2)` which we then use as the `TypeError` for the `fn(fn(..))` which later causes the ICE as the `2` does not correspond to any input or output types in `fn(_)`
r? `@estebank`
Suggest dereference of `Box` when inner type is expected
For example:
enum Ty {
Unit,
List(Box<Ty>),
}
fn foo(x: Ty) -> Ty {
match x {
Ty::Unit => Ty::Unit,
Ty::List(elem) => foo(elem),
}
}
Before, the only suggestion was to rewrap `inner` with `Ty::Wrapper`,
which is unhelpful and confusing:
error[E0308]: mismatched types
--> src/test/ui/suggestions/boxed-variant-field.rs:9:31
|
9 | Ty::List(elem) => foo(elem),
| ^^^^
| |
| expected enum `Ty`, found struct `Box`
| help: try using a variant of the expected enum: `Ty::List(elem)`
|
= note: expected enum `Ty`
found struct `Box<Ty>`
Now, rustc will first suggest dereferencing the `Box`, which is most
likely what the user intended:
error[E0308]: mismatched types
--> src/test/ui/suggestions/boxed-variant-field.rs:9:31
|
9 | Ty::List(elem) => foo(elem),
| ^^^^ expected enum `Ty`, found struct `Box`
|
= note: expected enum `Ty`
found struct `Box<Ty>`
help: try dereferencing the `Box`
|
9 | Ty::List(elem) => foo(*elem),
| +
help: try using a variant of the expected enum
|
9 | Ty::List(elem) => foo(Ty::List(elem)),
| ~~~~~~~~~~~~~~
r? ``@davidtwco``
Apply adjustments for field expression even if inaccessible
The adjustments are used later by ExprUseVisitor to build Place projections and without adjustments it can produce invalid result.
Fix#90483
``@rustbot`` label: T-compiler
This stabilizes dereferencing immutable raw pointers in const contexts.
It does not stabilize `*mut T` dereferencing. This is placed behind the
`const_raw_mut_ptr_deref` feature gate.
For example:
enum Ty {
Unit,
List(Box<Ty>),
}
fn foo(x: Ty) -> Ty {
match x {
Ty::Unit => Ty::Unit,
Ty::List(elem) => foo(elem),
}
}
Before, the only suggestion was to rewrap `elem` with `Ty::List`,
which is unhelpful and confusing:
error[E0308]: mismatched types
--> src/test/ui/suggestions/boxed-variant-field.rs:9:31
|
9 | Ty::List(elem) => foo(elem),
| ^^^^
| |
| expected enum `Ty`, found struct `Box`
| help: try using a variant of the expected enum: `Ty::List(elem)`
|
= note: expected enum `Ty`
found struct `Box<Ty>`
Now, rustc will first suggest dereferencing the `Box`, which is most
likely what the user intended:
error[E0308]: mismatched types
--> src/test/ui/suggestions/boxed-variant-field.rs:9:31
|
9 | Ty::List(elem) => foo(elem),
| ^^^^ expected enum `Ty`, found struct `Box`
|
= note: expected enum `Ty`
found struct `Box<Ty>`
help: try dereferencing the `Box`
|
9 | Ty::List(elem) => foo(*elem),
| +
help: try using a variant of the expected enum
|
9 | Ty::List(elem) => foo(Ty::List(elem)),
| ~~~~~~~~~~~~~~
Append .0 to unsuffixed float if it would otherwise become int token
Previously the unsuffixed f32/f64 constructors of `proc_macro::Literal` would create literal tokens that are definitely not a float:
```rust
Literal::f32_unsuffixed(10.0) // 10
Literal::f32_suffixed(10.0) // 10f32
Literal::f64_unsuffixed(10.0) // 10
Literal::f64_suffixed(10.0) // 10f64
```
Notice that the `10` are actually integer tokens if you were to reparse them, not float tokens.
This diff updates `Literal::f32_unsuffixed` and `Literal::f64_unsuffixed` to produce tokens that unambiguously parse as a float. This matches longstanding behavior of the proc-macro2 crate's implementation of these APIs dating back at least 3.5 years, so it's likely an unobjectionable behavior.
```rust
Literal::f32_unsuffixed(10.0) // 10.0
Literal::f32_suffixed(10.0) // 10f32
Literal::f64_unsuffixed(10.0) // 10.0
Literal::f64_suffixed(10.0) // 10f64
```
Fixes https://github.com/dtolnay/syn/issues/1085.
Implementation of GATs outlives lint
See #87479 for background. Closes#87479
The basic premise of this lint/error is to require the user to write where clauses on a GAT when those bounds can be implied or proven from any function on the trait returning that GAT.
## Intuitive Explanation (Attempt) ##
Let's take this trait definition as an example:
```rust
trait Iterable {
type Item<'x>;
fn iter<'a>(&'a self) -> Self::Item<'a>;
}
```
Let's focus on the `iter` function. The first thing to realize is that we know that `Self: 'a` because of `&'a self`. If an impl wants `Self::Item` to contain any data with references, then those references must be derived from `&'a self`. Thus, they must live only as long as `'a`. Furthermore, because of the `Self: 'a` implied bound, they must live only as long as `Self`. Since it's `'a` is used in place of `'x`, it is reasonable to assume that any value of `Self::Item<'x>`, and thus `'x`, will only be able to live as long as `Self`. Therefore, we require this bound on `Item` in the trait.
As another example:
```rust
trait Deserializer<T> {
type Out<'x>;
fn deserialize<'a>(&self, input: &'a T) -> Self::Out<'a>;
}
```
The intuition is similar here, except rather than a `Self: 'a` implied bound, we have a `T: 'a` implied bound. Thus, the data on `Self::Out<'a>` is derived from `&'a T`, and thus it is reasonable to expect that the lifetime `'x` will always be less than `T`.
## Implementation Algorithm ##
* Given a GAT `<P0 as Trait<P1..Pi>>::G<Pi...Pn>` declared as `trait T<A1..Ai> for A0 { type G<Ai...An>; }` used in return type of one associated function `F`
* Given env `E` (including implied bounds) for `F`
* For each lifetime parameter `'a` in `P0...Pn`:
* For each other type parameter `Pi != 'a` in `P0...Pn`: // FIXME: this include of lifetime parameters too
* If `E => (P: 'a)`:
* Require where clause `Ai: 'a`
## Follow-up questions ##
* What should we do when we don't pass params exactly?
For this example:
```rust
trait Des {
type Out<'x, D>;
fn des<'z, T>(&self, data: &'z Wrap<T>) -> Self::Out<'z, Wrap<T>>;
}
```
Should we be requiring a `D: 'x` clause? We pass `Wrap<T>` as `D` and `'z` as `'x`, and should be able to prove that `Wrap<T>: 'z`.
r? `@nikomatsakis`
Rollup of 5 pull requests
Successful merges:
- #89942 (Reorder `widening_impl`s to make the doc clearer)
- #90569 (Fix tests using `only-i686` to use the correct `only-x86` directive)
- #90597 (Warn for variables that are no longer captured)
- #90623 (Remove more checks for LLVM < 12)
- #90626 (Properly register text_direction_codepoint_in_comment lint.)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
Properly register text_direction_codepoint_in_comment lint.
This makes it known to the compiler so it can be configured like with `#![allow(text_direction_codepoint_in_comment)]`.
Fixes#90614.
Fix ICE when rustdoc is scraping examples inside of a proc macro
This PR provides a clearer semantics for how --scrape-examples interacts with macros. If an expression's span AND it's enclosing item's span both are not `from_expansion`, then the example will be scraped. The added test case `rustdoc-scrape-examples-macros` shows a variety of situations.
* A macro-rules macro that takes a function call as input: good
* A macro-rules macro that generates a function call as output: bad
* A proc-macro that generates a function call as output: bad
* An attribute macro that generates a function call as output: bad
* An attribute macro that takes a function call as input: good, if the proc macro is designed to propagate the input spans
I ran this updated rustdoc on pyo3 and confirmed that it successfully scrapes examples from inside a proc macro, eg
<img width="1013" alt="Screen Shot 2021-11-04 at 1 11 28 PM" src="https://user-images.githubusercontent.com/663326/140412691-81a3bb6b-a448-4a1b-a293-f7a795553634.png">
(cc `@mejrs)`
Additionally, this PR fixes an ordering bug in the highlighting logic.
Fixes https://github.com/rust-lang/rust/issues/90567.
r? `@jyn514`
Clean up some `-Z unstable-options` in tests.
Several of these tests were for features that have been stabilized, or otherwise don't need `-Z unstable-options`.
Add beginner friendly lifetime elision hint to E0623
Address #90170
Suggest adding a new lifetime parameter when two elided lifetimes should match up but don't.
Example:
```
error[E0623]: lifetime mismatch
--> $DIR/issue-90170-elision-mismatch.rs:2:35
|
LL | fn foo(slice_a: &mut [u8], slice_b: &mut [u8]) {
| --------- --------- these two types are declared with different lifetimes...
LL | core::mem::swap(&mut slice_a, &mut slice_b);
| ^^^^^^^^^^^^ ...but data from `slice_b` flows into `slice_a` here
|
= note: each elided lifetime in input position becomes a distinct lifetime
help: explicitly declare a lifetime and assign it to both
|
LL | fn foo<'a>(slice_a: &'a mut [u8], slice_b: &'a mut [u8]) {
| ++++ ++ ++
```
for
```rust
fn foo(slice_a: &mut [u8], slice_b: &mut [u8]) {
core::mem::swap(&mut slice_a, &mut slice_b);
}
```
Suggest adding a new lifetime parameter when two elided lifetimes should match up but don't
Issue #90170
This also changes the tests introduced by the previous commits because of another rustc issue (#90258)
The exact set of permissions granted when forming a raw reference is
currently undecided https://github.com/rust-lang/rust/issues/56604.
To avoid presupposing any particular outcome, adjust the const
qualification to be compatible with decision where raw reference
constructed from `addr_of!` grants mutable access.
Split doc_cfg and doc_auto_cfg features
Part of #90497.
With this feature, `doc_cfg` won't pick up items automatically anymore.
cc `@Mark-Simulacrum`
r? `@jyn514`
Collect `panic/panic_bounds_check` during monomorphization
This would prevent link time errors if these functions are `#[inline]` (e.g. when `panic_immediate_abort` is used).
Fix#90405Fixrust-lang/cargo#10019
`@rustbot` label: T-compiler A-codegen
[master] Fix CVE-2021-42574
This PR implements new lints to mitigate the impact of [CVE-2021-42574], caused by the presence of bidirectional-override Unicode codepoints in the compiled source code. [See the advisory][advisory] for more information about the vulnerability.
The changes in this PR will be released in tomorrow's nightly release.
[CVE-2021-42574]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-42574
[advisory]: https://blog.rust-lang.org/2021/11/01/cve-2021-42574.html
Test that promotion follows references when looking for drop
Noticed that this wasn't covered by any of existing tests.
The const checking and const qualification, which currently shares the
implementation with promotion, will likely need a different behaviour
here (see issue #90193).
Fix rare ICE during typeck in rustdoc scrape_examples
While testing the `--scrape-examples` extension on the [wasmtime](https://github.com/bytecodealliance/wasmtime) repository, I found some additional edge cases. Specifically, when asking to typecheck a body containing a function call, I would sometimes get an ICE if:
* The body doesn't exist
* The function's HIR node didn't have a type
This adds checks for both of those conditions.
(Also this updates a test to check that the sources of a reverse-dependency are correctly generated and linked.)
r? `@jyn514`
rustdoc: remove flicker during page load
The search bar has a `:disabled` style that makes it grey, which creates a distracting flicker from grey to white when the page finishes loading. The search bar should stay the same color throughout page load.
A blank white search bar might create an incorrect impression for users with JS turned off. Since they can't use the search functionality, I've hidden the search bar in noscript.css.
Fixes#90246
r? `@GuillaumeGomez`
Demo: https://rustdoc.crud.net/jsha/flashy-searchbar/std/string/struct.String.html
Noticed that this wasn't covered by any of existing tests.
The const checking and const qualification, which currently shares the
implementation with promotion, will likely need a different behaviour
here (see issue #90193).
Add #[must_use] to mem/ptr functions
There's a lot of low-level / unsafe stuff here. Are there legit use cases for ignoring any of these return values?
* No regressions in `./x.py test --stage 1 library/std src/tools/clippy`.
* One regression in `./x.py test --stage 1 src/test/ui`. Fixed.
* I am unable to run `./x.py doc` on my machine so I'll need to wait for the CI to verify doctests pass. I eyeballed all the adjacent tests and they all look okay.
Parent issue: #89692
r? ```@joshtriplett```
Use h3 and h4 for the variant name and the "Fields" subheading.
Remove the "of T" part of the "Fields" subheading.
Remove border-bottom from "Fields" subheading.
Move docblock below "Fields" listing.
Skipping verbose diagnostic suggestions when calling .as_ref() on type not implementing AsRef
Addresses #89806
Skipping suggestions when calling `.as_ref()` for types that do not implement the `AsRef` trait.
r? `@estebank`
Use `is_global` in `candidate_should_be_dropped_in_favor_of`
This manifistated in #90195 with compiler being unable to keep
one candidate for a trait impl, if where is a global impl and more
than one trait bound in the where clause.
Before #87280 `candidate_should_be_dropped_in_favor_of` was using
`TypeFoldable::is_global()` that was enough to discard the two
`ParamCandidate`s. But #87280 changed it to use
`TypeFoldable::is_known_global()` instead, which is pessimistic, so
now the compiler drops the global impl instead (because
`is_known_global` is not sure) and then can't decide between the
two `ParamCandidate`s.
Switching it to use `is_global` again solves the issue.
Fixes#90195.
Improve and test cross-crate hygiene
- Decode the parent expansion for traits and enums in `rustc_resolve`, this was already being used for resolution in typeck
- Avoid suggesting importing names with def-site hygiene, since it's often not useful
- Add more tests
r? `@petrochenkov`
Show all Deref implementations recursively
Fixes#87783.
This is a re-implementation of #80653, so taking the original PR comment:
This changes `rustdoc` to recursively follow `Deref` targets so that methods from all levels are added to the rendered output. This implementation displays the methods from all levels in the expanded state with separate sections for each level.
![image](https://user-images.githubusercontent.com/279572/103482863-46723b00-4ddb-11eb-972b-c463351a425c.png)
cc `@camelid`
r? `@jyn514`
Repace use of `static_nobundle` with `native_link_modifiers` within Rust codebase
This fixes warnings when building Rust and running tests:
```
warning: library kind `static-nobundle` has been superseded by specifying `-bundle` on library kind `static`. Try `static:-bundle`
warning: `rustc_llvm` (lib) generated 2 warnings (1 duplicate)
```
Unify titles in rustdoc book doc attributes chapter
As discussed in https://github.com/rust-lang/rust/pull/90339.
I wasn't able to find out where the link to the titles was used so let's see if the CI fails. :)
r? ``@camelid``
rustdoc: Fix generics generation in search index
The generics were not added to the search index as they should, instead they were added as arguments. I used this opportunity to allow generics to have generics themselves (will come in very handy for my current rewrite of the search engine!).
r? `@jyn514`
Use type based qualification for unions
Union field access is currently qualified based on the qualification of
a value previously assigned to the union. At the same time, every union
access transmutes the content of the union, which might result in a
different qualification.
For example, consider constants A and B as defined below, under the
current rules neither contains interior mutability, since a value used
in the initial assignment did not contain `UnsafeCell` constructor.
```rust
#![feature(untagged_unions)]
union U { i: u32, c: std::cell::Cell<u32> }
const A: U = U { i: 0 };
const B: std::cell::Cell<u32> = unsafe { U { i: 0 }.c };
```
To avoid the issue, the changes here propose to consider the content of
a union as opaque and use type based qualification for union types.
Fixes#90268.
`@rust-lang/wg-const-eval`
Consider indirect mutation during const qualification dataflow
Previously a local would be qualified if either one of two separate data
flow computations indicated so. First determined if a local could
contain the qualif, but ignored any forms of indirect mutation. Second
determined if a local could be mutably borrowed (and so indirectly
mutated), but which in turn ignored the qualif.
The end result was incorrect because the effect of indirect mutation was
effectivelly ignored in the all but the final stage of computation.
In the new implementation the indirect mutation is directly incorporated
into the qualif data flow. The local variable becomes immediately
qualified once it is mutably borrowed and borrowed place type can
contain the qualif.
In general we will now reject additional programs, program that were
prevously unintentionally accepted.
There are also some cases which are now accepted but were previously
rejected, because previous implementation didn't consider whether
borrowed place could have the qualif under the consideration.
Fixes#90124.
r? `@ecstatic-morse`
Revert "Add rustc lint, warning when iterating over hashmaps"
Fixes perf regressions introduced in https://github.com/rust-lang/rust/pull/90235 by temporarily reverting the relevant PR.
Fixes incorrect handling of ADT's drop requirements
Fixes#90024 and a bunch of duplicates.
The main issue was just that the contract of `NeedsDropTypes::adt_components` was inconsistent; the list of types it might return were the generic parameters themselves or the fields of the ADT, depending on the nature of the drop impl. This meant that the caller could not determine whether a `.subst()` call was still needed on those types; it called `.subst()` in all cases, and this led to ICEs when the returned types were the generic params.
First contribution of more than a few lines, so feedback definitely appreciated.
Union field access is currently qualified based on the qualification of
a value previously assigned to the union. At the same time, every union
access transmutes the content of the union, which might result in a
different qualification.
For example, consider constants A and B as defined below, under the
current rules neither contains interior mutability, since a value used
in the initial assignment did not contain `UnsafeCell` constructor.
```rust
#![feature(untagged_unions)]
union U { i: u32, c: std::cell::Cell<u32> }
const A: U = U { i: 0 };
const B: std::cell::Cell<u32> = unsafe { U { i: 0 }.c };
```
To avoid the issue, the changes here propose to consider the content of
a union as opaque and use type based qualification for union types.
Add hint for people missing `TryFrom`, `TryInto`, `FromIterator` import pre-2021
Adds a hint anytime a `TryFrom`, `TryInto`, `FromIterator` import is suggested noting that these traits are automatically imported in Edition 2021.
fix: inner attribute followed by outer attribute causing ICE
Fixes#87936, #88938, and #89971.
This removes the assertion that validates that there are no outer attributes following inner attributes. Where the inner attribute is invalid you get an actual error.
Add LLVM CFI support to the Rust compiler
This PR adds LLVM Control Flow Integrity (CFI) support to the Rust compiler. It initially provides forward-edge control flow protection for Rust-compiled code only by aggregating function pointers in groups identified by their number of arguments.
Forward-edge control flow protection for C or C++ and Rust -compiled code "mixed binaries" (i.e., for when C or C++ and Rust -compiled code share the same virtual address space) will be provided in later work as part of this project by defining and using compatible type identifiers (see Type metadata in the design document in the tracking issue #89653).
LLVM CFI can be enabled with -Zsanitizer=cfi and requires LTO (i.e., -Clto).
Thank you, `@eddyb` and `@pcc,` for all the help!
Rollup of 3 pull requests
Successful merges:
- #90154 (rustdoc: Remove `GetDefId`)
- #90232 (rustdoc: Use TTF based font instead of OTF for CJK glyphs to improve readability)
- #90278 (rustdoc: use better highlighting for *const, *mut, and &mut)
Failed merges:
r? `@ghost`
`@rustbot` modify labels: rollup
rustdoc: Use TTF based font instead of OTF for CJK glyphs to improve readability
Due to Windows' implementation of font rendering, OpenType fonts can be distorted. So the existing font, Noto Sans KR, is not very readable on Windows. This PR improves readability of Korean glyphs on Windows.
## Before
![원1](https://user-images.githubusercontent.com/11029378/138592394-16b15787-532d-4421-a5eb-ed85675290fa.png)
## After
![원2](https://user-images.githubusercontent.com/11029378/138592409-f3a440ee-f0fc-40e4-9561-42c479439c9f.png)
The fonts included in this PR are licensed under the SIL Open Font License and generated with these commands:
```sh
pyftsubset NanumBarunGothic.ttf \
--unicodes=U+AC00-D7AF,U+1100-11FF,U+3130-318F,U+A960-A97F,U+D7B0-D7FF \
--output-file=NanumBarunGothic.ttf.woff --flavor=woff
```
```sh
pyftsubset NanumBarunGothic.ttf \
--unicodes=U+AC00-D7AF,U+1100-11FF,U+3130-318F,U+A960-A97F,U+D7B0-D7FF \
--output-file=NanumBarunGothic.ttf.woff2 --flavor=woff2
```
r? ``@GuillaumeGomez``
Properly check `target_features` not to trigger an assertion
Fixes#89875
I think it should be a condition instead of an assertion to check if it's a register as it's possible that `reg` is a register class.
Also, this isn't related to the issue directly, but `is_target_supported` doesn't check `target_features` attributes. Is there any way to check it on rustc_codegen_llvm?
r? `@Amanieu`
Edit error messages for `rustc_resolve::AmbiguityKind` variants
Edit the language of the ambiguity descriptions for E0659. These strings now appear as notes.
Closes#79717.
Previously a local would be qualified if either one of two separate data
flow computations indicated so. First determined if a local could
contain the qualif, but ignored any forms of indirect mutation. Second
determined if a local could be mutably borrowed (and so indirectly
mutated), but which in turn ignored the qualif.
The end result was incorrect because the effect of indirect mutation was
effectivelly ignored in the all but the final stage of computation.
In the new implementation the indirect mutation is directly incorporated
into the qualif data flow. The local variable becomes immediately
qualified once it is mutably borrowed and borrowed place type can
contain the qualif.
In general we will now reject additional programs, program that were
prevously unintentionally accepted.
There are also some cases which are now accepted but were previously
rejected, because previous implementation didn't consider whether
borrowed place could have the qualif under the consideration.
Emit description of the ambiguity as a note.
Co-authored-by: Noah Lev <camelidcamel@gmail.com>
Co-authored-by: Vadim Petrochenkov <vadim.petrochenkov@gmail.com>
Avoid a branch on key being local for queries that use the same local and extern providers
Currently based on https://github.com/rust-lang/rust/pull/85810 as it slightly conflicts with it. Only the last two commits are new.
This commit adds LLVM Control Flow Integrity (CFI) support to the Rust
compiler. It initially provides forward-edge control flow protection for
Rust-compiled code only by aggregating function pointers in groups
identified by their number of arguments.
Forward-edge control flow protection for C or C++ and Rust -compiled
code "mixed binaries" (i.e., for when C or C++ and Rust -compiled code
share the same virtual address space) will be provided in later work as
part of this project by defining and using compatible type identifiers
(see Type metadata in the design document in the tracking issue #89653).
LLVM CFI can be enabled with -Zsanitizer=cfi and requires LTO (i.e.,
-Clto).
Prevent duplicate caller bounds candidates by exposing default substs in Unevaluated
Fixes https://github.com/rust-lang/rust/issues/89334
The changes introduced in https://github.com/rust-lang/rust/pull/87280 allowed for "duplicate" caller bounds candidates to be assembled that only differed in their default substs having been "exposed" or not and resulted in an ambiguity error during trait selection. To fix this we expose the defaults substs during the creation of the ParamEnv.
r? `@lcnr`
Do not mention a reexported item if it's private
Fixes#90113
The _actual_ regression was introduced in #73652, then #88838 made it worse. This fixes the issue by not counting such an import as a candidate.
Use the "nice E0277 errors"[1] for `!Send` `impl Future` from foreign crate
Partly address #78543 by making the error quieter.
We don't have access to the `typeck` tables from foreign crates, so we
used to completely skip the new code when checking foreign crates. Now,
we carry on and don't provide as nice output (we don't clarify *what* is
making the `Future: !Send`), but at least we no longer emit a sea of
derived obligations in the output.
[1]: https://blog.rust-lang.org/inside-rust/2019/10/11/AsyncAwait-Not-Send-Error-Improvements.html
r? `@tmandry`
Partly address #78543 by making the error quieter.
We don't have access to the `typeck` tables from foreign crates, so we
used to completely skip the new code when checking foreign crates. Now,
we carry on and don't provide as nice output (we don't clarify *what* is
making the `Future: !Send`), but at least we no longer emit a sea of
derived obligations in the output.
[1]: https://blog.rust-lang.org/inside-rust/2019/10/11/AsyncAwait-Not-Send-Error-Improvements.html
Fix ICE when forgetting to `Box` a parameter to a `Self::func` call
Closes#90213 .
Assuming we can get the `DefId` of the receiver causes an ICE if the receiver is `Self`. We can just avoid doing this though.