This commit is contained in:
132ikl 2025-03-10 05:06:09 -07:00 committed by GitHub
commit 0a2106c2a9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 24 additions and 5 deletions

View File

@ -6534,7 +6534,12 @@ pub fn discover_captures_in_expr(
if !seen.contains(var_id) {
if let Some(variable) = working_set.get_variable_if_possible(*var_id) {
if variable.mutable {
return Err(ParseError::CaptureOfMutableVar(*span));
let var_name = working_set.get_span_contents(*span);
return Err(ParseError::CaptureOfMutableVar {
var: String::from_utf8_lossy(var_name).into_owned(),
var_span: span.before(),
closure_span: block.span,
});
}
}
}

View File

@ -145,9 +145,15 @@ pub enum ParseError {
help: Option<&'static str>,
},
#[error("Capture of mutable variable.")]
#[diagnostic(code(nu::parser::expected_keyword))]
CaptureOfMutableVar(#[label("capture of mutable variable")] Span),
#[error("Cannot capture mutable variables inside closures.")]
#[diagnostic(code(nu::parser::mutable_capture))]
CaptureOfMutableVar {
var: String,
#[label("could not capture within this closure")]
closure_span: Option<Span>,
#[label("attempted to capture mutable variable {var}")]
var_span: Span,
},
#[error("Expected keyword.")]
#[diagnostic(code(nu::parser::expected_keyword))]
@ -570,7 +576,7 @@ impl ParseError {
ParseError::BuiltinCommandInPipeline(_, s) => *s,
ParseError::AssignInPipeline(_, _, _, s) => *s,
ParseError::NameIsBuiltinVar(_, s) => *s,
ParseError::CaptureOfMutableVar(s) => *s,
ParseError::CaptureOfMutableVar { var_span, .. } => *var_span,
ParseError::IncorrectValue(_, s, _) => *s,
ParseError::MultipleRestParams(s) => *s,
ParseError::VariableNotFound(_, s) => *s,

View File

@ -140,6 +140,14 @@ impl Span {
self.start <= span.start && span.end <= self.end && span.end != 0
}
/// Point to the space just before this span
pub fn before(&self) -> Self {
Self {
start: self.start,
end: self.start,
}
}
/// Point to the space just past this span, useful for missing values
pub fn past(&self) -> Self {
Self {