implemented but did not test attributes

This commit is contained in:
Tim 'Piepmatz' Hesse 2024-06-07 14:26:10 +02:00
parent f9281d90dd
commit ba095be2ab
5 changed files with 267 additions and 64 deletions

View File

@ -0,0 +1,112 @@
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" => {
let case: LitStr = meta.value()?.parse()?;
let case = match case.value().as_str() {
"UPPER CASE" => Case::Upper,
"lower case" => Case::Lower,
"Title Case" => Case::Title,
"tOGGLE cASE" => Case::Toggle,
"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" => Case::Cobol,
"Tain-Case" => Case::Train,
"flatcase" => Case::Flat,
"UPPERFLATCASE" => Case::UpperFlat,
"aLtErNaTiNg CaSe" => Case::Alternating,
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(())
}

View File

@ -0,0 +1,81 @@
use std::{any, fmt::Debug, marker::PhantomData};
use proc_macro2::Span;
use proc_macro_error::{Diagnostic, Level};
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 documenation for `{derive_name}` for valid attributes"),
)
}
DeriveError::InvalidAttributeValue { value_span, value } => {
Diagnostic::spanned(value_span, Level::Error, format!("invalid value {value:?}"))
.help(format!(
"check documenation for `{derive_name}` for valid attribute values"
))
}
}
}
}

View File

