Files
nushell/crates/nu-command/tests/commands/mut_.rs
132ikl a4bd51a11d Fix type checking for assignment operators (#16107)
<!--
if this PR closes one or more issues, you can automatically link the PR
with
them by using one of the [*linking
keywords*](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue#linking-a-pull-request-to-an-issue-using-a-keyword),
e.g.
- this PR should close #xxxx
- fixes #xxxx

you can also mention related issues, PRs or discussions!
-->

# Description
<!--
Thank you for improving Nushell. Please, check our [contributing
guide](../CONTRIBUTING.md) and talk to the core team before making major
changes.

Description of your pull request goes here. **Provide examples and/or
screenshots** if your changes affect the user experience.
-->

Rel: #14429, #16079

Finishes up a TODO in the assignment type checking. 

- For regular assignment operations (only applies to `mut`), type
checking is now done using `type_compatible` (which is what `let` uses)
- This allows some mutable assignments to work which weren't allowed
before

Before:
```nushell
let x: glob = "" 
# => ok, no error
mut x: glob = ""; $x = ""
# => Error: nu::parser::operator_incompatible_types
# => 
# =>   × Types 'glob' and 'string' are not compatible for the '=' operator.
# =>    ╭─[entry #6:1:19]
# =>  1 │ mut x: glob = ""; $x = ""
# =>    ·                   ─┬ ┬ ─┬
# =>    ·                    │ │  ╰── string
# =>    ·                    │ ╰── does not operate between 'glob' and 'string'
# =>    ·                    ╰── glob
# =>    ╰────

let x: number = 1
# ok, no error
mut x: number = 1; $x = 2
# => Error: nu::parser::operator_incompatible_types
# => 
# =>   × Types 'number' and 'int' are not compatible for the '=' operator.
# =>    ╭─[source:1:20]
# =>  1 │ mut x: number = 1; $x = 2
# =>    ·                    ─┬ ┬ ┬
# =>    ·                     │ │ ╰── int
# =>    ·                     │ ╰── does not operate between 'number' and 'int'
# =>    ·                     ╰── number
# =>    ╰────
```

After:
```nushell
let x: glob = ""
# ok, no error (same as before)
mut x: glob = ""; $x = ""
# ok, no error

let x: number = 1
# ok, no error (same as before)
mut x: number = 1; $x = 2
# ok, no error
```

- Properly type check compound operations. First checks if the operation
(eg. `+` for `+=`) type checks successfully, and then checks if the
assignment type checks successfully (also using `type_compatible`)
- This fixes some issues where the "long version" of a compound
assignment operator would error, but the compound assignment operator
itself would not

Before:
```nushell
mut x = 1; $x = $x / 2
# => Error: nu::parser::operator_incompatible_types
# => 
# =>   × Types 'int' and 'float' are not compatible for the '=' operator.
# =>    ╭─[entry #15:1:12]
# =>  1 │ mut x = 1; $x = $x / 2
# =>    ·            ─┬ ┬ ───┬──
# =>    ·             │ │    ╰── float
# =>    ·             │ ╰── does not operate between 'int' and 'float'
# =>    ·             ╰── int
# =>    ╰────

mut x = 1; $x /= 2
# uh oh, no error...

mut x = (date now); $x = $x - 2019-05-10
# => Error: nu::parser::operator_incompatible_types
# => 
# =>   × Types 'datetime' and 'duration' are not compatible for the '=' operator.
# =>    ╭─[entry #1:1:21]
# =>  1 │ mut x = (date now); $x = $x - 2019-05-10
# =>    ·                     ─┬ ┬ ───────┬───────
# =>    ·                      │ │        ╰── duration
# =>    ·                      │ ╰── does not operate between 'datetime' and 'duration'
# =>    ·                      ╰── datetime
# =>    ╰────

mut x = (date now); $x -= 2019-05-10
# uh oh, no error... (the result of this is a duration, not a datetime)
```

After:
```nushell
mut x = 1; $x = $x / 2
# => Error: nu::parser::operator_incompatible_types
# => 
# =>   × Types 'int' and 'float' are not compatible for the '=' operator.
# =>    ╭─[entry #5:1:12]
# =>  1 │ mut x = 1; $x = $x / 2
# =>    ·            ─┬ ┬ ───┬──
# =>    ·             │ │    ╰── float
# =>    ·             │ ╰── does not operate between 'int' and 'float'
# =>    ·             ╰── int
# =>    ╰────

mut x = (date now); $x -= 2019-05-10
# => Error: nu::parser::operator_incompatible_types
# => 
# =>   × Types 'datetime' and 'datetime' are not compatible for the '-=' operator.
# =>    ╭─[entry #11:1:21]
# =>  1 │ mut x = (date now); $x -= 2019-05-10
# =>    ·                     ─┬ ─┬ ─────┬────
# =>    ·                      │  │      ╰── datetime
# =>    ·                      │  ╰── does not operate between 'datetime' and 'datetime'
# =>    ·                      ╰── datetime
# =>    ╰────
# =>   help: The result type of this operation is not compatible with the type of the variable.
```

This is technically a breaking change if you relied on the old behavior
(for example, there was a test that broke after this change because it
relied on `/=` improperly type checking)

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->
* Mutable assignment operations now use the same type checking rules as
normal assignments
* For example, `$x = 123` now uses the same type checking rules as `let
x = 123` or `mut x = 123`
* Compound assignment operations now type check using the same rules as
the operation they use
* Assignment errors will also now highlight the invalid assignment
operator in red


# 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` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use toolkit.nu; toolkit test stdlib"` to run the
tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->
Adds some tests for the examples given above

# 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.
-->
N/A
2025-07-04 02:48:49 -04:00

196 lines
4.3 KiB
Rust

use nu_test_support::nu;
use rstest::rstest;
#[test]
fn mut_variable() {
let actual = nu!("mut x = 3; $x = $x + 1; $x");
assert_eq!(actual.out, "4");
}
#[rstest]
#[case("mut in = 3")]
#[case("mut in: int = 3")]
fn mut_name_builtin_var(#[case] assignment: &str) {
assert!(
nu!(assignment)
.err
.contains("'in' is the name of a builtin Nushell variable")
);
}
#[test]
fn mut_name_builtin_var_with_dollar() {
let actual = nu!("mut $env = 3");
assert!(
actual
.err
.contains("'env' is the name of a builtin Nushell variable")
)
}
#[test]
fn mut_variable_in_loop() {
let actual = nu!("mut x = 1; for i in 1..10 { $x = $x + $i}; $x");
assert_eq!(actual.out, "56");
}
#[test]
fn capture_of_mutable_var() {
let actual = nu!("mut x = 123; {|| $x }");
assert!(actual.err.contains("capture of mutable variable"));
}
#[test]
fn mut_add_assign() {
let actual = nu!("mut y = 3; $y += 2; $y");
assert_eq!(actual.out, "5");
}
#[test]
fn mut_minus_assign() {
let actual = nu!("mut y = 3; $y -= 2; $y");
assert_eq!(actual.out, "1");
}
#[test]
fn mut_multiply_assign() {
let actual = nu!("mut y = 3; $y *= 2; $y");
assert_eq!(actual.out, "6");
}
#[test]
fn mut_divide_assign() {
let actual = nu!("mut y: number = 8; $y /= 2; $y");
assert_eq!(actual.out, "4.0");
}
#[test]
fn mut_divide_assign_should_error() {
let actual = nu!("mut y = 8; $y /= 2; $y");
assert!(actual.err.contains("parser::operator_incompatible_types"));
}
#[test]
fn mut_subtract_assign_should_error() {
let actual = nu!("mut x = (date now); $x -= 2019-05-10");
assert!(actual.err.contains("parser::operator_incompatible_types"));
}
#[test]
fn mut_assign_number() {
let actual = nu!("mut x: number = 1; $x = 2.0; $x");
assert_eq!(actual.out, "2.0");
}
#[test]
fn mut_assign_glob() {
let actual = nu!(r#"mut x: glob = ""; $x = "meow"; $x"#);
assert_eq!(actual.out, "meow");
}
#[test]
fn mut_path_insert() {
let actual = nu!("mut y = {abc: 123}; $y.abc = 456; $y.abc");
assert_eq!(actual.out, "456");
}
#[test]
fn mut_path_insert_list() {
let actual = nu!("mut a = [0 1 2]; $a.3 = 3; $a | to nuon");
assert_eq!(actual.out, "[0, 1, 2, 3]");
}
#[test]
fn mut_path_upsert() {
let actual = nu!("mut a = {b:[{c:1}]}; $a.b.0.d = 11; $a.b.0.d");
assert_eq!(actual.out, "11");
}
#[test]
fn mut_path_upsert_list() {
let actual = nu!("mut a = [[[3] 2] 1]; $a.0.0.1 = 0; $a.0.2 = 0; $a.2 = 0; $a | to nuon");
assert_eq!(actual.out, "[[[3, 0], 2, 0], 1, 0]");
}
#[test]
fn mut_path_operator_assign() {
let actual = nu!("mut a = {b:1}; $a.b += 3; $a.b -= 2; $a.b *= 10; $a.b /= 4; $a.b");
assert_eq!(actual.out, "5.0");
}
#[test]
fn mut_records_update_properly() {
let actual = nu!("mut a = {}; $a.b.c = 100; $a.b.c");
assert_eq!(actual.out, "100");
}
#[test]
fn mut_value_with_if() {
let actual = nu!("mut a = 3; $a = if 3 == 3 { 10 }; echo $a");
assert_eq!(actual.out, "10");
}
#[test]
fn mut_value_with_match() {
let actual = nu!("mut a = 3; $a = match 3 { 1 => { 'yes!' }, _ => { 'no!' } }; echo $a");
assert_eq!(actual.out, "no!");
}
#[test]
fn mut_glob_type() {
let actual = nu!("mut x: glob = 'aa'; $x | describe");
assert_eq!(actual.out, "glob");
}
#[test]
fn mut_raw_string() {
let actual = nu!(r#"mut x = r#'abcde""fghi"''''jkl'#; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"''''jkl"#);
let actual = nu!(r#"mut x = r##'abcde""fghi"''''#jkl'##; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"''''#jkl"#);
let actual = nu!(r#"mut x = r###'abcde""fghi"'''##'#jkl'###; $x"#);
assert_eq!(actual.out, r#"abcde""fghi"'''##'#jkl"#);
let actual = nu!(r#"mut x = r#'abc'#; $x"#);
assert_eq!(actual.out, "abc");
}
#[test]
fn def_should_not_mutate_mut() {
let actual = nu!("mut a = 3; def foo [] { $a = 4}");
assert!(actual.err.contains("capture of mutable variable"));
assert!(!actual.status.success())
}
#[test]
fn assign_to_non_mut_variable_raises_parse_error() {
let actual = nu!("let x = 3; $x = 4");
assert!(
actual
.err
.contains("parser::assignment_requires_mutable_variable")
);
let actual = nu!("mut x = 3; x = 5");
assert!(actual.err.contains("parser::assignment_requires_variable"));
}