Add functions for each Value case (#9736)

# Description
This PR ensures functions exist to extract and create each and every
`Value` case. It also renames `Value::boolean` to `Value::bool` to match
`Value::test_bool`, `Value::as_bool`, and `Value::Bool`. Similarly,
`Value::as_integer` was renamed to `Value::as_int` to be consistent with
`Value::int`, `Value::test_int`, and `Value::Int`. These two renames can
be undone if necessary.

# User-Facing Changes
No user facing changes, but two public functions were renamed which may
affect downstream dependents.
This commit is contained in:
Ian Manske 2023-07-21 13:20:33 +00:00 committed by GitHub
parent 0b1e368cea
commit 7e1b922ea7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
30 changed files with 413 additions and 216 deletions

View file

@ -94,10 +94,10 @@ fn convert_to_suggestions(
Some(span @ Value::Record { .. }) => { Some(span @ Value::Record { .. }) => {
let start = span let start = span
.get_data_by_key("start") .get_data_by_key("start")
.and_then(|val| val.as_integer().ok()); .and_then(|val| val.as_int().ok());
let end = span let end = span
.get_data_by_key("end") .get_data_by_key("end")
.and_then(|val| val.as_integer().ok()); .and_then(|val| val.as_int().ok());
match (start, end) { match (start, end) {
(Some(start), Some(end)) => { (Some(start), Some(end)) => {
let start = start.min(end); let start = start.min(end);

View file

@ -183,7 +183,7 @@ pub(crate) fn add_columnar_menu(
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_integer()?; let columns = columns.as_int()?;
columnar_menu.with_columns(columns as u16) columnar_menu.with_columns(columns as u16)
} }
Err(_) => columnar_menu, Err(_) => columnar_menu,
@ -191,7 +191,7 @@ pub(crate) fn add_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_integer()?; 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))
} }
Err(_) => columnar_menu.with_column_width(None), Err(_) => columnar_menu.with_column_width(None),
@ -199,7 +199,7 @@ pub(crate) fn add_columnar_menu(
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_integer()?; 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)
} }
Err(_) => columnar_menu, Err(_) => columnar_menu,
@ -285,7 +285,7 @@ pub(crate) fn add_list_menu(
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_integer()?; 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)
} }
Err(_) => list_menu, Err(_) => list_menu,
@ -371,7 +371,7 @@ pub(crate) fn add_description_menu(
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_integer()?; let columns = columns.as_int()?;
description_menu.with_columns(columns as u16) description_menu.with_columns(columns as u16)
} }
Err(_) => description_menu, Err(_) => description_menu,
@ -379,7 +379,7 @@ pub(crate) fn add_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_integer()?; 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))
} }
Err(_) => description_menu.with_column_width(None), Err(_) => description_menu.with_column_width(None),
@ -387,7 +387,7 @@ pub(crate) fn add_description_menu(
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_integer()?; 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)
} }
Err(_) => description_menu, Err(_) => description_menu,
@ -395,7 +395,7 @@ pub(crate) fn add_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_integer()?; 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)
} }
Err(_) => description_menu, Err(_) => description_menu,
@ -403,7 +403,7 @@ pub(crate) fn add_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_integer()?; 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)
} }
Err(_) => description_menu, Err(_) => description_menu,
@ -884,7 +884,7 @@ fn edit_from_record(
"movebigwordrightstart" => EditCommand::MoveBigWordRightStart, "movebigwordrightstart" => EditCommand::MoveBigWordRightStart,
"movetoposition" => { "movetoposition" => {
let value = extract_value("value", cols, vals, span)?; let value = extract_value("value", cols, vals, span)?;
EditCommand::MoveToPosition(value.as_integer()? as usize) EditCommand::MoveToPosition(value.as_int()? as usize)
} }
"insertchar" => { "insertchar" => {
let value = extract_value("value", cols, vals, span)?; let value = extract_value("value", cols, vals, span)?;

View file

@ -538,14 +538,14 @@ pub fn evaluate_repl(
let current_shell = stack.get_env_var(engine_state, "NUSHELL_CURRENT_SHELL"); let current_shell = stack.get_env_var(engine_state, "NUSHELL_CURRENT_SHELL");
let current_shell = if let Some(v) = current_shell { let current_shell = if let Some(v) = current_shell {
v.as_integer().unwrap_or_default() as usize v.as_int().unwrap_or_default() as usize
} else { } else {
0 0
}; };
let last_shell = stack.get_env_var(engine_state, "NUSHELL_LAST_SHELL"); let last_shell = stack.get_env_var(engine_state, "NUSHELL_LAST_SHELL");
let last_shell = if let Some(v) = last_shell { let last_shell = if let Some(v) = last_shell {
v.as_integer().unwrap_or_default() as usize v.as_int().unwrap_or_default() as usize
} else { } else {
0 0
}; };

View file

@ -88,7 +88,7 @@ fn command(
) )
})?; })?;
let value = Value::boolean(!bool.any(), call.head); let value = Value::bool(!bool.any(), call.head);
NuDataFrame::try_from_columns(vec![Column::new("all_false".to_string(), vec![value])]) NuDataFrame::try_from_columns(vec![Column::new("all_false".to_string(), vec![value])])
.map(|df| PipelineData::Value(NuDataFrame::into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::into_value(df, call.head), None))

View file

@ -88,7 +88,7 @@ fn command(
) )
})?; })?;
let value = Value::boolean(bool.all(), call.head); let value = Value::bool(bool.all(), call.head);
NuDataFrame::try_from_columns(vec![Column::new("all_true".to_string(), vec![value])]) NuDataFrame::try_from_columns(vec![Column::new("all_true".to_string(), vec![value])])
.map(|df| PipelineData::Value(NuDataFrame::into_value(df, call.head), None)) .map(|df| PipelineData::Value(NuDataFrame::into_value(df, call.head), None))

View file

