Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

codegen: Support newtype and tuple structs #259

Merged
merged 1 commit into from
Oct 19, 2019
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
12 changes: 11 additions & 1 deletion rustler_codegen/src/context.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use proc_macro2::{Span, TokenStream};
use syn::{Data, Field, Ident, Lit, Meta, NestedMeta, Variant};
use syn::{Data, Field, Fields, Ident, Lit, Meta, NestedMeta, Variant};

use super::RustlerAttr;

Expand All @@ -14,6 +14,7 @@ pub(crate) struct Context<'a> {
pub ident_with_lifetime: proc_macro2::TokenStream,
pub variants: Option<Vec<&'a Variant>>,
pub struct_fields: Option<Vec<&'a Field>>,
pub is_tuple_struct: bool,
}

impl<'a> Context<'a> {
Expand Down Expand Up @@ -56,12 +57,21 @@ impl<'a> Context<'a> {
_ => None,
};

let is_tuple_struct = match ast.data {
Data::Struct(ref data_struct) => match data_struct.fields {
Fields::Unnamed(_) => true,
_ => false,
},
_ => false,
};

Self {
attrs,
ident,
ident_with_lifetime,
variants,
struct_fields,
is_tuple_struct,
}
}

Expand Down
48 changes: 35 additions & 13 deletions rustler_codegen/src/record.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use proc_macro2::TokenStream;

use syn::{self, Field};
use syn::{self, Field, Index};

