Restrict closure expression to be something like {|| ...} (#8290)

# Description

As title, closes: #7921 closes: #8273

# User-Facing Changes

when define a closure without pipe, nushell will raise error for now:
```
❯ let x = {ss ss}
Error: nu::parser::closure_missing_pipe

  × Missing || inside closure
   ╭─[entry #2:1:1]
 1 │ let x = {ss ss}
   ·         ───┬───
   ·            ╰── Parsing as a closure, but || is missing
   ╰────
  help: Try add || to the beginning of closure
```

`any`, `each`, `all`, `where` command accepts closure, it forces user
input closure like `{||`, or parse error will returned.
```
❯ {major:2, minor:1, patch:4} | values | each { into string }
Error: nu::parser::closure_missing_pipe

  × Missing || inside closure
   ╭─[entry #4:1:1]
 1 │ {major:2, minor:1, patch:4} | values | each { into string }
   ·                                             ───────┬───────
   ·                                                    ╰── Parsing as a closure, but || is missing
   ╰────
  help: Try add || to the beginning of closure
```

`with-env`, `do`, `def`, `try` are special, they still remain the same,
although it says that it accepts a closure, but they don't need to be
written like `{||`, it's more likely a block but can capture variable
outside of scope:
```
❯ def test [input] { echo [0 1 2] | do { do { echo $input } } }; test aaa
aaa
```

Just realize that It's a big breaking change, we need to update config
and scripts...

# Tests + Formatting

Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used -A
clippy::needless_collect` to check that you're using the standard code
style
- `cargo test --workspace` to check that all tests pass

# After Submitting

If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
This commit is contained in:
WindSoilder
2023-03-17 20:36:28 +08:00
committed by GitHub
parent 400a9d3b1e
commit a8eef9af33
24 changed files with 108 additions and 71 deletions

View File

@ -38,6 +38,13 @@ pub enum ParseError {
#[diagnostic(code(nu::parser::parse_mismatch))]
Expected(String, #[label("expected {0}")] Span),
#[error("Missing || inside closure")]
#[diagnostic(
code(nu::parser::closure_missing_pipe),
help("Try add || to the beginning of closure")
)]
ClosureMissingPipe(#[label("Parsing as a closure, but || is missing")] Span),
#[error("Type mismatch during operation.")]
#[diagnostic(code(nu::parser::type_mismatch))]
Mismatch(String, String, #[label("expected {0}, found {1}")] Span), // expected, found, span
@ -487,6 +494,7 @@ impl ParseError {
ParseError::UnknownOperator(_, _, s) => *s,
ParseError::InvalidLiteral(_, _, s) => *s,
ParseError::NotAConstant(s) => *s,
ParseError::ClosureMissingPipe(s) => *s,
}
}
}

View File

@ -1779,8 +1779,10 @@ pub fn parse_brace_expr(
if matches!(second_token, None) {
// If we're empty, that means an empty record or closure
if matches!(shape, SyntaxShape::Closure(_)) {
parse_closure_expression(working_set, shape, span, expand_aliases_denylist)
if matches!(shape, SyntaxShape::Closure(None)) {
parse_closure_expression(working_set, shape, span, expand_aliases_denylist, false)
} else if matches!(shape, SyntaxShape::Closure(Some(_))) {
parse_closure_expression(working_set, shape, span, expand_aliases_denylist, true)
} else if matches!(shape, SyntaxShape::Block) {
parse_block_expression(working_set, span, expand_aliases_denylist)
} else {
@ -1789,11 +1791,13 @@ pub fn parse_brace_expr(
} else if matches!(second_token_contents, Some(TokenContents::Pipe))
|| matches!(second_token_contents, Some(TokenContents::PipePipe))
{
parse_closure_expression(working_set, shape, span, expand_aliases_denylist)
parse_closure_expression(working_set, shape, span, expand_aliases_denylist, true)
} else if matches!(third_token, Some(b":")) {
parse_full_cell_path(working_set, None, span, expand_aliases_denylist)
} else if matches!(shape, SyntaxShape::Closure(_)) || matches!(shape, SyntaxShape::Any) {
parse_closure_expression(working_set, shape, span, expand_aliases_denylist)
} else if matches!(shape, SyntaxShape::Closure(None)) {
parse_closure_expression(working_set, shape, span, expand_aliases_denylist, false)
} else if matches!(shape, SyntaxShape::Closure(Some(_))) || matches!(shape, SyntaxShape::Any) {
parse_closure_expression(working_set, shape, span, expand_aliases_denylist, true)
} else if matches!(shape, SyntaxShape::Block) {
parse_block_expression(working_set, span, expand_aliases_denylist)
} else {
@ -4414,6 +4418,7 @@ pub fn parse_closure_expression(
shape: &SyntaxShape,
span: Span,
expand_aliases_denylist: &[usize],
require_pipe: bool,
) -> (Expression, Option<ParseError>) {
trace!("parsing: closure expression");
@ -4490,7 +4495,15 @@ pub fn parse_closure_expression(
Some((Box::new(Signature::new("closure".to_string())), *span)),
1,
),
_ => (None, 0),
_ => {
if require_pipe {
error = error.or(Some(ParseError::ClosureMissingPipe(span)));
working_set.exit_scope();
return (garbage(span), error);
} else {
(None, 0)
}
}
};
// TODO: Finish this

View File

@ -1563,7 +1563,13 @@ mod input_types {
)
.optional(
"else_expression",
SyntaxShape::Keyword(b"else".to_vec(), Box::new(SyntaxShape::Expression)),
SyntaxShape::Keyword(
b"else".to_vec(),
Box::new(SyntaxShape::OneOf(vec![
SyntaxShape::Block,
SyntaxShape::Expression,
])),
),
"expression or block to run if check fails",
)
.category(Category::Core)