@ -1,11 +1,15 @@
use convert_case::{Case, Casing};
use proc_macro2::{Span, TokenStream as TokenStream2};
use proc_macro_error::{Diagnostic, Level};
use convert_case::Casing;
use proc_macro2::TokenStream as TokenStream2;
use proc_macro_error::Diagnostic;
use quote::{quote, ToTokens};
use syn::{spanned::Spanned, Data, DataEnum, DataStruct, DeriveInput, Fields, Generics, Ident};
use syn::{
spanned::Spanned, Attribute, Data, DataEnum, DataStruct, DeriveInput, Fields, Generics, Ident,
};
use crate::attributes::{self, ContainerAttributes};
struct FromValue;
type DeriveError = super::DeriveError<FromValue>;
type DeriveError = super::error::DeriveError<FromValue>;
pub fn derive_from_value(input: TokenStream2) -> Result<TokenStream2, impl Into<Diagnostic>> {
let input: DeriveInput = syn::parse2(input).map_err(DeriveError::Syn)?;
@ -14,27 +18,36 @@ pub fn derive_from_value(input: TokenStream2) -> Result<TokenStream2, impl Into<
input.ident,
data_struct,
input.generics,
)),
input.attrs,
)?),
Data::Enum(data_enum) => Ok(derive_enum_from_value(
input.ident,
data_enum,
input.generics,
input.attrs,
)?),
Data::Union(_) => Err(DeriveError::UnsupportedUnions),
}
}
fn derive_struct_from_value(ident: Ident, data: DataStruct, generics: Generics) -> TokenStream2 {
fn derive_struct_from_value(
ident: Ident,
data: DataStruct,
generics: Generics,
attrs: Vec<Attribute>,
) -> Result<TokenStream2, DeriveError> {
attributes::deny(&attrs)?;
attributes::deny_fields(&data.fields)?;
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let from_value_impl = struct_from_value(&data);
let expected_type_impl = struct_expected_type(&data.fields);
quote! {
Ok(quote! {
#[automatically_derived]
impl #impl_generics nu_protocol::FromValue for #ident #ty_generics #where_clause {
#from_value_impl
#expected_type_impl
}
}
})
}
fn struct_from_value(data: &DataStruct) -> TokenStream2 {
@ -101,9 +114,10 @@ fn derive_enum_from_value(
ident: Ident,
data: DataEnum,
generics: Generics,
attrs: Vec<Attribute>,
) -> Result<TokenStream2, DeriveError> {
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let from_value_impl = enum_from_value(&data)?;
let from_value_impl = enum_from_value(&data, &attrs)?;
// As variants are hard to type with the current type system, we use the
// default impl for `expected_type`.
Ok(quote! {
@ -114,13 +128,17 @@ fn derive_enum_from_value(
})
}
fn enum_from_value(data: &DataEnum) -> Result<TokenStream2, DeriveError> {
fn enum_from_value(data: &DataEnum, attrs: &[Attribute]) -> Result<TokenStream2, DeriveError> {
let container_attrs = ContainerAttributes::parse_attrs(attrs.iter())?;
let arms: Vec<TokenStream2> = data
.variants
.iter()
.map(|variant| {
attributes::deny(&variant.attrs)?;
let ident = &variant.ident;
let ident_s = format!("{ident}").as_str().to_case(Case::Snake);
let ident_s = format!("{ident}")
.as_str()
.to_case(container_attrs.rename_all);
match &variant.fields {
Fields::Named(fields) => Err(DeriveError::UnsupportedEnums {
fields_span: fields.span(),

View File

@ -1,26 +1,44 @@
use convert_case::{Case, Casing};
use proc_macro2::{Span, TokenStream as TokenStream2};
use proc_macro_error::{Diagnostic, Level};
use convert_case::Casing;
use proc_macro2::TokenStream as TokenStream2;
use proc_macro_error::Diagnostic;
use quote::{quote, ToTokens};
use syn::{
spanned::Spanned, Data, DataEnum, DataStruct, DeriveInput, Fields, Generics, Ident, Index,
spanned::Spanned, Attribute, Data, DataEnum, DataStruct, DeriveInput, Fields, Generics, Ident,
Index,
};
use crate::attributes::{self, ContainerAttributes};
struct IntoValue;
type DeriveError = super::DeriveError<IntoValue>;
type DeriveError = super::error::DeriveError<IntoValue>;
pub fn derive_into_value(input: TokenStream2) -> Result<TokenStream2, impl Into<Diagnostic>> {
let input: DeriveInput = syn::parse2(input).map_err(DeriveError::Syn)?;
match input.data {
Data::Struct(data_struct) => {
Ok(struct_into_value(input.ident, data_struct, input.generics))
}
Data::Enum(data_enum) => Ok(enum_into_value(input.ident, data_enum, input.generics)?),
Data::Struct(data_struct) => Ok(struct_into_value(
input.ident,
data_struct,
input.generics,
input.attrs,
)?),
Data::Enum(data_enum) => Ok(enum_into_value(
input.ident,
data_enum,
input.generics,
input.attrs,
)?),
Data::Union(_) => Err(DeriveError::UnsupportedUnions),
}
}
fn struct_into_value(ident: Ident, data: DataStruct, generics: Generics) -> TokenStream2 {
fn struct_into_value(
ident: Ident,
data: DataStruct,
generics: Generics,
attrs: Vec<Attribute>,
) -> Result<TokenStream2, DeriveError> {
attributes::deny(&attrs)?;
attributes::deny_fields(&data.fields)?;
let record = match &data.fields {
Fields::Named(fields) => {
let accessor = fields
@ -42,27 +60,32 @@ fn struct_into_value(ident: Ident, data: DataStruct, generics: Generics) -> Toke
Fields::Unit => quote!(nu_protocol::Value::nothing(span)),
};
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
quote! {
Ok(quote! {
#[automatically_derived]
impl #impl_generics nu_protocol::IntoValue for #ident #ty_generics #where_clause {
fn into_value(self, span: nu_protocol::Span) -> nu_protocol::Value {
#record
}
}
}
})
}
fn enum_into_value(
ident: Ident,
data: DataEnum,
generics: Generics,
attrs: Vec<Attribute>,
) -> Result<TokenStream2, DeriveError> {
let container_attrs = ContainerAttributes::parse_attrs(attrs.iter())?;
let arms: Vec<TokenStream2> = data
.variants
.into_iter()
.map(|variant| {
attributes::deny(&variant.attrs)?;
let ident = variant.ident;
let ident_s = format!("{ident}").as_str().to_case(Case::Snake);
let ident_s = format!("{ident}")
.as_str()
.to_case(container_attrs.rename_all);
match &variant.fields {
// In the future we can implement more complexe enums here.
Fields::Named(fields) => Err(DeriveError::UnsupportedEnums {

View File

@ -1,12 +1,14 @@
use std::{any, fmt::Display, marker::PhantomData};
use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use proc_macro_error::{proc_macro_error, Diagnostic, Level};
use proc_macro2::TokenStream as TokenStream2;
use proc_macro_error::proc_macro_error;
mod attributes;
mod error;
mod from;
mod into;
const HELPER_ATTRIBUTE: &str = "nu_value";
// We use `TokenStream2` internally to allow testing the token streams which
// isn't possible on `proc_macro::TokenStream`.
// Even if not used right now, this will be great in the future.
@ -18,7 +20,7 @@ mod into;
/// Derive macro generating an impl of the trait `IntoValue`.
///
/// For further information, see the docs on the trait itself.
#[proc_macro_derive(IntoValue)]
#[proc_macro_derive(IntoValue, attributes(nu_value))]
#[proc_macro_error]
pub fn derive_into_value(input: TokenStream) -> TokenStream {
let input = TokenStream2::from(input);
@ -32,7 +34,7 @@ pub fn derive_into_value(input: TokenStream) -> TokenStream {
/// Derive macro generating an impl of the trait `FromValue`.
///
/// For further information, see the docs on the trait itself.
#[proc_macro_derive(FromValue)]
#[proc_macro_derive(FromValue, attributes(nu_value))]
#[proc_macro_error]
pub fn derive_from_value(input: TokenStream) -> TokenStream {
let input = TokenStream2::from(input);
@ -42,36 +44,3 @@ pub fn derive_from_value(input: TokenStream) -> TokenStream {
};
TokenStream::from(output)
}
enum DeriveError<M> {
_Marker(PhantomData<M>),
Syn(syn::parse::Error),
UnsupportedUnions,
UnsupportedEnums { fields_span: Span },
}
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!("`{}` cannot be derived from unions", derive_name),
)
.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!("`{}` can only be derived from plain enums", derive_name),
)
.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()),
}
}
}