Commit graph

243 commits

Author SHA1 Message Date
Nadrieril
3715f1ed00 No need to expose Matrix internals 2020-11-27 18:20:30 +00:00
Nadrieril
d447bdff9b Disentangle Fields and PatStack 2020-11-27 18:20:30 +00:00
Nadrieril
b59792128c Move Constructor::apply to Fields 2020-11-27 18:20:30 +00:00
Jonas Schievink
815d96111d
Rollup merge of #79421 - camelid:_match-docs-fmt, r=petrochenkov
Fix docs formatting for `thir::pattern::_match`

They were being rendered all on one line.
2020-11-26 13:39:18 +01:00
Camelid
c5c70d4017 Fix docs formatting for thir::pattern::_match
A list was being rendered all on one line and there were other
formatting issues as well.
2020-11-25 13:23:06 -08:00
Camelid
82dc99ba7a Use the name "auto traits" everywhere in the compiler
Goodbye, OIBIT!
2020-11-24 16:25:43 -08:00
bors
c643dd2ec8 Auto merge of #79243 - Nadrieril:consolidate-tests, r=varkor
Consolidate exhaustiveness-related tests

I hunted for tests that only exercised the match exhaustiveness algorithm and regrouped them. I also improved integer-range tests since I had found them lacking while hacking around.
The interest is mainly so that one can pass `--test-args patterns` and catch most relevant tests.

r? `@varkor`
`@rustbot` modify labels: +A-exhaustiveness-checking
2020-11-22 18:29:38 +00:00
Nadrieril
82bf5b61cd Regroup many usefulness-related test in the same folder 2020-11-19 19:52:54 +00:00
Dylan DPC
5c7d530b5e
Rollup merge of #79149 - sexxi-goose:upvar_ref, r=nikomatsakis
Move capture lowering from THIR to MIR

This allows us to:
- Handle precise Places captured by a closure directly in MIR. Handling
  captures in MIR is easier since we can rely on/ tweak PlaceBuilder to
  generate `mir::Place`s that resemble how we store captures (`hir::Place`).

- Handle `let _ = x` case when feature `capture_disjoint_fields`
  is enabled directly in MIR. This is required to be done in MIR since
  patterns are desugared in MIR.

Closes: rust-lang/project-rfc-2229#25

r? ```@nikomatsakis```
2020-11-19 16:26:39 +01:00
bors
8256379832 Auto merge of #78995 - Nadrieril:clean-empty-match, r=varkor
Handle empty matches cleanly in exhaustiveness checking

This removes the special-casing of empty matches that was done in `check_match`. This fixes most of https://github.com/rust-lang/rust/issues/55123.
Somewhat unrelatedly, I also made `_match.rs` more self-contained, because I think it's cleaner.

r? `@varkor`
`@rustbot` modify labels: +A-exhaustiveness-checking
2020-11-18 21:24:40 +00:00
Aman Arora
9f70e782f7 Remove THIR::ExprKind::SelfRef
ExprKind::SelfRef was used to express accessing `self` in
the desugared Closure/Generator struct when lowering captures in THIR.

Since we handle captures in MIR now, we don't need `ExprKind::Self`.
2020-11-17 17:49:42 -05:00
Aman Arora
7faebe57b2 Move capture lowering from THIR to MIR
This allows us to:
- Handle precise Places captured by a closure directly in MIR. Handling
captures in MIR is easier since we can rely on/ tweak PlaceBuilder to
generate `mir::Place`s that resemble how we store captures (`hir::Place`).
- Allows us to handle `let _ = x` case when feature `capture_disjoint_fields`
is enabled directly in MIR. This is required to be done in MIR since
patterns are desugared in MIR.
2020-11-17 17:49:42 -05:00
Mara Bos
b6f52410bb
Rollup merge of #79072 - oli-obk:byte_str_pat, r=estebank
Fix exhaustiveness in case a byte string literal is used at slice type

fixes #79048
2020-11-17 16:13:53 +01:00
oli
a1cdf722f4 Fix exhaustiveness in case a byte string literal is used at slice type 2020-11-17 09:07:23 +00:00
bors
b5c37e86ff Auto merge of #78801 - sexxi-goose:min_capture, r=nikomatsakis
RFC-2229: Implement Precise Capture Analysis

### This PR introduces
- Feature gate for RFC-2229 (incomplete) `capture_disjoint_field`
- Rustc Attribute to print out the capture analysis `rustc_capture_analysis`
- Precise capture analysis

### Description of the analysis
1. If the feature gate is not set then all variables that are not local to the closure will be added to the list of captures. (This is for backcompat)
2. The rest of the analysis is based entirely on how the captured `Place`s are used within the closure. Precise information (i.e. projections) about the `Place` is maintained throughout.
3. To reduce the amount of information we need to keep track of, we do a minimization step. In this step, we determine a list such that no Place within this list represents an ancestor path to another entry in the list.  Check rust-lang/project-rfc-2229#9 for more detailed examples.
4. To keep the compiler functional as before we implement a Bridge between the results of this new analysis to existing data structures used for closure captures. Note the new capture analysis results are only part of MaybeTypeckTables that is the information is only available during typeck-ing.

