Replace &Span with Span since Span is Copy (#9770)

# Description
`Span` is `Copy`, so we probably should not be passing references of
`Span` around. This PR replaces all instances of `&Span` with `Span`,
copying spans where necessary.

# User-Facing Changes
This alters some public functions to take `Span` instead of `&Span` as
input. Namely, `EngineState::get_span_contents`,
`nu_protocol::extract_value`, a bunch of the math commands, and
`Gstat::gstat`.
This commit is contained in:
Ian Manske 2023-07-31 19:47:46 +00:00 committed by GitHub
parent 94bec72079
commit 583ef8674e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
35 changed files with 356 additions and 365 deletions

View File

@ -62,11 +62,11 @@ impl Command for KeybindingsList {
let all_options = ["modifiers", "keycodes", "edits", "modes", "events"]; let all_options = ["modifiers", "keycodes", "edits", "modes", "events"];
all_options all_options
.iter() .iter()
.flat_map(|argument| get_records(argument, &call.head)) .flat_map(|argument| get_records(argument, call.head))
.collect() .collect()
} else { } else {
call.named_iter() call.named_iter()
.flat_map(|(argument, _, _)| get_records(argument.item.as_str(), &call.head)) .flat_map(|(argument, _, _)| get_records(argument.item.as_str(), call.head))
.collect() .collect()
}; };
@ -78,7 +78,7 @@ impl Command for KeybindingsList {
} }
} }
fn get_records(entry_type: &str, span: &Span) -> Vec<Value> { fn get_records(entry_type: &str, span: Span) -> Vec<Value> {
let values = match entry_type { let values = match entry_type {
"modifiers" => get_reedline_keybinding_modifiers().sorted(), "modifiers" => get_reedline_keybinding_modifiers().sorted(),
"keycodes" => get_reedline_keycodes().sorted(), "keycodes" => get_reedline_keycodes().sorted(),
@ -95,15 +95,15 @@ fn get_records(entry_type: &str, span: &Span) -> Vec<Value> {
.collect() .collect()
} }
fn convert_to_record(edit: &str, entry_type: &str, span: &Span) -> Value { fn convert_to_record(edit: &str, entry_type: &str, span: Span) -> Value {
let entry_type = Value::string(entry_type, *span); let entry_type = Value::string(entry_type, span);
let name = Value::string(edit, *span); let name = Value::string(edit, span);
Value::Record { Value::Record {
cols: vec!["type".to_string(), "name".to_string()], cols: vec!["type".to_string(), "name".to_string()],
vals: vec![entry_type, name], vals: vec![entry_type, name],
span: *span, span,
} }
} }

View File

@ -131,7 +131,7 @@ fn add_menu(
config: &Config, config: &Config,
) -> Result<Reedline, ShellError> { ) -> Result<Reedline, ShellError> {
if let Value::Record { cols, vals, span } = &menu.menu_type { if let Value::Record { cols, vals, span } = &menu.menu_type {
let layout = extract_value("layout", cols, vals, span)?.into_string("", config); let layout = extract_value("layout", cols, vals, *span)?.into_string("", config);
match layout.as_str() { match layout.as_str() {
"columnar" => add_columnar_menu(line_editor, menu, engine_state, stack, config), "columnar" => add_columnar_menu(line_editor, menu, engine_state, stack, config),
@ -155,7 +155,7 @@ fn add_menu(
macro_rules! add_style { macro_rules! add_style {
// first arm match add!(1,2), add!(2,3) etc // first arm match add!(1,2), add!(2,3) etc
($name:expr, $cols: expr, $vals:expr, $span:expr, $config: expr, $menu:expr, $f:expr) => { ($name:expr, $cols: expr, $vals:expr, $span:expr, $config: expr, $menu:expr, $f:expr) => {
$menu = match extract_value($name, $cols, $vals, $span) { $menu = match extract_value($name, $cols, $vals, *$span) {
Ok(text) => { Ok(text) => {
let style = match text { let style = match text {
Value::String { val, .. } => lookup_ansi_color_style(&val), Value::String { val, .. } => lookup_ansi_color_style(&val),
@ -181,7 +181,7 @@ pub(crate) fn add_columnar_menu(
let mut columnar_menu = ColumnarMenu::default().with_name(&name); let mut columnar_menu = ColumnarMenu::default().with_name(&name);
if let Value::Record { cols, vals, span } = &menu.menu_type { if let Value::Record { cols, vals, span } = &menu.menu_type {
columnar_menu = match extract_value("columns", cols, vals, span) { columnar_menu = match extract_value("columns", cols, vals, *span) {
Ok(columns) => { Ok(columns) => {
let columns = columns.as_int()?; let columns = columns.as_int()?;
columnar_menu.with_columns(columns as u16) columnar_menu.with_columns(columns as u16)
@ -189,7 +189,7 @@ pub(crate) fn add_columnar_menu(
Err(_) => columnar_menu, Err(_) => columnar_menu,
}; };
columnar_menu = match extract_value("col_width", cols, vals, span) { columnar_menu = match extract_value("col_width", cols, vals, *span) {
Ok(col_width) => { Ok(col_width) => {
let col_width = col_width.as_int()?; let col_width = col_width.as_int()?;
columnar_menu.with_column_width(Some(col_width as usize)) columnar_menu.with_column_width(Some(col_width as usize))
@ -197,7 +197,7 @@ pub(crate) fn add_columnar_menu(
Err(_) => columnar_menu.with_column_width(None), Err(_) => columnar_menu.with_column_width(None),
}; };
columnar_menu = match extract_value("col_padding", cols, vals, span) { columnar_menu = match extract_value("col_padding", cols, vals, *span) {
Ok(col_padding) => { Ok(col_padding) => {
let col_padding = col_padding.as_int()?; let col_padding = col_padding.as_int()?;
columnar_menu.with_column_padding(col_padding as usize) columnar_menu.with_column_padding(col_padding as usize)
@ -283,7 +283,7 @@ pub(crate) fn add_list_menu(
let mut list_menu = ListMenu::default().with_name(&name); let mut list_menu = ListMenu::default().with_name(&name);
if let Value::Record { cols, vals, span } = &menu.menu_type { if let Value::Record { cols, vals, span } = &menu.menu_type {
list_menu = match extract_value("page_size", cols, vals, span) { list_menu = match extract_value("page_size", cols, vals, *span) {
Ok(page_size) => { Ok(page_size) => {
let page_size = page_size.as_int()?; let page_size = page_size.as_int()?;
list_menu.with_page_size(page_size as usize) list_menu.with_page_size(page_size as usize)
@ -369,7 +369,7 @@ pub(crate) fn add_description_menu(
let mut description_menu = DescriptionMenu::default().with_name(&name); let mut description_menu = DescriptionMenu::default().with_name(&name);
if let Value::Record { cols, vals, span } = &menu.menu_type { if let Value::Record { cols, vals, span } = &menu.menu_type {
description_menu = match extract_value("columns", cols, vals, span) { description_menu = match extract_value("columns", cols, vals, *span) {
Ok(columns) => { Ok(columns) => {
let columns = columns.as_int()?; let columns = columns.as_int()?;
description_menu.with_columns(columns as u16) description_menu.with_columns(columns as u16)
@ -377,7 +377,7 @@ pub(crate) fn add_description_menu(
Err(_) => description_menu, Err(_) => description_menu,
}; };
description_menu = match extract_value("col_width", cols, vals, span) { description_menu = match extract_value("col_width", cols, vals, *span) {
Ok(col_width) => { Ok(col_width) => {
let col_width = col_width.as_int()?; let col_width = col_width.as_int()?;
description_menu.with_column_width(Some(col_width as usize)) description_menu.with_column_width(Some(col_width as usize))
@ -385,7 +385,7 @@ pub(crate) fn add_description_menu(
Err(_) => description_menu.with_column_width(None), Err(_) => description_menu.with_column_width(None),
}; };
description_menu = match extract_value("col_padding", cols, vals, span) { description_menu = match extract_value("col_padding", cols, vals, *span) {
Ok(col_padding) => { Ok(col_padding) => {
let col_padding = col_padding.as_int()?; let col_padding = col_padding.as_int()?;
description_menu.with_column_padding(col_padding as usize) description_menu.with_column_padding(col_padding as usize)
@ -393,7 +393,7 @@ pub(crate) fn add_description_menu(
Err(_) => description_menu, Err(_) => description_menu,
}; };
description_menu = match extract_value("selection_rows", cols, vals, span) { description_menu = match extract_value("selection_rows", cols, vals, *span) {
Ok(selection_rows) => { Ok(selection_rows) => {
let selection_rows = selection_rows.as_int()?; let selection_rows = selection_rows.as_int()?;
description_menu.with_selection_rows(selection_rows as u16) description_menu.with_selection_rows(selection_rows as u16)
@ -401,7 +401,7 @@ pub(crate) fn add_description_menu(
Err(_) => description_menu, Err(_) => description_menu,
}; };
description_menu = match extract_value("description_rows", cols, vals, span) { description_menu = match extract_value("description_rows", cols, vals, *span) {
Ok(description_rows) => { Ok(description_rows) => {
let description_rows = description_rows.as_int()?; let description_rows = description_rows.as_int()?;
description_menu.with_description_rows(description_rows as usize) description_menu.with_description_rows(description_rows as usize)
@ -719,26 +719,26 @@ impl<'config> EventType<'config> {
fn try_from_columns( fn try_from_columns(
cols: &'config [String], cols: &'config [String],
vals: &'config [Value], vals: &'config [Value],
span: &'config Span, span: Span,
) -> Result<Self, ShellError> { ) -> Result<Self, ShellError> {
extract_value("send", cols, vals, span) extract_value("send", cols, vals, span)
.map(Self::Send) .map(Self::Send)
.or_else(|_| extract_value("edit", cols, vals, span).map(Self::Edit)) .or_else(|_| extract_value("edit", cols, vals, span).map(Self::Edit))
.or_else(|_| extract_value("until", cols, vals, span).map(Self::Until)) .or_else(|_| extract_value("until", cols, vals, span).map(Self::Until))
.map_err(|_| ShellError::MissingConfigValue("send, edit or until".to_string(), *span)) .map_err(|_| ShellError::MissingConfigValue("send, edit or until".to_string(), span))
} }
} }
fn parse_event(value: &Value, config: &Config) -> Result<Option<ReedlineEvent>, ShellError> { fn parse_event(value: &Value, config: &Config) -> Result<Option<ReedlineEvent>, ShellError> {
match value { match value {
Value::Record { cols, vals, span } => { Value::Record { cols, vals, span } => {
match EventType::try_from_columns(cols, vals, span)? { match EventType::try_from_columns(cols, vals, *span)? {
EventType::Send(value) => event_from_record( EventType::Send(value) => event_from_record(
value.into_string("", config).to_lowercase().as_str(), value.into_string("", config).to_lowercase().as_str(),
cols, cols,
vals, vals,
config, config,
span, *span,
) )
.map(Some), .map(Some),
EventType::Edit(value) => { EventType::Edit(value) => {
@ -747,7 +747,7 @@ fn parse_event(value: &Value, config: &Config) -> Result<Option<ReedlineEvent>,
cols, cols,
vals, vals,
config, config,
span, *span,
)?; )?;
Ok(Some(ReedlineEvent::Edit(vec![edit]))) Ok(Some(ReedlineEvent::Edit(vec![edit])))
} }
@ -810,7 +810,7 @@ fn event_from_record(
cols: &[String], cols: &[String],
vals: &[Value], vals: &[Value],
config: &Config, config: &Config,
span: &Span, span: Span,
) -> Result<ReedlineEvent, ShellError> { ) -> Result<ReedlineEvent, ShellError> {
let event = match name { let event = match name {
"none" => ReedlineEvent::None, "none" => ReedlineEvent::None,
@ -853,7 +853,7 @@ fn event_from_record(
return Err(ShellError::UnsupportedConfigValue( return Err(ShellError::UnsupportedConfigValue(
"Reedline event".to_string(), "Reedline event".to_string(),
v.to_string(), v.to_string(),
*span, span,
)) ))
} }
}; };
@ -866,7 +866,7 @@ fn edit_from_record(
cols: &[String], cols: &[String],
vals: &[Value], vals: &[Value],
config: &Config, config: &Config,
span: &Span, span: Span,
) -> Result<EditCommand, ShellError> { ) -> Result<EditCommand, ShellError> {
let edit = match name { let edit = match name {
"movetostart" => EditCommand::MoveToStart, "movetostart" => EditCommand::MoveToStart,
@ -968,7 +968,7 @@ fn edit_from_record(
return Err(ShellError::UnsupportedConfigValue( return Err(ShellError::UnsupportedConfigValue(
"reedline EditCommand".to_string(), "reedline EditCommand".to_string(),
e.to_string(), e.to_string(),
*span, span,
)) ))
} }
}; };
@ -995,7 +995,7 @@ mod test {
let vals = vec![Value::test_string("Enter")]; let vals = vec![Value::test_string("Enter")];
let span = Span::test_data(); let span = Span::test_data();
let b = EventType::try_from_columns(&cols, &vals, &span).unwrap(); let b = EventType::try_from_columns(&cols, &vals, span).unwrap();
assert!(matches!(b, EventType::Send(_))); assert!(matches!(b, EventType::Send(_)));
let event = Value::Record { let event = Value::Record {
@ -1015,7 +1015,7 @@ mod test {
let vals = vec![Value::test_string("Clear")]; let vals = vec![Value::test_string("Clear")];
let span = Span::test_data(); let span = Span::test_data();
let b = EventType::try_from_columns(&cols, &vals, &span).unwrap(); let b = EventType::try_from_columns(&cols, &vals, span).unwrap();
assert!(matches!(b, EventType::Edit(_))); assert!(matches!(b, EventType::Edit(_)));
let event = Value::Record { let event = Value::Record {
@ -1041,7 +1041,7 @@ mod test {
]; ];
let span = Span::test_data(); let span = Span::test_data();
let b = EventType::try_from_columns(&cols, &vals, &span).unwrap(); let b = EventType::try_from_columns(&cols, &vals, span).unwrap();
assert!(matches!(b, EventType::Send(_))); assert!(matches!(b, EventType::Send(_)));
let event = Value::Record { let event = Value::Record {
@ -1091,7 +1091,7 @@ mod test {
}]; }];
let span = Span::test_data(); let span = Span::test_data();
let b = EventType::try_from_columns(&cols, &vals, &span).unwrap(); let b = EventType::try_from_columns(&cols, &vals, span).unwrap();
assert!(matches!(b, EventType::Until(_))); assert!(matches!(b, EventType::Until(_)));
let event = Value::Record { let event = Value::Record {
@ -1159,7 +1159,7 @@ mod test {
let vals = vec![Value::test_string("Enter")]; let vals = vec![Value::test_string("Enter")];
let span = Span::test_data(); let span = Span::test_data();
let b = EventType::try_from_columns(&cols, &vals, &span); let b = EventType::try_from_columns(&cols, &vals, span);
assert!(matches!(b, Err(ShellError::MissingConfigValue(_, _)))); assert!(matches!(b, Err(ShellError::MissingConfigValue(_, _))));
} }
} }

View File

@ -59,7 +59,7 @@ impl Highlighter for NuHighlighter {
($shape:expr, $span:expr, $text:expr) => {{ ($shape:expr, $span:expr, $text:expr) => {{
let spans = split_span_by_highlight_positions( let spans = split_span_by_highlight_positions(
line, line,
&$span, $span,
&matching_brackets_pos, &matching_brackets_pos,
global_span_offset, global_span_offset,
); );
@ -143,7 +143,7 @@ impl Highlighter for NuHighlighter {
fn split_span_by_highlight_positions( fn split_span_by_highlight_positions(
line: &str, line: &str,
span: &Span, span: Span,
highlight_positions: &Vec<usize>, highlight_positions: &Vec<usize>,
global_span_offset: usize, global_span_offset: usize,
) -> Vec<(Span, bool)> { ) -> Vec<(Span, bool)> {

View File

@ -105,7 +105,7 @@ fn gather_env_vars(
span: full_span, span: full_span,
} = token } = token
{ {
let contents = engine_state.get_span_contents(&full_span); let contents = engine_state.get_span_contents(full_span);
let (parts, _) = lex(contents, full_span.start, &[], &[b'='], true); let (parts, _) = lex(contents, full_span.start, &[], &[b'='], true);
let name = if let Some(Token { let name = if let Some(Token {

View File

@ -129,13 +129,13 @@ fn operate(
input.map( input.map(
move |v| { move |v| {
if column_paths.is_empty() { if column_paths.is_empty() {
action(&v, fgs_hex, fge_hex, bgs_hex, bge_hex, &head) action(&v, fgs_hex, fge_hex, bgs_hex, bge_hex, head)
} else { } else {
let mut ret = v; let mut ret = v;
for path in &column_paths { for path in &column_paths {
let r = ret.update_cell_path( let r = ret.update_cell_path(
&path.members, &path.members,
Box::new(move |old| action(old, fgs_hex, fge_hex, bgs_hex, bge_hex, &head)), Box::new(move |old| action(old, fgs_hex, fge_hex, bgs_hex, bge_hex, head)),
); );
if let Err(error) = r { if let Err(error) = r {
return Value::Error { return Value::Error {
@ -156,10 +156,11 @@ fn action(
fg_end: Option<Rgb>, fg_end: Option<Rgb>,
bg_start: Option<Rgb>, bg_start: Option<Rgb>,
bg_end: Option<Rgb>, bg_end: Option<Rgb>,
command_span: &Span, command_span: Span,
) -> Value { ) -> Value {
match input { match input {
Value::String { val, span } => { Value::String { val, span } => {
let span = *span;
match (fg_start, fg_end, bg_start, bg_end) { match (fg_start, fg_end, bg_start, bg_end) {
(None, None, None, None) => { (None, None, None, None) => {
// Error - no colors // Error - no colors
@ -167,7 +168,7 @@ fn action(
error: Box::new(ShellError::MissingParameter { error: Box::new(ShellError::MissingParameter {
param_name: param_name:
"please supply foreground and/or background color parameters".into(), "please supply foreground and/or background color parameters".into(),
span: *command_span, span: command_span,
}), }),
} }
} }
@ -176,27 +177,27 @@ fn action(
let bg_start = Rgb::new(0, 0, 0); let bg_start = Rgb::new(0, 0, 0);
let gradient = Gradient::new(bg_start, bg_end); let gradient = Gradient::new(bg_start, bg_end);
let gradient_string = gradient.build(val, TargetGround::Background); let gradient_string = gradient.build(val, TargetGround::Background);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(None, None, Some(bg_start), None) => { (None, None, Some(bg_start), None) => {
// Error - missing bg_end, so assume black // Error - missing bg_end, so assume black
let bg_end = Rgb::new(0, 0, 0); let bg_end = Rgb::new(0, 0, 0);
let gradient = Gradient::new(bg_start, bg_end); let gradient = Gradient::new(bg_start, bg_end);
let gradient_string = gradient.build(val, TargetGround::Background); let gradient_string = gradient.build(val, TargetGround::Background);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(None, None, Some(bg_start), Some(bg_end)) => { (None, None, Some(bg_start), Some(bg_end)) => {
// Background Only // Background Only
let gradient = Gradient::new(bg_start, bg_end); let gradient = Gradient::new(bg_start, bg_end);
let gradient_string = gradient.build(val, TargetGround::Background); let gradient_string = gradient.build(val, TargetGround::Background);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(None, Some(fg_end), None, None) => { (None, Some(fg_end), None, None) => {
// Error - missing fg_start, so assume black // Error - missing fg_start, so assume black
let fg_start = Rgb::new(0, 0, 0); let fg_start = Rgb::new(0, 0, 0);
let gradient = Gradient::new(fg_start, fg_end); let gradient = Gradient::new(fg_start, fg_end);
let gradient_string = gradient.build(val, TargetGround::Foreground); let gradient_string = gradient.build(val, TargetGround::Foreground);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(None, Some(fg_end), None, Some(bg_end)) => { (None, Some(fg_end), None, Some(bg_end)) => {
// missing fg_start and bg_start, so assume black // missing fg_start and bg_start, so assume black
@ -205,7 +206,7 @@ fn action(
let fg_gradient = Gradient::new(fg_start, fg_end); let fg_gradient = Gradient::new(fg_start, fg_end);
let bg_gradient = Gradient::new(bg_start, bg_end); let bg_gradient = Gradient::new(bg_start, bg_end);
let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(None, Some(fg_end), Some(bg_start), None) => { (None, Some(fg_end), Some(bg_start), None) => {
// Error - missing fg_start and bg_end // Error - missing fg_start and bg_end
@ -214,7 +215,7 @@ fn action(
let fg_gradient = Gradient::new(fg_start, fg_end); let fg_gradient = Gradient::new(fg_start, fg_end);
let bg_gradient = Gradient::new(bg_start, bg_end); let bg_gradient = Gradient::new(bg_start, bg_end);
let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(None, Some(fg_end), Some(bg_start), Some(bg_end)) => { (None, Some(fg_end), Some(bg_start), Some(bg_end)) => {
// Error - missing fg_start, so assume black // Error - missing fg_start, so assume black
@ -222,14 +223,14 @@ fn action(
let fg_gradient = Gradient::new(fg_start, fg_end); let fg_gradient = Gradient::new(fg_start, fg_end);
let bg_gradient = Gradient::new(bg_start, bg_end); let bg_gradient = Gradient::new(bg_start, bg_end);
let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(Some(fg_start), None, None, None) => { (Some(fg_start), None, None, None) => {
// Error - missing fg_end, so assume black // Error - missing fg_end, so assume black
let fg_end = Rgb::new(0, 0, 0); let fg_end = Rgb::new(0, 0, 0);
let gradient = Gradient::new(fg_start, fg_end); let gradient = Gradient::new(fg_start, fg_end);
let gradient_string = gradient.build(val, TargetGround::Foreground); let gradient_string = gradient.build(val, TargetGround::Foreground);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(Some(fg_start), None, None, Some(bg_end)) => { (Some(fg_start), None, None, Some(bg_end)) => {
// Error - missing fg_end, bg_start, so assume black // Error - missing fg_end, bg_start, so assume black
@ -238,7 +239,7 @@ fn action(
let fg_gradient = Gradient::new(fg_start, fg_end); let fg_gradient = Gradient::new(fg_start, fg_end);
let bg_gradient = Gradient::new(bg_start, bg_end); let bg_gradient = Gradient::new(bg_start, bg_end);
let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(Some(fg_start), None, Some(bg_start), None) => { (Some(fg_start), None, Some(bg_start), None) => {
// Error - missing fg_end, bg_end, so assume black // Error - missing fg_end, bg_end, so assume black
@ -247,7 +248,7 @@ fn action(
let fg_gradient = Gradient::new(fg_start, fg_end); let fg_gradient = Gradient::new(fg_start, fg_end);
let bg_gradient = Gradient::new(bg_start, bg_end); let bg_gradient = Gradient::new(bg_start, bg_end);
let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(Some(fg_start), None, Some(bg_start), Some(bg_end)) => { (Some(fg_start), None, Some(bg_start), Some(bg_end)) => {
// Error - missing fg_end, so assume black // Error - missing fg_end, so assume black
@ -255,13 +256,13 @@ fn action(
let fg_gradient = Gradient::new(fg_start, fg_end); let fg_gradient = Gradient::new(fg_start, fg_end);
let bg_gradient = Gradient::new(bg_start, bg_end); let bg_gradient = Gradient::new(bg_start, bg_end);
let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(Some(fg_start), Some(fg_end), None, None) => { (Some(fg_start), Some(fg_end), None, None) => {
// Foreground Only // Foreground Only
let gradient = Gradient::new(fg_start, fg_end); let gradient = Gradient::new(fg_start, fg_end);
let gradient_string = gradient.build(val, TargetGround::Foreground); let gradient_string = gradient.build(val, TargetGround::Foreground);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(Some(fg_start), Some(fg_end), None, Some(bg_end)) => { (Some(fg_start), Some(fg_end), None, Some(bg_end)) => {
// Error - missing bg_start, so assume black // Error - missing bg_start, so assume black
@ -269,7 +270,7 @@ fn action(
let fg_gradient = Gradient::new(fg_start, fg_end); let fg_gradient = Gradient::new(fg_start, fg_end);
let bg_gradient = Gradient::new(bg_start, bg_end); let bg_gradient = Gradient::new(bg_start, bg_end);
let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(Some(fg_start), Some(fg_end), Some(bg_start), None) => { (Some(fg_start), Some(fg_end), Some(bg_start), None) => {
// Error - missing bg_end, so assume black // Error - missing bg_end, so assume black
@ -277,14 +278,14 @@ fn action(
let fg_gradient = Gradient::new(fg_start, fg_end); let fg_gradient = Gradient::new(fg_start, fg_end);
let bg_gradient = Gradient::new(bg_start, bg_end); let bg_gradient = Gradient::new(bg_start, bg_end);
let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
(Some(fg_start), Some(fg_end), Some(bg_start), Some(bg_end)) => { (Some(fg_start), Some(fg_end), Some(bg_start), Some(bg_end)) => {
// Foreground and Background Gradient // Foreground and Background Gradient
let fg_gradient = Gradient::new(fg_start, fg_end); let fg_gradient = Gradient::new(fg_start, fg_end);
let bg_gradient = Gradient::new(bg_start, bg_end); let bg_gradient = Gradient::new(bg_start, bg_end);
let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient); let gradient_string = build_all_gradient_text(val, fg_gradient, bg_gradient);
Value::string(gradient_string, *span) Value::string(gradient_string, span)
} }
} }
} }
@ -294,7 +295,7 @@ fn action(
Value::Error { Value::Error {
error: Box::new(ShellError::TypeMismatch { error: Box::new(ShellError::TypeMismatch {
err_message: got, err_message: got,
span: other.span().unwrap_or(*command_span), span: other.span().unwrap_or(command_span),
}), }),
} }
} }
@ -326,7 +327,7 @@ mod tests {
Some(fg_end), Some(fg_end),
None, None,
None, None,
&Span::test_data(), Span::test_data(),
); );
assert_eq!(actual, expected); assert_eq!(actual, expected);
} }

View File

@ -98,12 +98,12 @@ fn operate(
if column_paths.is_empty() { if column_paths.is_empty() {
input.map( input.map(
move |v| process_value(&v, &text, &command_span), move |v| process_value(&v, &text, command_span),
engine_state.ctrlc.clone(), engine_state.ctrlc.clone(),
) )
} else { } else {
input.map( input.map(
move |v| process_each_path(v, &column_paths, &text, &command_span), move |v| process_each_path(v, &column_paths, &text, command_span),
engine_state.ctrlc.clone(), engine_state.ctrlc.clone(),
) )
} }
@ -113,7 +113,7 @@ fn process_each_path(
mut value: Value, mut value: Value,
column_paths: &Vec<CellPath>, column_paths: &Vec<CellPath>,
text: &Option<String>, text: &Option<String>,
command_span: &Span, command_span: Span,
) -> Value { ) -> Value {
for path in column_paths { for path in column_paths {
let ret = value.update_cell_path( let ret = value.update_cell_path(
@ -129,7 +129,7 @@ fn process_each_path(
value value
} }
fn process_value(value: &Value, text: &Option<String>, command_span: &Span) -> Value { fn process_value(value: &Value, text: &Option<String>, command_span: Span) -> Value {
match value { match value {
Value::String { val, span } => { Value::String { val, span } => {
let text = text.as_deref().unwrap_or(val.as_str()); let text = text.as_deref().unwrap_or(val.as_str());
@ -142,7 +142,7 @@ fn process_value(value: &Value, text: &Option<String>, command_span: &Span) -> V
Value::Error { Value::Error {
error: Box::new(ShellError::TypeMismatch { error: Box::new(ShellError::TypeMismatch {
err_message: got, err_message: got,
span: other.span().unwrap_or(*command_span), span: other.span().unwrap_or(command_span),
}), }),
} }
} }

View File

@ -71,7 +71,7 @@ This command is a parser keyword. For details, check:
// See if the module is a file // See if the module is a file
let module_arg_str = String::from_utf8_lossy( let module_arg_str = String::from_utf8_lossy(
engine_state.get_span_contents(&import_pattern.head.span), engine_state.get_span_contents(import_pattern.head.span),
); );
let maybe_file_path = find_in_dirs_env( let maybe_file_path = find_in_dirs_env(

View File

@ -70,10 +70,10 @@ pub fn get_pipeline_elements(
while i < pipeline.elements.len() { while i < pipeline.elements.len() {
let pipeline_element = &pipeline.elements[i]; let pipeline_element = &pipeline.elements[i];
let pipeline_expression = pipeline_element.expression().clone(); let pipeline_expression = pipeline_element.expression().clone();
let pipeline_span = &pipeline_element.span(); let pipeline_span = pipeline_element.span();
let element_str = let element_str =
String::from_utf8_lossy(engine_state.get_span_contents(pipeline_span)); String::from_utf8_lossy(engine_state.get_span_contents(pipeline_span));
let value = Value::string(element_str.to_string(), *pipeline_span); let value = Value::string(element_str.to_string(), pipeline_span);
let expr = pipeline_expression.expr.clone(); let expr = pipeline_expression.expr.clone();
let (command_name, command_args_value) = if let Expr::Call(call) = expr { let (command_name, command_args_value) = if let Expr::Call(call) = expr {
let command = engine_state.get_decl(call.decl_id); let command = engine_state.get_decl(call.decl_id);

View File

@ -41,7 +41,7 @@ impl Command for ViewSource {
let block = engine_state.get_block(block_id); let block = engine_state.get_block(block_id);
if let Some(span) = block.span { if let Some(span) = block.span {
let contents = engine_state.get_span_contents(&span); let contents = engine_state.get_span_contents(span);
Ok(Value::string(String::from_utf8_lossy(contents), call.head) Ok(Value::string(String::from_utf8_lossy(contents), call.head)
.into_pipeline_data()) .into_pipeline_data())
} else { } else {
@ -61,7 +61,7 @@ impl Command for ViewSource {
if let Some(block_id) = decl.get_block_id() { if let Some(block_id) = decl.get_block_id() {
let block = engine_state.get_block(block_id); let block = engine_state.get_block(block_id);
if let Some(block_span) = block.span { if let Some(block_span) = block.span {
let contents = engine_state.get_span_contents(&block_span); let contents = engine_state.get_span_contents(block_span);
// name of function // name of function
let mut final_contents = format!("def {val} [ "); let mut final_contents = format!("def {val} [ ");
for n in vec_of_required { for n in vec_of_required {
@ -117,7 +117,7 @@ impl Command for ViewSource {
// arg is a module // arg is a module
let module = engine_state.get_module(module_id); let module = engine_state.get_module(module_id);
if let Some(module_span) = module.span { if let Some(module_span) = module.span {
let contents = engine_state.get_span_contents(&module_span); let contents = engine_state.get_span_contents(module_span);
Ok(Value::string(String::from_utf8_lossy(contents), call.head) Ok(Value::string(String::from_utf8_lossy(contents), call.head)
.into_pipeline_data()) .into_pipeline_data())
} else { } else {

View File

@ -42,7 +42,7 @@ impl Command for ViewSpan {
if start_span.item < end_span.item { if start_span.item < end_span.item {
let bin_contents = let bin_contents =
engine_state.get_span_contents(&Span::new(start_span.item, end_span.item)); engine_state.get_span_contents(Span::new(start_span.item, end_span.item));
Ok( Ok(
Value::string(String::from_utf8_lossy(bin_contents), call.head) Value::string(String::from_utf8_lossy(bin_contents), call.head)
.into_pipeline_data(), .into_pipeline_data(),

View File

@ -295,7 +295,7 @@ fn highlight_terms_in_record_with_search_columns(
search_cols: &Vec<String>, search_cols: &Vec<String>,
cols: &[String], cols: &[String],
vals: &[Value], vals: &[Value],
span: &Span, span: Span,
config: &Config, config: &Config,
terms: &[Value], terms: &[Value],
string_style: Style, string_style: Style,
@ -332,7 +332,7 @@ fn highlight_terms_in_record_with_search_columns(
Value::String { Value::String {
val: highlighted_str, val: highlighted_str,
span: *span, span,
} }
}) })
.map(|v| v.unwrap_or_else(|v| v)); .map(|v| v.unwrap_or_else(|v| v));
@ -340,7 +340,7 @@ fn highlight_terms_in_record_with_search_columns(
Value::Record { Value::Record {
cols: cols.to_vec(), cols: cols.to_vec(),
vals: new_vals.collect(), vals: new_vals.collect(),
span: *span, span,
} }
} }
@ -397,7 +397,7 @@ fn find_with_rest_and_highlight(
&cols_to_search_in_map, &cols_to_search_in_map,
cols, cols,
vals, vals,
span, *span,
&config, &config,
&terms, &terms,
string_style, string_style,
@ -414,7 +414,7 @@ fn find_with_rest_and_highlight(
value, value,
&filter_config, &filter_config,
&lower_terms, &lower_terms,
&span, span,
&cols_to_search_in_filter, &cols_to_search_in_filter,
invert, invert,
) )
@ -429,7 +429,7 @@ fn find_with_rest_and_highlight(
&cols_to_search_in_map, &cols_to_search_in_map,
cols, cols,
vals, vals,
span, *span,
&config, &config,
&terms, &terms,
string_style, string_style,
@ -443,7 +443,7 @@ fn find_with_rest_and_highlight(
value, value,
&filter_config, &filter_config,
&lower_terms, &lower_terms,
&span, span,
&cols_to_search_in_filter, &cols_to_search_in_filter,
invert, invert,
) )
@ -509,7 +509,7 @@ fn value_should_be_printed(
value: &Value, value: &Value,
filter_config: &Config, filter_config: &Config,
lower_terms: &[Value], lower_terms: &[Value],
span: &Span, span: Span,
columns_to_search: &Vec<String>, columns_to_search: &Vec<String>,
invert: bool, invert: bool,
) -> bool { ) -> bool {
@ -556,13 +556,13 @@ fn value_should_be_printed(
match_found match_found
} }
fn term_contains_value(term: &Value, value: &Value, span: &Span) -> bool { fn term_contains_value(term: &Value, value: &Value, span: Span) -> bool {
term.r#in(*span, value, *span) term.r#in(span, value, span)
.map_or(false, |value| value.is_true()) .map_or(false, |value| value.is_true())
} }
fn term_equals_value(term: &Value, value: &Value, span: &Span) -> bool { fn term_equals_value(term: &Value, value: &Value, span: Span) -> bool {
term.eq(*span, value, *span) term.eq(span, value, span)
.map_or(false, |value| value.is_true()) .map_or(false, |value| value.is_true())
} }
@ -572,7 +572,7 @@ fn record_matches_term(
columns_to_search: &Vec<String>, columns_to_search: &Vec<String>,
filter_config: &Config, filter_config: &Config,
term: &Value, term: &Value,
span: &Span, span: Span,
) -> bool { ) -> bool {
let cols_to_search = if columns_to_search.is_empty() { let cols_to_search = if columns_to_search.is_empty() {
cols.to_vec() cols.to_vec()

View File

@ -12,9 +12,9 @@ fn from_value_to_delimited_string(
) -> Result<String, ShellError> { ) -> Result<String, ShellError> {
match value { match value {
Value::Record { cols, vals, span } => { Value::Record { cols, vals, span } => {
record_to_delimited(cols, vals, span, separator, config, head) record_to_delimited(cols, vals, *span, separator, config, head)
} }
Value::List { vals, span } => table_to_delimited(vals, span, separator, config, head), Value::List { vals, span } => table_to_delimited(vals, *span, separator, config, head),
// Propagate errors by explicitly matching them before the final case. // Propagate errors by explicitly matching them before the final case.
Value::Error { error } => Err(*error.clone()), Value::Error { error } => Err(*error.clone()),
v => Err(make_unsupported_input_error(v, head, v.expect_span())), v => Err(make_unsupported_input_error(v, head, v.expect_span())),
@ -24,7 +24,7 @@ fn from_value_to_delimited_string(
fn record_to_delimited( fn record_to_delimited(
cols: &[String], cols: &[String],
vals: &[Value], vals: &[Value],
span: &Span, span: Span,
separator: char, separator: char,
config: &Config, config: &Config,
head: Span, head: Span,
@ -38,7 +38,7 @@ fn record_to_delimited(
for (k, v) in cols.iter().zip(vals.iter()) { for (k, v) in cols.iter().zip(vals.iter()) {
fields.push_back(k.clone()); fields.push_back(k.clone());
values.push_back(to_string_tagged_value(v, config, head, *span)?); values.push_back(to_string_tagged_value(v, config, head, span)?);
} }
wtr.write_record(fields).expect("can not write."); wtr.write_record(fields).expect("can not write.");
@ -49,13 +49,13 @@ fn record_to_delimited(
fn table_to_delimited( fn table_to_delimited(
vals: &Vec<Value>, vals: &Vec<Value>,
span: &Span, span: Span,
separator: char, separator: char,
config: &Config, config: &Config,
head: Span, head: Span,
) -> Result<String, ShellError> { ) -> Result<String, ShellError> {
if let Some(val) = find_non_record(vals) { if let Some(val) = find_non_record(vals) {
return Err(make_unsupported_input_error(val, head, *span)); return Err(make_unsupported_input_error(val, head, span));
} }
let mut wtr = WriterBuilder::new() let mut wtr = WriterBuilder::new()
@ -68,7 +68,7 @@ fn table_to_delimited(
let vals = vals let vals = vals
.iter() .iter()
.map(|ele| { .map(|ele| {
to_string_tagged_value(ele, config, head, *span).unwrap_or_else(|_| String::new()) to_string_tagged_value(ele, config, head, span).unwrap_or_else(|_| String::new())
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
wtr.write_record(vals).expect("can not write"); wtr.write_record(vals).expect("can not write");
@ -80,7 +80,7 @@ fn table_to_delimited(
let mut row = vec![]; let mut row = vec![];
for desc in &merged_descriptors { for desc in &merged_descriptors {
row.push(match l.to_owned().get_data_by_key(desc) { row.push(match l.to_owned().get_data_by_key(desc) {
Some(s) => to_string_tagged_value(&s, config, head, *span)?, Some(s) => to_string_tagged_value(&s, config, head, span)?,
None => String::new(), None => String::new(),
}); });
} }
@ -94,11 +94,11 @@ fn writer_to_string(writer: Writer<Vec<u8>>) -> Result<String, Box<dyn Error>> {
Ok(String::from_utf8(writer.into_inner()?)?) Ok(String::from_utf8(writer.into_inner()?)?)
} }
fn make_conversion_error(type_from: &str, span: &Span) -> ShellError { fn make_conversion_error(type_from: &str, span: Span) -> ShellError {
ShellError::CantConvert { ShellError::CantConvert {
to_type: type_from.to_string(), to_type: type_from.to_string(),
from_type: "string".to_string(), from_type: "string".to_string(),
span: *span, span,
help: None, help: None,
} }
} }

View File

@ -67,12 +67,12 @@ fn helper(engine_state: &EngineState, v: &Value) -> Result<toml::Value, ShellErr
} }
Value::List { vals, .. } => toml::Value::Array(toml_list(engine_state, vals)?), Value::List { vals, .. } => toml::Value::Array(toml_list(engine_state, vals)?),
Value::Block { span, .. } => { Value::Block { span, .. } => {
let code = engine_state.get_span_contents(span); let code = engine_state.get_span_contents(*span);
let code = String::from_utf8_lossy(code).to_string(); let code = String::from_utf8_lossy(code).to_string();
toml::Value::String(code) toml::Value::String(code)
} }
Value::Closure { span, .. } => { Value::Closure { span, .. } => {
let code = engine_state.get_span_contents(span); let code = engine_state.get_span_contents(*span);
let code = String::from_utf8_lossy(code).to_string(); let code = String::from_utf8_lossy(code).to_string();
toml::Value::String(code) toml::Value::String(code)
} }

View File

@ -131,7 +131,7 @@ pub fn help_aliases(
}; };
let alias_expansion = let alias_expansion =
String::from_utf8_lossy(engine_state.get_span_contents(&alias.wrapped_call.span)); String::from_utf8_lossy(engine_state.get_span_contents(alias.wrapped_call.span));
let usage = alias.usage(); let usage = alias.usage();
let extra_usage = alias.extra_usage(); let extra_usage = alias.extra_usage();

View File

@ -50,9 +50,9 @@ impl Command for SubCommand {
} }
} }
pub fn average(values: &[Value], span: Span, head: &Span) -> Result<Value, ShellError> { pub fn average(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let sum = reducer_for(Reduce::Summation); let sum = reducer_for(Reduce::Summation);
let total = &sum(Value::int(0, *head), values.to_vec(), span, *head)?; let total = &sum(Value::int(0, head), values.to_vec(), span, head)?;
match total { match total {
Value::Filesize { val, span } => Ok(Value::Filesize { Value::Filesize { val, span } => Ok(Value::Filesize {
val: val / values.len() as i64, val: val / values.len() as i64,
@ -62,7 +62,7 @@ pub fn average(values: &[Value], span: Span, head: &Span) -> Result<Value, Shell
val: val / values.len() as i64, val: val / values.len() as i64,
span: *span, span: *span,
}), }),
_ => total.div(*head, &Value::int(values.len() as i64, *head), *head), _ => total.div(head, &Value::int(values.len() as i64, head), head),
} }
} }

View File

@ -60,9 +60,9 @@ impl Command for SubCommand {
} }
} }
pub fn maximum(values: &[Value], span: Span, head: &Span) -> Result<Value, ShellError> { pub fn maximum(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let max_func = reducer_for(Reduce::Maximum); let max_func = reducer_for(Reduce::Maximum);
max_func(Value::nothing(*head), values.to_vec(), span, *head) max_func(Value::nothing(head), values.to_vec(), span, head)
} }
#[cfg(test)] #[cfg(test)]

View File

@ -69,7 +69,7 @@ enum Pick {
Median, Median,
} }
pub fn median(values: &[Value], span: Span, head: &Span) -> Result<Value, ShellError> { pub fn median(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let take = if values.len() % 2 == 0 { let take = if values.len() % 2 == 0 {
Pick::MedianAverage Pick::MedianAverage
} else { } else {
@ -87,7 +87,7 @@ pub fn median(values: &[Value], span: Span, head: &Span) -> Result<Value, ShellE
.map(|elem| { .map(|elem| {
if elem[0].partial_cmp(&elem[1]).is_none() { if elem[0].partial_cmp(&elem[1]).is_none() {
return Err(ShellError::OperatorMismatch { return Err(ShellError::OperatorMismatch {
op_span: *head, op_span: head,
lhs_ty: elem[0].get_type().to_string(), lhs_ty: elem[0].get_type().to_string(),
lhs_span: elem[0].span()?, lhs_span: elem[0].span()?,
rhs_ty: elem[1].get_type().to_string(), rhs_ty: elem[1].get_type().to_string(),
@ -110,7 +110,7 @@ pub fn median(values: &[Value], span: Span, head: &Span) -> Result<Value, ShellE
ShellError::UnsupportedInput( ShellError::UnsupportedInput(
"Empty input".to_string(), "Empty input".to_string(),
"value originates from here".into(), "value originates from here".into(),
*head, head,
span, span,
) )
})?; })?;
@ -126,7 +126,7 @@ pub fn median(values: &[Value], span: Span, head: &Span) -> Result<Value, ShellE
ShellError::UnsupportedInput( ShellError::UnsupportedInput(
"Empty input".to_string(), "Empty input".to_string(),
"value originates from here".into(), "value originates from here".into(),
*head, head,
span, span,
) )
})? })?
@ -138,7 +138,7 @@ pub fn median(values: &[Value], span: Span, head: &Span) -> Result<Value, ShellE
ShellError::UnsupportedInput( ShellError::UnsupportedInput(
"Empty input".to_string(), "Empty input".to_string(),
"value originates from here".into(), "value originates from here".into(),
*head, head,
span, span,
) )
})? })?

View File

@ -65,9 +65,9 @@ impl Command for SubCommand {
} }
} }
pub fn minimum(values: &[Value], span: Span, head: &Span) -> Result<Value, ShellError> { pub fn minimum(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let min_func = reducer_for(Reduce::Minimum); let min_func = reducer_for(Reduce::Minimum);
min_func(Value::nothing(*head), values.to_vec(), span, *head) min_func(Value::nothing(head), values.to_vec(), span, head)
} }
#[cfg(test)] #[cfg(test)]

View File

@ -107,13 +107,13 @@ impl Command for SubCommand {
} }
} }
pub fn mode(values: &[Value], _span: Span, head: &Span) -> Result<Value, ShellError> { pub fn mode(values: &[Value], _span: Span, head: Span) -> Result<Value, ShellError> {
if let Some(Err(values)) = values if let Some(Err(values)) = values
.windows(2) .windows(2)
.map(|elem| { .map(|elem| {
if elem[0].partial_cmp(&elem[1]).is_none() { if elem[0].partial_cmp(&elem[1]).is_none() {
return Err(ShellError::OperatorMismatch { return Err(ShellError::OperatorMismatch {
op_span: *head, op_span: head,
lhs_ty: elem[0].get_type().to_string(), lhs_ty: elem[0].get_type().to_string(),
lhs_span: elem[0].span()?, lhs_span: elem[0].span()?,
rhs_ty: elem[1].get_type().to_string(), rhs_ty: elem[1].get_type().to_string(),
@ -146,7 +146,7 @@ pub fn mode(values: &[Value], _span: Span, head: &Span) -> Result<Value, ShellEr
other => Err(ShellError::UnsupportedInput( other => Err(ShellError::UnsupportedInput(
"Unable to give a result with this input".to_string(), "Unable to give a result with this input".to_string(),
"value originates from here".into(), "value originates from here".into(),
*head, head,
other.expect_span(), other.expect_span(),
)), )),
}) })
@ -165,10 +165,10 @@ pub fn mode(values: &[Value], _span: Span, head: &Span) -> Result<Value, ShellEr
Ordering::Less => { Ordering::Less => {
max_freq = *frequency; max_freq = *frequency;
modes.clear(); modes.clear();
modes.push(recreate_value(value, *head)); modes.push(recreate_value(value, head));
} }
Ordering::Equal => { Ordering::Equal => {
modes.push(recreate_value(value, *head)); modes.push(recreate_value(value, head));
} }
Ordering::Greater => (), Ordering::Greater => (),
} }
@ -177,7 +177,7 @@ pub fn mode(values: &[Value], _span: Span, head: &Span) -> Result<Value, ShellEr
modes.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal)); modes.sort_by(|a, b| a.partial_cmp(b).unwrap_or(Ordering::Equal));
Ok(Value::List { Ok(Value::List {
vals: modes, vals: modes,
span: *head, span: head,
}) })
} }

View File

@ -46,9 +46,9 @@ impl Command for SubCommand {
} }
/// Calculate product of given values /// Calculate product of given values
pub fn product(values: &[Value], span: Span, head: &Span) -> Result<Value, ShellError> { pub fn product(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let product_func = reducer_for(Reduce::Product); let product_func = reducer_for(Reduce::Product);
product_func(Value::nothing(*head), values.to_vec(), span, *head) product_func(Value::nothing(head), values.to_vec(), span, head)
} }
#[cfg(test)] #[cfg(test)]

View File

@ -65,8 +65,8 @@ impl Command for SubCommand {
} }
} }
pub fn compute_stddev(sample: bool) -> impl Fn(&[Value], Span, &Span) -> Result<Value, ShellError> { pub fn compute_stddev(sample: bool) -> impl Fn(&[Value], Span, Span) -> Result<Value, ShellError> {
move |values: &[Value], span: Span, head: &Span| { move |values: &[Value], span: Span, head: Span| {
let variance = variance(sample)(values, span, head); let variance = variance(sample)(values, span, head);
match variance { match variance {
Ok(Value::Float { val, span }) => Ok(Value::Float { Ok(Value::Float { val, span }) => Ok(Value::Float {

View File

@ -59,9 +59,9 @@ impl Command for SubCommand {
} }
} }
pub fn summation(values: &[Value], span: Span, head: &Span) -> Result<Value, ShellError> { pub fn summation(values: &[Value], span: Span, head: Span) -> Result<Value, ShellError> {
let sum_func = reducer_for(Reduce::Summation); let sum_func = reducer_for(Reduce::Summation);
sum_func(Value::nothing(*head), values.to_vec(), span, *head) sum_func(Value::nothing(head), values.to_vec(), span, head)
} }
#[cfg(test)] #[cfg(test)]

View File

@ -5,7 +5,7 @@ use nu_protocol::{IntoPipelineData, PipelineData, ShellError, Span, Spanned, Val
pub fn run_with_function( pub fn run_with_function(
call: &Call, call: &Call,
input: PipelineData, input: PipelineData,
mf: impl Fn(&[Value], Span, &Span) -> Result<Value, ShellError>, mf: impl Fn(&[Value], Span, Span) -> Result<Value, ShellError>,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
let name = call.head; let name = call.head;
let res = calculate(input, name, mf); let res = calculate(input, name, mf);
@ -19,7 +19,7 @@ fn helper_for_tables(
values: &[Value], values: &[Value],
val_span: Span, val_span: Span,
name: Span, name: Span,
mf: impl Fn(&[Value], Span, &Span) -> Result<Value, ShellError>, mf: impl Fn(&[Value], Span, Span) -> Result<Value, ShellError>,
) -> Result<Value, ShellError> { ) -> Result<Value, ShellError> {
// If we are not dealing with Primitives, then perhaps we are dealing with a table // If we are not dealing with Primitives, then perhaps we are dealing with a table
// Create a key for each column name // Create a key for each column name
@ -37,14 +37,14 @@ fn helper_for_tables(
Value::Error { error } => return Err(*error.clone()), Value::Error { error } => return Err(*error.clone()),
_ => { _ => {
//Turns out we are not dealing with a table //Turns out we are not dealing with a table
return mf(values, val.expect_span(), &name); return mf(values, val.expect_span(), name);
} }
} }
} }
// The mathematical function operates over the columns of the table // The mathematical function operates over the columns of the table
let mut column_totals = IndexMap::new(); let mut column_totals = IndexMap::new();
for (col_name, col_vals) in column_values { for (col_name, col_vals) in column_values {
if let Ok(out) = mf(&col_vals, val_span, &name) { if let Ok(out) = mf(&col_vals, val_span, name) {
column_totals.insert(col_name, out); column_totals.insert(col_name, out);
} }
} }
@ -66,7 +66,7 @@ fn helper_for_tables(
pub fn calculate( pub fn calculate(
values: PipelineData, values: PipelineData,
name: Span, name: Span,
mf: impl Fn(&[Value], Span, &Span) -> Result<Value, ShellError>, mf: impl Fn(&[Value], Span, Span) -> Result<Value, ShellError>,
) -> Result<Value, ShellError> { ) -> Result<Value, ShellError> {
// TODO implement spans for ListStream, thus negating the need for unwrap_or(). // TODO implement spans for ListStream, thus negating the need for unwrap_or().
let span = values.span().unwrap_or(name); let span = values.span().unwrap_or(name);
@ -81,13 +81,11 @@ pub fn calculate(
name, name,
mf, mf,
), ),
_ => mf(vals, span, &name), _ => mf(vals, span, name),
}, },
PipelineData::Value(Value::Record { vals, cols, span }, ..) => { PipelineData::Value(Value::Record { vals, cols, span }, ..) => {
let new_vals: Result<Vec<Value>, ShellError> = vals let new_vals: Result<Vec<Value>, ShellError> =
.into_iter() vals.into_iter().map(|val| mf(&[val], span, name)).collect();
.map(|val| mf(&[val], span, &name))
.collect();
match new_vals { match new_vals {
Ok(vec) => Ok(Value::Record { Ok(vec) => Ok(Value::Record {
cols, cols,
@ -100,12 +98,12 @@ pub fn calculate(
PipelineData::Value(Value::Range { val, span, .. }, ..) => { PipelineData::Value(Value::Range { val, span, .. }, ..) => {
let new_vals: Result<Vec<Value>, ShellError> = val let new_vals: Result<Vec<Value>, ShellError> = val
.into_range_iter(None)? .into_range_iter(None)?
.map(|val| mf(&[val], span, &name)) .map(|val| mf(&[val], span, name))
.collect(); .collect();
mf(&new_vals?, span, &name) mf(&new_vals?, span, name)
} }
PipelineData::Value(val, ..) => mf(&[val], span, &name), PipelineData::Value(val, ..) => mf(&[val], span, name),
PipelineData::Empty { .. } => Err(ShellError::PipelineEmpty { dst_span: name }), PipelineData::Empty { .. } => Err(ShellError::PipelineEmpty { dst_span: name }),
val => Err(ShellError::UnsupportedInput( val => Err(ShellError::UnsupportedInput(
"Only integers, floats, lists, records or ranges are supported".into(), "Only integers, floats, lists, records or ranges are supported".into(),

View File

@ -57,10 +57,10 @@ impl Command for SubCommand {
} }
} }
fn sum_of_squares(values: &[Value], span: &Span) -> Result<Value, ShellError> { fn sum_of_squares(values: &[Value], span: Span) -> Result<Value, ShellError> {
let n = Value::int(values.len() as i64, *span); let n = Value::int(values.len() as i64, span);
let mut sum_x = Value::int(0, *span); let mut sum_x = Value::int(0, span);
let mut sum_x2 = Value::int(0, *span); let mut sum_x2 = Value::int(0, span);
for value in values { for value in values {
let v = match &value { let v = match &value {
Value::Int { .. } | Value::Float { .. } => Ok(value), Value::Int { .. } | Value::Float { .. } => Ok(value),
@ -69,36 +69,36 @@ fn sum_of_squares(values: &[Value], span: &Span) -> Result<Value, ShellError> {
"Attempted to compute the sum of squares of a non-integer, non-float value" "Attempted to compute the sum of squares of a non-integer, non-float value"
.to_string(), .to_string(),
"value originates from here".into(), "value originates from here".into(),
*span, span,
value.expect_span(), value.expect_span(),
)), )),
}?; }?;
let v_squared = &v.mul(*span, v, *span)?; let v_squared = &v.mul(span, v, span)?;
sum_x2 = sum_x2.add(*span, v_squared, *span)?; sum_x2 = sum_x2.add(span, v_squared, span)?;
sum_x = sum_x.add(*span, v, *span)?; sum_x = sum_x.add(span, v, span)?;
} }
let sum_x_squared = sum_x.mul(*span, &sum_x, *span)?; let sum_x_squared = sum_x.mul(span, &sum_x, span)?;
let sum_x_squared_div_n = sum_x_squared.div(*span, &n, *span)?; let sum_x_squared_div_n = sum_x_squared.div(span, &n, span)?;
let ss = sum_x2.sub(*span, &sum_x_squared_div_n, *span)?; let ss = sum_x2.sub(span, &sum_x_squared_div_n, span)?;
Ok(ss) Ok(ss)
} }
pub fn compute_variance( pub fn compute_variance(
sample: bool, sample: bool,
) -> impl Fn(&[Value], Span, &Span) -> Result<Value, ShellError> { ) -> impl Fn(&[Value], Span, Span) -> Result<Value, ShellError> {
move |values: &[Value], span: Span, head: &Span| { move |values: &[Value], span: Span, head: Span| {
let n = if sample { let n = if sample {
values.len() - 1 values.len() - 1
} else { } else {
values.len() values.len()
}; };
// sum_of_squares() needs the span of the original value, not the call head. // sum_of_squares() needs the span of the original value, not the call head.
let ss = sum_of_squares(values, &span)?; let ss = sum_of_squares(values, span)?;
let n = Value::int(n as i64, *head); let n = Value::int(n as i64, head);
ss.div(*head, &n, *head) ss.div(head, &n, head)
} }
} }

View File

@ -204,10 +204,10 @@ impl From<DirInfo> for Value {
}); });
cols.push("directories".into()); cols.push("directories".into());
vals.push(value_from_vec(d.dirs, &d.tag)); vals.push(value_from_vec(d.dirs, d.tag));
cols.push("files".into()); cols.push("files".into());
vals.push(value_from_vec(d.files, &d.tag)); vals.push(value_from_vec(d.files, d.tag));
// if !d.errors.is_empty() { // if !d.errors.is_empty() {
// let v = d // let v = d
@ -271,17 +271,17 @@ impl From<FileInfo> for Value {
} }
} }
fn value_from_vec<V>(vec: Vec<V>, tag: &Span) -> Value fn value_from_vec<V>(vec: Vec<V>, tag: Span) -> Value
where where
V: Into<Value>, V: Into<Value>,
{ {
if vec.is_empty() { if vec.is_empty() {
Value::nothing(*tag) Value::nothing(tag)
} else { } else {
let values = vec.into_iter().map(Into::into).collect::<Vec<Value>>(); let values = vec.into_iter().map(Into::into).collect::<Vec<Value>>();
Value::List { Value::List {
vals: values, vals: values,
span: *tag, span: tag,
} }
} }
} }

View File

@ -262,7 +262,7 @@ impl Command for Char {
.positional_nth(i) .positional_nth(i)
.expect("Unexpected missing argument") .expect("Unexpected missing argument")
.span; .span;
multi_byte.push(integer_to_unicode_char(arg, &span)?) multi_byte.push(integer_to_unicode_char(arg, span)?)
} }
Ok(Value::string(multi_byte, call_span).into_pipeline_data()) Ok(Value::string(multi_byte, call_span).into_pipeline_data())
} else if call.has_flag("unicode") { } else if call.has_flag("unicode") {
@ -279,7 +279,7 @@ impl Command for Char {
.positional_nth(i) .positional_nth(i)
.expect("Unexpected missing argument") .expect("Unexpected missing argument")
.span; .span;
multi_byte.push(string_to_unicode_char(arg, &span)?) multi_byte.push(string_to_unicode_char(arg, span)?)
} }
Ok(Value::string(multi_byte, call_span).into_pipeline_data()) Ok(Value::string(multi_byte, call_span).into_pipeline_data())
} else { } else {
@ -306,7 +306,7 @@ impl Command for Char {
} }
} }
fn integer_to_unicode_char(value: i64, t: &Span) -> Result<char, ShellError> { fn integer_to_unicode_char(value: i64, t: Span) -> Result<char, ShellError> {
let decoded_char = value.try_into().ok().and_then(std::char::from_u32); let decoded_char = value.try_into().ok().and_then(std::char::from_u32);
if let Some(ch) = decoded_char { if let Some(ch) = decoded_char {
@ -314,12 +314,12 @@ fn integer_to_unicode_char(value: i64, t: &Span) -> Result<char, ShellError> {
} else { } else {
Err(ShellError::TypeMismatch { Err(ShellError::TypeMismatch {
err_message: "not a valid Unicode codepoint".into(), err_message: "not a valid Unicode codepoint".into(),
span: *t, span: t,
}) })
} }
} }
fn string_to_unicode_char(s: &str, t: &Span) -> Result<char, ShellError> { fn string_to_unicode_char(s: &str, t: Span) -> Result<char, ShellError> {
let decoded_char = u32::from_str_radix(s, 16) let decoded_char = u32::from_str_radix(s, 16)
.ok() .ok()
.and_then(std::char::from_u32); .and_then(std::char::from_u32);
@ -329,7 +329,7 @@ fn string_to_unicode_char(s: &str, t: &Span) -> Result<char, ShellError> {
} else { } else {
Err(ShellError::TypeMismatch { Err(ShellError::TypeMismatch {
err_message: "error decoding Unicode character".into(), err_message: "error decoding Unicode character".into(),
span: *t, span: t,
}) })
} }
} }

View File

@ -329,7 +329,7 @@ pub fn eval_expression(
Expr::ImportPattern(_) => Ok(Value::Nothing { span: expr.span }), Expr::ImportPattern(_) => Ok(Value::Nothing { span: expr.span }),
Expr::Overlay(_) => { Expr::Overlay(_) => {
let name = let name =
String::from_utf8_lossy(engine_state.get_span_contents(&expr.span)).to_string(); String::from_utf8_lossy(engine_state.get_span_contents(expr.span)).to_string();
Ok(Value::String { Ok(Value::String {
val: name, val: name,
@ -1128,7 +1128,7 @@ pub fn eval_block(
{ {
let element_span = pipeline.elements[i].span(); let element_span = pipeline.elements[i].span();
let element_str = String::from_utf8_lossy( let element_str = String::from_utf8_lossy(
engine_state.get_span_contents(&pipeline.elements[i].span()), engine_state.get_span_contents(pipeline.elements[i].span()),
) )
.to_string(); .to_string();

View File

@ -548,8 +548,7 @@ impl<'e, 's> ScopeData<'e, 's> {
Value::String { val: key, span }, Value::String { val: key, span },
Value::String { Value::String {
val: String::from_utf8_lossy( val: String::from_utf8_lossy(
self.engine_state self.engine_state.get_span_contents(alias.wrapped_call.span),
.get_span_contents(&alias.wrapped_call.span),
) )
.to_string(), .to_string(),
span, span,

View File

@ -267,9 +267,9 @@ impl Value {
if let Ok(b) = &$vals[$index].as_bool() { if let Ok(b) = &$vals[$index].as_bool() {
config.$setting = *b; config.$setting = *b;
} else { } else {
invalid!(Some(*$span), "should be a bool"); invalid!(Some($span), "should be a bool");
// Reconstruct // Reconstruct
$vals[$index] = Value::bool(config.$setting, *$span); $vals[$index] = Value::bool(config.$setting, $span);
} }
}; };
} }
@ -278,9 +278,9 @@ impl Value {
if let Ok(b) = &$vals[$index].as_int() { if let Ok(b) = &$vals[$index].as_int() {
config.$setting = *b; config.$setting = *b;
} else { } else {
invalid!(Some(*$span), "should be an int"); invalid!(Some($span), "should be an int");
// Reconstruct // Reconstruct
$vals[$index] = Value::int(config.$setting, *$span); $vals[$index] = Value::int(config.$setting, $span);
} }
}; };
} }
@ -311,6 +311,7 @@ impl Value {
// the current use_ls_colors config setting is converted to a Value::Boolean and inserted in the // the current use_ls_colors config setting is converted to a Value::Boolean and inserted in the
// record in place of the 2. // record in place of the 2.
if let Value::Record { cols, vals, span } = self { if let Value::Record { cols, vals, span } = self {
let span = *span;
// Because this whole algorithm removes while iterating, this must iterate in reverse. // Because this whole algorithm removes while iterating, this must iterate in reverse.
for index in (0..cols.len()).rev() { for index in (0..cols.len()).rev() {
let value = &vals[index]; let value = &vals[index];
@ -319,6 +320,7 @@ impl Value {
// Grouped options // Grouped options
"ls" => { "ls" => {
if let Value::Record { cols, vals, span } = &mut vals[index] { if let Value::Record { cols, vals, span } = &mut vals[index] {
let span = *span;
for index in (0..cols.len()).rev() { for index in (0..cols.len()).rev() {
let value = &vals[index]; let value = &vals[index];
let key2 = cols[index].as_str(); let key2 = cols[index].as_str();
@ -350,10 +352,10 @@ impl Value {
vals[index] = Value::record( vals[index] = Value::record(
vec!["use_ls_colors".into(), "clickable_links".into()], vec!["use_ls_colors".into(), "clickable_links".into()],
vec![ vec![
Value::bool(config.use_ls_colors, *span), Value::bool(config.use_ls_colors, span),
Value::bool(config.show_clickable_links_in_ls, *span), Value::bool(config.show_clickable_links_in_ls, span),
], ],
*span, span,
); );
} }
} }
@ -364,7 +366,7 @@ impl Value {
let key2 = cols[index].as_str(); let key2 = cols[index].as_str();
match key2 { match key2 {
"abbreviations" => { "abbreviations" => {
try_bool!(cols, vals, index, span, cd_with_abbreviations) try_bool!(cols, vals, index, *span, cd_with_abbreviations)
} }
x => { x => {
invalid_key!( invalid_key!(
@ -383,10 +385,10 @@ impl Value {
vals[index] = Value::record( vals[index] = Value::record(
vec!["use_ls_colors".into(), "clickable_links".into()], vec!["use_ls_colors".into(), "clickable_links".into()],
vec![ vec![
Value::bool(config.use_ls_colors, *span), Value::bool(config.use_ls_colors, span),
Value::bool(config.show_clickable_links_in_ls, *span), Value::bool(config.show_clickable_links_in_ls, span),
], ],
*span, span,
); );
} }
} }
@ -397,7 +399,7 @@ impl Value {
let key2 = cols[index].as_str(); let key2 = cols[index].as_str();
match key2 { match key2 {
"always_trash" => { "always_trash" => {
try_bool!(cols, vals, index, span, rm_always_trash) try_bool!(cols, vals, index, *span, rm_always_trash)
} }
x => { x => {
invalid_key!( invalid_key!(
@ -415,8 +417,8 @@ impl Value {
// Reconstruct // Reconstruct
vals[index] = Value::record( vals[index] = Value::record(
vec!["always_trash".into()], vec!["always_trash".into()],
vec![Value::bool(config.rm_always_trash, *span)], vec![Value::bool(config.rm_always_trash, span)],
*span, span,
); );
} }
} }
@ -428,11 +430,12 @@ impl Value {
HistoryFileFormat::Sqlite => "sqlite", HistoryFileFormat::Sqlite => "sqlite",
HistoryFileFormat::PlainText => "plaintext", HistoryFileFormat::PlainText => "plaintext",
}, },
*$span, $span,
) )
}; };
} }
if let Value::Record { cols, vals, span } = &mut vals[index] { if let Value::Record { cols, vals, span } = &mut vals[index] {
let span = *span;
for index in (0..cols.len()).rev() { for index in (0..cols.len()).rev() {
let value = &vals[index]; let value = &vals[index];
let key2 = cols[index].as_str(); let key2 = cols[index].as_str();
@ -459,7 +462,7 @@ impl Value {
HistoryFileFormat::PlainText HistoryFileFormat::PlainText
} }
_ => { _ => {
invalid!(Some(*span), invalid!(Some(span),
"unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'sqlite' or 'plaintext'" "unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'sqlite' or 'plaintext'"
); );
// Reconstruct // Reconstruct
@ -468,7 +471,7 @@ impl Value {
} }
}; };
} else { } else {
invalid!(Some(*span), "should be a string"); invalid!(Some(span), "should be a string");
// Reconstruct // Reconstruct
vals[index] = reconstruct_history_file_format!(span); vals[index] = reconstruct_history_file_format!(span);
} }
@ -495,12 +498,12 @@ impl Value {
"isolation".into(), "isolation".into(),
], ],
vec![ vec![
Value::bool(config.sync_history_on_enter, *span), Value::bool(config.sync_history_on_enter, span),
Value::int(config.max_history_size, *span), Value::int(config.max_history_size, span),
reconstruct_history_file_format!(span), reconstruct_history_file_format!(span),
Value::bool(config.history_isolation, *span), Value::bool(config.history_isolation, span),
], ],
*span, span,
); );
} }
} }
@ -510,10 +513,10 @@ impl Value {
if let Some(block) = config.external_completer { if let Some(block) = config.external_completer {
Value::Block { Value::Block {
val: block, val: block,
span: *$span, span: $span,
} }
} else { } else {
Value::Nothing { span: *$span } Value::Nothing { span: $span }
} }
}; };
} }
@ -522,15 +525,16 @@ impl Value {
Value::record( Value::record(
vec!["max_results".into(), "completer".into(), "enable".into()], vec!["max_results".into(), "completer".into(), "enable".into()],
vec![ vec![
Value::int(config.max_external_completion_results, *$span), Value::int(config.max_external_completion_results, $span),
reconstruct_external_completer!($span), reconstruct_external_completer!($span),
Value::bool(config.enable_external_completion, *$span), Value::bool(config.enable_external_completion, $span),
], ],
*$span, $span,
) )
}; };
} }
if let Value::Record { cols, vals, span } = &mut vals[index] { if let Value::Record { cols, vals, span } = &mut vals[index] {
let span = *span;
for index in (0..cols.len()).rev() { for index in (0..cols.len()).rev() {
let value = &vals[index]; let value = &vals[index];
let key2 = cols[index].as_str(); let key2 = cols[index].as_str();
@ -550,22 +554,22 @@ impl Value {
config.completion_algorithm = val_str config.completion_algorithm = val_str
} }
_ => { _ => {
invalid!( Some(*span), invalid!( Some(span),
"unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'prefix' or 'fuzzy'" "unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'prefix' or 'fuzzy'"
); );
// Reconstruct // Reconstruct
vals[index] = Value::string( vals[index] = Value::string(
config.completion_algorithm.clone(), config.completion_algorithm.clone(),
*span, span,
); );
} }
}; };
} else { } else {
invalid!(Some(*span), "should be a string"); invalid!(Some(span), "should be a string");
// Reconstruct // Reconstruct
vals[index] = Value::string( vals[index] = Value::string(
config.completion_algorithm.clone(), config.completion_algorithm.clone(),
*span, span,
); );
} }
} }
@ -581,6 +585,7 @@ impl Value {
"external" => { "external" => {
if let Value::Record { cols, vals, span } = &mut vals[index] if let Value::Record { cols, vals, span } = &mut vals[index]
{ {
let span = *span;
for index in (0..cols.len()).rev() { for index in (0..cols.len()).rev() {
let value = &vals[index]; let value = &vals[index];
let key3 = cols[index].as_str(); let key3 = cols[index].as_str();
@ -602,7 +607,7 @@ impl Value {
Value::Nothing { .. } => {} Value::Nothing { .. } => {}
_ => { _ => {
invalid!( invalid!(
Some(*span), Some(span),
"should be a block or null" "should be a block or null"
); );
// Reconstruct // Reconstruct
@ -634,7 +639,7 @@ impl Value {
} }
} }
} else { } else {
invalid!(Some(*span), "should be a record"); invalid!(Some(span), "should be a record");
// Reconstruct // Reconstruct
vals[index] = reconstruct_external!(span); vals[index] = reconstruct_external!(span);
} }
@ -662,13 +667,13 @@ impl Value {
"external".into(), "external".into(),
], ],
vec![ vec![
Value::bool(config.quick_completions, *span), Value::bool(config.quick_completions, span),
Value::bool(config.partial_completions, *span), Value::bool(config.partial_completions, span),
Value::string(config.completion_algorithm.clone(), *span), Value::string(config.completion_algorithm.clone(), span),
Value::bool(config.case_sensitive_completions, *span), Value::bool(config.case_sensitive_completions, span),
reconstruct_external!(span), reconstruct_external!(span),
], ],
*span, span,
); );
} }
} }
@ -684,11 +689,12 @@ impl Value {
NuCursorShape::BlinkBlock => "blink_block", NuCursorShape::BlinkBlock => "blink_block",
NuCursorShape::BlinkUnderScore => "blink_underscore", NuCursorShape::BlinkUnderScore => "blink_underscore",
}, },
*$span, $span,
) )
}; };
} }
if let Value::Record { cols, vals, span } = &mut vals[index] { if let Value::Record { cols, vals, span } = &mut vals[index] {
let span = *span;
for index in (0..cols.len()).rev() { for index in (0..cols.len()).rev() {
let value = &vals[index]; let value = &vals[index];
let key2 = cols[index].as_str(); let key2 = cols[index].as_str();
@ -722,7 +728,7 @@ impl Value {
NuCursorShape::BlinkUnderScore; NuCursorShape::BlinkUnderScore;
} }
_ => { _ => {
invalid!(Some(*span), invalid!(Some(span),
"unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'line', 'block', 'underscore', 'blink_line', 'blink_block', or 'blink_underscore'" "unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'line', 'block', 'underscore', 'blink_line', 'blink_block', or 'blink_underscore'"
); );
// Reconstruct // Reconstruct
@ -733,7 +739,7 @@ impl Value {
} }
}; };
} else { } else {
invalid!(Some(*span), "should be a string"); invalid!(Some(span), "should be a string");
// Reconstruct // Reconstruct
vals[index] = reconstruct_cursor_shape!( vals[index] = reconstruct_cursor_shape!(
config.cursor_shape_vi_insert, config.cursor_shape_vi_insert,
@ -770,7 +776,7 @@ impl Value {
NuCursorShape::BlinkUnderScore; NuCursorShape::BlinkUnderScore;
} }
_ => { _ => {
invalid!(Some(*span), invalid!(Some(span),
"unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'line', 'block', 'underscore', 'blink_line', 'blink_block', or 'blink_underscore'" "unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'line', 'block', 'underscore', 'blink_line', 'blink_block', or 'blink_underscore'"
); );
// Reconstruct // Reconstruct
@ -781,7 +787,7 @@ impl Value {
} }
}; };
} else { } else {
invalid!(Some(*span), "should be a string"); invalid!(Some(span), "should be a string");
// Reconstruct // Reconstruct
vals[index] = reconstruct_cursor_shape!( vals[index] = reconstruct_cursor_shape!(
config.cursor_shape_vi_normal, config.cursor_shape_vi_normal,
@ -817,7 +823,7 @@ impl Value {
NuCursorShape::BlinkUnderScore; NuCursorShape::BlinkUnderScore;
} }
_ => { _ => {
invalid!(Some(*span), invalid!(Some(span),
"unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'line', 'block', 'underscore', 'blink_line', 'blink_block', or 'blink_underscore'" "unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'line', 'block', 'underscore', 'blink_line', 'blink_block', or 'blink_underscore'"
); );
// Reconstruct // Reconstruct
@ -828,7 +834,7 @@ impl Value {
} }
}; };
} else { } else {
invalid!(Some(*span), "should be a string"); invalid!(Some(span), "should be a string");
// Reconstruct // Reconstruct
vals[index] = reconstruct_cursor_shape!( vals[index] = reconstruct_cursor_shape!(
config.cursor_shape_emacs, config.cursor_shape_emacs,
@ -857,7 +863,7 @@ impl Value {
reconstruct_cursor_shape!(config.cursor_shape_vi_normal, span), reconstruct_cursor_shape!(config.cursor_shape_vi_normal, span),
reconstruct_cursor_shape!(config.cursor_shape_emacs, span), reconstruct_cursor_shape!(config.cursor_shape_emacs, span),
], ],
*span, span,
); );
} }
} }
@ -870,7 +876,7 @@ impl Value {
TableIndexMode::Never => "never", TableIndexMode::Never => "never",
TableIndexMode::Auto => "auto", TableIndexMode::Auto => "auto",
}, },
*$span, $span,
) )
}; };
} }
@ -883,29 +889,30 @@ impl Value {
"wrapping_try_keep_words".into(), "wrapping_try_keep_words".into(),
], ],
vec![ vec![
Value::string("wrapping", *$span), Value::string("wrapping", $span),
Value::bool(*try_to_keep_words, *$span), Value::bool(*try_to_keep_words, $span),
], ],
*$span, $span,
), ),
TrimStrategy::Truncate { suffix } => Value::record( TrimStrategy::Truncate { suffix } => Value::record(
vec!["methodology".into(), "truncating_suffix".into()], vec!["methodology".into(), "truncating_suffix".into()],
match suffix { match suffix {
Some(s) => vec![ Some(s) => vec![
Value::string("truncating", *$span), Value::string("truncating", $span),
Value::string(s.clone(), *$span), Value::string(s.clone(), $span),
], ],
None => vec![ None => vec![
Value::string("truncating", *$span), Value::string("truncating", $span),
Value::Nothing { span: *span }, Value::Nothing { span: $span },
], ],
}, },
*$span, $span,
), ),
} }
}; };
} }
if let Value::Record { cols, vals, span } = &mut vals[index] { if let Value::Record { cols, vals, span } = &mut vals[index] {
let span = *span;
for index in (0..cols.len()).rev() { for index in (0..cols.len()).rev() {
let value = &vals[index]; let value = &vals[index];
let key2 = cols[index].as_str(); let key2 = cols[index].as_str();
@ -914,9 +921,9 @@ impl Value {
if let Ok(v) = value.as_string() { if let Ok(v) = value.as_string() {
config.table_mode = v; config.table_mode = v;
} else { } else {
invalid!(Some(*span), "should be a string"); invalid!(Some(span), "should be a string");
vals[index] = vals[index] =
Value::string(config.table_mode.clone(), *span); Value::string(config.table_mode.clone(), span);
} }
} }
"index_mode" => { "index_mode" => {
@ -933,14 +940,14 @@ impl Value {
config.table_index_mode = TableIndexMode::Auto config.table_index_mode = TableIndexMode::Auto
} }
_ => { _ => {
invalid!( Some(*span), invalid!( Some(span),
"unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'never', 'always' or 'auto'" "unrecognized $env.config.{key}.{key2} '{val_str}'; expected either 'never', 'always' or 'auto'"
); );
vals[index] = reconstruct_index_mode!(span); vals[index] = reconstruct_index_mode!(span);
} }
} }
} else { } else {
invalid!(Some(*span), "should be a string"); invalid!(Some(span), "should be a string");
vals[index] = reconstruct_index_mode!(span); vals[index] = reconstruct_index_mode!(span);
} }
} }
@ -979,17 +986,18 @@ impl Value {
"show_empty".into(), "show_empty".into(),
], ],
vec![ vec![
Value::string(config.table_mode.clone(), *span), Value::string(config.table_mode.clone(), span),
reconstruct_index_mode!(span), reconstruct_index_mode!(span),
reconstruct_trim_strategy!(span), reconstruct_trim_strategy!(span),
Value::bool(config.table_show_empty, *span), Value::bool(config.table_show_empty, span),
], ],
*span, span,
) )
} }
} }
"filesize" => { "filesize" => {
if let Value::Record { cols, vals, span } = &mut vals[index] { if let Value::Record { cols, vals, span } = &mut vals[index] {
let span = *span;
for index in (0..cols.len()).rev() { for index in (0..cols.len()).rev() {
let value = &vals[index]; let value = &vals[index];
let key2 = cols[index].as_str(); let key2 = cols[index].as_str();
@ -1001,12 +1009,10 @@ impl Value {
if let Ok(v) = value.as_string() { if let Ok(v) = value.as_string() {
config.filesize_format = v.to_lowercase(); config.filesize_format = v.to_lowercase();
} else { } else {
invalid!(Some(*span), "should be a string"); invalid!(Some(span), "should be a string");
// Reconstruct // Reconstruct
vals[index] = Value::string( vals[index] =
config.filesize_format.clone(), Value::string(config.filesize_format.clone(), span);
*span,
);
} }
} }
x => { x => {
@ -1026,10 +1032,10 @@ impl Value {
vals[index] = Value::record( vals[index] = Value::record(
vec!["metric".into(), "format".into()], vec!["metric".into(), "format".into()],
vec![ vec![
Value::bool(config.filesize_metric, *span), Value::bool(config.filesize_metric, span),
Value::string(config.filesize_format.clone(), *span), Value::string(config.filesize_format.clone(), span),
], ],
*span, span,
); );
} }
} }
@ -1039,7 +1045,7 @@ impl Value {
} else { } else {
invalid!(vals[index].span().ok(), "should be a record"); invalid!(vals[index].span().ok(), "should be a record");
// Reconstruct // Reconstruct
vals[index] = Value::record_from_hashmap(&config.explore, *span); vals[index] = Value::record_from_hashmap(&config.explore, span);
} }
} }
// Misc. options // Misc. options
@ -1049,7 +1055,7 @@ impl Value {
} else { } else {
invalid!(vals[index].span().ok(), "should be a record"); invalid!(vals[index].span().ok(), "should be a record");
// Reconstruct // Reconstruct
vals[index] = Value::record_from_hashmap(&config.color_config, *span); vals[index] = Value::record_from_hashmap(&config.color_config, span);
} }
} }
"use_grid_icons" => { "use_grid_icons" => {
@ -1068,7 +1074,7 @@ impl Value {
}, },
}; };
} else { } else {
invalid!(Some(*span), "should be a string"); invalid!(Some(span), "should be a string");
// Reconstruct // Reconstruct
vals[index] = Value::String { vals[index] = Value::String {
val: match config.footer_mode { val: match config.footer_mode {
@ -1077,7 +1083,7 @@ impl Value {
FooterMode::Always => "always".into(), FooterMode::Always => "always".into(),
FooterMode::RowCount(number) => number.to_string(), FooterMode::RowCount(number) => number.to_string(),
}, },
span: *span, span,
}; };
} }
} }
@ -1091,9 +1097,9 @@ impl Value {
if let Ok(v) = value.as_string() { if let Ok(v) = value.as_string() {
config.edit_mode = v.to_lowercase(); config.edit_mode = v.to_lowercase();
} else { } else {
invalid!(Some(*span), "should be a string"); invalid!(Some(span), "should be a string");
// Reconstruct // Reconstruct
vals[index] = Value::string(config.edit_mode.clone(), *span); vals[index] = Value::string(config.edit_mode.clone(), span);
} }
} }
"shell_integration" => { "shell_integration" => {
@ -1103,7 +1109,7 @@ impl Value {
if let Ok(v) = value.as_string() { if let Ok(v) = value.as_string() {
config.buffer_editor = v.to_lowercase(); config.buffer_editor = v.to_lowercase();
} else { } else {
invalid!(Some(*span), "should be a string"); invalid!(Some(span), "should be a string");
} }
} }
"show_banner" => { "show_banner" => {
@ -1119,7 +1125,7 @@ impl Value {
"menus" => match create_menus(value) { "menus" => match create_menus(value) {
Ok(map) => config.menus = map, Ok(map) => config.menus = map,
Err(e) => { Err(e) => {
invalid!(Some(*span), "should be a valid list of menus"); invalid!(Some(span), "should be a valid list of menus");
errors.push(e); errors.push(e);
// Reconstruct // Reconstruct
vals[index] = Value::List { vals[index] = Value::List {
@ -1152,12 +1158,12 @@ impl Value {
menu_type.clone(), menu_type.clone(),
source.clone(), source.clone(),
], ],
span: *span, span,
} }
}, },
) )
.collect(), .collect(),
span: *span, span,
} }
} }
}, },
@ -1165,7 +1171,7 @@ impl Value {
"keybindings" => match create_keybindings(value) { "keybindings" => match create_keybindings(value) {
Ok(keybindings) => config.keybindings = keybindings, Ok(keybindings) => config.keybindings = keybindings,
Err(e) => { Err(e) => {
invalid!(Some(*span), "should be a valid keybindings list"); invalid!(Some(span), "should be a valid keybindings list");
errors.push(e); errors.push(e);
// Reconstruct // Reconstruct
vals[index] = Value::List { vals[index] = Value::List {
@ -1192,12 +1198,12 @@ impl Value {
mode.clone(), mode.clone(),
event.clone(), event.clone(),
], ],
span: *span, span,
} }
}, },
) )
.collect(), .collect(),
span: *span, span,
} }
} }
}, },
@ -1205,7 +1211,7 @@ impl Value {
"hooks" => match create_hooks(value) { "hooks" => match create_hooks(value) {
Ok(hooks) => config.hooks = hooks, Ok(hooks) => config.hooks = hooks,
Err(e) => { Err(e) => {
invalid!(Some(*span), "should be a valid hooks list"); invalid!(Some(span), "should be a valid hooks list");
errors.push(e); errors.push(e);
// Reconstruct // Reconstruct
let mut hook_cols = vec![]; let mut hook_cols = vec![];
@ -1229,7 +1235,7 @@ impl Value {
vals.push(Value::Record { vals.push(Value::Record {
cols: hook_cols, cols: hook_cols,
vals: hook_vals, vals: hook_vals,
span: *span, span,
}); });
} }
}, },
@ -1270,10 +1276,10 @@ impl Value {
vals[index] = Value::record( vals[index] = Value::record(
vec!["metric".into(), "format".into()], vec!["metric".into(), "format".into()],
vec![ vec![
Value::bool(config.filesize_metric, *span), Value::bool(config.filesize_metric, span),
Value::string(config.filesize_format.clone(), *span), Value::string(config.filesize_format.clone(), span),
], ],
*span, span,
); );
} }
} }
@ -1458,6 +1464,7 @@ fn create_hooks(value: &Value) -> Result<Hooks, ShellError> {
fn create_keybindings(value: &Value) -> Result<Vec<ParsedKeybinding>, ShellError> { fn create_keybindings(value: &Value) -> Result<Vec<ParsedKeybinding>, ShellError> {
match value { match value {
Value::Record { cols, vals, span } => { Value::Record { cols, vals, span } => {
let span = *span;
// Finding the modifier value in the record // Finding the modifier value in the record
let modifier = extract_value("modifier", cols, vals, span)?.clone(); let modifier = extract_value("modifier", cols, vals, span)?.clone();
let keycode = extract_value("keycode", cols, vals, span)?.clone(); let keycode = extract_value("keycode", cols, vals, span)?.clone();
@ -1495,6 +1502,7 @@ fn create_keybindings(value: &Value) -> Result<Vec<ParsedKeybinding>, ShellError
pub fn create_menus(value: &Value) -> Result<Vec<ParsedMenu>, ShellError> { pub fn create_menus(value: &Value) -> Result<Vec<ParsedMenu>, ShellError> {
match value { match value {
Value::Record { cols, vals, span } => { Value::Record { cols, vals, span } => {
let span = *span;
// Finding the modifier value in the record // Finding the modifier value in the record
let name = extract_value("name", cols, vals, span)?.clone(); let name = extract_value("name", cols, vals, span)?.clone();
let marker = extract_value("marker", cols, vals, span)?.clone(); let marker = extract_value("marker", cols, vals, span)?.clone();
@ -1506,7 +1514,7 @@ pub fn create_menus(value: &Value) -> Result<Vec<ParsedMenu>, ShellError> {
// Source is an optional value // Source is an optional value
let source = match extract_value("source", cols, vals, span) { let source = match extract_value("source", cols, vals, span) {
Ok(source) => source.clone(), Ok(source) => source.clone(),
Err(_) => Value::Nothing { span: *span }, Err(_) => Value::Nothing { span },
}; };
let menu = ParsedMenu { let menu = ParsedMenu {
@ -1538,10 +1546,10 @@ pub fn extract_value<'record>(
name: &str, name: &str,
cols: &'record [String], cols: &'record [String],
vals: &'record [Value], vals: &'record [Value],
span: &Span, span: Span,
) -> Result<&'record Value, ShellError> { ) -> Result<&'record Value, ShellError> {
cols.iter() cols.iter()
.position(|col| col.as_str() == name) .position(|col| col.as_str() == name)
.and_then(|index| vals.get(index)) .and_then(|index| vals.get(index))
.ok_or_else(|| ShellError::MissingConfigValue(name.to_string(), *span)) .ok_or_else(|| ShellError::MissingConfigValue(name.to_string(), span))
} }

View File

@ -724,7 +724,7 @@ impl EngineState {
output output
} }
pub fn get_span_contents(&self, span: &Span) -> &[u8] { pub fn get_span_contents(&self, span: Span) -> &[u8] {
for (contents, start, finish) in &self.file_contents { for (contents, start, finish) in &self.file_contents {
if span.start >= *start && span.end <= *finish { if span.start >= *start && span.end <= *finish {
return &contents[(span.start - start)..(span.end - start)]; return &contents[(span.start - start)..(span.end - start)];
@ -902,7 +902,7 @@ impl EngineState {
pub fn build_usage(&self, spans: &[Span]) -> (String, String) { pub fn build_usage(&self, spans: &[Span]) -> (String, String) {
let comment_lines: Vec<&[u8]> = spans let comment_lines: Vec<&[u8]> = spans
.iter() .iter()
.map(|span| self.get_span_contents(span)) .map(|span| self.get_span_contents(*span))
.collect(); .collect();
build_usage(&comment_lines) build_usage(&comment_lines)
} }
@ -1370,7 +1370,7 @@ impl<'a> StateWorkingSet<'a> {
} }
} }
} else { } else {
return self.permanent_state.get_span_contents(&span); return self.permanent_state.get_span_contents(span);
} }
panic!("internal error: missing span contents in file cache") panic!("internal error: missing span contents in file cache")

View File

@ -480,25 +480,25 @@ impl Value {
/// Get the span for the current value /// Get the span for the current value
pub fn span(&self) -> Result<Span, ShellError> { pub fn span(&self) -> Result<Span, ShellError> {
match self { match self {
Value::Bool { span, .. }
| Value::Int { span, .. }
| Value::Float { span, .. }
| Value::Filesize { span, .. }
| Value::Duration { span, .. }
| Value::Date { span, .. }
| Value::Range { span, .. }
| Value::String { span, .. }
| Value::Record { span, .. }
| Value::List { span, .. }
| Value::Block { span, .. }
| Value::Closure { span, .. }
| Value::Nothing { span, .. }
| Value::Binary { span, .. }
| Value::CellPath { span, .. }
| Value::CustomValue { span, .. }
| Value::LazyRecord { span, .. }
| Value::MatchPattern { span, .. } => Ok(*span),
Value::Error { error } => Err(*error.clone()), Value::Error { error } => Err(*error.clone()),
Value::Bool { span, .. } => Ok(*span),
Value::Int { span, .. } => Ok(*span),
Value::Float { span, .. } => Ok(*span),
Value::Filesize { span, .. } => Ok(*span),
Value::Duration { span, .. } => Ok(*span),
Value::Date { span, .. } => Ok(*span),
Value::Range { span, .. } => Ok(*span),
Value::String { span, .. } => Ok(*span),
Value::Record { span, .. } => Ok(*span),
Value::List { span, .. } => Ok(*span),
Value::Block { span, .. } => Ok(*span),
Value::Closure { span, .. } => Ok(*span),
Value::Nothing { span, .. } => Ok(*span),
Value::Binary { span, .. } => Ok(*span),
Value::CellPath { span, .. } => Ok(*span),
Value::CustomValue { span, .. } => Ok(*span),
Value::LazyRecord { span, .. } => Ok(*span),
Value::MatchPattern { span, .. } => Ok(*span),
} }
} }
@ -512,25 +512,25 @@ impl Value {
/// Update the value with a new span /// Update the value with a new span
pub fn with_span(mut self, new_span: Span) -> Value { pub fn with_span(mut self, new_span: Span) -> Value {
match &mut self { match &mut self {
Value::Bool { span, .. } => *span = new_span, Value::Bool { span, .. }
Value::Int { span, .. } => *span = new_span, | Value::Int { span, .. }
Value::Float { span, .. } => *span = new_span, | Value::Float { span, .. }
Value::Filesize { span, .. } => *span = new_span, | Value::Filesize { span, .. }
Value::Duration { span, .. } => *span = new_span, | Value::Duration { span, .. }
Value::Date { span, .. } => *span = new_span, | Value::Date { span, .. }
Value::Range { span, .. } => *span = new_span, | Value::Range { span, .. }
Value::String { span, .. } => *span = new_span, | Value::String { span, .. }
Value::Record { span, .. } => *span = new_span, | Value::Record { span, .. }
Value::LazyRecord { span, .. } => *span = new_span, | Value::LazyRecord { span, .. }
Value::List { span, .. } => *span = new_span, | Value::List { span, .. }
Value::Closure { span, .. } => *span = new_span, | Value::Closure { span, .. }
Value::Block { span, .. } => *span = new_span, | Value::Block { span, .. }
Value::Nothing { span, .. } => *span = new_span, | Value::Nothing { span, .. }
Value::Error { .. } => {} | Value::Binary { span, .. }
Value::Binary { span, .. } => *span = new_span, | Value::CellPath { span, .. }
Value::CellPath { span, .. } => *span = new_span, | Value::CustomValue { span, .. }
Value::CustomValue { span, .. } => *span = new_span, | Value::MatchPattern { span, .. } => *span = new_span,
Value::MatchPattern { span, .. } => *span = new_span, Value::Error { .. } => (),
} }
self self

View File

@ -27,7 +27,7 @@ impl GStat {
&self, &self,
value: &Value, value: &Value,
path: Option<Spanned<String>>, path: Option<Spanned<String>>,
span: &Span, span: Span,
) -> Result<Value, LabeledError> { ) -> Result<Value, LabeledError> {
// use std::any::Any; // use std::any::Any;
// eprintln!("input type: {:?} value: {:#?}", &value.type_id(), &value); // eprintln!("input type: {:?} value: {:#?}", &value.type_id(), &value);
@ -55,7 +55,7 @@ impl GStat {
} }
None => Spanned { None => Spanned {
item: ".".to_string(), item: ".".to_string(),
span: *span, span,
}, },
}; };
@ -146,54 +146,51 @@ impl GStat {
let mut vals = vec![]; let mut vals = vec![];
cols.push("idx_added_staged".into()); cols.push("idx_added_staged".into());
vals.push(Value::int(stats.idx_added_staged as i64, *span)); vals.push(Value::int(stats.idx_added_staged as i64, span));
cols.push("idx_modified_staged".into()); cols.push("idx_modified_staged".into());
vals.push(Value::int(stats.idx_modified_staged as i64, *span)); vals.push(Value::int(stats.idx_modified_staged as i64, span));
cols.push("idx_deleted_staged".into()); cols.push("idx_deleted_staged".into());
vals.push(Value::int(stats.idx_deleted_staged as i64, *span)); vals.push(Value::int(stats.idx_deleted_staged as i64, span));
cols.push("idx_renamed".into()); cols.push("idx_renamed".into());
vals.push(Value::int(stats.idx_renamed as i64, *span)); vals.push(Value::int(stats.idx_renamed as i64, span));
cols.push("idx_type_changed".into()); cols.push("idx_type_changed".into());
vals.push(Value::int(stats.idx_type_changed as i64, *span)); vals.push(Value::int(stats.idx_type_changed as i64, span));
cols.push("wt_untracked".into()); cols.push("wt_untracked".into());
vals.push(Value::int(stats.wt_untracked as i64, *span)); vals.push(Value::int(stats.wt_untracked as i64, span));
cols.push("wt_modified".into()); cols.push("wt_modified".into());
vals.push(Value::int(stats.wt_modified as i64, *span)); vals.push(Value::int(stats.wt_modified as i64, span));
cols.push("wt_deleted".into()); cols.push("wt_deleted".into());
vals.push(Value::int(stats.wt_deleted as i64, *span)); vals.push(Value::int(stats.wt_deleted as i64, span));
cols.push("wt_type_changed".into()); cols.push("wt_type_changed".into());
vals.push(Value::int(stats.wt_type_changed as i64, *span)); vals.push(Value::int(stats.wt_type_changed as i64, span));
cols.push("wt_renamed".into()); cols.push("wt_renamed".into());
vals.push(Value::int(stats.wt_renamed as i64, *span)); vals.push(Value::int(stats.wt_renamed as i64, span));
cols.push("ignored".into()); cols.push("ignored".into());
vals.push(Value::int(stats.ignored as i64, *span)); vals.push(Value::int(stats.ignored as i64, span));
cols.push("conflicts".into()); cols.push("conflicts".into());
vals.push(Value::int(stats.conflicts as i64, *span)); vals.push(Value::int(stats.conflicts as i64, span));
cols.push("ahead".into()); cols.push("ahead".into());
vals.push(Value::int(stats.ahead as i64, *span)); vals.push(Value::int(stats.ahead as i64, span));
cols.push("behind".into()); cols.push("behind".into());
vals.push(Value::int(stats.behind as i64, *span)); vals.push(Value::int(stats.behind as i64, span));
cols.push("stashes".into()); cols.push("stashes".into());
vals.push(Value::int(stats.stashes as i64, *span)); vals.push(Value::int(stats.stashes as i64, span));
cols.push("repo_name".into()); cols.push("repo_name".into());
vals.push(Value::String { vals.push(Value::String {
val: repo_name, val: repo_name,
span: *span, span,
}); });
cols.push("tag".into()); cols.push("tag".into());
vals.push(Value::String { vals.push(Value::String { val: tag, span });
val: tag,
span: *span,
});
cols.push("branch".into()); cols.push("branch".into());
vals.push(Value::String { vals.push(Value::String {
val: stats.branch, val: stats.branch,
span: *span, span,
}); });
cols.push("remote".into()); cols.push("remote".into());
vals.push(Value::String { vals.push(Value::String {
val: stats.remote, val: stats.remote,
span: *span, span,
}); });
// Leave this in case we want to turn it into a table instead of a list // Leave this in case we want to turn it into a table instead of a list
@ -206,61 +203,53 @@ impl GStat {
// span: *span, // span: *span,
// }) // })
Ok(Value::Record { Ok(Value::Record { cols, vals, span })
cols,
vals,
span: *span,
})
} }
fn create_empty_git_status(&self, span: &Span) -> Value { fn create_empty_git_status(&self, span: Span) -> Value {
let mut cols = vec![]; let mut cols = vec![];
let mut vals = vec![]; let mut vals = vec![];
cols.push("idx_added_staged".into()); cols.push("idx_added_staged".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("idx_modified_staged".into()); cols.push("idx_modified_staged".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("idx_deleted_staged".into()); cols.push("idx_deleted_staged".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("idx_renamed".into()); cols.push("idx_renamed".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("idx_type_changed".into()); cols.push("idx_type_changed".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("wt_untracked".into()); cols.push("wt_untracked".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("wt_modified".into()); cols.push("wt_modified".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("wt_deleted".into()); cols.push("wt_deleted".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("wt_type_changed".into()); cols.push("wt_type_changed".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("wt_renamed".into()); cols.push("wt_renamed".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("ignored".into()); cols.push("ignored".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("conflicts".into()); cols.push("conflicts".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("ahead".into()); cols.push("ahead".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("behind".into()); cols.push("behind".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("stashes".into()); cols.push("stashes".into());
vals.push(Value::int(-1, *span)); vals.push(Value::int(-1, span));
cols.push("repo_name".into()); cols.push("repo_name".into());
vals.push(Value::string("no_repository", *span)); vals.push(Value::string("no_repository", span));
cols.push("tag".into()); cols.push("tag".into());
vals.push(Value::string("no_tag", *span)); vals.push(Value::string("no_tag", span));
cols.push("branch".into()); cols.push("branch".into());
vals.push(Value::string("no_branch", *span)); vals.push(Value::string("no_branch", span));
cols.push("remote".into()); cols.push("remote".into());
vals.push(Value::string("no_remote", *span)); vals.push(Value::string("no_remote", span));
Value::Record { Value::Record { cols, vals, span }
cols,
vals,
span: *span,
}
} }
} }

View File

@ -22,6 +22,6 @@ impl Plugin for GStat {
let repo_path: Option<Spanned<String>> = call.opt(0)?; let repo_path: Option<Spanned<String>> = call.opt(0)?;
// eprintln!("input value: {:#?}", &input); // eprintln!("input value: {:#?}", &input);
self.gstat(input, repo_path, &call.head) self.gstat(input, repo_path, call.head)
} }
} }

View File

@ -47,7 +47,7 @@ pub fn execute_json_query(
let json_str = val.json(); let json_str = val.json();
Ok(Value::string(json_str, call.head)) Ok(Value::string(json_str, call.head))
} else { } else {
Ok(convert_gjson_value_to_nu_value(&val, &call.head)) Ok(convert_gjson_value_to_nu_value(&val, call.head))
} }
} }
@ -70,7 +70,7 @@ fn query_contains_modifiers(query: &str) -> bool {
// @join: Joins multiple objects into a single object. // @join: Joins multiple objects into a single object.
} }
fn convert_gjson_value_to_nu_value(v: &gjValue, span: &Span) -> Value { fn convert_gjson_value_to_nu_value(v: &gjValue, span: Span) -> Value {
match v.kind() { match v.kind() {
gjson::Kind::Array => { gjson::Kind::Array => {
let mut vals = vec![]; let mut vals = vec![];
@ -79,20 +79,20 @@ fn convert_gjson_value_to_nu_value(v: &gjValue, span: &Span) -> Value {
true true
}); });
Value::List { vals, span: *span } Value::List { vals, span }
} }
gjson::Kind::Null => Value::nothing(*span), gjson::Kind::Null => Value::nothing(span),
gjson::Kind::False => Value::bool(false, *span), gjson::Kind::False => Value::bool(false, span),
gjson::Kind::Number => { gjson::Kind::Number => {
let str_value = v.str(); let str_value = v.str();
if str_value.contains('.') { if str_value.contains('.') {
Value::float(v.f64(), *span) Value::float(v.f64(), span)
} else { } else {
Value::int(v.i64(), *span) Value::int(v.i64(), span)
} }
} }
gjson::Kind::String => Value::string(v.str(), *span), gjson::Kind::String => Value::string(v.str(), span),
gjson::Kind::True => Value::bool(true, *span), gjson::Kind::True => Value::bool(true, span),
gjson::Kind::Object => { gjson::Kind::Object => {
let mut cols = vec![]; let mut cols = vec![];
let mut vals = vec![]; let mut vals = vec![];
@ -101,11 +101,7 @@ fn convert_gjson_value_to_nu_value(v: &gjValue, span: &Span) -> Value {
vals.push(convert_gjson_value_to_nu_value(&v, span)); vals.push(convert_gjson_value_to_nu_value(&v, span));
true true
}); });
Value::Record { Value::Record { cols, vals, span }
cols,
vals,
span: *span,
}
} }
} }
} }

View File

@ -10,7 +10,7 @@ pub fn execute_xpath_query(
query: Option<Spanned<String>>, query: Option<Spanned<String>>,
) -> Result<Value, LabeledError> { ) -> Result<Value, LabeledError> {
let (query_string, span) = match &query { let (query_string, span) = match &query {
Some(v) => (&v.item, &v.span), Some(v) => (&v.item, v.span),
None => { None => {
return Err(LabeledError { return Err(LabeledError {
msg: "problem with input data".to_string(), msg: "problem with input data".to_string(),
@ -101,20 +101,20 @@ pub fn execute_xpath_query(
} }
} }
fn build_xpath(xpath_str: &str, span: &Span) -> Result<sxd_xpath::XPath, LabeledError> { fn build_xpath(xpath_str: &str, span: Span) -> Result<sxd_xpath::XPath, LabeledError> {
let factory = Factory::new(); let factory = Factory::new();
if let Ok(xpath) = factory.build(xpath_str) { if let Ok(xpath) = factory.build(xpath_str) {
xpath.ok_or_else(|| LabeledError { xpath.ok_or_else(|| LabeledError {
label: "invalid xpath query".to_string(), label: "invalid xpath query".to_string(),
msg: "invalid xpath query".to_string(), msg: "invalid xpath query".to_string(),
span: Some(*span), span: Some(span),
}) })
} else { } else {
Err(LabeledError { Err(LabeledError {
label: "expected valid xpath query".to_string(), label: "expected valid xpath query".to_string(),
msg: "expected valid xpath query".to_string(), msg: "expected valid xpath query".to_string(),
span: Some(*span), span: Some(span),
}) })
} }
} }