@ -89,7 +89,7 @@ fn ends_with(val: &Value, args: &Arguments, span: Span) -> Value {
Value::Binary { Value::Binary {
val, val,
span: val_span, span: val_span,
} => Value::boolean(val.ends_with(&args.pattern), *val_span), } => Value::bool(val.ends_with(&args.pattern), *val_span),
// Propagate errors by explicitly matching them before the final case. // Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => val.clone(), Value::Error { .. } => val.clone(),
other => Value::Error { other => Value::Error {

View file

@ -98,16 +98,16 @@ impl Command for BytesStartsWith {
i += max; i += max;
if i >= arg.pattern.len() { if i >= arg.pattern.len() {
return Ok(Value::boolean(true, span).into_pipeline_data()); return Ok(Value::bool(true, span).into_pipeline_data());
} }
} else { } else {
return Ok(Value::boolean(false, span).into_pipeline_data()); return Ok(Value::bool(false, span).into_pipeline_data());
} }
} }
// We reached the end of the stream and never returned, // We reached the end of the stream and never returned,
// the pattern wasn't exhausted so it probably doesn't match // the pattern wasn't exhausted so it probably doesn't match
Ok(Value::boolean(false, span).into_pipeline_data()) Ok(Value::bool(false, span).into_pipeline_data())
} }
_ => operate( _ => operate(
starts_with, starts_with,
@ -145,7 +145,7 @@ fn starts_with(val: &Value, args: &Arguments, span: Span) -> Value {
Value::Binary { Value::Binary {
val, val,
span: val_span, span: val_span,
} => Value::boolean(val.starts_with(&args.pattern), *val_span), } => Value::bool(val.starts_with(&args.pattern), *val_span),
// Propagate errors by explicitly matching them before the final case. // Propagate errors by explicitly matching them before the final case.
Value::Error { .. } => val.clone(), Value::Error { .. } => val.clone(),
other => Value::Error { other => Value::Error {

View file

@ -59,27 +59,27 @@ impl Command for SubCommand {
vals: vec![ vals: vec![
Value::Record { Value::Record {
cols: vec!["value".to_string()], cols: vec!["value".to_string()],
vals: vec![Value::boolean(false, span)], vals: vec![Value::bool(false, span)],
span, span,
}, },
Value::Record { Value::Record {
cols: vec!["value".to_string()], cols: vec!["value".to_string()],
vals: vec![Value::boolean(true, span)], vals: vec![Value::bool(true, span)],
span, span,
}, },
Value::Record { Value::Record {
cols: vec!["value".to_string()], cols: vec!["value".to_string()],
vals: vec![Value::boolean(false, span)], vals: vec![Value::bool(false, span)],
span, span,
}, },
Value::Record { Value::Record {
cols: vec!["value".to_string()], cols: vec!["value".to_string()],
vals: vec![Value::boolean(true, span)], vals: vec![Value::bool(true, span)],
span, span,
}, },
Value::Record { Value::Record {
cols: vec!["value".to_string()], cols: vec!["value".to_string()],
vals: vec![Value::boolean(true, span)], vals: vec![Value::bool(true, span)],
span, span,
}, },
], ],
@ -89,27 +89,27 @@ impl Command for SubCommand {
Example { Example {
description: "Convert bool to boolean", description: "Convert bool to boolean",
example: "true | into bool", example: "true | into bool",
result: Some(Value::boolean(true, span)), result: Some(Value::bool(true, span)),
}, },
Example { Example {
description: "convert integer to boolean", description: "convert integer to boolean",
example: "1 | into bool", example: "1 | into bool",
result: Some(Value::boolean(true, span)), result: Some(Value::bool(true, span)),
}, },
Example { Example {
description: "convert decimal to boolean", description: "convert decimal to boolean",
example: "0.3 | into bool", example: "0.3 | into bool",
result: Some(Value::boolean(true, span)), result: Some(Value::bool(true, span)),
}, },
Example { Example {
description: "convert decimal string to boolean", description: "convert decimal string to boolean",
example: "'0.0' | into bool", example: "'0.0' | into bool",
result: Some(Value::boolean(false, span)), result: Some(Value::bool(false, span)),
}, },
Example { Example {
description: "convert string to boolean", description: "convert string to boolean",
example: "'true' | into bool", example: "'true' | into bool",
result: Some(Value::boolean(true, span)), result: Some(Value::bool(true, span)),
}, },
] ]
} }

View file

@ -52,7 +52,7 @@ impl Command for SubCommand {
example: "[[value]; [false]] | into record", example: "[[value]; [false]] | into record",
result: Some(Value::Record { result: Some(Value::Record {
cols: vec!["value".to_string()], cols: vec!["value".to_string()],
vals: vec![Value::boolean(false, span)], vals: vec![Value::bool(false, span)],
span, span,
}), }),
}, },

View file

@ -34,7 +34,7 @@ impl Command for IsAdmin {
call: &Call, call: &Call,
_input: PipelineData, _input: PipelineData,
) -> Result<PipelineData, ShellError> { ) -> Result<PipelineData, ShellError> {
Ok(Value::boolean(is_root(), call.head).into_pipeline_data()) Ok(Value::bool(is_root(), call.head).into_pipeline_data())
} }
fn examples(&self) -> Vec<Example> { fn examples(&self) -> Vec<Example> {

View file

@ -118,8 +118,8 @@ impl Command for DropNth {
rows rows
} }
Either::Right(row_range) => { Either::Right(row_range) => {
let from = row_range.from.as_integer()?; // as usize; let from = row_range.from.as_int()?; // as usize;
let to = row_range.to.as_integer()?; // as usize; let to = row_range.to.as_int()?; // as usize;
// check for negative range inputs, e.g., (2..-5) // check for negative range inputs, e.g., (2..-5)
if from.is_negative() || to.is_negative() { if from.is_negative() || to.is_negative() {
@ -187,7 +187,7 @@ fn extract_int_or_range(
) -> Result<Either<i64, Range>, ShellError> { ) -> Result<Either<i64, Range>, ShellError> {
let value = call.req::<Value>(engine_state, stack, 0)?; let value = call.req::<Value>(engine_state, stack, 0)?;
let int_opt = value.as_integer().map(Either::Left).ok(); let int_opt = value.as_int().map(Either::Left).ok();
let range_opt: Result<nu_protocol::Range, ShellError> = FromValue::from_value(&value); let range_opt: Result<nu_protocol::Range, ShellError> = FromValue::from_value(&value);
let range_opt = range_opt.map(Either::Right).ok(); let range_opt = range_opt.map(Either::Right).ok();

View file

@ -76,13 +76,13 @@ fn empty(
let val = val.clone(); let val = val.clone();
match val.follow_cell_path(&column.members, false) { match val.follow_cell_path(&column.members, false) {
Ok(Value::Nothing { .. }) => {} Ok(Value::Nothing { .. }) => {}
Ok(_) => return Ok(Value::boolean(false, head).into_pipeline_data()), Ok(_) => return Ok(Value::bool(false, head).into_pipeline_data()),
Err(err) => return Err(err), Err(err) => return Err(err),
} }
} }
} }
Ok(Value::boolean(true, head).into_pipeline_data()) Ok(Value::bool(true, head).into_pipeline_data())
} else { } else {
match input { match input {
PipelineData::Empty => Ok(PipelineData::Empty), PipelineData::Empty => Ok(PipelineData::Empty),
@ -91,17 +91,17 @@ fn empty(
let bytes = s.into_bytes(); let bytes = s.into_bytes();
match bytes { match bytes {
Ok(s) => Ok(Value::boolean(s.item.is_empty(), head).into_pipeline_data()), Ok(s) => Ok(Value::bool(s.item.is_empty(), head).into_pipeline_data()),
Err(err) => Err(err), Err(err) => Err(err),
} }
} }
None => Ok(Value::boolean(true, head).into_pipeline_data()), None => Ok(Value::bool(true, head).into_pipeline_data()),
}, },
PipelineData::ListStream(s, ..) => { PipelineData::ListStream(s, ..) => {
Ok(Value::boolean(s.count() == 0, head).into_pipeline_data()) Ok(Value::bool(s.count() == 0, head).into_pipeline_data())
} }
PipelineData::Value(value, ..) => { PipelineData::Value(value, ..) => {
Ok(Value::boolean(value.is_empty(), head).into_pipeline_data()) Ok(Value::bool(value.is_empty(), head).into_pipeline_data())
} }
} }
} }