### Known issues
- Statements like `let _ = x` will make the compiler ICE when used within a closure with the feature enabled. More generally speaking the issue is caused by `let` statements that create no bindings and are init'ed using a Place expression.

### Testing
We removed the code that would handle the case where the feature gate is not set, to enable the feature as default and did a bors try and perf run. More information here: #78762

### Thanks
This has been slowly in the works for a while now.
I want to call out `@Azhng` `@ChrisPardy` `@null-sleep` `@jenniferwills` `@logmosier` `@roxelo` for working on this and the previous PRs that led up to this, `@nikomatsakis` for guiding us.

Closes rust-lang/project-rfc-2229#7
Closes rust-lang/project-rfc-2229#9
Closes rust-lang/project-rfc-2229#6
Closes rust-lang/project-rfc-2229#19

r? `@nikomatsakis`
2020-11-17 03:56:03 +00:00
Bastian Kauschke
2bf93bd852 compiler: fold by value 2020-11-16 22:34:57 +01:00
Nadrieril
36e3409f67 Apply suggestions from code review
Co-authored-by: varkor <github@varkor.com>
2020-11-16 01:00:33 +00:00
Jonas Schievink
ce775bc4f6
Rollup merge of #79036 - cjgillot:steal, r=oli-obk
Move Steal to rustc_data_structures.
2020-11-15 13:39:59 +01:00
Jonas Schievink
8825942e86
Rollup merge of #77802 - jyn514:bootstrap-specific, r=nikomatsakis
Allow making `RUSTC_BOOTSTRAP` conditional on the crate name

