Stabilize move_ref_pattern
# Implementation
- Initially the rule was added in the run-up to 1.0. The AST-based borrow checker was having difficulty correctly enforcing match expressions that combined ref and move bindings, and so it was decided to simplify forbid the combination out right.
- The move to MIR-based borrow checking made it possible to enforce the rules in a finer-grained level, but we kept the rule in place in an effort to be conservative in our changes.
- In #68376, @Centril lifted the restriction but required a feature-gate.
- This PR removes the feature-gate.
Tracking issue: #68354.
# Description
This PR is to stabilize the feature `move_ref_pattern`, which allows patterns
containing both `by-ref` and `by-move` bindings at the same time.
For example: `Foo(ref x, y)`, where `x` is `by-ref`,
and `y` is `by-move`.
The rules of moving a variable also apply here when moving *part* of a variable,
such as it can't be referenced or moved before.
If this pattern is used, it would result in *partial move*, which means that
part of the variable is moved. The variable that was partially moved from
cannot be used as a whole in this case, only the parts that are still
not moved can be used.
## Documentation
- The reference (rust-lang/reference#881)
- Rust by example (rust-lang/rust-by-example#1377)
## Tests
There are many tests, but I think one of the comperhensive ones:
- [borrowck-move-ref-pattern-pass.rs](85fbf49ce0/src/test/ui/pattern/move-ref-patterns/borrowck-move-ref-pattern-pass.rs)
- [borrowck-move-ref-pattern.rs](85fbf49ce0/src/test/ui/pattern/move-ref-patterns/borrowck-move-ref-pattern.rs)
# Examples
```rust
#[derive(PartialEq, Eq)]
struct Finished {}
#[derive(PartialEq, Eq)]
struct Processing {
status: ProcessStatus,
}
#[derive(PartialEq, Eq)]
enum ProcessStatus {
One,
Two,
Three,
}
#[derive(PartialEq, Eq)]
enum Status {
Finished(Finished),
Processing(Processing),
}
fn check_result(_url: &str) -> Status {
// fetch status from some server
Status::Processing(Processing {
status: ProcessStatus::One,
})
}
fn wait_for_result(url: &str) -> Finished {
let mut previous_status = None;
loop {
match check_result(url) {
Status::Finished(f) => return f,
Status::Processing(p) => {
match (&mut previous_status, p.status) {
(None, status) => previous_status = Some(status), // first status
(Some(previous), status) if *previous == status => {} // no change, ignore
(Some(previous), status) => { // Now it can be used
// new status
*previous = status;
}
}
}
}
}
}
```
Before, we would have used:
```rust
match (&previous_status, p.status) {
(Some(previous), status) if *previous == status => {} // no change, ignore
(_, status) => {
// new status
previous_status = Some(status);
}
}
```
Demonstrating *partial move*
```rust
fn main() {
#[derive(Debug)]
struct Person {
name: String,
age: u8,
}
let person = Person {
name: String::from("Alice"),
age: 20,
};
// `name` is moved out of person, but `age` is referenced
let Person { name, ref age } = person;
println!("The person's age is {}", age);
println!("The person's name is {}", name);
// Error! borrow of partially moved value: `person` partial move occurs
//println!("The person struct is {:?}", person);
// `person` cannot be used but `person.age` can be used as it is not moved
println!("The person's age from person struct is {}", person.age);
}
```
mangling: mangle impl params w/ v0 scheme
This PR modifies v0 symbol mangling to include all generic parameters from impl blocks (not just those used in the self type) - an alternative fix to #75326.
```
original:
_RNCNvXCs4fqI2P2rA04_19impl_param_manglingINtB4_3FooppENtNtNtNtCsfnEnqCNU58Z_4core4iter6traits8iterator8Iterator4next0B4_
// |------------ B4_ ----------------|
// _R (N C (N v (X (C ((s 4fqI2p2rA04_) 19impl_param_mangling)) (I (N t B4_ 3Foo) pp E) (N t (N t (N t (N t (C ((s fnEnqCNU58Z_) 4core)) 4iter) 6traits) 8iterator) 8Iterator)) 4next) 0) B4_
modified:
_RNvXINICs4fqI2P2rA04_11issue_753260pppEINtB5_3FooppENtNtNtNtCsfnEnqCNU58Z_4core4iter6traits8iterator8Iterator4nextB5_
// _R (N v (X (I (N I (C ((s 4fqI2P2rA04_) 11issue_75326)) 0) ppp E) (I (N t B5_ 3Foo) pp E) (N t (N t (N t (N t (C ((s fnEnqCNU58Z_) 4core)) 4iter) 6traits) 8iterator) 8Iterator)) 4next) B5_
// | ^ |
// | | |
// | new impl namespace |
```
~~Submitted as a draft as after some discussion w/ @eddyb, I'm going to do some investigation into (yet more alternative) changes to polymorphization that might remove the necessity for this.~~
r? @eddyb
ensure arguments are included in count mismatch span
The current diagnostic isn't very helpful if the function header spans multiple lines. Lines comprising the function signature may be elided to keep the diagnostic short, but these lines are essential to fixing the error. This is made worse when the function has a body, because the last two lines of the span are then dedicated to showing the end of the body, which is irrelevant.
This PR changes the span to be a multispan made up of the header and the the arguments, ensuring they won't be elided. It also discards the function body from the span.
[Old](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f92d9f81a8c9416f0f04e4e09923b6d4):
```
error[E0061]: this function takes 6 arguments but 1 argument was supplied
--> src/main.rs:18:5
|
1 | / fn bar(
2 | | a: i32,
3 | | b: i32,
4 | | c: i32,
... |
14 | | println!("{}", f);
15 | | }
| |_- defined here
...
18 | bar(1);
| ^^^ - supplied 1 argument
| |
| expected 6 arguments
```
New:
```
error[E0061]: this function takes 6 arguments but 1 argument was supplied
--> $DIR/not-enough-arguments.rs:28:3
|
LL | bar(1);
| ^^^ - supplied 1 argument
| |
| expected 6 arguments
|
note: function defined here
--> $DIR/not-enough-arguments.rs:9:1
|
LL | / fn bar(
LL | | a: i32,
| | ^^^^^^^
LL | | b: i32,
| | ^^^^^^^
LL | | c: i32,
| | ^^^^^^^
LL | | d: i32,
| | ^^^^^^^
LL | | e: i32,
| | ^^^^^^^
LL | | f: i32,
| | ^^^^^^^
LL | | ) {
| |_^
```
This commit improves the tuple struct case added in rust-lang/rust#77341
so that the context is mentioned in more of the message.
Signed-off-by: David Wood <david@davidtw.co>
This commit improves the diagnostic modified in rust-lang/rust#77341 to
suggest not only those variants which do not have fields, but those with
fields (by suggesting with placeholders).
Signed-off-by: David Wood <david@davidtw.co>
Ideally, we would want to handle a broader set of cases to fully fix the
underlying bug here. That is currently relatively expensive at compile and
runtime, so we don't do that for now.
This commit modifies v0 symbol mangling to include all generic
parameters from impl blocks (not just those used in the self type).
Signed-off-by: David Wood <david@davidtw.co>
This commit adjust `#[rustc_symbol_name]` so that it can be applied to
non-monomorphic functions without producing an ICE.
Signed-off-by: David Wood <david@davidtw.co>
The wrapper type led to tons of target.target
across the compiler. Its ptr_width field isn't
required any more, as target_pointer_width
is already present in parsed form.
Preparation for a subsequent change that replaces
rustc_target::config::Config with its wrapped Target.
On its own, this commit breaks the build. I don't like making
build-breaking commits, but in this instance I believe that it
makes review easier, as the "real" changes of this PR can be
seen much more easily.
Result of running:
find compiler/ -type f -exec sed -i -e 's/target\.target\([)\.,; ]\)/target\1/g' {} \;
find compiler/ -type f -exec sed -i -e 's/target\.target$/target/g' {} \;
find compiler/ -type f -exec sed -i -e 's/target.ptr_width/target.pointer_width/g' {} \;
./x.py fmt
Rename target_pointer_width to pointer_width because it is already
member of the Target struct.
The compiler supports only three valid values for target_pointer_width:
16, 32, 64. Thus it can safely be turned into an int.
This means less allocations and clones as well as easier handling of the type.
Also change target_pointer_width to pointer_width.
Preparation for a subsequent type change of
target_pointer_width to an integer together with a rename
to pointer_width.
On its own, this commit breaks the build. I don't like making
build-breaking commits, but in this instance I believe that it
makes review easier, as the "real" changes of this PR can be
seen much more easily.
Result of running:
find compiler/rustc_target/src/spec/ -type f -exec sed -i -e 's/target_pointer_width: "\(.*\)"\..*,/pointer_width: \1,/g' {} \;
Replace tuple of infer vars for upvar_tys with single infer var
This commit allows us to decide the number of captures required after
completing capture ananysis, which is required as part of implementing
RFC-2229.
closes https://github.com/rust-lang/project-rfc-2229/issues/4
r? `@nikomatsakis`
Remove unused code
Rustc has a builtin lint for detecting unused code inside a crate, but when an item is marked `pub`, the code, even if unused inside the entire workspace, is never marked as such. Therefore, I've built [warnalyzer](https://github.com/est31/warnalyzer) to detect unused items in a cross-crate setting.
Closes https://github.com/est31/warnalyzer/issues/2
Rollup of 8 pull requests
Successful merges:
- #77765 (Add LLVM flags to limit DWARF version to 2 on BSD)
- #77788 (BTreeMap: fix gdb provider on BTreeMap with ZST keys or values)
- #77795 (Codegen backend interface refactor)
- #77808 (Moved the main `impl` for FnCtxt to its own file.)
- #77817 (Switch rustdoc from `clean::Stability` to `rustc_attr::Stability`)
- #77829 (bootstrap: only use compiler-builtins-c if they exist)
- #77870 (Use intra-doc links for links to module-level docs)
- #77897 (Move `Strip` into a separate rustdoc pass)
Failed merges:
- #77879 (Provide better documentation and help messages for x.py setup)
- #77902 (Include aarch64-pc-windows-msvc in the dist manifests)
r? `@ghost`
Switch rustdoc from `clean::Stability` to `rustc_attr::Stability`
This gives greater type safety and is less work to maintain on the rustdoc end. It also makes rustdoc more consistent with rustc.
Noticed this while working on https://github.com/rust-lang/rust/issues/76998.
- Remove `clean::Stability` in favor of `rustc_attr::Stability`
- Remove `impl Clean for Stability`; it's no longer necessary
r? @GuillaumeGomez
cc @petrochenkov
Moved the main `impl` for FnCtxt to its own file.
Resolves#77085 without breaking the API of the `FnCtxt` struct.
This is a solution to the file length being over 3000 (see issue #60302).
The other solution to the file length is
1. to change the API of this struct by
2. encapulating certain fields of the struct into other structs.
Codegen backend interface refactor
This moves several things away from the codegen backend to rustc_interface. There are a few behavioral changes where previously the incremental cache (incorrectly) wouldn't get finalized, but now it does. See the individual commit messages.
Add LLVM flags to limit DWARF version to 2 on BSD
This has been a thorn in my side for a while, I can finally generate flamegraphs of rust programs on bsd again. This fixes dtrace profiling on freebsd, I think it might help with lldb as well but I can't test that because my current rust-lldb setup is messed up.
I'm limiting the dwarf version to 2 on all bsd's (netbsd/openbsd/freebsd) since it looks like this applies to all of them, but I have only tested on freebsd.
Let me know if there's anything I can improve!
---
Currently on FreeBSD dtrace profiling does not work and shows jumbled/incorrect
symbols in the backtraces. FreeBSD does not support the latest versions of DWARF
in dtrace (and lldb?) yet, and needs to be limited to DWARF2 in the same way as macos.
This adds an is_like_bsd flag since it was missing. NetBSD/OpenBSD/FreeBSD all
match this.
This effectively copies #11864 but targets FreeBSD instead of macos.
Refactor AST pretty-printing to allow skipping insertion of extra parens
Fixes#75734
Makes progress towards #43081
Unblocks PR #76130
When pretty-printing an AST node, we may insert additional parenthesis
to ensure that precedence is properly preserved in code we output.
However, the proc macro implementation relies on comparing a
pretty-printed AST node to the captured `TokenStream`. Inserting extra
parenthesis changes the structure of the reparsed `TokenStream`, making
the comparison fail.
This PR refactors the AST pretty-printing code to allow skipping the
insertion of additional parenthesis. Several freestanding methods are
moved to trait methods on `PrintState`, which keep track of an internal
`insert_extra_parens` flag. This flag is normally `true`, but we expose
a public method which allows pretty-printing a nonterminal with
`insert_extra_parens = false`.
To avoid changing the public interface of `rustc_ast_pretty`, the
freestanding `_to_string` methods are changed to delegate to a
newly-crated `State`. The main pretty-printing code is moved to a new
`state` module to ensure that it does not accidentally call any of these
public helper functions (instead, the internal functions with the same
name should be used).
A promoted inherits all scopes from the parent body. At the same time,
almost all statements and terminators inside the promoted body so far
refer only to one of those scopes: the outermost one.
Instead of inheriting all scopes, inherit only a single scope
corresponding to the location of the promoted, making sure that there
are no references to other scopes.
Replace absolute paths with relative ones
Modern compilers allow reaching external crates
like std or core via relative paths in modules
outside of lib.rs and main.rs.
Replace trivial bool matches with the `matches!` macro
This derives `PartialEq` on one enum (and two structs it contains) to enable the `==` operator for it. If there's some downside to this, I could respin with the `matches!` macro instead.
Certain platforms need to limit the DWARF version emitted (oxs, *bsd). This
change adds a dwarf_version entry to the options that allows a platform to
specify the dwarf version to use. By default this option is none and the default
DWARF version is selected.
Also adds an option for printing Option<u32> json keys
Use tracing spans in rustc_trait_selection
Spans are very helpful when debugging this code. It's also hot enough to make a good benchmark.
r? `@oli-obk`
Mono collector: replace pair of ints with Range
I found the initial PR (#33171) that introduced this piece of code but I didn't find any information about why a tuple was preferred over a `Range<usize>`.
I'm hoping there are no technical reasons to not do this.
Remove unnecessary unsafe block around calls to discriminant_value
Since 63793 the discriminant_value intrinsic is safe to call. Remove
unnecessary unsafe block around calls to this intrinsic in built-in
derive macros.
Use llvm::computeLTOCacheKey to determine post-ThinLTO CGU reuse
During incremental ThinLTO compilation, we attempt to re-use the
optimized (post-ThinLTO) bitcode file for a module if it is 'safe' to do
so.
Up until now, 'safe' has meant that the set of modules that our current
modules imports from/exports to is unchanged from the previous
compilation session. See PR #67020 and PR #71131 for more details.
However, this turns out be insufficient to guarantee that it's safe
to reuse the post-LTO module (i.e. that optimizing the pre-LTO module
would produce the same result). When LLVM optimizes a module during
ThinLTO, it may look at other information from the 'module index', such
as whether a (non-imported!) global variable is used. If this
information changes between compilation runs, we may end up re-using an
optimized module that (for example) had dead-code elimination run on a
function that is now used by another module.
Fortunately, LLVM implements its own ThinLTO module cache, which is used
when ThinLTO is performed by a linker plugin (e.g. when clang is used to
compile a C proect). Using this cache directly would require extensive
refactoring of our code - but fortunately for us, LLVM provides a
function that does exactly what we need.
The function `llvm::computeLTOCacheKey` is used to compute a SHA-1 hash
from all data that might influence the result of ThinLTO on a module.
In addition to the module imports/exports that we manually track, it
also hashes information about global variables (e.g. their liveness)
which might be used during optimization. By using this function, we
shouldn't have to worry about new LLVM passes breaking our module re-use
behavior.
In LLVM, the output of this function forms part of the filename used to
store the post-ThinLTO module. To keep our current filename structure
intact, this PR just writes out the mapping 'CGU name -> Hash' to a
file. To determine if a post-LTO module should be reused, we compare
hashes from the previous session.
This should unblock PR #75199 - by sheer chance, it seems to have hit
this issue due to the particular CGU partitioning and optimization
decisions that end up getting made.
Recognize discriminant reads as no-ops in RemoveNoopLandingPads
The cleanup blocks often contain read of discriminants. Teach
RemoveNoopLandingPads to recognize them as no-ops to remove
additional no-op landing pads.
Fixes#74616
Makes progress towards #43081
Unblocks PR #76130
When pretty-printing an AST node, we may insert additional parenthesis
to ensure that precedence is properly preserved in code we output.
However, the proc macro implementation relies on comparing a
pretty-printed AST node to the captured `TokenStream`. Inserting extra
parenthesis changes the structure of the reparsed `TokenStream`, making
the comparison fail.
This PR refactors the AST pretty-printing code to allow skipping the
insertion of additional parenthesis. Several freestanding methods are
moved to trait methods on `PrintState`, which keep track of an internal
`insert_extra_parens` flag. This flag is normally `true`, but we expose
a public method which allows pretty-printing a nonterminal with
`insert_extra_parens = false`.
To avoid changing the public interface of `rustc_ast_pretty`, the
freestanding `_to_string` methods are changed to delegate to a
newly-crated `State`. The main pretty-printing code is moved to a new
`state` module to ensure that it does not accidentally call any of these
public helper functions (instead, the internal functions with the same
name should be used).
Depending on if upvar_tys inferred or not, we were returning either an
inference variable which later resolves to a tuple or else the upvar tys
themselves
Co-authored-by: Roxane Fruytier <roxane.fruytier@hotmail.com>
This commit allows us to decide the number of captures required after
completing capture ananysis, which is required as part of implementing
RFC-2229.
Co-authored-by: Aman Arora <me@aman-arora.com>
Co-authored-by: Jenny Wills <wills.jenniferg@gmail.com>
Add -Z codegen-backend dylib to deps
When the codegen-backend dylib changes, the program should be rebuilt.
---
Unfortunately I was unable to test this works locally due to running into a TLS issue when running the custom backend, `thread 'rustc' panicked at 'no ImplicitCtxt stored in tls', compiler/rustc_middle/src/ty/context.rs:1750:54`, which seems similar to https://github.com/rust-lang/rust/issues/62717 but has a completely different cause and backtrace.
`@eddyb` said to ping `@Mark-Simulacrum` about what they think about this, so, ping!
This is a solution to the file length being over 3000, something Clippy has a problem with.
The other solution to the file length is
1. to change the API of this struct by
2. encapulating certain fields of the struct into other structs.
Since 63793 the discriminant_value intrinsic is safe to call. Remove
unnecessary unsafe block around calls to this intrinsic in built-in
derive macros.
Provide structured suggestions when finding structs when expecting a trait
When finding an ADT in a trait object definition provide some solutions. Fix#45817.
Given `<Param as Trait>::Assoc: Ty` suggest `Param: Trait<Assoc = Ty>`. Fix#75829.
Allow generic parameters in intra-doc links
Fixes#62834.
---
The contents of the generics will be mostly ignored (except for warning
if fully-qualified syntax is used, which is currently unsupported in
intra-doc links - see issue #74563).
* Allow links like `Vec<T>`, `Result<T, E>`, and `Option<Box<T>>`
* Allow links like `Vec::<T>::new()`
* Warn on
* Unbalanced angle brackets (e.g. `Vec<T` or `Vec<T>>`)
* Missing type to apply generics to (`<T>` or `<Box<T>>`)
* Use of fully-qualified syntax (`<Vec as IntoIterator>::into_iter`)
* Invalid path separator (`Vec:<T>:new`)
* Too many angle brackets (`Vec<<T>>`)
* Empty angle brackets (`Vec<>`)
Note that this implementation *does* allow some constructs that aren't
valid in the actual Rust syntax, for example `Box::<T>new()`. That may
not be supported in rustdoc in the future; it is an implementation
detail.
They were not formatted correctly, so rustdoc was interpreting some
parts as code. Also cleaned up some other query docs that weren't
causing issues, but were formatted incorrectly.
Add TraitDef::find_map_relevant_impl
This PR adds a method to `TraitDef`. While `for_each_relevant_impl` covers the general use case, sometimes it's not necessary to scan through all the relevant implementations, so this PR introduces a new method, `find_map_relevant_impl`. I've also replaced the `for_each_relevant_impl` calls where possible.
I'm hoping for a tiny bit of efficiency gain here and there.
Cleanup of `eat_while()` in lexer
The size of a lexer Token was inflated by the largest `TokenKind` variants `LiteralKind::RawStr` and `RawByteStr`, because
* it used `usize` although `u32` is sufficient in rustc, since crates must be smaller than 4GB,
* and it stored the 20 bytes big `RawStrError` enum for error reporting.
If a raw string is invalid, it now needs to be reparsed to get the `RawStrError` data, but that is a very cold code path.
Technically this breaks other tools that depend on rustc_lexer because they are now also restricted to a max file size of 4GB. But this shouldn't matter in practice, and rustc_lexer isn't stable anyway.
Can I also get a perf run?
Edit: This makes no difference in performance. The PR now only contains a small cleanup.
Add asm! support for mips64
- [x] Updated `src/doc/unstable-book/src/library-features/asm.md`.
- [ ] No vector type support. I don't know much about those types.
cc #76839
rustc_target: Refactor away `TargetResult`
Follow-up to https://github.com/rust-lang/rust/pull/77202.
Construction of a built-in target is always infallible now, so `TargetResult` is no longer necessary.
The second commit contains some further cleanup based on built-in target construction being infallible.
The cleanup blocks often contain read of discriminants. Teach
RemoveNoopLandingPads to recognize them as no-ops to remove
additional no-op landing pads.
Implementation of RFC2867
https://github.com/rust-lang/rust/issues/74727
So I've started work on this, I think my next steps are to make use of the `instruction_set` value in the llvm codegen but this is the point where I begin to get a bit lost. I'm looking at the code but it would be nice to have some guidance on what I've currently done and what I'm doing next 😄