View file

@ -145,7 +145,7 @@ fn from_ods(
DataType::String(s) => Value::string(s, head), DataType::String(s) => Value::string(s, head),
DataType::Float(f) => Value::float(*f, head), DataType::Float(f) => Value::float(*f, head),
DataType::Int(i) => Value::int(*i, head), DataType::Int(i) => Value::int(*i, head),
DataType::Bool(b) => Value::boolean(*b, head), DataType::Bool(b) => Value::bool(*b, head),
_ => Value::nothing(head), _ => Value::nothing(head),
}; };

View file

@ -144,7 +144,7 @@ fn from_xlsx(
DataType::String(s) => Value::string(s, head), DataType::String(s) => Value::string(s, head),
DataType::Float(f) => Value::float(*f, head), DataType::Float(f) => Value::float(*f, head),
DataType::Int(i) => Value::int(*i, head), DataType::Int(i) => Value::int(*i, head),
DataType::Bool(b) => Value::boolean(*b, head), DataType::Bool(b) => Value::bool(*b, head),
_ => Value::nothing(head), _ => Value::nothing(head),
}; };

View file

@ -77,9 +77,9 @@ fn integer(
let (min, max) = if let Some(r) = range { let (min, max) = if let Some(r) = range {
if r.is_end_inclusive() { if r.is_end_inclusive() {
(r.from.as_integer()?, r.to.as_integer()?) (r.from.as_int()?, r.to.as_int()?)
} else if r.to.as_integer()? > 0 { } else if r.to.as_int()? > 0 {
(r.from.as_integer()?, r.to.as_integer()? - 1) (r.from.as_int()?, r.to.as_int()? - 1)
} else { } else {
(0, 0) (0, 0)
} }

View file

@ -164,7 +164,7 @@ fn action(
head: Span, head: Span,
) -> Value { ) -> Value {
match input { match input {
Value::String { val, .. } => Value::boolean( Value::String { val, .. } => Value::bool(
match case_insensitive { match case_insensitive {
true => { true => {
if *not_contain { if *not_contain {

View file

@ -94,7 +94,7 @@ fn action(input: &Value, args: &Arguments, head: Span) -> Value {
} else { } else {
s.ends_with(&args.substring) s.ends_with(&args.substring)
}; };
Value::boolean(ends_with, head) Value::bool(ends_with, head)
} }
Value::Error { .. } => input.clone(), Value::Error { .. } => input.clone(),
_ => Value::Error { _ => Value::Error {

View file

@ -110,7 +110,7 @@ fn action(
} else { } else {
s.starts_with(substring) s.starts_with(substring)
}; };
Value::boolean(starts_with, head) Value::bool(starts_with, head)
} }
Value::Error { .. } => input.clone(), Value::Error { .. } => input.clone(),
_ => Value::Error { _ => Value::Error {

View file

@ -246,7 +246,7 @@ fn heuristic_parse(
Vec::new(), Vec::new(),
)) ))
} else { } else {
Ok(PipelineData::Value(Value::boolean(false, span), None)) Ok(PipelineData::Value(Value::bool(false, span), None))
} }
} }
} }
@ -291,7 +291,7 @@ fn heuristic_parse_file(
Vec::new(), Vec::new(),
)) ))
} else { } else {
Ok(PipelineData::Value(Value::boolean(false, call.head), None)) Ok(PipelineData::Value(Value::bool(false, call.head), None))
} }
} }
} }
@ -337,10 +337,10 @@ fn parse_module(
Vec::new(), Vec::new(),
)) ))
} else { } else {
Ok(PipelineData::Value(Value::boolean(false, new_span), None)) Ok(PipelineData::Value(Value::bool(false, new_span), None))
} }
} else { } else {
Ok(PipelineData::Value(Value::boolean(true, new_span), None)) Ok(PipelineData::Value(Value::bool(true, new_span), None))
} }
} }
@ -370,10 +370,10 @@ fn parse_script(
Vec::new(), Vec::new(),
)) ))
} else { } else {
Ok(PipelineData::Value(Value::boolean(false, span), None)) Ok(PipelineData::Value(Value::bool(false, span), None))
} }
} else { } else {
Ok(PipelineData::Value(Value::boolean(true, span), None)) Ok(PipelineData::Value(Value::bool(true, span), None))
} }
} }

