mirror of
https://github.com/nushell/nushell.git
synced 2026-12-03 02:27:37 +08:00
## Description
What started out as trying to fix startup errors turned into a root
canal for the lexer in order to preserve spans where errors occur and a
little parser work.
The focus of this PR is to improved how Nushell reports **delimiter
parse failures** (`{`/`}`, `[`/`]`, `(`/`)`, quotes, signature `<>`,
closure `|…|`) and how **startup config/script load** surfaces those
errors.
### Lexer
- Track each open delimiter as an `OpenFrame { kind, open_span }`
instead of only a kind stack.
- On **unclosed** (stack non-empty at end of token / EOF): emit
`ParseError::Unclosed` with:
- secondary label on the **opener**
- primary label where the **closer was expected**
- help text, optionally including a **structure hint** (`def greet`,
record field `ls`, …)
- On **unbalanced** (wrong or extra closer): emit
`ParseError::Unbalanced` naming open kind and closer.
### Parser
Update unclosed and unbalanced functions and add better labels instead
of just unexpected_eof.
## User-facing changes (Release notes)
### Clearer delimiter errors
Nushell now reports **unclosed** and **unbalanced** delimiters with:
- The **kind** of delimiter involved (`{`, `}`, `[`, `]`, `(`, `)`, `"`,
`'`, `>`, `|`, …)
- **Where it opened** and **where the closer was expected** (when known)
- Help text that suggests a fix, sometimes with a structure hint (e.g.
which `def` or record field is open)
Common mistakes such as forgetting `[` before list elements, forgetting
`(` before a grouped expression, forgetting `{` after
`if`/`while`/`for`/`try`/`match`, or writing bare record fields without
`{` point **near the mistake** instead of only at a distant `}` or EOF.
## Additional notes
## Detailed examples of the new diagnostics
These were captured with a build from this branch (`nu -n
--no-config-file -c '…'`). Labels and help text are the user-visible
improvement; line numbers are for the snippet as shown. Clanker
generated.
---
### 1. Extra closing brace (unbalanced `}`)
**Input:**
```nushell
{a:{b:5}}}
```
**Error:**
```nushell
Error: nu::parser::unbalanced_delimiter
× Unbalanced delimiter.
╭─[source:1:10]
1 │ {a:{b:5}}}
· ┬
· ╰── unexpected `}` (unbalanced with `{`)
╰────
help: Remove this `}`, or add a matching `{` earlier. If you closed a block
too early, the real mistake may be above.
```
**Why it helps:** Names both sides of the mismatch (`}` vs `{`) and
marks the offending closer.
---
### 2. Lone extra brace
**Input:**
```nushell
}
```
**Error:**
```nushell
Error: nu::parser::unbalanced_delimiter
× Unbalanced delimiter.
╭─[source:1:1]
1 │ }
· ┬
· ╰── unexpected `}` (unbalanced with `{`)
╰────
help: Remove this `}`, or add a matching `{` earlier. If you closed a block
too early, the real mistake may be above.
```
---
### 3. Unclosed brace (opens here + expected closer)
**Input:**
```nushell
{
```
**Error:**
```nushell
Error: nu::parser::unclosed_delimiter
× Unclosed delimiter.
╭─[source:1:1]
1 │ {
· ┬┬
· │╰── expected `}` here
· ╰── unclosed — opens here (need `}`)
╰────
help: Add a matching `}` to close this delimiter, or check that an earlier
closer closed the wrong block.
```
**Why it helps:** Two labels: where `{` opened and where `}` is expected
(here, same line at EOF).
---
### 4. Nested unclosed config-style record (structure hint)
**Input:**
```nushell
$env.config = {
ls: {
use_ls_colors: true
```
**Error:**
```nushell
Error: nu::parser::unclosed_delimiter
× Unclosed delimiter.
╭─[source:3:24]
1 │ $env.config = {
2 │ ls: {
· ┬
· ╰── unclosed — opens here (need `}`)
3 │ use_ls_colors: true
· ┬
· ╰── expected `}` here
╰────
help: Add a matching `}` to close record field `ls`, or check that an
earlier closer closed the wrong block.
```
**Why it helps:** Prefers the **inner** open (`ls: {`) and help mentions
**record field `ls`**, not only a generic “unclosed”.
---
### 5. Missing `{` after `if` (orphan closer → unbalanced)
**Input:**
```nushell
def f [] {
each {|r|
if $x != string
$r
}
}
}
```
**Error:**
```nushell
Error: nu::parser::unbalanced_delimiter
× Unbalanced delimiter.
╭─[source:7:1]
6 │ }
7 │ }
· ┬
· ╰── unexpected `}` (unbalanced with `{`)
╰────
help: Remove this `}` if it is extra, or add a matching `{` earlier. If you
closed a block too early, the real mistake may be above.
```
Same plain-unbalanced presentation applies to similar **while** /
**for** / **try** / **match** / **else if** shapes that leave an orphan
`}`.
---
### 6. Missing `{` for a bare record field
**Input** (pattern from real scripts: forgot `{` before `type: …`):
```nushell
def f [] {
insert content {
each {|lst|
type: $lst.0}
| if $true { 1 } else { 2 }
}
}
}
```
**Error:**
```nushell
Error: nu::parser::unbalanced_delimiter
× Unbalanced delimiter.
╭─[source:8:1]
7 │ }
8 │ }
· ┬
· ╰── unexpected `}` (unbalanced with `{`)
╰────
help: Remove this `}` if it is extra, or add a matching `{` earlier. If you
closed a block too early, the real mistake may be above.
```
---
### 7. Missing `[` before list elements
**Input:**
```nushell
def f [] {
if $true {
2 ($in_ten - 2) 0]
}
}
```
**Error:**
```nushell
Error: nu::parser::unbalanced_delimiter
× Unbalanced delimiter.
╭─[source:3:24]
2 │ if $true {
3 │ 2 ($in_ten - 2) 0]
· ┬
· ╰── unexpected `]` (unbalanced with `{`)
4 │ }
╰────
help: Remove this `]` if it is extra, or add a matching `{` earlier. If you
closed a block too early, the real mistake may be above.
```
---
### 8. Missing `(` before a grouped expression
**Input:**
```nushell
def f [] {
if $true {
print -n ansi green)
}
}
```
**Error:**
```nushell
Error: nu::parser::unbalanced_delimiter
× Unbalanced delimiter.
╭─[source:3:28]
2 │ if $true {
3 │ print -n ansi green)
· ┬
· ╰── unexpected `)` (unbalanced with `{`)
4 │ }
╰────
help: Remove this `)` if it is extra, or add a matching `{` earlier. If you
closed a block too early, the real mistake may be above.
```
---
### 9. Wrong closer kinds stay precise
**List closed with `)`:**
```nushell
[1, 2, 3)
```
```nushell
Error: nu::parser::unbalanced_delimiter
× Unbalanced delimiter.
╭─[source:1:9]
1 │ [1, 2, 3)
· ┬
· ╰── unexpected `)` (unbalanced with `[`)
╰────
help: Remove this `)`, or add a matching `[` earlier. …
```
**Group closed with `]`:**
```nushell
(1, 2]
```
```nushell
Error: nu::parser::unbalanced_delimiter
× Unbalanced delimiter.
╭─[source:1:6]
1 │ (1, 2]
· ┬
· ╰── unexpected `]` (unbalanced with `(`)
╰────
help: Remove this `]`, or add a matching `(` earlier. …
```
**Why it helps:** Open kind is the **real** stack top (`[` or `(`), not
a generic or inverted guess. Missing-`[` / missing-`(` presentation is
suppressed when the stack top is already a list/paren (avoids false
“missing open” for pure mismatches).
---
### 10. Missing `}` before the next pipeline step (closure + `|`)
**Input** (forgot `}` after the first closure body before `| upsert b`):
```nushell
def f [] {
ls | upsert a {|n|
$n | length
| upsert b {|x|
$x
}
```
**Error:**
```nushell
Error: nu::parser::unclosed_delimiter
× Unclosed delimiter.
╭─[source:4:3]
1 │ def f [] {
2 │ ls | upsert a {|n|
· ┬
· ╰── unclosed — opens here (need `}`)
3 │ $n | length
4 │ | upsert b {|x|
· ┬
· ╰── expected `}` here
5 │ $x
╰────
help: Add a matching `}` to close this delimiter, or check that an earlier
closer closed the wrong block.
```
**Why it helps:** Expected closer is labeled at **`| upsert b`**, not
only at EOF — where the user almost always forgot `}`.
---
### 11. Missing `]` before `def` body `{`
**Input:**
```nushell
def prepend-if-not-in [
value: string
{
let list = $in
}
```
**Error:**
```nushell
Error: nu::parser::unclosed_delimiter
× Unclosed delimiter.
╭─[source:3:2]
1 │ def prepend-if-not-in [
· ┬
· ╰── unclosed — opens here (need `]`)
2 │ value: string
3 │ {
· ┬
· ╰── expected `]` here
4 │ let list = $in
╰────
help: Add a matching `]` to close `def prepend-if-not-in`, or check that an
earlier closer closed the wrong block.
```
**Why it helps:** Users often open the body before closing the parameter
list; the label sits on the body `{`, and help names **`def
prepend-if-not-in`**.
---
### 12. Unclosed quote (doesn't affect multiline with closing quote on
the next line)
**Input:**
```nushell
let x = "hello
```
**Error:**
```nushell
Error: nu::parser::unclosed_delimiter
× Unclosed delimiter.
╭─[source:1:14]
1 │ let x = "hello
· ┬ ┬
· │ ╰── expected `"` here
· ╰── unclosed — opens here (need `"`)
╰────
help: Add a matching `"` to close this delimiter, or check that an earlier
closer closed the wrong block.
```
---
### 13. Unclosed list (doesn't affect multiline with closing bracket on
next line)
**Input:**
```nushell
let x = [1, 2, 3
```
**Error:**
```nushell
Error: nu::parser::unclosed_delimiter
× Unclosed delimiter.
╭─[source:1:16]
1 │ let x = [1, 2, 3
· ┬ ┬
· │ ╰── expected `]` here
· ╰── unclosed — opens here (need `]`)
╰────
help: Add a matching `]` to close this delimiter, or check that an earlier
closer closed the wrong block.
```
(Diagnostic code: `nu::parser::unclosed_delimiter` — not
`unexpected_eof`.)
---
### 14. Unclosed type annotation (`>` in signatures)
**Input:**
```nushell
def my_run [list: list<string] {$list}
```
**Error:**
```nushell
Error: nu::parser::unclosed_delimiter
× Unclosed delimiter.
╭─[source:1:29]
1 │ def my_run [list: list<string] {$list}
· ┬ ┬
· │ ╰── expected `>` here
· ╰── unclosed — opens here (need `>`)
╰────
help: Add a matching `>` to close record field `list`, or check that an
earlier closer closed the wrong block.
```
Same pattern for incomplete `record<…`, `table<…`, `oneof<…`.
---
### 15. Unclosed closure parameter bars
**Input:**
```nushell
{ |a $a }
```
**Error:**
```nushell
Error: nu::parser::unclosed_delimiter
× Unclosed delimiter.
╭─[source:1:9]
1 │ { |a $a }
· ┬ ▲
· │ ╰── expected `|` here
· ╰── unclosed — opens here (need `|`)
╰────
help: Add a matching `|` to close this delimiter, or check that an earlier
closer closed the wrong block.
```
---
### 16. Incomplete record field (parser-level, related)
**Input:**
```nushell
{ a: 2 b }
```
**Error:**
```nushell
Error: nu::parser::error
× Incomplete record field
╭─[source:1:9]
1 │ { a: 2 b }
· ▲
· ╰── expected `:` after this key
╰────
help: Record fields look like `key: value`. Add a colon after the key.
```
---
### 17. Extra closing paren
**Input:**
```nushell
)
```
**Error:**
```nushell
Error: nu::parser::unbalanced_delimiter
× Unbalanced delimiter.
╭─[source:1:1]
1 │ )
· ┬
· ╰── unexpected `)` (unbalanced with `(`)
╰────
help: Remove this `)`, or add a matching `(` earlier. …
```
185 lines
4.9 KiB
Rust
185 lines
4.9 KiB
Rust
use crate::repl::tests::{TestResult, fail_test, run_test};
|
|
|
|
#[test]
|
|
fn cjk_in_substrings() -> TestResult {
|
|
run_test(
|
|
"let s = '[Rust 程序设计语言](title-page.md)'; let start = ($s | str index-of '('); let end = ($s | str index-of ')'); $s | str substring ($start + 1)..<($end)",
|
|
"title-page.md",
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn string_not_in_string() -> TestResult {
|
|
run_test("'d' not-in 'abc'", "true")
|
|
}
|
|
|
|
#[test]
|
|
fn string_in_string() -> TestResult {
|
|
run_test("'z' in 'abc'", "false")
|
|
}
|
|
|
|
#[test]
|
|
fn non_string_in_string() -> TestResult {
|
|
fail_test("42 in 'abc'", "nu::parser::operator_incompatible_types")
|
|
}
|
|
|
|
#[test]
|
|
fn string_in_record() -> TestResult {
|
|
run_test(r#""a" in ('{ "a": 13, "b": 14 }' | from json)"#, "true")
|
|
}
|
|
|
|
#[test]
|
|
fn non_string_in_record() -> TestResult {
|
|
fail_test(
|
|
r#"4 in ('{ "a": 13, "b": 14 }' | from json)"#,
|
|
"nu::shell::operator_incompatible_types",
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn unbalance_string() -> TestResult {
|
|
fail_test(r#""aaaab"cc"#, "invalid characters")?;
|
|
fail_test("'aaaab'cc", "invalid characters")?;
|
|
fail_test(r#"$"aaaab"cc"#, "invalid characters")?;
|
|
fail_test("$'aaaab'cc", "invalid characters")
|
|
}
|
|
|
|
#[test]
|
|
fn string_in_valuestream() -> TestResult {
|
|
run_test(
|
|
r#"
|
|
'Hello' in ("Hello
|
|
World" | lines)"#,
|
|
"true",
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn single_tick_interpolation() -> TestResult {
|
|
run_test("$'(3 + 4)'", "7")
|
|
}
|
|
|
|
#[test]
|
|
fn unclosed_interpolation_subexpression() -> TestResult {
|
|
fail_test("$\"foo (2 + 3\"", "expected `)`")
|
|
}
|
|
|
|
#[test]
|
|
fn detect_newlines() -> TestResult {
|
|
run_test("'hello\r\nworld' | lines | get 0 | str length", "5")
|
|
}
|
|
|
|
#[test]
|
|
fn case_insensitive_sort() -> TestResult {
|
|
run_test(
|
|
"[a, B, d, C, f] | sort -i | to json --raw",
|
|
"[\"a\",\"B\",\"C\",\"d\",\"f\"]",
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn case_insensitive_sort_columns() -> TestResult {
|
|
run_test(
|
|
r#"[[version, package]; ["two", "Abc"], ["three", "abc"], ["four", "abc"]] | sort-by -i package version | to json --raw"#,
|
|
r#"[{"version":"four","package":"abc"},{"version":"three","package":"abc"},{"version":"two","package":"Abc"}]"#,
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn raw_string() -> TestResult {
|
|
run_test(r#"r#'abcde""fghi"''''jkl'#"#, r#"abcde""fghi"''''jkl"#)?;
|
|
run_test(r#"r##'abcde""fghi"''''#jkl'##"#, r#"abcde""fghi"''''#jkl"#)?;
|
|
run_test(
|
|
r#"r###'abcde""fghi"'''##'#jkl'###"#,
|
|
r#"abcde""fghi"'''##'#jkl"#,
|
|
)?;
|
|
run_test("r#''#", "")?;
|
|
run_test(
|
|
"r#'a string with sharp inside # and ends with #'#",
|
|
"a string with sharp inside # and ends with #",
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn raw_string_inside_parentheses() -> TestResult {
|
|
let (left, right) = ('(', ')');
|
|
run_test(
|
|
&format!(r#"{left}r#'abcde""fghi"''''jkl'#{right}"#),
|
|
r#"abcde""fghi"''''jkl"#,
|
|
)?;
|
|
run_test(
|
|
&format!(r#"{left}r##'abcde""fghi"''''#jkl'##{right}"#),
|
|
r#"abcde""fghi"''''#jkl"#,
|
|
)?;
|
|
run_test(
|
|
&format!(r#"{left}r###'abcde""fghi"'''##'#jkl'###{right}"#),
|
|
r#"abcde""fghi"'''##'#jkl"#,
|
|
)?;
|
|
run_test(&format!("{left}r#''#{right}"), "")?;
|
|
run_test(
|
|
&format!("{left}r#'a string with sharp inside # and ends with #'#{right}"),
|
|
"a string with sharp inside # and ends with #",
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn raw_string_inside_list() -> TestResult {
|
|
let (left, right) = ('[', ']');
|
|
run_test(
|
|
&format!(r#"{left}r#'abcde""fghi"''''jkl'#{right} | get 0"#),
|
|
r#"abcde""fghi"''''jkl"#,
|
|
)?;
|
|
run_test(
|
|
&format!(r#"{left}r##'abcde""fghi"''''#jkl'##{right} | get 0"#),
|
|
r#"abcde""fghi"''''#jkl"#,
|
|
)?;
|
|
run_test(
|
|
&format!(r#"{left}r###'abcde""fghi"'''##'#jkl'###{right} | get 0"#),
|
|
r#"abcde""fghi"'''##'#jkl"#,
|
|
)?;
|
|
run_test(&format!("{left}r#''#{right} | get 0"), "")?;
|
|
run_test(
|
|
&format!("{left}r#'a string with sharp inside # and ends with #'#{right} | get 0"),
|
|
"a string with sharp inside # and ends with #",
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn raw_string_inside_closure() -> TestResult {
|
|
let (left, right) = ('{', '}');
|
|
run_test(
|
|
&format!(r#"do {left}r#'abcde""fghi"''''jkl'#{right}"#),
|
|
r#"abcde""fghi"''''jkl"#,
|
|
)?;
|
|
run_test(
|
|
&format!(r#"do {left}r##'abcde""fghi"''''#jkl'##{right}"#),
|
|
r#"abcde""fghi"''''#jkl"#,
|
|
)?;
|
|
run_test(
|
|
&format!(r#"do {left}r###'abcde""fghi"'''##'#jkl'###{right}"#),
|
|
r#"abcde""fghi"'''##'#jkl"#,
|
|
)?;
|
|
run_test(&format!("do {left}r#''#{right}"), "")?;
|
|
run_test(
|
|
&format!("do {left}r#'a string with sharp inside # and ends with #'#{right}"),
|
|
"a string with sharp inside # and ends with #",
|
|
)
|
|
}
|
|
|
|
#[test]
|
|
fn incomplete_string() -> TestResult {
|
|
fail_test("r#abc", "expected '")?;
|
|
fail_test("r#'bc", "expected closing '#")?;
|
|
fail_test("'ab\"", "expected `'`")?;
|
|
fail_test("\"ab'", "expected `\"`")?;
|
|
fail_test(
|
|
r#"def func [] {
|
|
{
|
|
"A": ""B" # <- the quote is bad
|
|
}
|
|
}
|
|
"#,
|
|
"expected `\"`",
|
|
)
|
|
}
|