Skip to content

Name the Value conversion functions more clearly - #11851

Merged
IanManske merged 23 commits into
nushell:mainfrom
IanManske:value-as-into-coerce
Feb 17, 2024
Merged

IanManske merged 23 commits into
nushell:mainfrom
IanManske:value-as-into-coerce

Conversation

@IanManske

@IanManske IanManske commented Feb 13, 2024 •

Copy link
Copy Markdown
Member

Description

This PR renames the conversion functions on Value to be more consistent. It follows the Rust API guidelines for ad-hoc conversions. The conversion functions on Value now come in a few forms:

  • coerce_{type} takes a &Value and attempts to convert the value to type (e.g., i64 are converted to f64). This is the old behavior of some of the as_{type} functions -- these functions have simply been renamed to better reflect what they do.
  • The new as_{type} functions take a &Value and returns an Ok result only if the value is of type (no conversion is attempted). The returned value will be borrowed if type is non-Copy, otherwise an owned value is returned.
  • into_{type} exists for non-Copy types, but otherwise does not attempt conversion just like as_type. It takes an owned Value and always returns an owned result.
  • coerce_into_{type} has the same relationship with coerce_{type} as into_{type} does with as_{type}.
  • to_{kind}_string: conversion to different string formats (debug, abbreviated, etc.). Only two of the old string conversion functions were removed, the rest have been renamed only.
  • to_{type}: other conversion functions. Currently, only to_path exists. (And to_string through Display.)

This table summaries the above:

Form Cost Input Ownership Output Ownership Converts Value case/type
as_{type} Cheap Borrowed Borrowed/Owned No
into_{type} Cheap Owned Owned No
coerce_{type} Cheap Borrowed Borrowed/Owned Yes
coerce_into_{type} Cheap Owned Owned Yes
to_{kind}_string Expensive Borrowed Owned Yes
to_{type} Expensive Borrowed Owned Yes

User-Facing Changes

Breaking API change for Value in nu-protocol which is exposed as part of the plugin API.

@IanManske
IanManske marked this pull request as ready for review February 13, 2024 23:54
@sholderbach

Copy link
Copy Markdown
Member

Thank you so much for tackling the weird coercions under a wrong name.

Can we provide some recommendations on the plethora of munch_it_somehow_into_a_string methods, when to use what?

@IanManske

Copy link
Copy Markdown
Member Author

Can we provide some recommendations on the plethora of munch_it_somehow_into_a_string methods, when to use what?

I was able to remove yet another one of the to_{kind}_string functions. Otherwise, I added docs for the remaining four. The docs describe what each function does, but they don't say when to use each (except for to_debug_string). I'm not sure when to use each of the other three.

@sholderbach sholderbach left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the comment improvements!

The into_ lifting may sometimes become a double edged sword if folks trying to make changes in the future may feel incentivised to clone the whole Value as it is now taken by value and the borrowcheck message will suggest that first. But that is a future skill issue :P

Comment on lines +379 to +383
/// - `Int`
/// - `Float`
/// - `String`
/// - `Binary` (only if valid utf-8)
/// - `Date`

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for making this clear across the different methods!

Should we doctest this?
(preferrably probably the inverse but that would be unwieldy to read)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's quite a simple function so I'm not sure. Maybe the doctests could go in an # Examples section to make it more readable?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the more unfortunate situation would be if someone adds another coercion and doesn't document it but that is kind of harder to write concisely. (Having just the given ones as one line asserts would be easy as examples)

@IanManske IanManske Feb 15, 2024 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking of doing something like this:

