-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add derive macros for
FromValue
and IntoValue
to ease the use of …
…`Value`s in Rust code (#13031) # Description After discussing with @sholderbach the cumbersome usage of `nu_protocol::Value` in Rust, I created a derive macro to simplify it. I’ve added a new crate called `nu-derive-value`, which includes two macros, `IntoValue` and `FromValue`. These are re-exported in `nu-protocol` and should be encouraged to be used via that re-export. The macros ensure that all types can easily convert from and into `Value`. For example, as a plugin author, you can define your plugin configuration using a Rust struct and easily convert it using `FromValue`. This makes plugin configuration less of a hassle. I introduced the `IntoValue` trait for a standardized approach to converting values into `Value` (and a fallible variant `TryIntoValue`). This trait could potentially replace existing `into_value` methods. Along with this, I've implemented `FromValue` for several standard types and refined other implementations to use blanket implementations where applicable. I made these design choices with input from @devyn. There are more improvements possible, but this is a solid start and the PR is already quite substantial. # User-Facing Changes For `nu-protocol` users, these changes simplify the handling of `Value`s. There are no changes for end-users of nushell itself. # Tests + Formatting Documenting the macros itself is not really possible, as they cannot really reference any other types since they are the root of the dependency graph. The standard library has the same problem ([std::Debug](https://doc.rust-lang.org/stable/std/fmt/derive.Debug.html)). However I documented the `FromValue` and `IntoValue` traits completely. For testing, I made of use `proc-macro2` in the derive macro code. This would allow testing the generated source code. Instead I just tested that the derived functionality is correct. This is done in `nu_protocol::value::test_derive`, as a consumer of `nu-derive-value` needs to do the testing of the macro usage. I think that these tests should provide a stable baseline so that users can be sure that the impl works. # After Submitting With these macros available, we can probably use them in some examples for plugins to showcase the use of them.
- Loading branch information
1 parent
3a6d8aa
commit b79a225
Showing
24 changed files
with
2,351 additions
and
358 deletions.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
[package] | ||
authors = ["The Nushell Project Developers"] | ||
description = "Macros implementation of #[derive(FromValue, IntoValue)]" | ||
edition = "2021" | ||
license = "MIT" | ||
name = "nu-derive-value" | ||
repository = "https://github.com/nushell/nushell/tree/main/crates/nu-derive-value" | ||
version = "0.94.3" | ||
|
||
[lib] | ||
proc-macro = true | ||
# we can only use exposed macros in doctests really, | ||
# so we cannot test anything useful in a doctest | ||
doctest = false | ||
|
||
[dependencies] | ||
proc-macro2 = { workspace = true } | ||
syn = { workspace = true } | ||
quote = { workspace = true } | ||
proc-macro-error = { workspace = true } | ||
convert_case = { workspace = true } |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2019 - 2023 The Nushell Project Developers | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,116 @@ | ||
use convert_case::Case; | ||
use syn::{spanned::Spanned, Attribute, Fields, LitStr}; | ||
|
||
use crate::{error::DeriveError, HELPER_ATTRIBUTE}; | ||
|
||
#[derive(Debug)] | ||
pub struct ContainerAttributes { | ||
pub rename_all: Case, | ||
} | ||
|
||
impl Default for ContainerAttributes { | ||
fn default() -> Self { | ||
Self { | ||
rename_all: Case::Snake, | ||
} | ||
} | ||
} | ||
|
||
impl ContainerAttributes { | ||
pub fn parse_attrs<'a, M>( | ||
iter: impl Iterator<Item = &'a Attribute>, | ||
) -> Result<Self, DeriveError<M>> { | ||
let mut container_attrs = ContainerAttributes::default(); | ||
for attr in filter(iter) { | ||
// This is a container to allow returning derive errors inside the parse_nested_meta fn. | ||
let mut err = Ok(()); | ||
|
||
attr.parse_nested_meta(|meta| { | ||
let ident = meta.path.require_ident()?; | ||
match ident.to_string().as_str() { | ||
"rename_all" => { | ||
// The matched case are all useful variants from `convert_case` with aliases | ||
// that `serde` uses. | ||
let case: LitStr = meta.value()?.parse()?; | ||
let case = match case.value().as_str() { | ||
"UPPER CASE" | "UPPER WITH SPACES CASE" => Case::Upper, | ||
"lower case" | "lower with spaces case" => Case::Lower, | ||
"Title Case" => Case::Title, | ||
"camelCase" => Case::Camel, | ||
"PascalCase" | "UpperCamelCase" => Case::Pascal, | ||
"snake_case" => Case::Snake, | ||
"UPPER_SNAKE_CASE" | "SCREAMING_SNAKE_CASE" => Case::UpperSnake, | ||
"kebab-case" => Case::Kebab, | ||
"COBOL-CASE" | "UPPER-KEBAB-CASE" | "SCREAMING-KEBAB-CASE" => { | ||
Case::Cobol | ||
} | ||
"Train-Case" => Case::Train, | ||
"flatcase" | "lowercase" => Case::Flat, | ||
"UPPERFLATCASE" | "UPPERCASE" => Case::UpperFlat, | ||
// Although very funny, we don't support `Case::{Toggle, Alternating}`, | ||
// as we see no real benefit. | ||
c => { | ||
err = Err(DeriveError::InvalidAttributeValue { | ||
value_span: case.span(), | ||
value: Box::new(c.to_string()), | ||
}); | ||
return Ok(()); // We stored the err in `err`. | ||
} | ||
}; | ||
container_attrs.rename_all = case; | ||
} | ||
ident => { | ||
err = Err(DeriveError::UnexpectedAttribute { | ||
meta_span: ident.span(), | ||
}); | ||
} | ||
} | ||
|
||
Ok(()) | ||
}) | ||
.map_err(DeriveError::Syn)?; | ||
|
||
err?; // Shortcircuit here if `err` is holding some error. | ||
} | ||
|
||
Ok(container_attrs) | ||
} | ||
} | ||
|
||
pub fn filter<'a>( | ||
iter: impl Iterator<Item = &'a Attribute>, | ||
) -> impl Iterator<Item = &'a Attribute> { | ||
iter.filter(|attr| attr.path().is_ident(HELPER_ATTRIBUTE)) | ||
} | ||
|
||
// The deny functions are built to easily deny the use of the helper attribute if used incorrectly. | ||
// As the usage of it gets more complex, these functions might be discarded or replaced. | ||
|
||
/// Deny any attribute that uses the helper attribute. | ||
pub fn deny<M>(attrs: &[Attribute]) -> Result<(), DeriveError<M>> { | ||
match filter(attrs.iter()).next() { | ||
Some(attr) => Err(DeriveError::InvalidAttributePosition { | ||
attribute_span: attr.span(), | ||
}), | ||
None => Ok(()), | ||
} | ||
} | ||
|
||
/// Deny any attributes that uses the helper attribute on any field. | ||
pub fn deny_fields<M>(fields: &Fields) -> Result<(), DeriveError<M>> { | ||
match fields { | ||
Fields::Named(fields) => { | ||
for field in fields.named.iter() { | ||
deny(&field.attrs)?; | ||
} | ||
} | ||
Fields::Unnamed(fields) => { | ||
for field in fields.unnamed.iter() { | ||
deny(&field.attrs)?; | ||
} | ||
} | ||
Fields::Unit => (), | ||
} | ||
|
||
Ok(()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,82 @@ | ||
use std::{any, fmt::Debug, marker::PhantomData}; | ||
|
||
use proc_macro2::Span; | ||
use proc_macro_error::{Diagnostic, Level}; | ||
|
||
#[derive(Debug)] | ||
pub enum DeriveError<M> { | ||
/// Marker variant, makes the `M` generic parameter valid. | ||
_Marker(PhantomData<M>), | ||
|
||
/// Parsing errors thrown by `syn`. | ||
Syn(syn::parse::Error), | ||
|
||
/// `syn::DeriveInput` was a union, currently not supported | ||
UnsupportedUnions, | ||
|
||
/// Only plain enums are supported right now. | ||
UnsupportedEnums { fields_span: Span }, | ||
|
||
/// Found a `#[nu_value(x)]` attribute where `x` is unexpected. | ||
UnexpectedAttribute { meta_span: Span }, | ||
|
||
/// Found a `#[nu_value(x)]` attribute at a invalid position. | ||
InvalidAttributePosition { attribute_span: Span }, | ||
|
||
/// Found a valid `#[nu_value(x)]` attribute but the passed values is invalid. | ||
InvalidAttributeValue { | ||
value_span: Span, | ||
value: Box<dyn Debug>, | ||
}, | ||
} | ||
|
||
impl<M> From<DeriveError<M>> for Diagnostic { | ||
fn from(value: DeriveError<M>) -> Self { | ||
let derive_name = any::type_name::<M>().split("::").last().expect("not empty"); | ||
match value { | ||
DeriveError::_Marker(_) => panic!("used marker variant"), | ||
|
||
DeriveError::Syn(e) => Diagnostic::spanned(e.span(), Level::Error, e.to_string()), | ||
|
||
DeriveError::UnsupportedUnions => Diagnostic::new( | ||
Level::Error, | ||
format!("`{derive_name}` cannot be derived from unions"), | ||
) | ||
.help("consider refactoring to a struct".to_string()) | ||
.note("if you really need a union, consider opening an issue on Github".to_string()), | ||
|
||
DeriveError::UnsupportedEnums { fields_span } => Diagnostic::spanned( | ||
fields_span, | ||
Level::Error, | ||
format!("`{derive_name}` can only be derived from plain enums"), | ||
) | ||
.help( | ||
"consider refactoring your data type to a struct with a plain enum as a field" | ||
.to_string(), | ||
) | ||
.note("more complex enums could be implemented in the future".to_string()), | ||
|
||
DeriveError::InvalidAttributePosition { attribute_span } => Diagnostic::spanned( | ||
attribute_span, | ||
Level::Error, | ||
"invalid attribute position".to_string(), | ||
) | ||
.help(format!( | ||
"check documentation for `{derive_name}` for valid placements" | ||
)), | ||
|
||
DeriveError::UnexpectedAttribute { meta_span } => { | ||
Diagnostic::spanned(meta_span, Level::Error, "unknown attribute".to_string()).help( | ||
format!("check documentation for `{derive_name}` for valid attributes"), | ||
) | ||
} | ||
|
||
DeriveError::InvalidAttributeValue { value_span, value } => { | ||
Diagnostic::spanned(value_span, Level::Error, format!("invalid value {value:?}")) | ||
.help(format!( | ||
"check documentation for `{derive_name}` for valid attribute values" | ||
)) | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.