Commit graph

98 commits

Author SHA1 Message Date
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