/// ```
/// # use nu_protocol::{
/// #     ast::{CellPath, RangeInclusion},
/// #     engine::Closure,
/// #     Range, Record, ShellError, Span, Value
/// # };
/// # use chrono::DateTime;
/// #
/// # let values: Vec<Value> = vec![
/// #     Value::test_bool(false),
/// #     Value::test_int(0),
/// #     Value::test_filesize(0),
/// #     Value::test_duration(0),
/// #     Value::test_date(DateTime::UNIX_EPOCH.into()),
/// #     Value::test_range(Range {
/// #         from: Value::test_nothing(),
/// #         incr: Value::test_nothing(),
/// #         to: Value::test_nothing(),
/// #         inclusion: RangeInclusion::Inclusive,
/// #     }),
/// #     Value::test_float(0.0),
/// #     Value::test_string(String::new()),
/// #     Value::test_record(Record::new()),
/// #     // Value::test_lazy_record(),
/// #     Value::test_list(Vec::new()),
/// #     Value::test_block(0),
/// #     Value::test_closure(Closure {
/// #         block_id: 0,
/// #         captures: Vec::new(),
/// #     }),
/// #     Value::test_nothing(),
/// #     Value::error(
/// #         ShellError::NushellFailed { msg: String::new() },
/// #         Span::test_data(),
/// #     ),
/// #     Value::test_binary(Vec::new()),
/// #     Value::test_cell_path(CellPath {
/// #         members: Vec::new(),
/// #     }),
/// #     // Value::test_custom_value(0),
/// # ];
/// #
/// # for val in &values {
/// assert_eq!(matches!(val, Value::Float { .. } | Value::Int { .. }), val.coerce_float().is_ok())
/// # };
/// ```

