bugfix: math commands now return error with infinite range [#15135] (#15236)

### Description
Fixes issue #15135

Result

![image](https://github.com/user-attachments/assets/9ff4397f-db79-46df-b1da-2d09f50dd63f)

Also this works with other commands: min, max, sum, product, avg...

### User-Facing Changes
Error is returned, instead of console completely blocked and having to
be killed
I chose "Incorrect value", because commands accept inputs of range type,
just cannot work with unbounded ranges.

### Tests + Formatting
- ran cargo fmt, clippy
- added tests
This commit is contained in:
Loïc Riegel
2025-03-11 14:40:26 +01:00
committed by GitHub
parent 81e496673e
commit b432866dc9
17 changed files with 136 additions and 3 deletions

View File

@ -1,6 +1,8 @@
use core::slice;
use core::{ops::Bound, slice};
use indexmap::IndexMap;
use nu_protocol::{engine::Call, IntoPipelineData, PipelineData, ShellError, Signals, Span, Value};
use nu_protocol::{
engine::Call, IntoPipelineData, PipelineData, Range, ShellError, Signals, Span, Value,
};
pub fn run_with_function(
call: &Call,
@ -91,6 +93,10 @@ pub fn calculate(
Ok(Value::record(record, span))
}
PipelineData::Value(Value::Range { val, .. }, ..) => {
match *val {
Range::IntRange(range) => ensure_bounded(range.end(), span, name)?,
Range::FloatRange(range) => ensure_bounded(range.end(), span, name)?,
}
let new_vals: Result<Vec<Value>, ShellError> = val
.into_range_iter(span, Signals::empty())
.map(|val| mf(&[val], span, name))
@ -110,3 +116,18 @@ pub fn calculate(
}),
}
}
pub fn ensure_bounded<T>(
bound: Bound<T>,
val_span: Span,
call_span: Span,
) -> Result<(), ShellError> {
match bound {
Bound::<T>::Unbounded => Err(ShellError::IncorrectValue {
msg: "Range must be bounded".to_string(),
val_span,
call_span,
}),
_ => Ok(()),
}
}