use super::context::Context;
use super::RustlerAttr;
Expand Down Expand Up @@ -50,34 +50,53 @@ fn gen_decoder(ctx: &Context, atom_defs: &TokenStream, fields: &[&Field]) -> Tok
.iter()
.enumerate()
.map(|(index, field)| {
let ident = field.ident.as_ref().unwrap();
let ident = field.ident.as_ref();
let pos_in_struct = if let Some(ident) = ident {
ident.to_string()
} else {
index.to_string()
};
let error_message = format!(
"Could not decode field :{} on Record {}",
ident.to_string(),
"Could not decode field {} on Record {}",
pos_in_struct,
struct_name.to_string()
);
let actual_index = index + 1;
let decoder = quote! {
match ::rustler::Decoder::decode(terms[#index + 1]) {
match ::rustler::Decoder::decode(terms[#actual_index]) {
Err(_) => return Err(::rustler::Error::RaiseTerm(Box::new(#error_message))),
Ok(value) => value
}
};

quote! { #ident: #decoder }
match ident {
None => quote! { #decoder },
Some(ident) => quote! { #ident: #decoder },
}
})
.collect();

let field_num = field_defs.len();
let struct_name_str = struct_name.to_string();

// The implementation itself
let construct = if ctx.is_tuple_struct {
quote! {
#struct_name ( #(#field_defs),* )
}
} else {
quote! {
#struct_name { #(#field_defs),* }
}
};
let gen = quote! {
impl<'a> ::rustler::Decoder<'a> for #struct_type {
fn decode(term: ::rustler::Term<'a>) -> Result<Self, ::rustler::Error> {
#atom_defs

let terms = match ::rustler::types::tuple::get_tuple(term) {
Err(_) => return Err(::rustler::Error::RaiseTerm(Box::new(format!("Invalid Record structure for {}", #struct_name_str)))),
Err(_) => return Err(::rustler::Error::RaiseTerm(
Box::new(format!("Invalid Record structure for {}", #struct_name_str)))),
Ok(value) => value,
};

Expand All @@ -92,9 +111,7 @@ fn gen_decoder(ctx: &Context, atom_defs: &TokenStream, fields: &[&Field]) -> Tok
}

Ok(
#struct_name {
#(#field_defs),*
}
#construct
)
}
}
Expand All @@ -109,9 +126,14 @@ fn gen_encoder(ctx: &Context, atom_defs: &TokenStream, fields: &[&Field]) -> Tok
// Make a field encoder expression for each of the items in the struct.
let field_encoders: Vec<TokenStream> = fields
.iter()
.map(|field| {
let field_ident = field.ident.as_ref().unwrap();
let field_source = quote! { self.#field_ident };
.enumerate()
.map(|(index, field)| {
let literal_index = Index::from(index);
let field_source = match field.ident.as_ref() {
None => quote! { self.#literal_index },
Some(ident) => quote! { self.#ident },
};

quote! { #field_source.encode(env) }
})
.collect();
Expand Down
57 changes: 37 additions & 20 deletions rustler_codegen/src/tuple.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use proc_macro2::TokenStream;

use syn::{self, Field};
use syn::{self, Field, Index};

use super::context::Context;

Expand All @@ -13,13 +13,13 @@ pub fn transcoder_decorator(ast: &syn::DeriveInput) -> TokenStream {
.expect("NifTuple can only be used with structs");

let decoder = if ctx.decode() {
gen_decoder(&ctx, &struct_fields, false)
gen_decoder(&ctx, &struct_fields)
} else {
quote! {}
};

let encoder = if ctx.encode() {
gen_encoder(&ctx, &struct_fields, false)
gen_encoder(&ctx, &struct_fields)
} else {
quote! {}
};
Expand All @@ -32,7 +32,7 @@ pub fn transcoder_decorator(ast: &syn::DeriveInput) -> TokenStream {
gen
}

fn gen_decoder(ctx: &Context, fields: &[&Field], is_tuple: bool) -> TokenStream {
fn gen_decoder(ctx: &Context, fields: &[&Field]) -> TokenStream {
let struct_type = &ctx.ident_with_lifetime;
let struct_name = ctx.ident;

Expand All @@ -41,26 +41,44 @@ fn gen_decoder(ctx: &Context, fields: &[&Field], is_tuple: bool) -> TokenStream
.iter()
.enumerate()
.map(|(index, field)| {
let error_message = format!("Could not decode index {} on tuple", index);
let ident = field.ident.as_ref();
let pos_in_struct = if let Some(ident) = ident {
ident.to_string()
} else {
index.to_string()
};
let error_message = format!(
"Could not decode field {} on {}",
pos_in_struct,
struct_name.to_string()
);

let decoder = quote! {
match ::rustler::Decoder::decode(terms[#index]) {
Err(_) => return Err(::rustler::Error::RaiseTerm(Box::new(#error_message))),
Ok(value) => value
}
};

if is_tuple {
unimplemented!();
} else {
let ident = field.ident.as_ref().unwrap();
quote! { #ident: #decoder }
match ident {
None => quote! { #decoder },
Some(ident) => quote! { #ident: #decoder },
}
})
.collect();

let field_num = field_defs.len();

// The implementation itself
let construct = if ctx.is_tuple_struct {
quote! {
#struct_name ( #(#field_defs),* )
}
} else {
quote! {
#struct_name { #(#field_defs),* }
}
};
let gen = quote! {
impl<'a> ::rustler::Decoder<'a> for #struct_type {
fn decode(term: ::rustler::Term<'a>) -> Result<Self, ::rustler::Error> {
Expand All @@ -69,9 +87,7 @@ fn gen_decoder(ctx: &Context, fields: &[&Field], is_tuple: bool) -> TokenStream
return Err(::rustler::Error::BadArg);
}
Ok(
#struct_name {
#(#field_defs),*
}
#construct
)
}
}
Expand All @@ -80,19 +96,20 @@ fn gen_decoder(ctx: &Context, fields: &[&Field], is_tuple: bool) -> TokenStream
gen
}

fn gen_encoder(ctx: &Context, fields: &[&Field], is_tuple: bool) -> TokenStream {
fn gen_encoder(ctx: &Context, fields: &[&Field]) -> TokenStream {
let struct_type = &ctx.ident_with_lifetime;

// Make a field encoder expression for each of the items in the struct.
let field_encoders: Vec<TokenStream> = fields
.iter()
.map(|field| {
let field_source = if is_tuple {
unimplemented!();
} else {
let field_ident = field.ident.as_ref().unwrap();
quote! { self.#field_ident }
.enumerate()
.map(|(index, field)| {
let literal_index = Index::from(index);
let field_source = match field.ident.as_ref() {
None => quote! { self.#literal_index },
Some(ident) => quote! { self.#ident },
};

quote! { #field_source.encode(env) }
})
.collect();
Expand Down
4 changes: 4 additions & 0 deletions rustler_tests/lib/rustler_test.ex
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ defmodule RustlerTest do
def unit_enum_echo(_), do: err()
def untagged_enum_echo(_), do: err()
def untagged_enum_with_truthy(_), do: err()
def newtype_echo(_), do: err()
def tuplestruct_echo(_), do: err()
def newtype_record_echo(_), do: err()
def tuplestruct_record_echo(_), do: err()

def dirty_io(), do: err()
def dirty_cpu(), do: err()
Expand Down
8 changes: 8 additions & 0 deletions rustler_tests/native/rustler_test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@ rustler::init!(
1,
test_codegen::untagged_enum_with_truthy
),
("newtype_echo", 1, test_codegen::newtype_echo),
("tuplestruct_echo", 1, test_codegen::tuplestruct_echo),
("newtype_record_echo", 1, test_codegen::newtype_record_echo),
(
"tuplestruct_record_echo",
1,
test_codegen::tuplestruct_record_echo
),
("dirty_cpu", 0, test_dirty::dirty_cpu, DirtyCpu),
("dirty_io", 0, test_dirty::dirty_io, DirtyIo),
("sum_range", 1, test_range::sum_range),
Expand Down
37 changes: 37 additions & 0 deletions rustler_tests/native/rustler_test/src/test_codegen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,3 +88,40 @@ pub fn untagged_enum_with_truthy<'a>(
let untagged_enum: UntaggedEnumWithTruthy = args[0].decode()?;
Ok(untagged_enum)
}

#[derive(NifTuple)]
pub struct Newtype(i64);

pub fn newtype_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<Newtype> {
let newtype: Newtype = args[0].decode()?;
Ok(newtype)
}

#[derive(NifTuple)]
pub struct TupleStruct(i64, i64, i64);

pub fn tuplestruct_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<TupleStruct> {
let tuplestruct: TupleStruct = args[0].decode()?;
Ok(tuplestruct)
}

#[derive(NifRecord)]
#[tag = "newtype"]
pub struct NewtypeRecord(i64);

pub fn newtype_record_echo<'a>(_env: Env<'a>, args: &[Term<'a>]) -> NifResult<NewtypeRecord> {
let newtype: NewtypeRecord = args[0].decode()?;
Ok(newtype)
}

#[derive(NifRecord)]
#[tag = "tuplestruct"]
pub struct TupleStructRecord(i64, i64, i64);

pub fn tuplestruct_record_echo<'a>(
_env: Env<'a>,
args: &[Term<'a>],
) -> NifResult<TupleStructRecord> {
let tuplestruct: TupleStructRecord = args[0].decode()?;
Ok(tuplestruct)
}
Loading