But this would have to be copy-pasted for each function. Or, we can add a public function somewhere that returns a Vec<Value> containing one of each Value case (perhaps it could be #[doc(hidden)]).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a mouthful 😄

(as we already have the Value::test_... in the general API it probably wouldn't be too bad to have a sample generating function)

but I don't want to block those changes on this. It will cause churn with a lot of PRs anyways.

@IanManske
IanManske merged commit 1c49ca5 into nushell:main Feb 17, 2024
@sholderbach

Copy link
Copy Markdown
Member

Nice! Thanks for implementing the elegant doctests as well!

@hustcer hustcer added this to the v0.91.0 milestone Feb 18, 2024
sholderbach pushed a commit that referenced this pull request Feb 18, 2024
# Description
Following #11851, this PR adds one final conversion function for
`Value`. `Value::coerce_str` takes a `&Value` and converts it to a
`Cow<str>`, creating an owned `String` for types that needed converting.
Otherwise, it returns a borrowed `str` for `String` and `Binary`
`Value`s which avoids a clone/allocation. Where possible, `coerce_str`
and `coerce_into_string` should be used instead of `coerce_string`,
since `coerce_string` always allocates a new `String`.
dmatos2012 pushed a commit to dmatos2012/nushell that referenced this pull request Feb 20, 2024
# Description
This PR renames the conversion functions on `Value` to be more consistent.
It follows the Rust [API guidelines](https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv) for ad-hoc conversions.
The conversion functions on `Value` now come in a few forms:
- `coerce_{type}` takes a `&Value` and attempts to convert the value to
`type` (e.g., `i64` are converted to `f64`). This is the old behavior of
some of the `as_{type}` functions -- these functions have simply been
renamed to better reflect what they do.
- The new `as_{type}` functions take a `&Value` and returns an `Ok`
result only if the value is of `type` (no conversion is attempted). The
returned value will be borrowed if `type` is non-`Copy`, otherwise an
owned value is returned.
- `into_{type}` exists for non-`Copy` types, but otherwise does not
attempt conversion just like `as_type`. It takes an owned `Value` and
always returns an owned result.
- `coerce_into_{type}` has the same relationship with `coerce_{type}` as
`into_{type}` does with `as_{type}`.
- `to_{kind}_string`: conversion to different string formats (debug,
abbreviated, etc.). Only two of the old string conversion functions were
removed, the rest have been renamed only.
- `to_{type}`: other conversion functions. Currently, only `to_path`
exists. (And `to_string` through `Display`.)

This table summaries the above:
| Form | Cost | Input Ownership | Output Ownership | Converts `Value`
case/`type` |
| ---------------------------- | ----- | --------------- |
---------------- | -------- |
| `as_{type}` | Cheap | Borrowed | Borrowed/Owned | No |
| `into_{type}` | Cheap | Owned | Owned | No |
| `coerce_{type}` | Cheap | Borrowed | Borrowed/Owned | Yes |
| `coerce_into_{type}` | Cheap | Owned | Owned | Yes |
| `to_{kind}_string` | Expensive | Borrowed | Owned | Yes |
| `to_{type}` | Expensive | Borrowed | Owned | Yes |

# User-Facing Changes
Breaking API change for `Value` in `nu-protocol` which is exposed as
part of the plugin API.
dmatos2012 pushed a commit to dmatos2012/nushell that referenced this pull request Feb 20, 2024
# Description
Following nushell#11851, this PR adds one final conversion function for
`Value`. `Value::coerce_str` takes a `&Value` and converts it to a
`Cow<str>`, creating an owned `String` for types that needed converting.
Otherwise, it returns a borrowed `str` for `String` and `Binary`
`Value`s which avoids a clone/allocation. Where possible, `coerce_str`
and `coerce_into_string` should be used instead of `coerce_string`,
since `coerce_string` always allocates a new `String`.
kik4444 pushed a commit to kik4444/nushell-fork that referenced this pull request Feb 28, 2024
# Description
This PR renames the conversion functions on `Value` to be more consistent.
It follows the Rust [API guidelines](https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv) for ad-hoc conversions.
The conversion functions on `Value` now come in a few forms:
- `coerce_{type}` takes a `&Value` and attempts to convert the value to
`type` (e.g., `i64` are converted to `f64`). This is the old behavior of
some of the `as_{type}` functions -- these functions have simply been
renamed to better reflect what they do.
- The new `as_{type}` functions take a `&Value` and returns an `Ok`
result only if the value is of `type` (no conversion is attempted). The
returned value will be borrowed if `type` is non-`Copy`, otherwise an
owned value is returned.
- `into_{type}` exists for non-`Copy` types, but otherwise does not
attempt conversion just like `as_type`. It takes an owned `Value` and
always returns an owned result.
- `coerce_into_{type}` has the same relationship with `coerce_{type}` as
`into_{type}` does with `as_{type}`.
- `to_{kind}_string`: conversion to different string formats (debug,
abbreviated, etc.). Only two of the old string conversion functions were
removed, the rest have been renamed only.
- `to_{type}`: other conversion functions. Currently, only `to_path`
exists. (And `to_string` through `Display`.)

This table summaries the above:
| Form | Cost | Input Ownership | Output Ownership | Converts `Value`
case/`type` |
| ---------------------------- | ----- | --------------- |
---------------- | -------- |
| `as_{type}` | Cheap | Borrowed | Borrowed/Owned | No |
| `into_{type}` | Cheap | Owned | Owned | No |
| `coerce_{type}` | Cheap | Borrowed | Borrowed/Owned | Yes |
| `coerce_into_{type}` | Cheap | Owned | Owned | Yes |
| `to_{kind}_string` | Expensive | Borrowed | Owned | Yes |
| `to_{type}` | Expensive | Borrowed | Owned | Yes |

# User-Facing Changes
Breaking API change for `Value` in `nu-protocol` which is exposed as
part of the plugin API.
kik4444 pushed a commit to kik4444/nushell-fork that referenced this pull request Feb 28, 2024
# Description
Following nushell#11851, this PR adds one final conversion function for
`Value`. `Value::coerce_str` takes a `&Value` and converts it to a
`Cow<str>`, creating an owned `String` for types that needed converting.
Otherwise, it returns a borrowed `str` for `String` and `Binary`
`Value`s which avoids a clone/allocation. Where possible, `coerce_str`
and `coerce_into_string` should be used instead of `coerce_string`,
since `coerce_string` always allocates a new `String`.
@IanManske
IanManske deleted the value-as-into-coerce branch March 26, 2024 14:54
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants