Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions ssh-derive/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use quote::quote;
pub(crate) struct ContainerAttributes {
pub(crate) length_prefixed: bool,
pub(crate) discriminant_type: Option<TokenStream>,
pub(crate) error_type: Option<syn::Type>,
}

impl TryFrom<&syn::DeriveInput> for ContainerAttributes {
Expand All @@ -12,12 +13,18 @@ impl TryFrom<&syn::DeriveInput> for ContainerAttributes {
fn try_from(input: &syn::DeriveInput) -> Result<Self, Self::Error> {
let mut length_prefixed = false;
let mut discriminant_type = None;
let mut error_type = None;
for attr in &input.attrs {
if attr.path().is_ident("ssh") {
attr.parse_nested_meta(|meta| {
// #[ssh(length_prefixed)]
if meta.path.is_ident("length_prefixed") {
length_prefixed = true;
} else if meta.path.is_ident("error") {
if error_type.is_some() {
return Err(meta.error("duplicate `error` attribute"));
}
error_type = Some(meta.value()?.parse()?);
} else {
return Err(syn::Error::new_spanned(meta.path, "unknown attribute"));
}
Expand Down Expand Up @@ -65,6 +72,7 @@ impl TryFrom<&syn::DeriveInput> for ContainerAttributes {
Ok(Self {
length_prefixed,
discriminant_type,
error_type,
})
}
}
Expand Down
96 changes: 38 additions & 58 deletions ssh-derive/src/decode.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,29 @@
//! Support for deriving the `Decode` trait on structs.
//! Support for deriving the `Decode` trait on structs and enums.

use proc_macro2::TokenStream;
use quote::quote;
use syn::{DataEnum, DataStruct, DeriveInput, spanned::Spanned};
use syn::{DataEnum, DeriveInput, Ident, spanned::Spanned};

use crate::attributes::{ContainerAttributes, FieldAttributes, validate_variant_attributes};

pub(crate) fn try_derive_decode(input: DeriveInput) -> syn::Result<TokenStream> {
match input.data {
syn::Data::Struct(ref data) => try_derive_decode_for_struct(&input, data),
syn::Data::Enum(ref data) => try_derive_decode_for_enum(&input, data),
syn::Data::Union(_) => abort!(input.ident, "can't derive `Decode` on union types",),
}
}

fn try_derive_decode_for_struct(
input: &DeriveInput,
DataStruct { fields, .. }: &DataStruct,
) -> syn::Result<TokenStream> {
let container_attributes = ContainerAttributes::try_from(input)?;
let struct_name = &input.ident;
let body = derive_for_fields(fields, quote! { Self })?;
let body = maybe_length_prefixed_result(container_attributes.length_prefixed, &body);
let attrs = ContainerAttributes::try_from(&input)?;
let name = &input.ident;
let body = match &input.data {
syn::Data::Struct(data) => derive_for_fields(&data.fields, quote! { Self })?,
syn::Data::Enum(data) => derive_for_enum(name, data, attrs.discriminant_type.as_ref())?,
syn::Data::Union(_) => abort!(name, "can't derive `Decode` on union types"),
};
let body = maybe_length_prefixed_result(attrs.length_prefixed, &body);
let error_type = attrs
.error_type
.unwrap_or_else(|| syn::parse_quote!(::ssh_encoding::Error));
let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();

Ok(quote! {
#[automatically_derived]
impl #impl_generics ::ssh_encoding::Decode for #struct_name #type_generics #where_clause {
type Error = ::ssh_encoding::Error;
impl #impl_generics ::ssh_encoding::Decode for #name #type_generics #where_clause {
type Error = #error_type;

fn decode(reader: &mut ::ssh_encoding::Decoder<impl ::ssh_encoding::Reader>) -> ::core::result::Result<Self, Self::Error> {
#body
Expand All @@ -36,21 +32,17 @@ fn try_derive_decode_for_struct(
})
}

fn try_derive_decode_for_enum(
input: &DeriveInput,
fn derive_for_enum(
enum_name: &Ident,
DataEnum { variants, .. }: &DataEnum,
discriminant_type: Option<&TokenStream>,
) -> syn::Result<TokenStream> {
let container_attributes = ContainerAttributes::try_from(input)?;
let enum_name = &input.ident;
let discriminant_type = container_attributes
.discriminant_type
.clone()
.ok_or_else(|| {
syn::Error::new(
input.ident.span(),
"enums must have a repr attribute to derive `Decode`",
)
})?;
let discriminant_type = discriminant_type.ok_or_else(|| {
syn::Error::new(
enum_name.span(),
"enums must have a repr attribute to derive `Decode`",
)
})?;
let variant_branches = variants
.iter()
.map(|variant| {
Expand All @@ -70,28 +62,15 @@ fn try_derive_decode_for_enum(
Ok(quote! { if discriminant == const { #discriminant } { #body } })
})
.collect::<syn::Result<Vec<_>>>()?;
let (impl_generics, type_generics, where_clause) = input.generics.split_for_impl();

let body = quote! {
Ok(quote! {
let discriminant = <#discriminant_type as ::ssh_encoding::Decode>::decode(reader)?;
#(#variant_branches else)* {
return Err(::ssh_encoding::Error::InvalidDiscriminant(
::core::convert::TryFrom::try_from(discriminant)
.map_err(|_| ::ssh_encoding::Error::Overflow)?,
let discriminant = ::core::convert::TryFrom::try_from(discriminant)
.map_err(|_| ::ssh_encoding::Error::Overflow)?;
return Err(::core::convert::From::from(
::ssh_encoding::Error::InvalidDiscriminant(discriminant),
));
}
};
let body = maybe_length_prefixed_result(container_attributes.length_prefixed, &body);

Ok(quote! {
#[automatically_derived]
impl #impl_generics ::ssh_encoding::Decode for #enum_name #type_generics #where_clause {
type Error = ::ssh_encoding::Error;

fn decode(reader: &mut ::ssh_encoding::Decoder<impl ::ssh_encoding::Reader>) -> ::core::result::Result<Self, Self::Error> {
#body
}
}
})
}

Expand Down Expand Up @@ -137,7 +116,7 @@ fn maybe_length_prefixed_result(length_prefix: bool, body: &TokenStream) -> Toke
if length_prefix {
quote! {
reader.read_prefixed(|reader| {
Ok::<_, ::ssh_encoding::Error>({#body})
Ok::<_, Self::Error>({#body})
})
}
} else {
Expand All @@ -162,7 +141,7 @@ mod tests {
let actual = maybe_length_prefixed_result(true, &quote! { () });
let expected = quote! {
reader.read_prefixed(|reader| {
Ok::<_, ::ssh_encoding::Error>({()})
Ok::<_, Self::Error>({()})
})
};
assert_eq_tokens!(actual, expected);
Expand Down Expand Up @@ -264,7 +243,7 @@ mod tests {
#[test]
fn test_try_derive_decode_for_enum() {
let input = syn::parse_quote! {
#[ssh(length_prefixed)]
#[ssh(length_prefixed, error = crate::Error)]
#[repr(u8)]
enum Foo {
A = 0,
Expand All @@ -275,20 +254,21 @@ mod tests {
let expected = quote! {
#[automatically_derived]
impl ::ssh_encoding::Decode for Foo {
type Error = ::ssh_encoding::Error;
type Error = crate::Error;

fn decode(reader: &mut ::ssh_encoding::Decoder<impl ::ssh_encoding::Reader>) -> ::core::result::Result<Self, Self::Error> {
reader.read_prefixed(|reader| {
Ok::<_, ::ssh_encoding::Error>({
Ok::<_, Self::Error>({
let discriminant = <u8 as ::ssh_encoding::Decode>::decode(reader)?;
if discriminant == const { 0 } {
Foo::A
} else if discriminant == const { 1 } {
Foo::B
} else {
return Err(::ssh_encoding::Error::InvalidDiscriminant(
::core::convert::TryFrom::try_from(discriminant)
.map_err(|_| ::ssh_encoding::Error::Overflow)?,
let discriminant = ::core::convert::TryFrom::try_from(discriminant)
.map_err(|_| ::ssh_encoding::Error::Overflow)?;
return Err(::core::convert::From::from(
::ssh_encoding::Error::InvalidDiscriminant(discriminant),
));
}
})
Expand Down
3 changes: 3 additions & 0 deletions ssh-derive/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,7 @@ mod tests {
let container_attributes = ContainerAttributes {
discriminant_type: None,
length_prefixed: false,
error_type: None,
};
let err = derive_for_variants(&container_attributes, iter::once(&variant), &enum_name)
.unwrap_err();
Expand All @@ -348,6 +349,7 @@ mod tests {
let container_attributes = ContainerAttributes {
discriminant_type: Some(quote! { u8 }),
length_prefixed: false,
error_type: None,
};
let err = derive_for_variants(&container_attributes, iter::once(&variant), &enum_name)
.unwrap_err();
Expand All @@ -367,6 +369,7 @@ mod tests {
let container_attributes = ContainerAttributes {
discriminant_type: Some(quote! { u8 }),
length_prefixed: false,
error_type: None,
};
let (length_arms, encode_arms) =
derive_for_variants(&container_attributes, variants.iter(), &enum_name).unwrap();
Expand Down
25 changes: 22 additions & 3 deletions ssh-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,13 @@ mod encode;
use proc_macro::TokenStream;
use syn::{DeriveInput, parse_macro_input};

/// Derive the [`Decode`][1] trait on a `struct`.
/// Derive the [`Decode`][1] trait for a struct or enum.
///
/// [1]: https://docs.rs/ssh-derive/latest/ssh-derive/trait.Decode.html
/// Use `#[ssh(error = crate::Error)]` on the type to override the default
/// `ssh_encoding::Error`. The chosen type must implement `From<ssh_encoding::Error>`
/// and `From` for each field's decoding error.
///
/// [1]: https://docs.rs/ssh-encoding/latest/ssh_encoding/trait.Decode.html
#[proc_macro_derive(Decode, attributes(ssh))]
pub fn derive_decode(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
Expand Down Expand Up @@ -55,7 +59,11 @@ mod tests {
#[test]
fn reject_ssh_attributes_on_variants() {
for derive in [encode::try_derive_encode, decode::try_derive_decode] {
for option in [quote!(length_prefixed), quote!(unknown)] {
for option in [
quote!(length_prefixed),
quote!(error = crate::Error),
quote!(unknown),
] {
let input = syn::parse_quote! {
#[repr(u8)]
enum Message {
Expand All @@ -71,4 +79,15 @@ mod tests {
}
}
}

#[test]
fn reject_duplicate_error_type() {
let input = syn::parse_quote! {
#[ssh(error = First)]
#[ssh(error = Second)]
struct Message;
};
let err = decode::try_derive_decode(input).expect_err("duplicate error type");
assert_eq!(err.to_string(), "duplicate `error` attribute");
}
}
36 changes: 36 additions & 0 deletions ssh-encoding/tests/derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -215,3 +215,39 @@ fn derive_length_prefixed_usize_discriminant() {
Err(Error::InvalidDiscriminant(0xabcd))
);
}

#[test]
fn derive_custom_decode_error() {
#[derive(Debug, PartialEq)]
struct MessageError(Error);

impl From<Error> for MessageError {
fn from(error: Error) -> Self {
Self(error)
}
}

#[derive(Debug, PartialEq, Decode, Encode)]
#[ssh(error = MessageError)]
#[repr(u8)]
enum Kind {
Data = 1,
}

#[derive(Debug, PartialEq, Decode, Encode)]
#[ssh(length_prefixed, error = MessageError)]
struct Message(#[ssh(length_prefixed)] Kind);

let decode = |bytes: &[u8]| Message::decode(&mut bytes.into_decoder().unwrap());
let mut bytes = [0, 0, 0, 5, 0, 0, 0, 1, 1];
let message = Message(Kind::Data);
assert_eq!(message.encode_vec().unwrap(), bytes);
assert_eq!(decode(&bytes), Ok(message));
assert_eq!(decode(&bytes[..8]), Err(MessageError(Error::Length)));

bytes[8] = 42;
assert_eq!(
decode(&bytes),
Err(MessageError(Error::InvalidDiscriminant(42)))
);
}