rust-analyzer/crates/syntax/src
bors[bot] 88e8b0a5fa
Merge #7620
7620: Support control flow in `extract_function` assist r=matklad a=cpud36

Support `return`ing from outer function, `break`ing and `continue`ing outer loops when extracting function.

# Example
Transforms
```rust
fn foo() -> i32 {
  let items = [1,2,3];
  let mut sum = 0;
  for &item in items {
    <|>if item == 42 {
      break;
    }<|>
    sum += item;
  }
  sum
}
```
Into 
```rust
fn foo() -> i32 {
  let items = [1,2,3];
  let mut sum = 0;
  for &item in items {
    if fun_name(item) {
      break;
    }
    sum += item;
  }
  sum
}

fn fun_name(item: i32) -> bool {
  if item == 42 {
    return true;
  }
  false
}
```

![add_explicit_type_infer_type](https://user-images.githubusercontent.com/4218373/107544222-0fadf280-6bdb-11eb-9625-ed6194ba92c0.gif)

# Features

Supported variants
- break and function does not return => uses `bool` and plain if
- break and function does return => uses `Option<T>` and matches on it
- break with value and function does not return => uses `Option<T>` and if let
- break with value and function does return => uses `Result<T, U>` and matches on t
- same for `return` and `continue`(but we can't continue with value)

Assist does handle nested loops and nested items(like functions, modules, impls)

Try `expr?` operator is allowed together with `return Err(_)` and `return None`.
`return expr` is not allowed.

# Not supported
## Mixing `return` with `break` or `continue`
If we have e.g. a `return` and a `break` in the selected code, it is unclear what the produced code should look like.
We can try `Result<T, Option<U>>` or something like that, but it isn't idiomatic, nor it is established. Otherwise, implementation
is relatively simple.

## `break` with label
Not sure how to handle different labels for multiple `break`s.

[edit] implemented try `expr?`

Co-authored-by: Vladyslav Katasonov <cpud47@gmail.com>
2021-02-16 14:01:09 +00:00
..
ast Merge #7620 2021-02-16 14:01:09 +00:00
parsing ⬆️ rowan 2021-01-20 14:04:53 +03:00
validation Rename ra_syntax -> syntax 2020-08-12 18:30:53 +02:00
algo.rs ⬆️ rowan 2021-01-19 22:11:42 +03:00
ast.rs . 2021-01-20 01:56:11 +03:00
display.rs Introduce more appropriate assertion mechanism 2021-01-14 18:25:19 +03:00
fuzz.rs Rename ra_syntax -> syntax 2020-08-12 18:30:53 +02:00
lib.rs ⬆️ rowan 2021-01-20 14:04:53 +03:00
parsing.rs Deny unreachable-pub 2020-11-02 14:07:08 +01:00
ptr.rs Document privacy invariant of SyntaxPtr 2020-10-06 20:06:14 +02:00
syntax_error.rs Rename ra_syntax -> syntax 2020-08-12 18:30:53 +02:00
syntax_node.rs ⬆️ rowan 2021-01-20 14:04:53 +03:00
tests.rs Add parsing benchmark 2021-02-09 21:52:34 +03:00
validation.rs Add validation for mutable const items 2021-01-24 02:17:41 +01:00