Motivation: This came up in the [Zulip stream](https://rust-lang.zulipchat.com/#narrow/stream/233931-t-compiler.2Fmajor-changes/topic/Require.20users.20to.20confirm.20they.20know.20RUSTC_.E2.80.A6.20compiler-team.23350/near/208403962) for https://github.com/rust-lang/compiler-team/issues/350.
See also https://github.com/rust-lang/cargo/pull/6608#issuecomment-458546258; this implements https://github.com/rust-lang/cargo/issues/6627.
The goal is for this to eventually allow prohibiting setting `RUSTC_BOOTSTRAP` in build.rs (https://github.com/rust-lang/cargo/issues/7088).

## User-facing changes

- `RUSTC_BOOTSTRAP=1` still works; there is no current plan to remove this.
- Things like `RUSTC_BOOTSTRAP=0` no longer activate nightly features. In practice this shouldn't be a big deal, since `RUSTC_BOOTSTRAP` is the opposite of stable and everyone uses `RUSTC_BOOTSTRAP=1` anyway.
- `RUSTC_BOOTSTRAP=x` will enable nightly features only for crate `x`.
- `RUSTC_BOOTSTRAP=x,y` will enable nightly features only for crates `x` and `y`.

## Implementation changes

The main change is that `UnstableOptions::from_environment` now requires
an (optional) crate name. If the crate name is unknown (`None`), then the new feature is not available and you still have to use `RUSTC_BOOTSTRAP=1`. In practice this means the feature is only available for `--crate-name`, not for `#![crate_name]`; I'm interested in supporting the second but I'm not sure how.

Other major changes:

- Added `Session::is_nightly_build()`, which uses the `crate_name` of
the session
- Added `nightly_options::match_is_nightly_build`, a convenience method
for looking up `--crate-name` from CLI arguments.
`Session::is_nightly_build()`should be preferred where possible, since
it will take into account `#![crate_name]` (I think).
- Added `unstable_features` to `rustdoc::RenderOptions`

I'm not sure whether this counts as T-compiler or T-lang; _technically_ RUSTC_BOOTSTRAP is an implementation detail, but it's been used so much it seems like this counts as a language change too.

r? `@joshtriplett`
cc `@Mark-Simulacrum` `@hsivonen`
2020-11-15 13:39:43 +01:00
Dylan DPC
a29b68f326
Rollup merge of #78856 - mark-i-m:fix-or-pat-ice, r=matthewjasper
Explicitly checking for or-pattern before test

Fixes https://github.com/rust-lang/rust/issues/72680

cc https://github.com/rust-lang/rust/issues/54883

r? ````@varkor````
2020-11-15 03:02:40 +01:00
Camille GILLOT
41c44b498f Move Steal to rustc_data_structures. 2020-11-14 01:30:56 +01:00
Nadrieril
b9da2b372f Factor out match usefulness computation in check_match
This make `_match` a lot more self-contained
2020-11-12 18:17:42 +00:00
Nadrieril
d5a7ec0929 Unreachable subpatterns are rare
We may as well leave early when we know there's nothing to report.
2020-11-12 17:42:02 +00:00
Nadrieril
b025813f03 Handle empty matches cleanly 2020-11-12 17:41:36 +00:00
Aman Arora
127a6ede1d Use Places to express closure/generator Captures
Co-authored-by: Archer Zhang <archer.xn@gmail.com>
2020-11-10 20:44:47 -05:00
mark
43e4783ce3 address reviewer comments 2020-11-09 12:19:34 -06:00
Dylan DPC
abaa78baeb
Rollup merge of #78748 - fanzier:tuple-assignment, r=petrochenkov
Implement destructuring assignment for tuples

This is the first step towards implementing destructuring assignment (RFC: https://github.com/rust-lang/rfcs/pull/2909, tracking issue: #71126). This PR is the first part of #71156, which was split up to allow for easier review.

Quick summary: This change allows destructuring the LHS of an assignment if it's a (possibly nested) tuple.
It is implemented via a desugaring (AST -> HIR lowering) as follows:
```rust
(a,b) = (1,2)
```
... becomes ...
```rust
{
  let (lhs0,lhs1) = (1,2);
  a = lhs0;
  b = lhs1;
}
```

Thanks to `@varkor` who helped with the implementation, particularly around default binding modes.

r? `@petrochenkov`
2020-11-09 01:13:44 +01:00
mark
459dae94a1 fix #72680 by explicitly checking for or-pattern before test 2020-11-07 23:22:47 -06:00
Joshua Nelson
622c48e4f1 Allow making RUSTC_BOOTSTRAP conditional on the crate name
The main change is that `UnstableOptions::from_environment` now requires
an (optional) crate name. If the crate name is unknown (`None`), then the new feature is not available and you still have to use `RUSTC_BOOTSTRAP=1`. In practice this means the feature is only available for `--crate-name`, not for `#![crate_name]`; I'm interested in supporting the second but I'm not sure how.

Other major changes:

- Added `Session::is_nightly_build()`, which uses the `crate_name` of
the session
- Added `nightly_options::match_is_nightly_build`, a convenience method
for looking up `--crate-name` from CLI arguments.
`Session::is_nightly_build()`should be preferred where possible, since
it will take into account `#![crate_name]` (I think).
- Added `unstable_features` to `rustdoc::RenderOptions`

  There is a user-facing change here: things like `RUSTC_BOOTSTRAP=0` no
  longer active nightly features. In practice this shouldn't be a big
  deal, since `RUSTC_BOOTSTRAP` is the opposite of stable and everyone
  uses `RUSTC_BOOTSTRAP=1` anyway.

- Add tests

  Check against `Cheat`, not whether nightly features are allowed.
  Nightly features are always allowed on the nightly channel.

- Only call `is_nightly_build()` once within a function

- Use booleans consistently for rustc_incremental

  Sessions can't be passed through threads, so `read_file` couldn't take a
  session. To be consistent, also take a boolean in `write_file_header`.
2020-11-07 13:45:11 -05:00
Fabian Zaiser
3a7a997323 Implement destructuring assignment for tuples
Co-authored-by: varkor <github@varkor.com>
2020-11-07 13:17:19 +00:00
Yuki Okushi
91153d5009
Rollup merge of #78167 - Nadrieril:fix-76836_, r=varkor
Fix unreachable sub-branch detection in or-patterns

The previous implementation was too eager to avoid unnecessary "unreachable pattern" warnings. I feel more confident about this implementation than I felt about the previous one.
Fixes https://github.com/rust-lang/rust/issues/76836.

``@rustbot`` modify labels: +A-exhaustiveness-checking
2020-11-07 01:02:05 +09:00
bors
f92b931045 Auto merge of #77856 - GuillaumeGomez:automatic-links-lint, r=jyn514,ollie27
Add non_autolinks lint

Part of #77501.

r? `@jyn514`
2020-11-06 04:17:41 +00:00
Nadrieril
107a29a901 Emit lints in the order in which they occur in the file. 2020-11-05 22:17:26 +00:00
Nadrieril
25e272e388 Fix unreachable sub-branch detection
This fixes https://github.com/rust-lang/rust/issues/76836
2020-11-05 22:02:35 +00:00
Guillaume Gomez
99200f760b Fix even more URLs 2020-11-05 20:11:29 +01:00
bors
b1d9f31e04 Auto merge of #78638 - vn-ki:bindigs-after-at-issue-69971, r=oli-obk
reverse binding order in matches to allow the subbinding of copyable fields in bindings after @

Fixes #69971

### TODO

- [x] Regression tests

r? `@oli-obk`
2020-11-05 13:26:08 +00:00
oli
abacaf2aef u128 truncation and sign extension are not just interpreter related 2020-11-04 13:41:58 +00:00
Vishnunarayan K I
5827fbadf6 review comments 2020-11-03 17:14:51 +05:30
Vishnunarayan K I
f422e811e4 preserve bindings order for Some 2020-11-03 12:15:41 +05:30
Vishnunarayan K I
6bdce7bedd new fix method and update tests 2020-11-02 22:29:20 +05:30
Vishnunarayan K I
c93d25b6af reverse binding order in matches ...
... to allow the subbinding of copyable fields in bindings after `@`

Fixes #69971
2020-11-02 00:05:55 +05:30
bors
1899c489d4 Auto merge of #78553 - Nadrieril:fix-78549, r=varkor
Fix #78549

Before #78430, this worked because `specialize_constructor` didn't actually care too much which constructor was passed to it unless needed. That PR however handles `&str` as a special case, and I did not anticipate patterns for the `&str` type other than string literals.
I am not very confident there are not other similar oversights left, but hopefully only `&str` was different enough to break my assumptions.

Fixes https://github.com/rust-lang/rust/issues/78549
2020-11-01 14:37:50 +00:00
Nadrieril
1bdcd02a70 The need for Single to cover Unlistable was a hack
It is now unneeded, since we handle `&str` patterns in a consistent way.
2020-11-01 02:05:58 +00:00
Nadrieril
4cd30197eb Fix #78549
Before #78430, string literals worked because `specialize_constructor`
didn't actually care too much which constructor was passed to it unless
needed. Since then, string literals are special cased and a bit hacky. I
did not anticipate patterns for the `&str` type other than string
literals, hence this bug. This makes string literals less hacky.
2020-11-01 02:04:42 +00:00
Joshua Nelson
57c6ed0c07 Fix even more clippy warnings 2020-10-30 10:13:39 -04:00
bors
f9187adaef Auto merge of #78430 - Nadrieril:taking-constructors-seriously2, r=varkor
Clarify main code paths in exhaustiveness checking

This PR massively clarifies the main code paths of exhaustiveness checking, by using the `Constructor` enum to a fuller extent. I've been itching to write it for more than a year, but the complexity of matching consts had prevented me. Behold a massive simplification :D.
This in particular removes a fair amount of duplication between various parts, localizes code into methods of relevant types when applicable, makes some implicit assumptions explicit, and overall improves legibility a lot (or so I hope). Additionally, after my changes undoing #76918 turned out to be a noticeable perf gain.

As usual I tried my best to make the commits self-contained and easy to follow. I've also tried to keep the code well-commented, but I tend to forget how complex this file is; I'm happy to clarify things as needed.
My measurements show good perf improvements on the two match-heavy benchmarks (-18.0% on `unicode_normalization-check`! :D); I'd like a perf run to check the overall impact.

r? `@varkor`
`@rustbot` modify labels: +A-exhaustiveness-checking
2020-10-29 01:37:49 +00:00
Nadrieril
41a74ace4a Apply suggestions from code review
Co-authored-by: Who? Me?! <mark-i-m@users.noreply.github.com>
Co-authored-by: varkor <github@varkor.com>
2020-10-28 19:08:01 +00:00
Santiago Pastorino
708fc3b1a2
Add unsized_fn_params feature 2020-10-27 14:45:02 -03:00
Nadrieril
766ab78a1c Simplify slice splitting a bit 2020-10-27 03:27:11 +00:00
Nadrieril
cd4c7144de Deduplicate work between splitting and subtraction
After splitting, subtraction becomes much simpler
2020-10-27 03:27:11 +00:00
Nadrieril
1fab669f8d Be honest about being able to list constructors
The test change is because we used to treat `&str` like other `&T`s, ie
as having a single constructor. That's not quite true though since we
consider `&str` constants as atomic instead of refs to `str` constants.
2020-10-27 03:09:55 +00:00
Nadrieril
db9a8480c4 Simplify specialize_constructor
Also removes the ugly caching that was introduced in #76918. It was
bolted on without deeper knowledge of the workings of the algorithm.
This commit manages to be more performant without any of the complexity.
It should be better on representative workloads too.
2020-10-27 03:08:38 +00:00
Nadrieril
54fa70290d Unify the paths through is_useful 2020-10-27 00:49:32 +00:00
Nadrieril
c96bd28ab3 Recompute MissingConstructors when needed
This only happens in a slow (diagnostics) path, so the code clarity gain
is worth it.
2020-10-27 00:46:33 +00:00
Nadrieril
b49f90760d Pass more things through PatCtxt
This is even a perf improvement on the match-heavy benchmarks.
2020-10-27 00:46:33 +00:00
Nadrieril
cdafd1e1bd Let MissingConstructors handle the subtleties of missing constructors 2020-10-27 00:46:32 +00:00
Nadrieril
1190e7275c Cache head constructor in PatStack
Since the constructor is recomputed a lot, caching is worth it.
2020-10-27 00:46:32 +00:00
Nadrieril
833089fbc9 Unify the two kinds of specialization by adding a Wildcard ctor 2020-10-27 00:46:32 +00:00
Nadrieril
41e7ca499d Inline specialize_one_pattern 2020-10-27 00:46:32 +00:00
Nadrieril
c511955a9f Factor out the two specialization steps 2020-10-27 00:46:32 +00:00
Nadrieril
6ad9f44a50 Clarify specialization into two steps
First is checking for constructor overlap, second is extracting the
resulting fields.
2020-10-27 00:46:32 +00:00
Nadrieril
7c4f94be48 Use pat_constructor to simplify specialize_one_pattern 2020-10-27 00:46:32 +00:00
Nadrieril
feb1e13960 Split split_grouped_constructor into smaller functions 2020-10-27 00:46:32 +00:00
Yuki Okushi
b72d70ef61
Rollup merge of #78377 - LeSeulArtichaut:patch-docs, r=jonas-schievink
Fix typo in debug statement
2020-10-27 08:45:14 +09:00
bors
0da6d42f29 Auto merge of #68965 - eddyb:mir-inline-scope, r=nagisa,oli-obk
rustc_mir: track inlined callees in SourceScopeData.

We now record which MIR scopes are the roots of *other* (inlined) functions's scope trees, which allows us to generate the correct debuginfo in codegen, similar to what LLVM inlining generates.
This PR makes the `ui` test `backtrace-debuginfo` pass, if the MIR inliner is turned on by default.

Also, `#[track_caller]` is now correct in the face of MIR inlining (cc `@anp).`

Fixes #76997.

r? `@rust-lang/wg-mir-opt`
2020-10-26 18:50:22 +00:00
LeSeulArtichaut
9de15188b0 Fix typo in debug statement 2020-10-25 20:54:44 +01:00
Jonas Schievink
e12e97223f
Rollup merge of #78072 - Nadrieril:cleanup-constant-matching, r=varkor
Cleanup constant matching in exhaustiveness checking

This supercedes https://github.com/rust-lang/rust/pull/77390. I made the `Opaque` constructor work.
I have opened two issues https://github.com/rust-lang/rust/issues/78071 and https://github.com/rust-lang/rust/issues/78057 from the discussion we had on the previous PR. They are not regressions nor directly related to the current PR so I thought we'd deal with them separately.

I left a FIXME somewhere because I didn't know how to compare string constants for equality. There might even be some unicode things that need to happen there. In the meantime I preserved previous behavior.

EDIT: I accidentally fixed #78071
2020-10-24 22:39:51 +02:00
Jonas Schievink
a547055184
Rollup merge of #76614 - NoraCodes:nora/control_flow_enum, r=scottmcm
change the order of type arguments on ControlFlow

This allows ControlFlow<BreakType> which is much more ergonomic for common iterator combinator use cases.

Addresses one component of #75744
2020-10-24 22:39:41 +02:00
Yuki Okushi
709de7817d
Rollup merge of #78098 - camelid:fixup-docs, r=steveklabnik
Clean up and improve some docs

* compiler docs
  * Don't format list as part of a code block
  * Clean up some other formatting
* rustdoc book
  * Update CommonMark spec version to latest (0.28 -> 0.29)
  * Clean up some various wording and formatting
2020-10-23 18:26:28 +09:00
Leonora Tindall
bc2317915f Don't re-export std::ops::ControlFlow in the compiler. 2020-10-22 17:26:55 -07:00
Camelid
d725da129e Clean up and improve some docs
* compiler docs
  * Don't format list as part of a code block
  * Clean up some other formatting
* rustdoc book
  * Update CommonMark spec version to latest (0.28 -> 0.29)
  * Clean up some various wording and formatting
2020-10-21 18:01:04 -07:00
Nadrieril
faf87105db Explain the Opaque special case in specialization 2020-10-21 20:15:02 +01:00
bishtpawan
7f5847735a Fix formatting 2020-10-21 11:42:52 +05:30
Eduard-Mihai Burtescu
6451b39a25 rustc_mir: support MIR-inlining #[track_caller] functions. 2020-10-21 04:43:56 +03:00
Eduard-Mihai Burtescu
6bc5eafbce rustc_mir: track inlined callees in SourceScopeData. 2020-10-21 04:43:56 +03:00
bishtpawan
fa094044a9 Fix build failure of rustfmt 2020-10-20 23:13:21 +05:30
Nadrieril
c4ae6c2bb9 Add comment 2020-10-18 17:05:19 +01:00
Nadrieril
da0ba2f645 The only remaining constant patterns are opaque 2020-10-18 14:21:20 +01:00
Nadrieril
d1a784e7b9 Treat string literals separately from other constants 2020-10-18 14:21:20 +01:00
Nadrieril
aa4172076e Handle ranges of float consistently
This deconfuses the comparison of floats, that currently mixed ranges
and non-ranges.
2020-10-18 14:21:20 +01:00
Nadrieril
f504e9a425 Fix comment 2020-10-18 14:21:20 +01:00
Oliver Scherer
3708c86de1 Treat booleans as integers with valid range 0..=1 2020-10-18 14:21:20 +01:00
Nadrieril
99852e0db6 A ConstantValue constructor with a slice pattern is an error 2020-10-18 14:21:20 +01:00
Oliver Scherer
c3d0445021 Destructure byte slices and remove all the workarounds 2020-10-18 14:21:20 +01:00
Oliver Scherer
bb8111069e Destructure byte array constants to array patterns instead of keeping them opaque 2020-10-18 14:21:20 +01:00
bors
6af9846fcc Auto merge of #77124 - spastorino:const-exprs-rfc-2920, r=oli-obk
Implement const expressions and patterns (RFC 2920)

cc `@ecstatic-morse` `@lcnr` `@oli-obk` `@petrochenkov`
2020-10-17 14:44:51 +00:00
Tomasz Miąsko
a65a283332 Remove unused cached_unreachable_block from MIR builder 2020-10-17 00:00:00 +00:00
Santiago Pastorino
fe922e567f
Lower inline const down to MIR 2020-10-16 15:21:18 -03:00
Dylan DPC
85dbb03490
Rollup merge of #76119 - Amjad50:stabilizing-move_ref_pattern, r=nikomatsakis
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);
}
```
2020-10-16 02:10:07 +02:00
bors
f243a2ad90 Auto merge of #77917 - JohnTitor:rollup-e47h2qt, r=JohnTitor
Rollup of 14 pull requests

Successful merges:

 - #77239 (Enable building Cargo for aarch64-apple-darwin)
 - #77569 (BTreeMap: type-specific variants of node_as_mut and cast_unchecked)
 - #77719 (Remove unnecessary rustc_const_stable attributes.)
 - #77722 (Remove unsafety from sys/unsupported and add deny(unsafe_op_in_unsafe_fn).)
 - #77725 (Add regression issue template)
 - #77776 ( Give an error when running `x.py test --stage 0 src/test/ui`)
 - #77786 (Mention rustdoc in `x.py setup`)
 - #77825 (`min_const_generics` diagnostics improvements)
 - #77868 (Include `llvm-dis`, `llc` and `opt` in `llvm-tools-preview` component)
 - #77884 (Use Option::unwrap_or instead of open-coding it)
 - #77886 (Replace trivial bool matches with the `matches!` macro)
 - #77892 (Replace absolute paths with relative ones)
 - #77895 (Include aarch64-apple-darwin in the dist manifests)
 - #77909 (bootstrap: set correct path for the build-manifest binary)

Failed merges:

 - #77902 (Include aarch64-pc-windows-msvc in the dist manifests)

r? `@ghost`
2020-10-13 22:13:09 +00:00
Ding Xiang Fei
f9ccd39ae3
documentation fix 2020-10-14 00:50:54 +08:00
est31
a0fc455d30 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.
2020-10-13 14:16:45 +02:00
Jonas Schievink
432535da2b Refactor how SwitchInt stores jump targets 2020-10-10 17:46:11 +02:00
Yuki Okushi
5c1e01196d
Rollup merge of #77560 - rschoon:fix-litkind-rc-bytebuf, r=lcnr
Fix LitKind's byte buffer to use refcounted slice

While working on adding a new lint for clippy (see https://github.com/rust-lang/rust-clippy/pull/6044) for avoiding shared ownership of "mutable buffer" types (such as using `Rc<Vec<T>>` instead of `Rc<[T]>`), I noticed a type exported from rustc_ast and used by clippy gets caught by the lint. This PR fixes the exported type.

This PR includes the actual change to clippy too, but I will open a PR directly against clippy for that part (although it will currently fail to build there).
2020-10-06 16:26:11 +09:00
bors
62bfcfd8a3 Auto merge of #77552 - ecstatic-morse:body-def-id, r=lcnr
Replace `(Body, DefId)` with `Body` where possible

Follow-up to #77430.

I `grep`-ed for parameter lists in which a `Body` appeared within a few lines of a `DefId`, so it's possible that I missed some cases, but this should be pretty complete. Most of these changes were mechanical, but there's a few places where I started calling things "caller" and "callee" when multiple `DefId`s were in-scope at once. Also, we should probably have a helper function on `Body` that returns a `LocalDefId`. I can do that in this PR or in a follow-up.
2020-10-05 09:26:32 +00:00
bors
ced813fec0 Auto merge of #77466 - Aaron1011:reland-drop-tree, r=matthewjasper
Re-land PR #71840 (Rework MIR drop tree lowering)

PR https://github.com/rust-lang/rust/pull/71840 was reverted in https://github.com/rust-lang/rust/pull/72989 to fix an LLVM error (https://github.com/rust-lang/rust/issues/72470). That LLVM error no longer occurs with the recent upgrade to LLVM 11 (https://github.com/rust-lang/rust/pull/73526), so let's try re-landing this PR.

I've cherry-picked the commits from the original PR (with the exception of the commit blessing test output), making as few modifications as possible. I addressed the rebase fallout in separate commits on top of those.

r? `@matthewjasper`
2020-10-05 00:35:58 +00:00
Dylan MacKenzie
e72e43c730 Replace (Body, DefId) with Body where possible
A `Body` now contains its `MirSource`, which in turn contains the
`DefId` of the item associated with the `Body`.
2020-10-04 16:07:03 -07:00
Robin Schoonover
5ab19676ed Remove extra indirection in LitKind::ByteStr 2020-10-04 15:52:15 -06:00
Dylan MacKenzie
606655edc4 HACK: Overwrite the MIR's source with the correct const param
There's a cleaner way of doing this, but it involves passing
`WithOptConstParam` around in more places. We're going to try to explore
different approaches before committing to that.
2020-10-04 11:02:16 -07:00
Dylan MacKenzie
6f61e71648 Remember the MirSource for each Body 2020-10-04 11:01:38 -07:00
Aaron Hill
eb94cdd85e
Apply suggestions from review
Co-authored-by: matthewjasper <20113453+matthewjasper@users.noreply.github.com>
2020-10-04 07:54:03 -04:00
Aaron Hill
8478385ea4
Fix broken link 2020-10-04 07:54:02 -04:00
Aaron Hill
4c83eec008
Fix rebase fallout 2020-10-04 07:54:02 -04:00
Matthew Jasper
8902ce5d84
Address review comments 2020-10-04 07:54:02 -04:00
Matthew Jasper
1e71862046
Add some more comments 2020-10-04 07:54:02 -04:00
Matthew Jasper
fa3e2fcbe4
Defer creating drop trees in MIR lowering until leaving that scope 2020-10-04 07:54:01 -04:00
Dylan MacKenzie
bb6c249f99 Speed up IntRange::from_pat
Previously, this method called the more general `pat_constructor`
function, which can return other pattern variants besides `IntRange`.
Then it throws away any non-`IntRange` variants. Specialize it so work
is only done when it could result in an `IntRange`.
2020-09-26 20:00:54 -07:00
bors
fd15e6180d Auto merge of #70743 - oli-obk:eager_const_to_pat_conversion, r=eddyb
Fully destructure constants into patterns

r? `@varkor`

as discussed in https://rust-lang.zulipchat.com/#narrow/stream/131828-t-compiler/topic/constants.20in.20patterns/near/192789924

we should probably crater it once reviewed
2020-09-26 06:44:28 +00:00
bors
e599b53e67 Auto merge of #76918 - ishitatsuyuki:match-fastpath, r=oli-obk
Add fast path for match checking

This adds a fast path that would reduce the complexity to linear on matches consisting of only variant patterns (i.e. enum matches). (Also see: #7462) Unfortunately, I was too lazy to add a similar fast path for constants (mostly for integer matches), ideally that could be added another day.

TBH, I'm not confident with the performance claims due to the fact that enums tends to be small and FxHashMap could add a lot of overhead.

r? `@Mark-Simulacrum`

needs perf
2020-09-24 17:22:56 +00:00
Oliver Scherer
fc9f2947da Document FallbackToConstRef and make sure we don't accidentally use it 2020-09-24 17:01:03 +02:00
Oliver Scherer
9550ca6242 Deduplicate the "needs partialeq derive" message creation sites 2020-09-24 10:18:51 +02:00
Oliver Scherer
e4928d77a1 Use correct type in diagnostics again 2020-09-24 10:06:07 +02:00
Oliver Scherer
da217644a1 Make sure we keep emitting a hard error 2020-09-23 18:36:53 +02:00
Oliver Scherer
017423179a Make sure we report a future incompat error in all cases 2020-09-23 18:04:44 +02:00
Oliver Scherer
6a33de0170 Name function correctly 2020-09-23 17:55:14 +02:00
Oliver Scherer
9a7e66aeaf Make sure we don't hide errors just because a lint has been emitted 2020-09-23 17:52:37 +02:00
Oliver Scherer
177d0cef48 Deduplicate errors in const to pat conversion 2020-09-23 17:03:31 +02:00
Oliver Scherer
d486486afd Talk about unpredictable instead of "not deterministic" 2020-09-23 16:38:30 +02:00
Oliver Scherer
1b1b6eabaa Remove the "lift constant to reference" logic 2020-09-23 16:28:45 +02:00
Ishi Tatsuyuki
01a771a7d8 Add debug assertions against slow path reference results 2020-09-22 14:40:44 +09:00
Ishi Tatsuyuki
f95e4f3ca9 Improve code and documentation clarity 2020-09-21 20:29:12 +09:00
yuk1ty
16047d46a1 fix typo in docs and comments 2020-09-21 12:14:28 +09:00
Oliver Scherer
adf98ab2dc Use precise errors during const to pat conversion instead of a catch-all on the main constant 2020-09-20 18:42:15 +02:00
Oliver Scherer
aba5ea1430 Lint on function pointers used in patterns 2020-09-20 18:42:15 +02:00
Oliver Scherer
3795886f7e Split check for PartialEq impl into a method 2020-09-20 16:59:15 +02:00
Ralf Jung
8405d50e12
Rollup merge of #76890 - matthiaskrgr:matches_simpl, r=lcnr
use matches!() macro for simple if let conditions
2020-09-20 15:52:01 +02:00
Oliver Scherer
b2532a8730 Implement destructuring for all aggregates and for references 2020-09-20 13:28:18 +02:00
Oliver Scherer
b54f122a1c Merge tuple and struct pattern generation. 2020-09-20 12:31:37 +02:00
Bastian Kauschke
bfb221b21e array pattern 2020-09-20 08:11:05 +02:00
Bastian Kauschke
3435683fd5 use array_windows instead of windows in the compiler 2020-09-20 08:11:05 +02:00
ishitatsuyuki
7c98f6f584 Add fast path for match checking 2020-09-19 22:00:10 +09:00
Ralf Jung
4831523ac4
Rollup merge of #76757 - matthiaskrgr:clippy_try_into, r=lcnr
don't convert types to the same type with try_into (clippy::useless_conversion)
2020-09-19 11:47:52 +02:00
Matthias Krüger
40dddd3305 use matches!() macro for simple if let conditions 2020-09-18 20:28:35 +02:00
Matthias Krüger
f567287f9f don't convert types to the same type with try_into (clippy::useless_conversion) 2020-09-15 22:49:50 +02:00
Amjad Alsharafi
da700cba08 Stabilize move_ref_pattern 2020-09-15 14:23:05 +08:00
Aaron Hill
d18b4bb7a7
Note when a a move/borrow error is caused by a deref coercion
Fixes #73268

When a deref coercion occurs, we may end up with a move error if the
base value has been partially moved out of. However, we do not indicate
anywhere that a deref coercion is occuring, resulting in an error
message with a confusing span.

This PR adds an explicit note to move errors when a deref coercion is
involved. We mention the name of the type that the deref-coercion
resolved to, as well as the `Deref::Target` associated type being used.
2020-09-10 20:56:20 -04:00
bors
88197214b8 Auto merge of #75573 - Aaron1011:feature/const-mutation-lint, r=oli-obk
Add CONST_ITEM_MUTATION lint

Fixes #74053
Fixes #55721

This PR adds a new lint `CONST_ITEM_MUTATION`.
Given an item `const FOO: SomeType = ..`, this lint fires on:

* Attempting to write directly to a field (`FOO.field = some_val`) or
  array entry (`FOO.array_field[0] = val`)
* Taking a mutable reference to the `const` item (`&mut FOO`), including
  through an autoderef `FOO.some_mut_self_method()`

The lint message explains that since each use of a constant creates a
new temporary, the original `const` item will not be modified.
2020-09-10 05:54:26 +00:00
Aaron Hill
f422ef141a
Add CONST_ITEM_MUTATION lint
Fixes #74053
Fixes #55721

This PR adds a new lint `CONST_ITEM_MUTATION`.
Given an item `const FOO: SomeType = ..`, this lint fires on:

* Attempting to write directly to a field (`FOO.field = some_val`) or
  array entry (`FOO.array_field[0] = val`)
* Taking a mutable reference to the `const` item (`&mut FOO`), including
  through an autoderef `FOO.some_mut_self_method()`

The lint message explains that since each use of a constant creates a
new temporary, the original `const` item will not be modified.
2020-09-07 08:44:35 -04:00
Dylan DPC
acd33e1d14
Rollup merge of #76318 - scottmcm:one-control-flow, r=ecstatic-morse
Use ops::ControlFlow in rustc_data_structures::graph::iterate

Since I only know about this because you mentioned it,
r? @ecstatic-morse

If we're not supposed to use new `core` things in compiler for a while then feel free to close, but it felt reasonable to merge the two types since they're the same, and it might be convenient for people to use `?` in their traversal code.

(This doesn't do the type parameter swap; NoraCodes has signed up to do that one.)
2020-09-07 01:18:05 +02:00
LeSeulArtichaut
3e14b684dd Change ty.kind to a method 2020-09-04 17:47:51 +02:00
Scott McMurray
fac272688e Use ops::ControlFlow in graph::iterate 2020-09-04 01:45:10 -07:00
Dan Aloni
07e7823c01 pretty: trim paths of unique symbols
If a symbol name can only be imported from one place for a type, and
as long as it was not glob-imported anywhere in the current crate, we
can trim its printed path and print only the name.

This has wide implications on error messages with types, for example,
shortening `std::vec::Vec` to just `Vec`, as long as there is no other
`Vec` importable anywhere.

This adds a new '-Z trim-diagnostic-paths=false' option to control this
feature.

On the good path, with no diagnosis printed, we should try to avoid
issuing this query, so we need to prevent trimmed_def_paths query on
several cases.

This change also relies on a previous commit that differentiates
between `Debug` and `Display` on various rustc types, where the latter
is trimmed and presented to the user and the former is not.
2020-09-02 22:26:37 +03:00
mark
9e5f7d5631 mv compiler to compiler/ 2020-08-30 18:45:07 +03:00