type-check default values of list annotations (#8600)

# Description

@fdncred noticed an
[issue](https://github.com/nushell/nushell/pull/8529#issuecomment-1482770636)
with list annotations that while i was trying to find a fix found
another issue.

innitially, this was accepted by the parser
```nu
def err [list: list<int> = ['a' 'b' 'c']] {}
```

but now an error is raised
```nu
Error: nu::parser::assignment_mismatch

  × Default value wrong type
   ╭─[entry #1:1:1]
 1 │ def err [list: list<int> = ['a' 'b' 'c']] {}
   ·                            ──────┬────
   ·                                   ╰── expected default value to be `list<int>`
   ╰────
```

# User-Facing Changes

none

# Tests + Formatting

done
This commit is contained in:
mike 2023-03-24 22:57:18 +03:00 committed by GitHub
parent b4b68afa17
commit 744a28b31d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 39 additions and 9 deletions

View File

@ -3995,19 +3995,35 @@ pub fn parse_signature_helper(
expression.ty.clone(),
);
}
Type::List(_) => {
if var_type.is_list() && expression.ty.is_list() {
working_set.set_variable_type(
var_id,
expression.ty.clone(),
);
Type::List(param_ty) => {
if let Type::List(expr_ty) = &expression.ty {
if param_ty == expr_ty
|| **param_ty == Type::Any
{
working_set.set_variable_type(
var_id,
expression.ty.clone(),
);
} else {
error = error.or_else(|| {
Some(
ParseError::AssignmentMismatch(
"Default value wrong type"
.into(),
format!(
"expected default value to be `{var_type}`",
),
expression.span,
),
)
})
}
} else {
error = error.or_else(|| {
Some(ParseError::AssignmentMismatch(
"Default value wrong type".into(),
format!(
"default value not {0}",
expression.ty
"expected default value to be `{var_type}`",
),
expression.span,
))
@ -4019,7 +4035,7 @@ pub fn parse_signature_helper(
error = error.or_else(|| {
Some(ParseError::AssignmentMismatch(
"Default value wrong type".into(),
format!("default value not {t}"),
format!("expected default value to be `{t}`"),
expression.span,
))
})

View File

@ -111,3 +111,17 @@ fn list_annotations_unknown_separators() -> TestResult {
let expected = "unknown type";
fail_test(input, expected)
}
#[test]
fn list_annotations_with_default_val_1() -> TestResult {
let input = "def run [list: list<int> = [2 5 4]] {$list | length}; run";
let expected = "3";
run_test(input, expected)
}
#[test]
fn list_annotations_with_default_val_2() -> TestResult {
let input = "def run [list: list<string> = [2 5 4]] {$list | length}; run";
let expected = "Default value wrong type";
fail_test(input, expected)
}