Fixed the panic when type a statement similar to let f = 'f' $ in the nushell (#9851)

- this PR should close #9596 
- fixes #9596 
- this PR should close #9826 
- fixes #9826 

fixed the following bugs:
```nu
# type following statements in the nushell
let f = 'f' $;
mut f = 'f' $;
const f = 'f' $;

# then remove variable f, it will panics
let = 'f' $;
mut  = 'f' $;
const = 'f' $;
```
This commit is contained in:
mengsuenyan 2023-08-02 00:21:40 +08:00 committed by GitHub
parent f6033ac5af
commit fea822792f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 3 deletions

View file

@ -2894,7 +2894,9 @@ pub fn parse_let(working_set: &mut StateWorkingSet, spans: &[Span]) -> Pipeline
// so that the var-id created by the variable isn't visible in the expression that init it
for span in spans.iter().enumerate() {
let item = working_set.get_span_contents(*span.1);
if item == b"=" && spans.len() > (span.0 + 1) {
// https://github.com/nushell/nushell/issues/9596, let = if $
// let x = 'f', = at least start from index 2
if item == b"=" && spans.len() > (span.0 + 1) && span.0 > 1 {
let (tokens, parse_error) = lex(
working_set.get_span_contents(nu_protocol::span(&spans[(span.0 + 1)..])),
spans[span.0 + 1].start,
@ -3013,7 +3015,8 @@ pub fn parse_const(working_set: &mut StateWorkingSet, spans: &[Span]) -> Pipelin
// so that the var-id created by the variable isn't visible in the expression that init it
for span in spans.iter().enumerate() {
let item = working_set.get_span_contents(*span.1);
if item == b"=" && spans.len() > (span.0 + 1) {
// const x = 'f', = at least start from index 2
if item == b"=" && spans.len() > (span.0 + 1) && span.0 > 1 {
let mut idx = span.0;
// let rvalue = parse_multispan_value(
// working_set,
@ -3151,7 +3154,8 @@ pub fn parse_mut(working_set: &mut StateWorkingSet, spans: &[Span]) -> Pipeline
// so that the var-id created by the variable isn't visible in the expression that init it
for span in spans.iter().enumerate() {
let item = working_set.get_span_contents(*span.1);
if item == b"=" && spans.len() > (span.0 + 1) {
// mut x = 'f', = at least start from index 2
if item == b"=" && spans.len() > (span.0 + 1) && span.0 > 1 {
let (tokens, parse_error) = lex(
working_set.get_span_contents(nu_protocol::span(&spans[(span.0 + 1)..])),
spans[span.0 + 1].start,

View file

@ -145,6 +145,25 @@ fn bad_var_name2() -> TestResult {
fail_test(r#"let $foo-bar = 4"#, "valid variable")
}
#[test]
fn assignment_with_no_var() -> TestResult {
let cases = [
"let = if $",
"mut = if $",
"const = if $",
"let = 'foo' | $in; $x | describe",
"mut = 'foo' | $in; $x | describe",
];
let expected = "valid variable";
for case in cases {
fail_test(case, expected)?;
}
Ok(())
}
#[test]
fn long_flag() -> TestResult {
run_test(