View file

@ -121,7 +121,7 @@ pub fn eval_call(
} else if let Some(value) = &named.default_value { } else if let Some(value) = &named.default_value {
callee_stack.add_var(var_id, value.to_owned()); callee_stack.add_var(var_id, value.to_owned());
} else { } else {
callee_stack.add_var(var_id, Value::boolean(true, call.head)) callee_stack.add_var(var_id, Value::bool(true, call.head))
} }
found = true; found = true;
} }
@ -133,7 +133,7 @@ pub fn eval_call(
} else if let Some(value) = &named.default_value { } else if let Some(value) = &named.default_value {
callee_stack.add_var(var_id, value.to_owned()); callee_stack.add_var(var_id, value.to_owned());
} else { } else {
callee_stack.add_var(var_id, Value::boolean(true, call.head)) callee_stack.add_var(var_id, Value::bool(true, call.head))
} }
found = true; found = true;
} }
@ -141,7 +141,7 @@ pub fn eval_call(
if !found { if !found {
if named.arg.is_none() { if named.arg.is_none() {
callee_stack.add_var(var_id, Value::boolean(false, call.head)) callee_stack.add_var(var_id, Value::bool(false, call.head))
} else if let Some(value) = named.default_value { } else if let Some(value) = named.default_value {
callee_stack.add_var(var_id, value); callee_stack.add_var(var_id, value);
} else { } else {
@ -275,7 +275,7 @@ pub fn eval_expression(
expr: &Expression, expr: &Expression,
) -> Result<Value, ShellError> { ) -> Result<Value, ShellError> {
match &expr.expr { match &expr.expr {
Expr::Bool(b) => Ok(Value::boolean(*b, expr.span)), Expr::Bool(b) => Ok(Value::bool(*b, expr.span)),
Expr::Int(i) => Ok(Value::int(*i, expr.span)), Expr::Int(i) => Ok(Value::int(*i, expr.span)),
Expr::Float(f) => Ok(Value::float(*f, expr.span)), Expr::Float(f) => Ok(Value::float(*f, expr.span)),
Expr::Binary(b) => Ok(Value::Binary { Expr::Binary(b) => Ok(Value::Binary {
@ -367,7 +367,7 @@ pub fn eval_expression(
Expr::UnaryNot(expr) => { Expr::UnaryNot(expr) => {
let lhs = eval_expression(engine_state, stack, expr)?; let lhs = eval_expression(engine_state, stack, expr)?;
match lhs { match lhs {
Value::Bool { val, .. } => Ok(Value::boolean(!val, expr.span)), Value::Bool { val, .. } => Ok(Value::bool(!val, expr.span)),
_ => Err(ShellError::TypeMismatch { _ => Err(ShellError::TypeMismatch {
err_message: "bool".to_string(), err_message: "bool".to_string(),
span: expr.span, span: expr.span,
@ -384,7 +384,7 @@ pub fn eval_expression(
match boolean { match boolean {
Boolean::And => { Boolean::And => {
if lhs.is_false() { if lhs.is_false() {
Ok(Value::boolean(false, expr.span)) Ok(Value::bool(false, expr.span))
} else { } else {
let rhs = eval_expression(engine_state, stack, rhs)?; let rhs = eval_expression(engine_state, stack, rhs)?;
lhs.and(op_span, &rhs, expr.span) lhs.and(op_span, &rhs, expr.span)
@ -392,7 +392,7 @@ pub fn eval_expression(
} }
Boolean::Or => { Boolean::Or => {
if lhs.is_true() { if lhs.is_true() {
Ok(Value::boolean(true, expr.span)) Ok(Value::bool(true, expr.span))
} else { } else {
let rhs = eval_expression(engine_state, stack, rhs)?; let rhs = eval_expression(engine_state, stack, rhs)?;
lhs.or(op_span, &rhs, expr.span) lhs.or(op_span, &rhs, expr.span)

View file

@ -337,7 +337,7 @@ impl<'e, 's> ScopeData<'e, 's> {
Value::nothing(span), Value::nothing(span),
Value::string("input", span), Value::string("input", span),
Value::string(input_type.to_shape().to_string(), span), Value::string(input_type.to_shape().to_string(), span),
Value::boolean(false, span), Value::bool(false, span),
Value::nothing(span), Value::nothing(span),
Value::nothing(span), Value::nothing(span),
Value::nothing(span), Value::nothing(span),
@ -352,7 +352,7 @@ impl<'e, 's> ScopeData<'e, 's> {
Value::string(&req.name, span), Value::string(&req.name, span),
Value::string("positional", span), Value::string("positional", span),
Value::string(req.shape.to_string(), span), Value::string(req.shape.to_string(), span),
Value::boolean(false, span), Value::bool(false, span),
Value::nothing(span), Value::nothing(span),
Value::string(&req.desc, span), Value::string(&req.desc, span),
Value::string( Value::string(
@ -375,7 +375,7 @@ impl<'e, 's> ScopeData<'e, 's> {
Value::string(&opt.name, span), Value::string(&opt.name, span),
Value::string("positional", span), Value::string("positional", span),
Value::string(opt.shape.to_string(), span), Value::string(opt.shape.to_string(), span),
Value::boolean(true, span), Value::bool(true, span),
Value::nothing(span), Value::nothing(span),
Value::string(&opt.desc, span), Value::string(&opt.desc, span),
Value::string( Value::string(
@ -402,7 +402,7 @@ impl<'e, 's> ScopeData<'e, 's> {
Value::string(if rest.name == "rest" { "" } else { &rest.name }, span), Value::string(if rest.name == "rest" { "" } else { &rest.name }, span),
Value::string("rest", span), Value::string("rest", span),
Value::string(rest.shape.to_string(), span), Value::string(rest.shape.to_string(), span),
Value::boolean(true, span), Value::bool(true, span),
Value::nothing(span), Value::nothing(span),
Value::string(&rest.desc, span), Value::string(&rest.desc, span),
Value::string( Value::string(
@ -449,7 +449,7 @@ impl<'e, 's> ScopeData<'e, 's> {
Value::string(&named.long, span), Value::string(&named.long, span),
flag_type, flag_type,
shape, shape,
Value::boolean(!named.required, span), Value::bool(!named.required, span),
short_flag, short_flag,
Value::string(&named.desc, span), Value::string(&named.desc, span),
Value::string(custom_completion_command_name, span), Value::string(custom_completion_command_name, span),
@ -474,7 +474,7 @@ impl<'e, 's> ScopeData<'e, 's> {
Value::nothing(span), Value::nothing(span),
Value::string("output", span), Value::string("output", span),
Value::string(output_type.to_shape().to_string(), span), Value::string(output_type.to_shape().to_string(), span),
Value::boolean(false, span), Value::bool(false, span),
Value::nothing(span), Value::nothing(span),
Value::nothing(span), Value::nothing(span),
Value::nothing(span), Value::nothing(span),

View file

@ -85,8 +85,8 @@ impl SimpleCommand for TweakCmd {
fn parse_value(value: &str) -> Value { fn parse_value(value: &str) -> Value {
match value { match value {
"true" => Value::boolean(true, NuSpan::unknown()), "true" => Value::bool(true, NuSpan::unknown()),
"false" => Value::boolean(false, NuSpan::unknown()), "false" => Value::bool(false, NuSpan::unknown()),
s => Value::string(s.to_owned(), NuSpan::unknown()), s => Value::string(s.to_owned(), NuSpan::unknown()),
} }
} }

View file

@ -340,7 +340,7 @@ fn insert_bool(map: &mut HashMap<String, Value>, key: &str, value: bool) {
return; return;
} }
map.insert(String::from(key), Value::boolean(value, Span::unknown())); map.insert(String::from(key), Value::bool(value, Span::unknown()));
} }
fn include_nu_config(config: &mut HashMap<String, Value>, style_computer: &StyleComputer) { fn include_nu_config(config: &mut HashMap<String, Value>, style_computer: &StyleComputer) {

View file

@ -12,7 +12,7 @@ pub fn eval_constant(
expr: &Expression, expr: &Expression,
) -> Result<Value, ParseError> { ) -> Result<Value, ParseError> {
match &expr.expr { match &expr.expr {
Expr::Bool(b) => Ok(Value::boolean(*b, expr.span)), Expr::Bool(b) => Ok(Value::bool(*b, expr.span)),
Expr::Int(i) => Ok(Value::int(*i, expr.span)), Expr::Int(i) => Ok(Value::int(*i, expr.span)),
Expr::Float(f) => Ok(Value::float(*f, expr.span)), Expr::Float(f) => Ok(Value::float(*f, expr.span)),
Expr::Binary(b) => Ok(Value::Binary { Expr::Binary(b) => Ok(Value::Binary {

View file

@ -269,13 +269,13 @@ impl Value {
} else { } else {
invalid!(Some(*$span), "should be a bool"); invalid!(Some(*$span), "should be a bool");
// Reconstruct // Reconstruct
$vals[$index] = Value::boolean(config.$setting, *$span); $vals[$index] = Value::bool(config.$setting, *$span);
} }
}; };
} }
macro_rules! try_int { macro_rules! try_int {
($cols:ident, $vals:ident, $index:ident, $span:expr, $setting:ident) => { ($cols:ident, $vals:ident, $index:ident, $span:expr, $setting:ident) => {
if let Ok(b) = &$vals[$index].as_integer() { 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");
@ -350,8 +350,8 @@ 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::boolean(config.use_ls_colors, *span), Value::bool(config.use_ls_colors, *span),
Value::boolean(config.show_clickable_links_in_ls, *span), Value::bool(config.show_clickable_links_in_ls, *span),
], ],
*span, *span,
); );
@ -383,8 +383,8 @@ 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::boolean(config.use_ls_colors, *span), Value::bool(config.use_ls_colors, *span),
Value::boolean(config.show_clickable_links_in_ls, *span), Value::bool(config.show_clickable_links_in_ls, *span),
], ],
*span, *span,
); );
@ -415,7 +415,7 @@ impl Value {
// Reconstruct // Reconstruct
vals[index] = Value::record( vals[index] = Value::record(
vec!["always_trash".into()], vec!["always_trash".into()],
vec![Value::boolean(config.rm_always_trash, *span)], vec![Value::bool(config.rm_always_trash, *span)],
*span, *span,
); );
} }
@ -495,10 +495,10 @@ impl Value {
"isolation".into(), "isolation".into(),
], ],
vec![ vec![
Value::boolean(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::boolean(config.history_isolation, *span), Value::bool(config.history_isolation, *span),
], ],
*span, *span,
); );
@ -524,7 +524,7 @@ impl Value {
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::boolean(config.enable_external_completion, *$span), Value::bool(config.enable_external_completion, *$span),
], ],
*$span, *$span,
) )
@ -662,10 +662,10 @@ impl Value {
"external".into(), "external".into(),
], ],
vec![ vec![
Value::boolean(config.quick_completions, *span), Value::bool(config.quick_completions, *span),
Value::boolean(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::boolean(config.case_sensitive_completions, *span), Value::bool(config.case_sensitive_completions, *span),
reconstruct_external!(span), reconstruct_external!(span),
], ],
*span, *span,
@ -884,7 +884,7 @@ impl Value {
], ],
vec![ vec![
Value::string("wrapping", *$span), Value::string("wrapping", *$span),
Value::boolean(*try_to_keep_words, *$span), Value::bool(*try_to_keep_words, *$span),
], ],
*$span, *$span,
), ),
@ -982,7 +982,7 @@ impl Value {
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::boolean(config.table_show_empty, *span), Value::bool(config.table_show_empty, *span),
], ],
*span, *span,
) )
@ -1026,7 +1026,7 @@ impl Value {
vals[index] = Value::record( vals[index] = Value::record(
vec!["metric".into(), "format".into()], vec!["metric".into(), "format".into()],
vec![ vec![
Value::boolean(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,
@ -1270,7 +1270,7 @@ impl Value {
vals[index] = Value::record( vals[index] = Value::record(
vec!["metric".into(), "format".into()], vec!["metric".into(), "format".into()],
vec![ vec![
Value::boolean(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,

View file

@ -125,7 +125,7 @@ pub enum Value {
impl Clone for Value { impl Clone for Value {
fn clone(&self) -> Self { fn clone(&self) -> Self {
match self { match self {
Value::Bool { val, span } => Value::boolean(*val, *span), Value::Bool { val, span } => Value::bool(*val, *span),
Value::Int { val, span } => Value::int(*val, *span), Value::Int { val, span } => Value::int(*val, *span),
Value::Filesize { val, span } => Value::Filesize { Value::Filesize { val, span } => Value::Filesize {
val: *val, val: *val,
@ -193,20 +193,84 @@ impl Clone for Value {
} }
impl Value { impl Value {
pub fn as_char(&self) -> Result<char, ShellError> { pub fn as_bool(&self) -> Result<bool, ShellError> {
match self { match self {
Value::String { val, span } => { Value::Bool { val, .. } => Ok(*val),
let mut chars = val.chars(); x => Err(ShellError::CantConvert {
match (chars.next(), chars.next()) { to_type: "boolean".into(),
(Some(c), None) => Ok(c), from_type: x.get_type().to_string(),
_ => Err(ShellError::MissingParameter { span: self.span()?,
param_name: "single character separator".into(), help: None,
span: *span,
}), }),
} }
} }
pub fn as_int(&self) -> Result<i64, ShellError> {
match self {
Value::Int { val, .. } => Ok(*val),
x => Err(ShellError::CantConvert { x => Err(ShellError::CantConvert {
to_type: "char".into(), to_type: "integer".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_float(&self) -> Result<f64, ShellError> {
match self {
Value::Float { val, .. } => Ok(*val),
Value::Int { val, .. } => Ok(*val as f64),
x => Err(ShellError::CantConvert {
to_type: "float".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_filesize(&self) -> Result<i64, ShellError> {
match self {
Value::Filesize { val, .. } => Ok(*val),
x => Err(ShellError::CantConvert {
to_type: "filesize".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_duration(&self) -> Result<i64, ShellError> {
match self {
Value::Duration { val, .. } => Ok(*val),
x => Err(ShellError::CantConvert {
to_type: "duration".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_date(&self) -> Result<DateTime<FixedOffset>, ShellError> {
match self {
Value::Date { val, .. } => Ok(*val),
x => Err(ShellError::CantConvert {
to_type: "date".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_range(&self) -> Result<&Range, ShellError> {
match self {
Value::Range { val, .. } => Ok(val.as_ref()),
x => Err(ShellError::CantConvert {
to_type: "range".into(),
from_type: x.get_type().to_string(), from_type: x.get_type().to_string(),
span: self.span()?, span: self.span()?,
help: None, help: None,
@ -270,6 +334,27 @@ impl Value {
} }
} }
pub fn as_char(&self) -> Result<char, ShellError> {
match self {
Value::String { val, span } => {
let mut chars = val.chars();
match (chars.next(), chars.next()) {
(Some(c), None) => Ok(c),
_ => Err(ShellError::MissingParameter {
param_name: "single character separator".into(),
span: *span,
}),
}
}
x => Err(ShellError::CantConvert {
to_type: "char".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_path(&self) -> Result<PathBuf, ShellError> { pub fn as_path(&self) -> Result<PathBuf, ShellError> {
match self { match self {
Value::String { val, .. } => Ok(PathBuf::from(val)), Value::String { val, .. } => Ok(PathBuf::from(val)),
@ -282,32 +367,6 @@ impl Value {
} }
} }
pub fn as_block(&self) -> Result<BlockId, ShellError> {
match self {
Value::Block { val, .. } => Ok(*val),
Value::Closure { val, .. } => Ok(*val),
x => Err(ShellError::CantConvert {
to_type: "block".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_binary(&self) -> Result<&[u8], ShellError> {
match self {
Value::Binary { val, .. } => Ok(val),
Value::String { val, .. } => Ok(val.as_bytes()),
x => Err(ShellError::CantConvert {
to_type: "binary".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_record(&self) -> Result<(&[String], &[Value]), ShellError> { pub fn as_record(&self) -> Result<(&[String], &[Value]), ShellError> {
match self { match self {
Value::Record { cols, vals, .. } => Ok((cols, vals)), Value::Record { cols, vals, .. } => Ok((cols, vals)),
@ -332,11 +391,12 @@ impl Value {
} }
} }
pub fn as_bool(&self) -> Result<bool, ShellError> { pub fn as_block(&self) -> Result<BlockId, ShellError> {
match self { match self {
Value::Bool { val, .. } => Ok(*val), Value::Block { val, .. } => Ok(*val),
Value::Closure { val, .. } => Ok(*val),
x => Err(ShellError::CantConvert { x => Err(ShellError::CantConvert {
to_type: "boolean".into(), to_type: "block".into(),
from_type: x.get_type().to_string(), from_type: x.get_type().to_string(),
span: self.span()?, span: self.span()?,
help: None, help: None,
@ -344,12 +404,11 @@ impl Value {
} }
} }
pub fn as_float(&self) -> Result<f64, ShellError> { pub fn as_closure(&self) -> Result<(BlockId, &HashMap<VarId, Value>), ShellError> {
match self { match self {
Value::Float { val, .. } => Ok(*val), Value::Closure { val, captures, .. } => Ok((*val, captures)),
Value::Int { val, .. } => Ok(*val as f64),
x => Err(ShellError::CantConvert { x => Err(ShellError::CantConvert {
to_type: "float".into(), to_type: "closure".into(),
from_type: x.get_type().to_string(), from_type: x.get_type().to_string(),
span: self.span()?, span: self.span()?,
help: None, help: None,
@ -357,11 +416,60 @@ impl Value {
} }
} }
pub fn as_integer(&self) -> Result<i64, ShellError> { pub fn as_binary(&self) -> Result<&[u8], ShellError> {
match self { match self {
Value::Int { val, .. } => Ok(*val), Value::Binary { val, .. } => Ok(val),
Value::String { val, .. } => Ok(val.as_bytes()),
x => Err(ShellError::CantConvert { x => Err(ShellError::CantConvert {
to_type: "integer".into(), to_type: "binary".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_cell_path(&self) -> Result<&CellPath, ShellError> {
match self {
Value::CellPath { val, .. } => Ok(val),
x => Err(ShellError::CantConvert {
to_type: "cell path".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_custom_value(&self) -> Result<&dyn CustomValue, ShellError> {
match self {
Value::CustomValue { val, .. } => Ok(val.as_ref()),
x => Err(ShellError::CantConvert {
to_type: "custom value".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_lazy_record(&self) -> Result<&dyn for<'a> LazyRecord<'a>, ShellError> {
match self {
Value::LazyRecord { val, .. } => Ok(val.as_ref()),
x => Err(ShellError::CantConvert {
to_type: "lazy record".into(),
from_type: x.get_type().to_string(),
span: self.span()?,
help: None,
}),
}
}
pub fn as_match_pattern(&self) -> Result<&MatchPattern, ShellError> {
match self {
Value::MatchPattern { val, .. } => Ok(val.as_ref()),
x => Err(ShellError::CantConvert {
to_type: "match pattern".into(),
from_type: x.get_type().to_string(), from_type: x.get_type().to_string(),
span: self.span()?, span: self.span()?,
help: None, help: None,
@ -768,11 +876,6 @@ impl Value {
matches!(self, Value::Nothing { .. }) matches!(self, Value::Nothing { .. })
} }
/// Create a new `Nothing` value
pub fn nothing(span: Span) -> Value {
Value::Nothing { span }
}
/// Follow a given cell path into the value: for example accessing select elements in a stream or list /// Follow a given cell path into the value: for example accessing select elements in a stream or list
pub fn follow_cell_path( pub fn follow_cell_path(
self, self,
@ -1635,18 +1738,8 @@ impl Value {
} }
} }
pub fn string(val: impl Into<String>, span: Span) -> Value { pub fn bool(val: bool, span: Span) -> Value {
Value::String { Value::Bool { val, span }
val: val.into(),
span,
}
}
pub fn binary(val: impl Into<Vec<u8>>, span: Span) -> Value {
Value::Binary {
val: val.into(),
span,
}
} }
pub fn int(val: i64, span: Span) -> Value { pub fn int(val: i64, span: Span) -> Value {
@ -1657,8 +1750,30 @@ impl Value {
Value::Float { val, span } Value::Float { val, span }
} }
pub fn boolean(val: bool, span: Span) -> Value { pub fn filesize(val: i64, span: Span) -> Value {
Value::Bool { val, span } Value::Filesize { val, span }
}
pub fn duration(val: i64, span: Span) -> Value {
Value::Duration { val, span }
}
pub fn date(val: DateTime<FixedOffset>, span: Span) -> Value {
Value::Date { val, span }
}
pub fn range(val: Range, span: Span) -> Value {
Value::Range {
val: Box::new(val),
span,
}
}
pub fn string(val: impl Into<String>, span: Span) -> Value {
Value::String {
val: val.into(),
span,
}
} }
pub fn record(cols: Vec<String>, vals: Vec<Value>, span: Span) -> Value { pub fn record(cols: Vec<String>, vals: Vec<Value>, span: Span) -> Value {
@ -1679,83 +1794,165 @@ impl Value {
Value::List { vals, span } Value::List { vals, span }
} }
/// Note: Only use this for test data, *not* live data, as it will point into unknown source pub fn block(val: BlockId, span: Span) -> Value {
/// when used in errors. Value::Block { val, span }
pub fn test_string(s: impl Into<String>) -> Value {
Value::string(s, Span::test_data())
} }
/// Note: Only use this for test data, *not* live data, as it will point into unknown source pub fn closure(val: BlockId, captures: HashMap<VarId, Value>, span: Span) -> Value {
/// when used in errors. Value::Closure {
pub fn test_int(val: i64) -> Value {
Value::Int {
val, val,
span: Span::test_data(), captures,
span,
} }
} }
/// Note: Only use this for test data, *not* live data, as it will point into unknown source /// Create a new `Nothing` value
/// when used in errors. pub fn nothing(span: Span) -> Value {
pub fn test_float(val: f64) -> Value { Value::Nothing { span }
Value::Float { }
val,
span: Span::test_data(), pub fn error(error: ShellError) -> Value {
Value::Error {
error: Box::new(error),
}
}
pub fn binary(val: impl Into<Vec<u8>>, span: Span) -> Value {
Value::Binary {
val: val.into(),
span,
}
}
pub fn cell_path(val: CellPath, span: Span) -> Value {
Value::CellPath { val, span }
}
pub fn custom_value(val: Box<dyn CustomValue>, span: Span) -> Value {
Value::CustomValue { val, span }
}
pub fn lazy_record(val: Box<dyn for<'a> LazyRecord<'a>>, span: Span) -> Value {
Value::LazyRecord { val, span }
}
pub fn match_pattern(val: MatchPattern, span: Span) -> Value {
Value::MatchPattern {
val: Box::new(val),
span,
} }
} }
/// Note: Only use this for test data, *not* live data, as it will point into unknown source /// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors. /// when used in errors.
pub fn test_bool(val: bool) -> Value { pub fn test_bool(val: bool) -> Value {
Value::Bool { Value::bool(val, Span::test_data())
val,
span: Span::test_data(),
} }
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_int(val: i64) -> Value {
Value::int(val, Span::test_data())
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_float(val: f64) -> Value {
Value::float(val, Span::test_data())
} }
/// Note: Only use this for test data, *not* live data, as it will point into unknown source /// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors. /// when used in errors.
pub fn test_filesize(val: i64) -> Value { pub fn test_filesize(val: i64) -> Value {
Value::Filesize { Value::filesize(val, Span::test_data())
val,
span: Span::test_data(),
}
} }
/// Note: Only use this for test data, *not* live data, as it will point into unknown source /// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors. /// when used in errors.
pub fn test_nothing() -> Value { pub fn test_duration(val: i64) -> Value {
Value::Nothing { Value::duration(val, Span::test_data())
span: Span::test_data(),
}
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_record(cols: Vec<impl Into<String>>, vals: Vec<Value>) -> Value {
Value::Record {
cols: cols.into_iter().map(|s| s.into()).collect(),
vals,
span: Span::test_data(),
}
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_list(vals: Vec<Value>) -> Value {
Value::List {
vals,
span: Span::test_data(),
}
} }
/// Note: Only use this for test data, *not* live data, as it will point into unknown source /// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors. /// when used in errors.
pub fn test_date(val: DateTime<FixedOffset>) -> Value { pub fn test_date(val: DateTime<FixedOffset>) -> Value {
Value::Date { Value::date(val, Span::test_data())
val,
span: Span::test_data(),
} }
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_range(val: Range) -> Value {
Value::range(val, Span::test_data())
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_string(val: impl Into<String>) -> Value {
Value::string(val, Span::test_data())
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_record(cols: Vec<impl Into<String>>, vals: Vec<Value>) -> Value {
Value::record(
cols.into_iter().map(|s| s.into()).collect(),
vals,
Span::test_data(),
)
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_list(vals: Vec<Value>) -> Value {
Value::list(vals, Span::test_data())
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_block(val: BlockId) -> Value {
Value::block(val, Span::test_data())
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_closure(val: BlockId, captures: HashMap<VarId, Value>) -> Value {
Value::closure(val, captures, Span::test_data())
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_nothing() -> Value {
Value::nothing(Span::test_data())
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_binary(val: impl Into<Vec<u8>>) -> Value {
Value::binary(val, Span::test_data())
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_cell_path(val: CellPath) -> Value {
Value::cell_path(val, Span::test_data())
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_custom_value(val: Box<dyn CustomValue>) -> Value {
Value::custom_value(val, Span::test_data())
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_lazy_record(val: Box<dyn for<'a> LazyRecord<'a>>) -> Value {
Value::lazy_record(val, Span::test_data())
}
/// Note: Only use this for test data, *not* live data, as it will point into unknown source
/// when used in errors.
pub fn test_match_pattern(val: MatchPattern) -> Value {
Value::match_pattern(val, Span::test_data())
} }
} }
@ -3892,7 +4089,7 @@ mod tests {
vals: vec![ vals: vec![
Value::int(0, Span::unknown()), Value::int(0, Span::unknown()),
Value::float(0.0, Span::unknown()), Value::float(0.0, Span::unknown()),
Value::boolean(false, Span::unknown()), Value::bool(false, Span::unknown()),
], ],
span: Span::unknown(), span: Span::unknown(),
}; };

View file

@ -105,11 +105,11 @@ impl Range {
} }
pub fn from(&self) -> Result<i64, ShellError> { pub fn from(&self) -> Result<i64, ShellError> {
self.from.as_integer() self.from.as_int()
} }
pub fn to(&self) -> Result<i64, ShellError> { pub fn to(&self) -> Result<i64, ShellError> {
let to = self.to.as_integer()?; let to = self.to.as_int()?;
if self.is_end_inclusive() { if self.is_end_inclusive() {
Ok(to) Ok(to)
} else { } else {

View file

@ -82,7 +82,7 @@ fn convert_gjson_value_to_nu_value(v: &gjValue, span: &Span) -> Value {
Value::List { vals, span: *span } Value::List { vals, span: *span }
} }
gjson::Kind::Null => Value::nothing(*span), gjson::Kind::Null => Value::nothing(*span),
gjson::Kind::False => Value::boolean(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('.') {
@ -92,7 +92,7 @@ fn convert_gjson_value_to_nu_value(v: &gjValue, span: &Span) -> Value {
} }
} }
gjson::Kind::String => Value::string(v.str(), *span), gjson::Kind::String => Value::string(v.str(), *span),
gjson::Kind::True => Value::boolean(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![];

View file

@ -66,7 +66,7 @@ pub fn execute_xpath_query(
} }
sxd_xpath::Value::Boolean(b) => { sxd_xpath::Value::Boolean(b) => {
cols.push(key.to_string()); cols.push(key.to_string());
vals.push(Value::boolean(b, call.head)); vals.push(Value::bool(b, call.head));
} }
sxd_xpath::Value::Number(n) => { sxd_xpath::Value::Number(n) => {
cols.push(key.to_string()); cols.push(key.to_string());

View file

@ -189,7 +189,7 @@ pub(crate) fn run_file(
let start_time = std::time::Instant::now(); let start_time = std::time::Instant::now();
let last_exit_code = stack.get_env_var(&*engine_state, "LAST_EXIT_CODE"); let last_exit_code = stack.get_env_var(&*engine_state, "LAST_EXIT_CODE");
if let Some(last_exit_code) = last_exit_code { if let Some(last_exit_code) = last_exit_code {
let value = last_exit_code.as_integer(); let value = last_exit_code.as_int();
if let Ok(value) = value { if let Ok(value) = value {
if value != 0 { if value != 0 {
std::process::exit(value as i32); std::process::exit(value as i32);