Add Span merging functions (#12511)

# Description
This PR adds a few functions to `Span` for merging spans together:
- `Span::append`: merges two spans that are known to be in order.
- `Span::concat`: returns a span that encompasses all the spans in a
slice. The spans must be in order.
- `Span::merge`: merges two spans (no order necessary).
- `Span::merge_many`: merges an iterator of spans into a single span (no
order necessary).

These are meant to replace the free-standing `nu_protocol::span`
function.

The spans in a `LiteCommand` (the `parts`) should always be in order
based on the lite parser and lexer. So, the parser code sees the most
usage of `Span::append` and `Span::concat` where the order is known. In
other code areas, `Span::merge` and `Span::merge_many` are used since
the order between spans is often not known.
This commit is contained in:
Ian Manske
2024-05-16 22:34:49 +00:00
committed by GitHub
parent 2a09dccc11
commit aec41f3df0
15 changed files with 305 additions and 241 deletions

View File

@ -1,7 +1,7 @@
use super::{operations::Axis, NuDataFrame};
use nu_protocol::{
ast::{Boolean, Comparison, Math, Operator},
span, ShellError, Span, Spanned, Value,
ShellError, Span, Spanned, Value,
};
use num::Zero;
use polars::prelude::{
@ -17,9 +17,10 @@ pub(super) fn between_dataframes(
right: &Value,
rhs: &NuDataFrame,
) -> Result<NuDataFrame, ShellError> {
let operation_span = span(&[left.span(), right.span()]);
match operator.item {
Operator::Math(Math::Plus) => lhs.append_df(rhs, Axis::Row, operation_span),
Operator::Math(Math::Plus) => {
lhs.append_df(rhs, Axis::Row, Span::merge(left.span(), right.span()))
}
_ => Err(ShellError::OperatorMismatch {
op_span: operator.span,
lhs_ty: left.get_type().to_string(),
@ -37,7 +38,7 @@ pub(super) fn compute_between_series(
right: &Value,
rhs: &Series,
) -> Result<NuDataFrame, ShellError> {
let operation_span = span(&[left.span(), right.span()]);
let operation_span = Span::merge(left.span(), right.span());
match operator.item {
Operator::Math(Math::Plus) => {
let mut res = lhs + rhs;

View File

@ -1,4 +1,4 @@
use nu_protocol::{span as span_join, ShellError, Span, Spanned, Value};
use nu_protocol::{ShellError, Span, Spanned, Value};
// Default value used when selecting rows from dataframe
pub const DEFAULT_ROWS: usize = 5;
@ -20,8 +20,8 @@ pub(crate) fn convert_columns(
span: Some(span),
help: None,
inner: vec![],
})
.map(|v| v.span())?;
})?
.span();
let res = columns
.into_iter()
@ -29,7 +29,7 @@ pub(crate) fn convert_columns(
let span = value.span();
match value {
Value::String { val, .. } => {
col_span = span_join(&[col_span, span]);
col_span = col_span.merge(span);
Ok(Spanned { item: val, span })
}
_ => Err(ShellError::GenericError {
@ -70,7 +70,7 @@ pub(crate) fn convert_columns_string(
let span = value.span();
match value {
Value::String { val, .. } => {
col_span = span_join(&[col_span, span]);
col_span = col_span.merge(span);
Ok(val)
}
_ => Err(ShellError::GenericError {