Move Value to helpers, separate span call (#10121)

# Description

As part of the refactor to split spans off of Value, this moves to using
helper functions to create values, and using `.span()` instead of
matching span out of Value directly.

Hoping to get a few more helping hands to finish this, as there are a
lot of commands to update :)

# User-Facing Changes
<!-- List of all changes that impact the user experience here. This
helps us keep track of breaking changes. -->

# Tests + Formatting
<!--
Don't forget to add tests that cover your changes.

Make sure you've run and fixed any issues with these commands:

- `cargo fmt --all -- --check` to check standard code formatting (`cargo
fmt --all` applies these changes)
- `cargo clippy --workspace -- -D warnings -D clippy::unwrap_used` to
check that you're using the standard code style
- `cargo test --workspace` to check that all tests pass (on Windows make
sure to [enable developer
mode](https://learn.microsoft.com/en-us/windows/apps/get-started/developer-mode-features-and-debugging))
- `cargo run -- -c "use std testing; testing run-tests --path
crates/nu-std"` to run the tests for the standard library

> **Note**
> from `nushell` you can also use the `toolkit` as follows
> ```bash
> use toolkit.nu # or use an `env_change` hook to activate it
automatically
> toolkit check pr
> ```
-->

# After Submitting
<!-- If your PR had any user-facing changes, update [the
documentation](https://github.com/nushell/nushell.github.io) after the
PR is merged, if necessary. This will help us keep the docs up to date.
-->

---------

Co-authored-by: Darren Schroeder <343840+fdncred@users.noreply.github.com>
Co-authored-by: WindSoilder <windsoilder@outlook.com>
This commit is contained in:
JT
2023-09-04 02:27:29 +12:00
committed by GitHub
parent af79eb2943
commit 6cdfee3573
372 changed files with 5811 additions and 7448 deletions

View File

@ -326,19 +326,19 @@ impl Value {
// $env.config.ls.use_ls_colors = 2 results in an error, so
// the current use_ls_colors config setting is converted to a Value::Boolean and inserted in the
// record in place of the 2.
if let Value::Record { val, span } = self {
if let Value::Record { val, .. } = self {
let Record { cols, vals } = val;
let span = *span;
// Because this whole algorithm removes while iterating, this must iterate in reverse.
for index in (0..cols.len()).rev() {
let value = &vals[index];
let key = cols[index].as_str();
let span = vals[index].span();
match key {
// Grouped options
"ls" => {
if let Value::Record { val, span } = &mut vals[index] {
if let Value::Record { val, .. } = &mut vals[index] {
let Record { cols, vals } = val;
let span = *span;
for index in (0..cols.len()).rev() {
let value = &vals[index];
let key2 = cols[index].as_str();
@ -377,14 +377,14 @@ impl Value {
}
}
"cd" => {
if let Value::Record { val, span } = &mut vals[index] {
if let Value::Record { val, .. } = &mut vals[index] {
let Record { cols, vals } = val;
for index in (0..cols.len()).rev() {
let value = &vals[index];
let key2 = cols[index].as_str();
match key2 {
"abbreviations" => {
try_bool!(cols, vals, index, *span, cd_with_abbreviations)
try_bool!(cols, vals, index, span, cd_with_abbreviations)
}
x => {
invalid_key!(
@ -410,14 +410,14 @@ impl Value {
}
}
"rm" => {
if let Value::Record { val, span } = &mut vals[index] {
if let Value::Record { val, .. } = &mut vals[index] {
let Record { cols, vals } = val;
for index in (0..cols.len()).rev() {
let value = &vals[index];
let key2 = cols[index].as_str();
match key2 {
"always_trash" => {
try_bool!(cols, vals, index, *span, rm_always_trash)
try_bool!(cols, vals, index, span, rm_always_trash)
}
x => {
invalid_key!(
@ -453,9 +453,8 @@ impl Value {
)
};
}
if let Value::Record { val, span } = &mut vals[index] {
if let Value::Record { val, .. } = &mut vals[index] {
let Record { cols, vals } = val;
let span = *span;
for index in (0..cols.len()).rev() {
let value = &vals[index];
let key2 = cols[index].as_str();
@ -525,12 +524,9 @@ impl Value {
macro_rules! reconstruct_external_completer {
($span: expr) => {
if let Some(block) = config.external_completer {
Value::Block {
val: block,
span: $span,
}
Value::block(block, $span)
} else {
Value::Nothing { span: $span }
Value::nothing($span)
}
};
}
@ -546,9 +542,8 @@ impl Value {
)
};
}
if let Value::Record { val, span } = &mut vals[index] {
if let Value::Record { val, .. } = &mut vals[index] {
let Record { cols, vals } = val;
let span = *span;
for index in (0..cols.len()).rev() {
let value = &vals[index];
let key2 = cols[index].as_str();
@ -597,9 +592,8 @@ impl Value {
)
}
"external" => {
if let Value::Record { val, span } = &mut vals[index] {
if let Value::Record { val, .. } = &mut vals[index] {
let Record { cols, vals } = val;
let span = *span;
for index in (0..cols.len()).rev() {
let value = &vals[index];
let key3 = cols[index].as_str();
@ -700,9 +694,8 @@ impl Value {
)
};
}
if let Value::Record { val, span } = &mut vals[index] {
if let Value::Record { val, .. } = &mut vals[index] {
let Record { cols, vals } = val;
let span = *span;
for index in (0..cols.len()).rev() {
let value = &vals[index];
let key2 = cols[index].as_str();
@ -905,7 +898,7 @@ impl Value {
},
None => record! {
"methodology" => Value::string("truncating", $span),
"truncating_suffix" => Value::Nothing { span: $span },
"truncating_suffix" => Value::nothing($span),
},
},
$span,
@ -913,9 +906,8 @@ impl Value {
}
};
}
if let Value::Record { val, span } = &mut vals[index] {
if let Value::Record { val, .. } = &mut vals[index] {
let Record { cols, vals } = val;
let span = *span;
for index in (0..cols.len()).rev() {
let value = &vals[index];
let key2 = cols[index].as_str();
@ -1046,9 +1038,8 @@ impl Value {
}
}
"filesize" => {
if let Value::Record { val, span } = &mut vals[index] {
if let Value::Record { val, .. } = &mut vals[index] {
let Record { cols, vals } = val;
let span = *span;
for index in (0..cols.len()).rev() {
let value = &vals[index];
let key2 = cols[index].as_str();
@ -1140,15 +1131,15 @@ impl Value {
} else {
invalid!(Some(span), "should be a string");
// Reconstruct
vals[index] = Value::String {
val: match config.footer_mode {
vals[index] = Value::string(
match config.footer_mode {
FooterMode::Auto => "auto".into(),
FooterMode::Never => "never".into(),
FooterMode::Always => "always".into(),
FooterMode::RowCount(number) => number.to_string(),
},
span,
};
);
}
}
"float_precision" => {
@ -1192,8 +1183,7 @@ impl Value {
invalid!(Some(span), "should be a valid list of menus");
errors.push(e);
// Reconstruct
vals[index] = Value::List {
vals: config
vals[index] = Value::list(config
.menus
.iter()
.map(
@ -1220,7 +1210,7 @@ impl Value {
)
.collect(),
span,
}
)
}
},
// Keybindings
@ -1230,8 +1220,8 @@ impl Value {
invalid!(Some(span), "should be a valid keybindings list");
errors.push(e);
// Reconstruct
vals[index] = Value::List {
vals: config
vals[index] = Value::list(
config
.keybindings
.iter()
.map(
@ -1254,7 +1244,7 @@ impl Value {
)
.collect(),
span,
}
)
}
},
// Hooks
@ -1281,9 +1271,8 @@ impl Value {
}
},
"datetime_format" => {
if let Value::Record { val, span } = &mut vals[index] {
if let Value::Record { val, .. } = &mut vals[index] {
let Record { cols, vals } = val;
let span = *span;
for index in (0..cols.len()).rev() {
let value = &vals[index];
let key2 = cols[index].as_str();
@ -1475,8 +1464,9 @@ fn create_map(value: &Value) -> Result<HashMap<String, Value>, ShellError> {
// Parse the hooks to find the blocks to run when the hooks fire
fn create_hooks(value: &Value) -> Result<Hooks, ShellError> {
let span = value.span();
match value {
Value::Record { val, span } => {
Value::Record { val, .. } => {
let mut hooks = Hooks::new();
for (col, val) in val {
@ -1491,7 +1481,7 @@ fn create_hooks(value: &Value) -> Result<Hooks, ShellError> {
"'pre_prompt', 'pre_execution', 'env_change', 'display_output', 'command_not_found'"
.to_string(),
x.to_string(),
*span,
span,
));
}
}
@ -1499,19 +1489,19 @@ fn create_hooks(value: &Value) -> Result<Hooks, ShellError> {
Ok(hooks)
}
v => Err(ShellError::UnsupportedConfigValue(
_ => Err(ShellError::UnsupportedConfigValue(
"record for 'hooks' config".into(),
"non-record value".into(),
v.span(),
span,
)),
}
}
// Parses the config object to extract the strings that will compose a keybinding for reedline
fn create_keybindings(value: &Value) -> Result<Vec<ParsedKeybinding>, ShellError> {
let span = value.span();
match value {
Value::Record { val, span } => {
let span = *span;
Value::Record { val, .. } => {
// Finding the modifier value in the record
let modifier = extract_value("modifier", val, span)?.clone();
let keycode = extract_value("keycode", val, span)?.clone();
@ -1547,9 +1537,9 @@ fn create_keybindings(value: &Value) -> Result<Vec<ParsedKeybinding>, ShellError
// Parses the config object to extract the strings that will compose a keybinding for reedline
pub fn create_menus(value: &Value) -> Result<Vec<ParsedMenu>, ShellError> {
let span = value.span();
match value {
Value::Record { val, span } => {
let span = *span;
Value::Record { val, .. } => {
// Finding the modifier value in the record
let name = extract_value("name", val, span)?.clone();
let marker = extract_value("marker", val, span)?.clone();
@ -1561,7 +1551,7 @@ pub fn create_menus(value: &Value) -> Result<Vec<ParsedMenu>, ShellError> {
// Source is an optional value
let source = match extract_value("source", val, span) {
Ok(source) => source.clone(),
Err(_) => Value::Nothing { span },
Err(_) => Value::nothing(span),
};
let menu = ParsedMenu {

View File

@ -75,13 +75,7 @@ impl Matcher for Pattern {
}
Pattern::Rest(var_id) => {
let rest_vals = vals[val_idx..].to_vec();
matches.push((
*var_id,
Value::List {
vals: rest_vals,
span: pattern.span,
},
));
matches.push((*var_id, Value::list(rest_vals, pattern.span)));
break;
}
_ => {

View File

@ -244,22 +244,13 @@ pub fn eval_constant(
Expr::Bool(b) => Ok(Value::bool(*b, expr.span)),
Expr::Int(i) => Ok(Value::int(*i, expr.span)),
Expr::Float(f) => Ok(Value::float(*f, expr.span)),
Expr::Binary(b) => Ok(Value::Binary {
val: b.clone(),
span: expr.span,
}),
Expr::Filepath(path) => Ok(Value::String {
val: path.clone(),
span: expr.span,
}),
Expr::Binary(b) => Ok(Value::binary(b.clone(), expr.span)),
Expr::Filepath(path) => Ok(Value::string(path.clone(), expr.span)),
Expr::Var(var_id) => match working_set.get_variable(*var_id).const_val.as_ref() {
Some(val) => Ok(val.clone()),
None => Err(ShellError::NotAConstant(expr.span)),
},
Expr::CellPath(cell_path) => Ok(Value::CellPath {
val: cell_path.clone(),
span: expr.span,
}),
Expr::CellPath(cell_path) => Ok(Value::cell_path(cell_path.clone(), expr.span)),
Expr::FullCellPath(cell_path) => {
let value = eval_constant(working_set, &cell_path.head)?;
@ -275,19 +266,13 @@ pub fn eval_constant(
)),
}
}
Expr::DateTime(dt) => Ok(Value::Date {
val: *dt,
span: expr.span,
}),
Expr::DateTime(dt) => Ok(Value::date(*dt, expr.span)),
Expr::List(x) => {
let mut output = vec![];
for expr in x {
output.push(eval_constant(working_set, expr)?);
}
Ok(Value::List {
vals: output,
span: expr.span,
})
Ok(Value::list(output, expr.span))
}
Expr::Record(fields) => {
let mut record = Record::new();
@ -330,17 +315,11 @@ pub fn eval_constant(
expr.span,
));
}
Ok(Value::List {
vals: output_rows,
span: expr.span,
})
Ok(Value::list(output_rows, expr.span))
}
Expr::Keyword(_, _, expr) => eval_constant(working_set, expr),
Expr::String(s) => Ok(Value::String {
val: s.clone(),
span: expr.span,
}),
Expr::Nothing => Ok(Value::Nothing { span: expr.span }),
Expr::String(s) => Ok(Value::string(s.clone(), expr.span)),
Expr::Nothing => Ok(Value::nothing(expr.span)),
Expr::ValueWithUnit(expr, unit) => {
if let Ok(Value::Int { val, .. }) = eval_constant(working_set, expr) {
unit.item.to_value(val, unit.span)

View File

@ -69,7 +69,7 @@ pub enum DataSource {
impl PipelineData {
pub fn new_with_metadata(metadata: Option<Box<PipelineMetadata>>, span: Span) -> PipelineData {
PipelineData::Value(Value::Nothing { span }, metadata)
PipelineData::Value(Value::nothing(span), metadata)
}
/// create a `PipelineData::ExternalStream` with proper exit_code
@ -133,10 +133,10 @@ impl PipelineData {
PipelineData::Empty => Value::nothing(span),
PipelineData::Value(Value::Nothing { .. }, ..) => Value::nothing(span),
PipelineData::Value(v, ..) => v.with_span(span),
PipelineData::ListStream(s, ..) => Value::List {
vals: s.collect(),
PipelineData::ListStream(s, ..) => Value::list(
s.collect(),
span, // FIXME?
},
),
PipelineData::ExternalStream {
stdout: None,
exit_code,
@ -146,7 +146,7 @@ impl PipelineData {
if let Some(exit_code) = exit_code {
let _: Vec<_> = exit_code.into_iter().collect();
}
Value::Nothing { span }
Value::nothing(span)
}
PipelineData::ExternalStream {
stdout: Some(mut s),
@ -162,10 +162,7 @@ impl PipelineData {
items.push(val);
}
Err(e) => {
return Value::Error {
error: Box::new(e),
span,
};
return Value::error(e, span);
}
}
}
@ -185,38 +182,30 @@ impl PipelineData {
output.extend(item);
}
Err(err) => {
return Value::Error {
error: Box::new(err),
span,
};
return Value::error(err, span);
}
}
}
Value::Binary {
val: output,
span, // FIXME?
}
Value::binary(
output, span, // FIXME?
)
} else {
let mut output = String::new();
for item in items {
match item.as_string() {
Ok(s) => output.push_str(&s),
Err(err) => {
return Value::Error {
error: Box::new(err),
span,
};
return Value::error(err, span);
}
}
}
if trim_end_newline {
output.truncate(output.trim_end_matches(LINE_ENDING_PATTERN).len())
}
Value::String {
val: output,
span, // FIXME?
}
Value::string(
output, span, // FIXME?
)
}
}
}
@ -288,7 +277,7 @@ impl PipelineData {
},
metadata,
))),
Value::Binary { val, span } => Ok(PipelineIterator(PipelineData::ListStream(
Value::Binary { val, .. } => Ok(PipelineIterator(PipelineData::ListStream(
ListStream {
stream: Box::new(val.into_iter().map(move |x| Value::int(x as i64, span))),
ctrlc: None,
@ -368,7 +357,7 @@ impl PipelineData {
) -> Result<(String, Span, Option<Box<PipelineMetadata>>), ShellError> {
match self {
PipelineData::Empty => Ok((String::new(), span, None)),
PipelineData::Value(Value::String { val, span }, metadata) => Ok((val, span, metadata)),
PipelineData::Value(Value::String { val, .. }, metadata) => Ok((val, span, metadata)),
PipelineData::Value(val, _) => Err(ShellError::TypeMismatch {
err_message: "string".into(),
span: val.span(),
@ -400,11 +389,9 @@ impl PipelineData {
) -> Result<Value, ShellError> {
match self {
// FIXME: there are probably better ways of doing this
PipelineData::ListStream(stream, ..) => Value::List {
vals: stream.collect(),
span: head,
PipelineData::ListStream(stream, ..) => {
Value::list(stream.collect(), head).follow_cell_path(cell_path, insensitive)
}
.follow_cell_path(cell_path, insensitive),
PipelineData::Value(v, ..) => v.follow_cell_path(cell_path, insensitive),
_ => Err(ShellError::IOError("can't follow stream paths".into())),
}
@ -418,11 +405,9 @@ impl PipelineData {
) -> Result<(), ShellError> {
match self {
// FIXME: there are probably better ways of doing this
PipelineData::ListStream(stream, ..) => Value::List {
vals: stream.collect(),
span: head,
PipelineData::ListStream(stream, ..) => {
Value::list(stream.collect(), head).upsert_cell_path(cell_path, callback)
}
.upsert_cell_path(cell_path, callback),
PipelineData::Value(v, ..) => v.upsert_cell_path(cell_path, callback),
_ => Ok(()),
}
@ -456,17 +441,9 @@ impl PipelineData {
if trim_end_newline {
st.truncate(st.trim_end_matches(LINE_ENDING_PATTERN).len());
}
Ok(f(Value::String {
val: st,
span: collected.span,
})
.into_pipeline_data())
Ok(f(Value::string(st, collected.span)).into_pipeline_data())
} else {
Ok(f(Value::Binary {
val: collected.item,
span: collected.span,
})
.into_pipeline_data())
Ok(f(Value::binary(collected.item, collected.span)).into_pipeline_data())
}
}
@ -513,19 +490,13 @@ impl PipelineData {
if trim_end_newline {
st.truncate(st.trim_end_matches(LINE_ENDING_PATTERN).len())
}
Ok(f(Value::String {
val: st,
span: collected.span,
})
.into_iter()
.into_pipeline_data(ctrlc))
Ok(f(Value::string(st, collected.span))
.into_iter()
.into_pipeline_data(ctrlc))
} else {
Ok(f(Value::Binary {
val: collected.item,
span: collected.span,
})
.into_iter()
.into_pipeline_data(ctrlc))
Ok(f(Value::binary(collected.item, collected.span))
.into_iter()
.into_pipeline_data(ctrlc))
}
}
PipelineData::Value(Value::Range { val, .. }, ..) => Ok(val
@ -563,10 +534,7 @@ impl PipelineData {
if trim_end_newline {
st.truncate(st.trim_end_matches(LINE_ENDING_PATTERN).len())
}
let v = Value::String {
val: st,
span: collected.span,
};
let v = Value::string(st, collected.span);
if f(&v) {
Ok(v.into_pipeline_data())
@ -574,10 +542,7 @@ impl PipelineData {
Ok(PipelineData::new_with_metadata(None, collected.span))
}
} else {
let v = Value::Binary {
val: collected.item,
span: collected.span,
};
let v = Value::binary(collected.item, collected.span);
if f(&v) {
Ok(v.into_pipeline_data())
@ -594,7 +559,7 @@ impl PipelineData {
if f(&v) {
Ok(v.into_pipeline_data())
} else {
Ok(Value::Nothing { span: v.span() }.into_pipeline_data())
Ok(Value::nothing(v.span()).into_pipeline_data())
}
}
}
@ -691,43 +656,43 @@ impl PipelineData {
/// `1..3 | to XX -> [1,2,3]`
pub fn try_expand_range(self) -> Result<PipelineData, ShellError> {
let input = match self {
PipelineData::Value(Value::Range { val, span }, ..) => {
match (&val.to, &val.from) {
(Value::Float { val, .. }, _) | (_, Value::Float { val, .. }) => {
if *val == f64::INFINITY || *val == f64::NEG_INFINITY {
return Err(ShellError::GenericError(
"Cannot create range".into(),
"Infinity is not allowed when converting to json".into(),
Some(span),
Some("Consider removing infinity".into()),
vec![],
));
PipelineData::Value(v, metadata) => match v {
Value::Range { val, .. } => {
let span = val.to.span();
match (&val.to, &val.from) {
(Value::Float { val, .. }, _) | (_, Value::Float { val, .. }) => {
if *val == f64::INFINITY || *val == f64::NEG_INFINITY {
return Err(ShellError::GenericError(
"Cannot create range".into(),
"Infinity is not allowed when converting to json".into(),
Some(span),
Some("Consider removing infinity".into()),
vec![],
));
}
}
}
(Value::Int { val, span }, _) => {
if *val == i64::MAX || *val == i64::MIN {
return Err(ShellError::GenericError(
"Cannot create range".into(),
"Unbounded ranges are not allowed when converting to json".into(),
Some(*span),
Some(
"Consider using ranges with valid start and end point.".into(),
),
vec![],
));
(Value::Int { val, .. }, _) => {
if *val == i64::MAX || *val == i64::MIN {
return Err(ShellError::GenericError(
"Cannot create range".into(),
"Unbounded ranges are not allowed when converting to json"
.into(),
Some(span),
Some(
"Consider using ranges with valid start and end point."
.into(),
),
vec![],
));
}
}
_ => (),
}
_ => (),
let range_values: Vec<Value> = val.into_range_iter(None)?.collect();
PipelineData::Value(Value::list(range_values, span), None)
}
let range_values: Vec<Value> = val.into_range_iter(None)?.collect();
PipelineData::Value(
Value::List {
vals: range_values,
span,
},
None,
)
}
x => PipelineData::Value(x, metadata),
},
_ => self,
};
Ok(input)
@ -847,34 +812,33 @@ impl IntoIterator for PipelineData {
fn into_iter(self) -> Self::IntoIter {
match self {
PipelineData::Value(Value::List { vals, .. }, metadata) => {
PipelineIterator(PipelineData::ListStream(
ListStream {
stream: Box::new(vals.into_iter()),
ctrlc: None,
PipelineData::Value(v, metadata) => {
let span = v.span();
match v {
Value::List { vals, .. } => PipelineIterator(PipelineData::ListStream(
ListStream {
stream: Box::new(vals.into_iter()),
ctrlc: None,
},
metadata,
)),
Value::Range { val, .. } => match val.into_range_iter(None) {
Ok(iter) => PipelineIterator(PipelineData::ListStream(
ListStream {
stream: Box::new(iter),
ctrlc: None,
},
metadata,
)),
Err(error) => PipelineIterator(PipelineData::ListStream(
ListStream {
stream: Box::new(std::iter::once(Value::error(error, span))),
ctrlc: None,
},
metadata,
)),
},
metadata,
))
}
PipelineData::Value(Value::Range { val, span }, metadata) => {
match val.into_range_iter(None) {
Ok(iter) => PipelineIterator(PipelineData::ListStream(
ListStream {
stream: Box::new(iter),
ctrlc: None,
},
metadata,
)),
Err(error) => PipelineIterator(PipelineData::ListStream(
ListStream {
stream: Box::new(std::iter::once(Value::Error {
error: Box::new(error),
span,
})),
ctrlc: None,
},
metadata,
)),
x => PipelineIterator(PipelineData::Value(x, metadata)),
}
}
x => PipelineIterator(x),
@ -941,10 +905,10 @@ impl Iterator for PipelineIterator {
..
} => stream.next().map(|x| match x {
Ok(x) => x,
Err(err) => Value::Error {
error: Box::new(err),
span: Span::unknown(), //FIXME: unclear where this span should come from
},
Err(err) => Value::error(
err,
Span::unknown(), //FIXME: unclear where this span should come from
),
}),
}
}

View File

@ -19,19 +19,11 @@ impl FromValue for Value {
impl FromValue for Spanned<i64> {
fn from_value(v: &Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Int { val, span } => Ok(Spanned {
item: *val,
span: *span,
}),
Value::Filesize { val, span } => Ok(Spanned {
item: *val,
span: *span,
}),
Value::Duration { val, span } => Ok(Spanned {
item: *val,
span: *span,
}),
Value::Int { val, .. } => Ok(Spanned { item: *val, span }),
Value::Filesize { val, .. } => Ok(Spanned { item: *val, span }),
Value::Duration { val, .. } => Ok(Spanned { item: *val, span }),
v => Err(ShellError::CantConvert {
to_type: "integer".into(),
@ -62,15 +54,13 @@ impl FromValue for i64 {
impl FromValue for Spanned<f64> {
fn from_value(v: &Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Int { val, span } => Ok(Spanned {
Value::Int { val, .. } => Ok(Spanned {
item: *val as f64,
span: *span,
}),
Value::Float { val, span } => Ok(Spanned {
item: *val,
span: *span,
span,
}),
Value::Float { val, .. } => Ok(Spanned { item: *val, span }),
v => Err(ShellError::CantConvert {
to_type: "float".into(),
@ -99,34 +89,35 @@ impl FromValue for f64 {
impl FromValue for Spanned<usize> {
fn from_value(v: &Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Int { val, span } => {
Value::Int { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue(*span))
Err(ShellError::NeedsPositiveValue(span))
} else {
Ok(Spanned {
item: *val as usize,
span: *span,
span,
})
}
}
Value::Filesize { val, span } => {
Value::Filesize { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue(*span))
Err(ShellError::NeedsPositiveValue(span))
} else {
Ok(Spanned {
item: *val as usize,
span: *span,
span,
})
}
}
Value::Duration { val, span } => {
Value::Duration { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue(*span))
Err(ShellError::NeedsPositiveValue(span))
} else {
Ok(Spanned {
item: *val as usize,
span: *span,
span,
})
}
}
@ -143,24 +134,25 @@ impl FromValue for Spanned<usize> {
impl FromValue for usize {
fn from_value(v: &Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Int { val, span } => {
Value::Int { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue(*span))
Err(ShellError::NeedsPositiveValue(span))
} else {
Ok(*val as usize)
}
}
Value::Filesize { val, span } => {
Value::Filesize { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue(*span))
Err(ShellError::NeedsPositiveValue(span))
} else {
Ok(*val as usize)
}
}
Value::Duration { val, span } => {
Value::Duration { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue(*span))
Err(ShellError::NeedsPositiveValue(span))
} else {
Ok(*val as usize)
}
@ -244,17 +236,20 @@ impl FromValue for Vec<Spanned<String>> {
match v {
Value::List { vals, .. } => vals
.iter()
.map(|val| match val {
Value::String { val, span } => Ok(Spanned {
item: val.clone(),
span: *span,
}),
c => Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: c.get_type().to_string(),
span: c.span(),
help: None,
}),
.map(|val| {
let val_span = val.span();
match val {
Value::String { val, .. } => Ok(Spanned {
item: val.clone(),
span: val_span,
}),
c => Err(ShellError::CantConvert {
to_type: "string".into(),
from_type: c.get_type().to_string(),
span: c.span(),
help: None,
}),
}
})
.collect::<Result<Vec<Spanned<String>>, ShellError>>(),
v => Err(ShellError::CantConvert {
@ -304,14 +299,14 @@ impl FromValue for CellPath {
optional: false,
}],
}),
Value::Int { val, span } => {
Value::Int { val, .. } => {
if val.is_negative() {
Err(ShellError::NeedsPositiveValue(*span))
Err(ShellError::NeedsPositiveValue(span))
} else {
Ok(CellPath {
members: vec![PathMember::Int {
val: *val as usize,
span: *span,
span,
optional: false,
}],
})
@ -343,11 +338,9 @@ impl FromValue for bool {
impl FromValue for Spanned<bool> {
fn from_value(v: &Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Bool { val, span } => Ok(Spanned {
item: *val,
span: *span,
}),
Value::Bool { val, .. } => Ok(Spanned { item: *val, span }),
v => Err(ShellError::CantConvert {
to_type: "bool".into(),
from_type: v.get_type().to_string(),
@ -374,11 +367,9 @@ impl FromValue for DateTime<FixedOffset> {
impl FromValue for Spanned<DateTime<FixedOffset>> {
fn from_value(v: &Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Date { val, span } => Ok(Spanned {
item: *val,
span: *span,
}),
Value::Date { val, .. } => Ok(Spanned { item: *val, span }),
v => Err(ShellError::CantConvert {
to_type: "date".into(),
from_type: v.get_type().to_string(),
@ -405,10 +396,11 @@ impl FromValue for Range {
impl FromValue for Spanned<Range> {
fn from_value(v: &Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Range { val, span } => Ok(Spanned {
Value::Range { val, .. } => Ok(Spanned {
item: (**val).clone(),
span: *span,
span,
}),
v => Err(ShellError::CantConvert {
to_type: "range".into(),
@ -437,14 +429,15 @@ impl FromValue for Vec<u8> {
impl FromValue for Spanned<Vec<u8>> {
fn from_value(v: &Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Binary { val, span } => Ok(Spanned {
Value::Binary { val, .. } => Ok(Spanned {
item: val.clone(),
span: *span,
span,
}),
Value::String { val, span } => Ok(Spanned {
Value::String { val, .. } => Ok(Spanned {
item: val.bytes().collect(),
span: *span,
span,
}),
v => Err(ShellError::CantConvert {
to_type: "binary data".into(),
@ -458,11 +451,12 @@ impl FromValue for Spanned<Vec<u8>> {
impl FromValue for Spanned<PathBuf> {
fn from_value(v: &Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::String { val, span } => Ok(Spanned {
Value::String { val, .. } => Ok(Spanned {
item: PathBuf::from_str(val)
.map_err(|err| ShellError::FileNotFoundCustom(err.to_string(), *span))?,
span: *span,
.map_err(|err| ShellError::FileNotFoundCustom(err.to_string(), span))?,
span,
}),
v => Err(ShellError::CantConvert {
to_type: "range".into(),
@ -540,17 +534,14 @@ impl FromValue for Block {
impl FromValue for Spanned<Closure> {
fn from_value(v: &Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::Closure {
val,
captures,
span,
} => Ok(Spanned {
Value::Closure { val, captures, .. } => Ok(Spanned {
item: Closure {
block_id: *val,
captures: captures.clone(),
},
span: *span,
span,
}),
v => Err(ShellError::CantConvert {
to_type: "Closure".into(),
@ -564,10 +555,11 @@ impl FromValue for Spanned<Closure> {
impl FromValue for Spanned<MatchPattern> {
fn from_value(v: &Value) -> Result<Self, ShellError> {
let span = v.span();
match v {
Value::MatchPattern { val, span } => Ok(Spanned {
Value::MatchPattern { val, .. } => Ok(Spanned {
item: *val.clone(),
span: *span,
span,
}),
v => Err(ShellError::CantConvert {
to_type: "Match pattern".into(),

File diff suppressed because it is too large Load Diff

View File

@ -171,15 +171,12 @@ impl RangeIterator {
let is_end_inclusive = range.is_end_inclusive();
let start = match range.from {
Value::Nothing { .. } => Value::Int { val: 0, span },
Value::Nothing { .. } => Value::int(0, span),
x => x,
};
let end = match range.to {
Value::Nothing { .. } => Value::Int {
val: i64::MAX,
span,
},
Value::Nothing { .. } => Value::int(i64::MAX, span),
x => x,
};
@ -215,10 +212,9 @@ impl Iterator for RangeIterator {
let Some(ordering) = ordering else {
self.done = true;
return Some(Value::Error {
error: Box::new(ShellError::CannotCreateRange { span: self.span }),
span: self.span,
});
return Some(Value::error(ShellError::CannotCreateRange { span: self.span },
self.span,
));
};
let desired_ordering = if self.moves_up {
@ -236,10 +232,7 @@ impl Iterator for RangeIterator {
Err(error) => {
self.done = true;
return Some(Value::Error {
error: Box::new(error),
span: self.span,
});
return Some(Value::error(error, self.span));
}
};
std::mem::swap(&mut self.curr, &mut next);

View File

@ -108,10 +108,7 @@ impl Iterator for RawStream {
v.insert(0, b);
}
}
Value::Binary {
val: v,
span: self.span,
}
Value::binary(v, self.span)
})
})
} else {
@ -129,10 +126,7 @@ impl Iterator for RawStream {
match String::from_utf8(v.clone()) {
Ok(s) => {
// Great, we have a complete string, let's output it
Some(Ok(Value::String {
val: s,
span: self.span,
}))
Some(Ok(Value::string(s, self.span)))
}
Err(err) => {
// Okay, we *might* have a string but we've also got some errors
@ -146,10 +140,7 @@ impl Iterator for RawStream {
// that it's not just a character spanning two frames.
// We now know we are definitely binary, so switch to binary and stay there.
self.is_binary = true;
Some(Ok(Value::Binary {
val: v,
span: self.span,
}))
Some(Ok(Value::binary(v, self.span)))
} else {
// Okay, we have a tiny bit of error at the end of the buffer. This could very well be
// a character that spans two frames. Since this is the case, remove the error from
@ -159,17 +150,11 @@ impl Iterator for RawStream {
let buf = v[0..err.utf8_error().valid_up_to()].to_vec();
match String::from_utf8(buf) {
Ok(s) => Some(Ok(Value::String {
val: s,
span: self.span,
})),
Ok(s) => Some(Ok(Value::string(s, self.span))),
Err(_) => {
// Something is definitely wrong. Switch to binary, and stay there
self.is_binary = true;
Some(Ok(Value::Binary {
val: v,
span: self.span,
}))
Some(Ok(Value::binary(v, self.span)))
}
}
}
@ -179,10 +164,7 @@ impl Iterator for RawStream {
Err(e) => Some(Err(e)),
}
} else if !self.leftover.is_empty() {
let output = Ok(Value::Binary {
val: self.leftover.clone(),
span: self.span,
});
let output = Ok(Value::binary(self.leftover.clone(), self.span));
self.leftover.clear();
Some(output)

View File

@ -34,72 +34,39 @@ pub enum Unit {
impl Unit {
pub fn to_value(&self, size: i64, span: Span) -> Result<Value, ShellError> {
match self {
Unit::Byte => Ok(Value::Filesize { val: size, span }),
Unit::Kilobyte => Ok(Value::Filesize {
val: size * 1000,
Unit::Byte => Ok(Value::filesize(size, span)),
Unit::Kilobyte => Ok(Value::filesize(size * 1000, span)),
Unit::Megabyte => Ok(Value::filesize(size * 1000 * 1000, span)),
Unit::Gigabyte => Ok(Value::filesize(size * 1000 * 1000 * 1000, span)),
Unit::Terabyte => Ok(Value::filesize(size * 1000 * 1000 * 1000 * 1000, span)),
Unit::Petabyte => Ok(Value::filesize(
size * 1000 * 1000 * 1000 * 1000 * 1000,
span,
}),
Unit::Megabyte => Ok(Value::Filesize {
val: size * 1000 * 1000,
)),
Unit::Exabyte => Ok(Value::filesize(
size * 1000 * 1000 * 1000 * 1000 * 1000 * 1000,
span,
}),
Unit::Gigabyte => Ok(Value::Filesize {
val: size * 1000 * 1000 * 1000,
span,
}),
Unit::Terabyte => Ok(Value::Filesize {
val: size * 1000 * 1000 * 1000 * 1000,
span,
}),
Unit::Petabyte => Ok(Value::Filesize {
val: size * 1000 * 1000 * 1000 * 1000 * 1000,
span,
}),
Unit::Exabyte => Ok(Value::Filesize {
val: size * 1000 * 1000 * 1000 * 1000 * 1000 * 1000,
span,
}),
)),
Unit::Kibibyte => Ok(Value::Filesize {
val: size * 1024,
Unit::Kibibyte => Ok(Value::filesize(size * 1024, span)),
Unit::Mebibyte => Ok(Value::filesize(size * 1024 * 1024, span)),
Unit::Gibibyte => Ok(Value::filesize(size * 1024 * 1024 * 1024, span)),
Unit::Tebibyte => Ok(Value::filesize(size * 1024 * 1024 * 1024 * 1024, span)),
Unit::Pebibyte => Ok(Value::filesize(
size * 1024 * 1024 * 1024 * 1024 * 1024,
span,
}),
Unit::Mebibyte => Ok(Value::Filesize {
val: size * 1024 * 1024,
)),
Unit::Exbibyte => Ok(Value::filesize(
size * 1024 * 1024 * 1024 * 1024 * 1024 * 1024,
span,
}),
Unit::Gibibyte => Ok(Value::Filesize {
val: size * 1024 * 1024 * 1024,
span,
}),
Unit::Tebibyte => Ok(Value::Filesize {
val: size * 1024 * 1024 * 1024 * 1024,
span,
}),
Unit::Pebibyte => Ok(Value::Filesize {
val: size * 1024 * 1024 * 1024 * 1024 * 1024,
span,
}),
Unit::Exbibyte => Ok(Value::Filesize {
val: size * 1024 * 1024 * 1024 * 1024 * 1024 * 1024,
span,
}),
)),
Unit::Nanosecond => Ok(Value::Duration { val: size, span }),
Unit::Microsecond => Ok(Value::Duration {
val: size * 1000,
span,
}),
Unit::Millisecond => Ok(Value::Duration {
val: size * 1000 * 1000,
span,
}),
Unit::Second => Ok(Value::Duration {
val: size * 1000 * 1000 * 1000,
span,
}),
Unit::Nanosecond => Ok(Value::duration(size, span)),
Unit::Microsecond => Ok(Value::duration(size * 1000, span)),
Unit::Millisecond => Ok(Value::duration(size * 1000 * 1000, span)),
Unit::Second => Ok(Value::duration(size * 1000 * 1000 * 1000, span)),
Unit::Minute => match size.checked_mul(1000 * 1000 * 1000 * 60) {
Some(val) => Ok(Value::Duration { val, span }),
Some(val) => Ok(Value::duration(val, span)),
None => Err(ShellError::GenericError(
"duration too large".into(),
"duration too large".into(),
@ -109,7 +76,7 @@ impl Unit {
)),
},
Unit::Hour => match size.checked_mul(1000 * 1000 * 1000 * 60 * 60) {
Some(val) => Ok(Value::Duration { val, span }),
Some(val) => Ok(Value::duration(val, span)),
None => Err(ShellError::GenericError(
"duration too large".into(),
"duration too large".into(),
@ -119,7 +86,7 @@ impl Unit {
)),
},
Unit::Day => match size.checked_mul(1000 * 1000 * 1000 * 60 * 60 * 24) {
Some(val) => Ok(Value::Duration { val, span }),
Some(val) => Ok(Value::duration(val, span)),
None => Err(ShellError::GenericError(
"duration too large".into(),
"duration too large".into(),
@ -129,7 +96,7 @@ impl Unit {
)),
},
Unit::Week => match size.checked_mul(1000 * 1000 * 1000 * 60 * 60 * 24 * 7) {
Some(val) => Ok(Value::Duration { val, span }),
Some(val) => Ok(Value::duration(val, span)),
None => Err(ShellError::GenericError(
"duration too large".into(),
"duration too large".into(),