From 130c9fdfb2294c0f93a2f07b431191089da5e554 Mon Sep 17 00:00:00 2001 From: Alex Sayers Date: Sat, 29 Sep 2018 20:23:57 +0900 Subject: [PATCH 01/11] Factor out dummy_const_trick() --- src/lib.rs | 101 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 60 insertions(+), 41 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 8269eb8..9e2e771 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -50,6 +50,43 @@ use proc_macro2::Span; use syn::{Data, Fields, Ident}; +// Within `exp`, you can bring things into scope with `extern crate`. +// +// We don't want to assume that `num_traits::` is in scope - the user may have imported it under a +// different name, or may have imported it in a non-toplevel module (common when putting impls +// behind a feature gate). +// +// Solution: let's just generate `extern crate num_traits as _num_traits` and then refer to +// `_num_traits` in the derived code. However, macros are not allowed to produce `extern crate` +// statements at the toplevel. +// +// Solution: let's generate `mod _impl_foo` and import num_traits within that. However, now we +// lose access to private members of the surrounding module. This is a problem if, for example, +// we're deriving for a newtype, where the inner type is defined in the same module, but not +// exported. +// +// Solution: use the dummy const trick. For some reason, `extern crate` statements are allowed +// here, but everything from the surrounding module is in scope. This trick is taken from serde. +fn dummy_const_trick( + trait_: &str, + name: &proc_macro2::Ident, + exp: T, +) -> proc_macro2::TokenStream { + let dummy_const = Ident::new( + &format!( + "_IMPL_NUM_{}_FOR_{}", + trait_.to_uppercase(), + format!("{}", name).to_uppercase() + ), + Span::call_site(), + ); + quote! { + const #dummy_const: () = { + #exp + }; + } +} + /// Derives [`num_traits::FromPrimitive`][from] for simple enums. /// /// [from]: https://docs.rs/num-traits/0.2/num_traits/cast/trait.FromPrimitive.html @@ -102,10 +139,6 @@ use syn::{Data, Fields, Ident}; pub fn from_primitive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; - let dummy_const = Ident::new( - &format!("_IMPL_NUM_FROM_PRIMITIVE_FOR_{}", name), - Span::call_site(), - ); let variants = match ast.data { Data::Enum(ref data_enum) => &data_enum.variants, @@ -143,28 +176,23 @@ pub fn from_primitive(input: TokenStream) -> TokenStream { from_i64_var }; - let res = quote! { - #[allow(non_upper_case_globals)] + dummy_const_trick("FromPrimative", &name, quote! { #[allow(unused_qualifications)] - const #dummy_const: () = { - extern crate num_traits as _num_traits; + extern crate num_traits as _num_traits; - impl _num_traits::FromPrimitive for #name { - #[allow(trivial_numeric_casts)] - fn from_i64(#from_i64_var: i64) -> Option { - #(#clauses else)* { - None - } - } - - fn from_u64(n: u64) -> Option { - Self::from_i64(n as i64) + impl _num_traits::FromPrimitive for #name { + #[allow(trivial_numeric_casts)] + fn from_i64(#from_i64_var: i64) -> Option { + #(#clauses else)* { + None } } - }; - }; - res.into() + fn from_u64(n: u64) -> Option { + Self::from_i64(n as i64) + } + } + }).into() } /// Derives [`num_traits::ToPrimitive`][to] for simple enums. @@ -219,10 +247,6 @@ pub fn from_primitive(input: TokenStream) -> TokenStream { pub fn to_primitive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; - let dummy_const = Ident::new( - &format!("_IMPL_NUM_TO_PRIMITIVE_FOR_{}", name), - Span::call_site(), - ); let variants = match ast.data { Data::Enum(ref data_enum) => &data_enum.variants, @@ -263,24 +287,19 @@ pub fn to_primitive(input: TokenStream) -> TokenStream { } }; - let res = quote! { - #[allow(non_upper_case_globals)] + dummy_const_trick("ToPrimative", &name, quote! { #[allow(unused_qualifications)] - const #dummy_const: () = { - extern crate num_traits as _num_traits; - - impl _num_traits::ToPrimitive for #name { - #[allow(trivial_numeric_casts)] - fn to_i64(&self) -> Option { - #match_expr - } + extern crate num_traits as _num_traits; - fn to_u64(&self) -> Option { - self.to_i64().map(|x| x as u64) - } + impl _num_traits::ToPrimitive for #name { + #[allow(trivial_numeric_casts)] + fn to_i64(&self) -> Option { + #match_expr } - }; - }; - res.into() + fn to_u64(&self) -> Option { + self.to_i64().map(|x| x as u64) + } + } + }).into() } From 9a9c80c1bb84535195578ac40e0c5c51004c3311 Mon Sep 17 00:00:00 2001 From: Alex Sayers Date: Wed, 3 Oct 2018 15:59:45 +0900 Subject: [PATCH 02/11] Add the standard num-* build.rs file --- build.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 build.rs diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..fd60866 --- /dev/null +++ b/build.rs @@ -0,0 +1,35 @@ +use std::env; +use std::io::Write; +use std::process::{Command, Stdio}; + +fn main() { + if probe("fn main() { 0i128; }") { + println!("cargo:rustc-cfg=has_i128"); + } else if env::var_os("CARGO_FEATURE_I128").is_some() { + panic!("i128 support was not detected!"); + } +} + +/// Test if a code snippet can be compiled +fn probe(code: &str) -> bool { + let rustc = env::var_os("RUSTC").unwrap_or_else(|| "rustc".into()); + let out_dir = env::var_os("OUT_DIR").expect("environment variable OUT_DIR"); + + let mut child = Command::new(rustc) + .arg("--out-dir") + .arg(out_dir) + .arg("--emit=obj") + .arg("-") + .stdin(Stdio::piped()) + .spawn() + .expect("rustc probe"); + + child + .stdin + .as_mut() + .expect("rustc stdin") + .write_all(code.as_bytes()) + .expect("write rustc stdin"); + + child.wait().expect("rustc probe").success() +} From 75b897241ff896f650cd99291f80ba52e0e8f99a Mon Sep 17 00:00:00 2001 From: Alex Sayers Date: Sat, 29 Sep 2018 20:36:09 +0900 Subject: [PATCH 03/11] Derive {To,From}Primitive for newtypes --- src/lib.rs | 318 ++++++++++++++++++++++++++++++++++------------- tests/newtype.rs | 26 ++++ 2 files changed, 257 insertions(+), 87 deletions(-) create mode 100644 tests/newtype.rs diff --git a/src/lib.rs b/src/lib.rs index 9e2e771..65d7812 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,7 @@ #![crate_type = "proc-macro"] #![doc(html_root_url = "https://docs.rs/num-derive/0.2")] +#![recursion_limit="256"] //! Procedural macros to derive numeric traits in Rust. //! @@ -87,7 +88,31 @@ fn dummy_const_trick( } } -/// Derives [`num_traits::FromPrimitive`][from] for simple enums. +// If `data` is a newtype, return the type it's wrapping. +fn newtype_inner(data: &syn::Data) -> Option { + match data { + &Data::Struct(ref s) => match s.fields { + Fields::Unnamed(ref fs) => { + if fs.unnamed.len() == 1 { + Some(fs.unnamed[0].ty.clone()) + } else { + None + } + } + Fields::Named(ref fs) => { + if fs.named.len() == 1 { + panic!("num-derive doesn't know how to handle newtypes with named fields yet. \ + Please use a tuple-style newtype, or submit a PR!"); + } + None + } + _ => None, + }, + _ => None, + } +} + +/// Derives [`num_traits::FromPrimitive`][from] for simple enums and newtypes. /// /// [from]: https://docs.rs/num-traits/0.2/num_traits/cast/trait.FromPrimitive.html /// @@ -140,62 +165,121 @@ pub fn from_primitive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; - let variants = match ast.data { - Data::Enum(ref data_enum) => &data_enum.variants, - _ => panic!( - "`FromPrimitive` can be applied only to the enums, {} is not an enum", - name - ), - }; - - let from_i64_var = quote! { n }; - let clauses: Vec<_> = variants - .iter() - .map(|variant| { - let ident = &variant.ident; - match variant.fields { - Fields::Unit => (), - _ => panic!( - "`FromPrimitive` can be applied only to unitary enums, \ - {}::{} is either struct or tuple", - name, ident - ), - } - + let impl_ = if let Some(inner_ty) = newtype_inner(&ast.data) { + let i128_fns = if cfg!(has_i128) { quote! { - if #from_i64_var == #name::#ident as i64 { - Some(#name::#ident) + fn from_i128(n: i128) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_i128(n).map(#name) + } + fn from_u128(n: u128) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_u128(n).map(#name) } } - }) - .collect(); + } else { + quote! {} + }; - let from_i64_var = if clauses.is_empty() { - quote!(_) + quote! { + extern crate num_traits as _num_traits; + impl _num_traits::FromPrimitive for #name { + fn from_i64(n: i64) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_i64(n).map(#name) + } + fn from_u64(n: u64) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_u64(n).map(#name) + } + fn from_isize(n: isize) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_isize(n).map(#name) + } + fn from_i8(n: i8) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_i8(n).map(#name) + } + fn from_i16(n: i16) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_i16(n).map(#name) + } + fn from_i32(n: i32) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_i32(n).map(#name) + } + fn from_usize(n: usize) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_usize(n).map(#name) + } + fn from_u8(n: u8) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_u8(n).map(#name) + } + fn from_u16(n: u16) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_u16(n).map(#name) + } + fn from_u32(n: u32) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_u32(n).map(#name) + } + fn from_f32(n: f32) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_f32(n).map(#name) + } + fn from_f64(n: f64) -> Option { + <#inner_ty as _num_traits::FromPrimitive>::from_f64(n).map(#name) + } + #i128_fns + } + } } else { - from_i64_var - }; + let variants = match ast.data { + Data::Enum(ref data_enum) => &data_enum.variants, + _ => panic!( + "`FromPrimitive` can be applied only to enums and newtypes, {} is neither", + name + ), + }; - dummy_const_trick("FromPrimative", &name, quote! { - #[allow(unused_qualifications)] - extern crate num_traits as _num_traits; + let from_i64_var = quote! { n }; + let clauses: Vec<_> = variants + .iter() + .map(|variant| { + let ident = &variant.ident; + match variant.fields { + Fields::Unit => (), + _ => panic!( + "`FromPrimitive` can be applied only to unitary enums and newtypes, \ + {}::{} is either struct or tuple", + name, ident + ), + } - impl _num_traits::FromPrimitive for #name { - #[allow(trivial_numeric_casts)] - fn from_i64(#from_i64_var: i64) -> Option { - #(#clauses else)* { - None + quote! { + if #from_i64_var == #name::#ident as i64 { + Some(#name::#ident) + } } - } + }).collect(); + + let from_i64_var = if clauses.is_empty() { + quote!(_) + } else { + from_i64_var + }; - fn from_u64(n: u64) -> Option { - Self::from_i64(n as i64) + quote! { + #[allow(unused_qualifications)] + extern crate num_traits as _num_traits; + + impl _num_traits::FromPrimitive for #name { + #[allow(trivial_numeric_casts)] + fn from_i64(#from_i64_var: i64) -> Option { + #(#clauses else)* { + None + } + } + + fn from_u64(n: u64) -> Option { + Self::from_i64(n as i64) + } } } - }).into() + }; + + dummy_const_trick("FromPrimitive", &name, impl_).into() } -/// Derives [`num_traits::ToPrimitive`][to] for simple enums. +/// Derives [`num_traits::ToPrimitive`][to] for simple enums and newtypes. /// /// [to]: https://docs.rs/num-traits/0.2/num_traits/cast/trait.ToPrimitive.html /// @@ -248,58 +332,118 @@ pub fn to_primitive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; - let variants = match ast.data { - Data::Enum(ref data_enum) => &data_enum.variants, - _ => panic!( - "`ToPrimitive` can be applied only to the enums, {} is not an enum", - name - ), - }; - - let variants: Vec<_> = variants - .iter() - .map(|variant| { - let ident = &variant.ident; - match variant.fields { - Fields::Unit => (), - _ => { - panic!("`ToPrimitive` can be applied only to unitary enums, {}::{} is either struct or tuple", name, ident) - }, + let impl_ = if let Some(inner_ty) = newtype_inner(&ast.data) { + let i128_fns = if cfg!(has_i128) { + quote! { + fn to_i128(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_i128(&self.0) + } + fn to_u128(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_u128(&self.0) + } } + } else { + quote! {} + }; - // NB: We have to check each variant individually, because we'll only have `&self` - // for the input. We can't move from that, and it might not be `Clone` or `Copy`. - // (Otherwise we could just do `*self as i64` without a `match` at all.) - quote!(#name::#ident => #name::#ident as i64) - }) - .collect(); - - let match_expr = if variants.is_empty() { - // No variants found, so do not use Some to not to trigger `unreachable_code` lint quote! { - match *self {} + extern crate num_traits as _num_traits; + impl _num_traits::ToPrimitive for #name { + fn to_i64(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_i64(&self.0) + } + fn to_u64(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_u64(&self.0) + } + fn to_isize(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_isize(&self.0) + } + fn to_i8(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_i8(&self.0) + } + fn to_i16(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_i16(&self.0) + } + fn to_i32(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_i32(&self.0) + } + fn to_usize(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_usize(&self.0) + } + fn to_u8(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_u8(&self.0) + } + fn to_u16(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_u16(&self.0) + } + fn to_u32(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_u32(&self.0) + } + fn to_f32(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_f32(&self.0) + } + fn to_f64(&self) -> Option { + <#inner_ty as _num_traits::ToPrimitive>::to_f64(&self.0) + } + #i128_fns + } } } else { - quote! { - Some(match *self { - #(#variants,)* - }) - } - }; + let variants = match ast.data { + Data::Enum(ref data_enum) => &data_enum.variants, + _ => panic!( + "`ToPrimitive` can be applied only to enums and newtypes, {} is neither", + name + ), + }; - dummy_const_trick("ToPrimative", &name, quote! { - #[allow(unused_qualifications)] - extern crate num_traits as _num_traits; + let variants: Vec<_> = variants + .iter() + .map(|variant| { + let ident = &variant.ident; + match variant.fields { + Fields::Unit => (), + _ => { + panic!("`ToPrimitive` can be applied only to unitary enums and newtypes, {}::{} is either struct or tuple", name, ident) + }, + } - impl _num_traits::ToPrimitive for #name { - #[allow(trivial_numeric_casts)] - fn to_i64(&self) -> Option { - #match_expr + // NB: We have to check each variant individually, because we'll only have `&self` + // for the input. We can't move from that, and it might not be `Clone` or `Copy`. + // (Otherwise we could just do `*self as i64` without a `match` at all.) + quote!(#name::#ident => #name::#ident as i64) + }) + .collect(); + + let match_expr = if variants.is_empty() { + // No variants found, so do not use Some to not to trigger `unreachable_code` lint + quote! { + match *self {} } + } else { + quote! { + Some(match *self { + #(#variants,)* + }) + } + }; + + quote! { + #[allow(unused_qualifications)] + extern crate num_traits as _num_traits; - fn to_u64(&self) -> Option { - self.to_i64().map(|x| x as u64) + impl _num_traits::ToPrimitive for #name { + #[allow(trivial_numeric_casts)] + fn to_i64(&self) -> Option { + #match_expr + } + + fn to_u64(&self) -> Option { + self.to_i64().map(|x| x as u64) + } } } - }).into() + }; + + dummy_const_trick("ToPrimitive", &name, impl_).into() } diff --git a/tests/newtype.rs b/tests/newtype.rs new file mode 100644 index 0000000..75f4008 --- /dev/null +++ b/tests/newtype.rs @@ -0,0 +1,26 @@ +extern crate num as num_renamed; +#[macro_use] +extern crate num_derive; + +use num_renamed::{FromPrimitive, ToPrimitive}; + +#[derive( + Debug, + Clone, + Copy, + PartialEq, + PartialOrd, + ToPrimitive, + FromPrimitive, +)] +struct MyFloat(f64); + +#[test] +fn test_from_primitive() { + assert_eq!(MyFloat::from_u32(25), Some(MyFloat(25.0))); +} + +#[test] +fn test_to_primitive() { + assert_eq!(MyFloat(25.0).to_u32(), Some(25)); +} From 52e86e241dfcb9137f32d7b853247e092ddf13dd Mon Sep 17 00:00:00 2001 From: Alex Sayers Date: Sat, 29 Sep 2018 21:10:19 +0900 Subject: [PATCH 04/11] Derive NumOps for newtypes This equates to deriving Add, Sub, Mul, Div, and Rem, where RHS=Self and Output=Self. --- src/lib.rs | 49 ++++++++++++++++++++++++++++++++++++++++++++++++ tests/newtype.rs | 10 ++++++++++ 2 files changed, 59 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 65d7812..f5efb99 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -447,3 +447,52 @@ pub fn to_primitive(input: TokenStream) -> TokenStream { dummy_const_trick("ToPrimitive", &name, impl_).into() } + +const NEWTYPE_ONLY: &'static str = "This trait can only be derived for newtypes"; + +/// Derives [`num_traits::NumOps`][num_ops] for newtypes. The inner type must already implement +/// `NumOps`. +/// +/// [num_ops]: https://docs.rs/num-traits/0.2/num_traits/trait.NumOps.html +/// +/// Note that, since `NumOps` is really a trait alias for `Add + Sub + Mul + Div + Rem`, this macro +/// generates impls for _those_ traits. Furthermore, in all generated impls, `RHS=Self` and +/// `Output=Self`. +#[proc_macro_derive(NumOps)] +pub fn num_ops(input: TokenStream) -> TokenStream { + let ast: syn::DeriveInput = syn::parse(input).unwrap(); + let name = &ast.ident; + let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); + dummy_const_trick("NumOps", &name, quote! { + impl ::std::ops::Add for #name { + type Output = Self; + fn add(self, other: Self) -> Self { + #name(<#inner_ty as ::std::ops::Add>::add(self.0, other.0)) + } + } + impl ::std::ops::Sub for #name { + type Output = Self; + fn sub(self, other: Self) -> Self { + #name(<#inner_ty as ::std::ops::Sub>::sub(self.0, other.0)) + } + } + impl ::std::ops::Mul for #name { + type Output = Self; + fn mul(self, other: Self) -> Self { + #name(<#inner_ty as ::std::ops::Mul>::mul(self.0, other.0)) + } + } + impl ::std::ops::Div for #name { + type Output = Self; + fn div(self, other: Self) -> Self { + #name(<#inner_ty as ::std::ops::Div>::div(self.0, other.0)) + } + } + impl ::std::ops::Rem for #name { + type Output = Self; + fn rem(self, other: Self) -> Self { + #name(<#inner_ty as ::std::ops::Rem>::rem(self.0, other.0)) + } + } + }).into() +} diff --git a/tests/newtype.rs b/tests/newtype.rs index 75f4008..1880c1b 100644 --- a/tests/newtype.rs +++ b/tests/newtype.rs @@ -12,6 +12,7 @@ use num_renamed::{FromPrimitive, ToPrimitive}; PartialOrd, ToPrimitive, FromPrimitive, + NumOps, )] struct MyFloat(f64); @@ -24,3 +25,12 @@ fn test_from_primitive() { fn test_to_primitive() { assert_eq!(MyFloat(25.0).to_u32(), Some(25)); } + +#[test] +fn test_num_ops() { + assert_eq!(MyFloat(25.0) + MyFloat(10.0), MyFloat(35.0)); + assert_eq!(MyFloat(25.0) - MyFloat(10.0), MyFloat(15.0)); + assert_eq!(MyFloat(25.0) * MyFloat(2.0), MyFloat(50.0)); + assert_eq!(MyFloat(25.0) / MyFloat(10.0), MyFloat(2.5)); + assert_eq!(MyFloat(25.0) % MyFloat(10.0), MyFloat(5.0)); +} From e4d40fe6b6c39d19f83bc5b34450d5087507447e Mon Sep 17 00:00:00 2001 From: Alex Sayers Date: Sat, 29 Sep 2018 21:19:23 +0900 Subject: [PATCH 05/11] Derive NumCast for newtypes --- src/lib.rs | 19 +++++++++++++++++++ tests/newtype.rs | 8 +++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index f5efb99..6579d30 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -496,3 +496,22 @@ pub fn num_ops(input: TokenStream) -> TokenStream { } }).into() } + +/// Derives [`num_traits::NumCast`][num_cast] for newtypes. The inner type must already implement +/// `NumCast`. +/// +/// [num_cast]: https://docs.rs/num-traits/0.2/num_traits/cast/trait.NumCast.html +#[proc_macro_derive(NumCast)] +pub fn num_cast(input: TokenStream) -> TokenStream { + let ast: syn::DeriveInput = syn::parse(input).unwrap(); + let name = &ast.ident; + let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); + dummy_const_trick("NumCast", &name, quote! { + extern crate num_traits as _num_traits; + impl _num_traits::NumCast for #name { + fn from(n: T) -> Option { + <#inner_ty as _num_traits::NumCast>::from(n).map(#name) + } + } + }).into() +} diff --git a/tests/newtype.rs b/tests/newtype.rs index 1880c1b..7ba0926 100644 --- a/tests/newtype.rs +++ b/tests/newtype.rs @@ -2,7 +2,7 @@ extern crate num as num_renamed; #[macro_use] extern crate num_derive; -use num_renamed::{FromPrimitive, ToPrimitive}; +use num_renamed::{FromPrimitive, ToPrimitive, NumCast}; #[derive( Debug, @@ -13,6 +13,7 @@ use num_renamed::{FromPrimitive, ToPrimitive}; ToPrimitive, FromPrimitive, NumOps, + NumCast, )] struct MyFloat(f64); @@ -34,3 +35,8 @@ fn test_num_ops() { assert_eq!(MyFloat(25.0) / MyFloat(10.0), MyFloat(2.5)); assert_eq!(MyFloat(25.0) % MyFloat(10.0), MyFloat(5.0)); } + +#[test] +fn test_num_cast() { + assert_eq!(::from(25u8), Some(MyFloat(25.0))); +} From b0999000f7aaf12e7d73f5a2cb78e3263ad67f81 Mon Sep 17 00:00:00 2001 From: Alex Sayers Date: Sat, 29 Sep 2018 21:24:25 +0900 Subject: [PATCH 06/11] Derive Zero and One for newtypes --- src/lib.rs | 42 ++++++++++++++++++++++++++++++++++++++++++ tests/newtype.rs | 14 +++++++++++++- 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 6579d30..be45dcf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -515,3 +515,45 @@ pub fn num_cast(input: TokenStream) -> TokenStream { } }).into() } + +/// Derives [`num_traits::Zero`][zero] for newtypes. The inner type must already implement `Zero`. +/// +/// [zero]: https://docs.rs/num-traits/0.2/num_traits/identities/trait.Zero.html +#[proc_macro_derive(Zero)] +pub fn zero(input: TokenStream) -> TokenStream { + let ast: syn::DeriveInput = syn::parse(input).unwrap(); + let name = &ast.ident; + let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); + dummy_const_trick("Zero", &name, quote! { + extern crate num_traits as _num_traits; + impl _num_traits::Zero for #name { + fn zero() -> Self { + #name(<#inner_ty as _num_traits::Zero>::zero()) + } + fn is_zero(&self) -> bool { + <#inner_ty as _num_traits::Zero>::is_zero(&self.0) + } + } + }).into() +} + +/// Derives [`num_traits::One`][one] for newtypes. The inner type must already implement `One`. +/// +/// [one]: https://docs.rs/num-traits/0.2/num_traits/identities/trait.One.html +#[proc_macro_derive(One)] +pub fn one(input: TokenStream) -> TokenStream { + let ast: syn::DeriveInput = syn::parse(input).unwrap(); + let name = &ast.ident; + let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); + dummy_const_trick("One", &name, quote! { + extern crate num_traits as _num_traits; + impl _num_traits::One for #name { + fn one() -> Self { + #name(<#inner_ty as _num_traits::One>::one()) + } + fn is_one(&self) -> bool { + <#inner_ty as _num_traits::One>::is_one(&self.0) + } + } + }).into() +} diff --git a/tests/newtype.rs b/tests/newtype.rs index 7ba0926..cbdff4d 100644 --- a/tests/newtype.rs +++ b/tests/newtype.rs @@ -2,7 +2,7 @@ extern crate num as num_renamed; #[macro_use] extern crate num_derive; -use num_renamed::{FromPrimitive, ToPrimitive, NumCast}; +use num_renamed::{FromPrimitive, ToPrimitive, NumCast, One, Zero}; #[derive( Debug, @@ -14,6 +14,8 @@ use num_renamed::{FromPrimitive, ToPrimitive, NumCast}; FromPrimitive, NumOps, NumCast, + One, + Zero, )] struct MyFloat(f64); @@ -40,3 +42,13 @@ fn test_num_ops() { fn test_num_cast() { assert_eq!(::from(25u8), Some(MyFloat(25.0))); } + +#[test] +fn test_zero() { + assert_eq!(MyFloat::zero(), MyFloat(0.0)); +} + +#[test] +fn test_one() { + assert_eq!(MyFloat::one(), MyFloat(1.0)); +} From a2887aca12b8a3031bb981dc3f88f445b8d2d69c Mon Sep 17 00:00:00 2001 From: Alex Sayers Date: Sat, 29 Sep 2018 21:28:07 +0900 Subject: [PATCH 07/11] Derive Num for newtypes --- src/lib.rs | 19 +++++++++++++++++++ tests/newtype.rs | 8 +++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index be45dcf..9ec13db 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -557,3 +557,22 @@ pub fn one(input: TokenStream) -> TokenStream { } }).into() } + +/// Derives [`num_traits::Num`][num] for newtypes. The inner type must already implement `Num`. +/// +/// [num]: https://docs.rs/num-traits/0.2/num_traits/trait.Num.html +#[proc_macro_derive(Num)] +pub fn num(input: TokenStream) -> TokenStream { + let ast: syn::DeriveInput = syn::parse(input).unwrap(); + let name = &ast.ident; + let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); + dummy_const_trick("Num", &name, quote! { + extern crate num_traits as _num_traits; + impl _num_traits::Num for #name { + type FromStrRadixErr = <#inner_ty as _num_traits::Num>::FromStrRadixErr; + fn from_str_radix(s: &str, radix: u32) -> Result { + <#inner_ty as _num_traits::Num>::from_str_radix(s, radix).map(#name) + } + } + }).into() +} diff --git a/tests/newtype.rs b/tests/newtype.rs index cbdff4d..7136357 100644 --- a/tests/newtype.rs +++ b/tests/newtype.rs @@ -2,7 +2,7 @@ extern crate num as num_renamed; #[macro_use] extern crate num_derive; -use num_renamed::{FromPrimitive, ToPrimitive, NumCast, One, Zero}; +use num_renamed::{FromPrimitive, ToPrimitive, NumCast, One, Zero, Num}; #[derive( Debug, @@ -16,6 +16,7 @@ use num_renamed::{FromPrimitive, ToPrimitive, NumCast, One, Zero}; NumCast, One, Zero, + Num, )] struct MyFloat(f64); @@ -52,3 +53,8 @@ fn test_zero() { fn test_one() { assert_eq!(MyFloat::one(), MyFloat(1.0)); } + +#[test] +fn test_num() { + assert_eq!(MyFloat::from_str_radix("25", 10).ok(), Some(MyFloat(25.0))); +} From 2e751bf960515a6c14559a381aa0cc10076b1e0a Mon Sep 17 00:00:00 2001 From: Alex Sayers Date: Sat, 29 Sep 2018 21:39:24 +0900 Subject: [PATCH 08/11] Derive Float for newtypes --- src/lib.rs | 190 ++++++++++++++++++++++++++++++++++++++++++++++- tests/newtype.rs | 16 +++- 2 files changed, 204 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 9ec13db..ed8997a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,7 +10,7 @@ #![crate_type = "proc-macro"] #![doc(html_root_url = "https://docs.rs/num-derive/0.2")] -#![recursion_limit="256"] +#![recursion_limit="512"] //! Procedural macros to derive numeric traits in Rust. //! @@ -576,3 +576,191 @@ pub fn num(input: TokenStream) -> TokenStream { } }).into() } + +/// Derives [`num_traits::Float`][float] for newtypes. The inner type must already implement +/// `Float`. +/// +/// [float]: https://docs.rs/num-traits/0.2/num_traits/float/trait.Float.html +#[proc_macro_derive(Float)] +pub fn float(input: TokenStream) -> TokenStream { + let ast: syn::DeriveInput = syn::parse(input).unwrap(); + let name = &ast.ident; + let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); + dummy_const_trick("Float", &name, quote! { + extern crate num_traits as _num_traits; + impl _num_traits::Float for #name { + fn nan() -> Self { + #name(<#inner_ty as _num_traits::Float>::nan()) + } + fn infinity() -> Self { + #name(<#inner_ty as _num_traits::Float>::infinity()) + } + fn neg_infinity() -> Self { + #name(<#inner_ty as _num_traits::Float>::neg_infinity()) + } + fn neg_zero() -> Self { + #name(<#inner_ty as _num_traits::Float>::neg_zero()) + } + fn min_value() -> Self { + #name(<#inner_ty as _num_traits::Float>::min_value()) + } + fn min_positive_value() -> Self { + #name(<#inner_ty as _num_traits::Float>::min_positive_value()) + } + fn max_value() -> Self { + #name(<#inner_ty as _num_traits::Float>::max_value()) + } + fn is_nan(self) -> bool { + <#inner_ty as _num_traits::Float>::is_nan(self.0) + } + fn is_infinite(self) -> bool { + <#inner_ty as _num_traits::Float>::is_infinite(self.0) + } + fn is_finite(self) -> bool { + <#inner_ty as _num_traits::Float>::is_finite(self.0) + } + fn is_normal(self) -> bool { + <#inner_ty as _num_traits::Float>::is_normal(self.0) + } + fn classify(self) -> ::std::num::FpCategory { + <#inner_ty as _num_traits::Float>::classify(self.0) + } + fn floor(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::floor(self.0)) + } + fn ceil(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::ceil(self.0)) + } + fn round(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::round(self.0)) + } + fn trunc(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::trunc(self.0)) + } + fn fract(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::fract(self.0)) + } + fn abs(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::abs(self.0)) + } + fn signum(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::signum(self.0)) + } + fn is_sign_positive(self) -> bool { + <#inner_ty as _num_traits::Float>::is_sign_positive(self.0) + } + fn is_sign_negative(self) -> bool { + <#inner_ty as _num_traits::Float>::is_sign_negative(self.0) + } + fn mul_add(self, a: Self, b: Self) -> Self { + #name(<#inner_ty as _num_traits::Float>::mul_add(self.0, a.0, b.0)) + } + fn recip(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::recip(self.0)) + } + fn powi(self, n: i32) -> Self { + #name(<#inner_ty as _num_traits::Float>::powi(self.0, n)) + } + fn powf(self, n: Self) -> Self { + #name(<#inner_ty as _num_traits::Float>::powf(self.0, n.0)) + } + fn sqrt(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::sqrt(self.0)) + } + fn exp(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::exp(self.0)) + } + fn exp2(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::exp2(self.0)) + } + fn ln(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::ln(self.0)) + } + fn log(self, base: Self) -> Self { + #name(<#inner_ty as _num_traits::Float>::log(self.0, base.0)) + } + fn log2(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::log2(self.0)) + } + fn log10(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::log10(self.0)) + } + fn max(self, other: Self) -> Self { + #name(<#inner_ty as _num_traits::Float>::max(self.0, other.0)) + } + fn min(self, other: Self) -> Self { + #name(<#inner_ty as _num_traits::Float>::min(self.0, other.0)) + } + fn abs_sub(self, other: Self) -> Self { + #name(<#inner_ty as _num_traits::Float>::abs_sub(self.0, other.0)) + } + fn cbrt(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::cbrt(self.0)) + } + fn hypot(self, other: Self) -> Self { + #name(<#inner_ty as _num_traits::Float>::hypot(self.0, other.0)) + } + fn sin(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::sin(self.0)) + } + fn cos(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::cos(self.0)) + } + fn tan(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::tan(self.0)) + } + fn asin(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::asin(self.0)) + } + fn acos(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::acos(self.0)) + } + fn atan(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::atan(self.0)) + } + fn atan2(self, other: Self) -> Self { + #name(<#inner_ty as _num_traits::Float>::atan2(self.0, other.0)) + } + fn sin_cos(self) -> (Self, Self) { + let (x, y) = <#inner_ty as _num_traits::Float>::sin_cos(self.0); + (#name(x), #name(y)) + } + fn exp_m1(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::exp_m1(self.0)) + } + fn ln_1p(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::ln_1p(self.0)) + } + fn sinh(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::sinh(self.0)) + } + fn cosh(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::cosh(self.0)) + } + fn tanh(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::tanh(self.0)) + } + fn asinh(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::asinh(self.0)) + } + fn acosh(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::acosh(self.0)) + } + fn atanh(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::atanh(self.0)) + } + fn integer_decode(self) -> (u64, i16, i8) { + <#inner_ty as _num_traits::Float>::integer_decode(self.0) + } + fn epsilon() -> Self { + #name(<#inner_ty as _num_traits::Float>::epsilon()) + } + fn to_degrees(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::to_degrees(self.0)) + } + fn to_radians(self) -> Self { + #name(<#inner_ty as _num_traits::Float>::to_radians(self.0)) + } + } + }).into() +} diff --git a/tests/newtype.rs b/tests/newtype.rs index 7136357..c08aec7 100644 --- a/tests/newtype.rs +++ b/tests/newtype.rs @@ -2,7 +2,8 @@ extern crate num as num_renamed; #[macro_use] extern crate num_derive; -use num_renamed::{FromPrimitive, ToPrimitive, NumCast, One, Zero, Num}; +use num_renamed::{FromPrimitive, ToPrimitive, NumCast, One, Zero, Num, Float}; +use std::ops::Neg; #[derive( Debug, @@ -17,9 +18,17 @@ use num_renamed::{FromPrimitive, ToPrimitive, NumCast, One, Zero, Num}; One, Zero, Num, + Float, )] struct MyFloat(f64); +impl Neg for MyFloat { + type Output = MyFloat; + fn neg(self) -> Self { + MyFloat(self.0.neg()) + } +} + #[test] fn test_from_primitive() { assert_eq!(MyFloat::from_u32(25), Some(MyFloat(25.0))); @@ -58,3 +67,8 @@ fn test_one() { fn test_num() { assert_eq!(MyFloat::from_str_radix("25", 10).ok(), Some(MyFloat(25.0))); } + +#[test] +fn test_float() { + assert_eq!(MyFloat(4.0).log(MyFloat(2.0)), MyFloat(2.0)); +} From 8f54ad2231b056106e29a7f2e65d1043cedf94d2 Mon Sep 17 00:00:00 2001 From: Alex Sayers Date: Sun, 30 Sep 2018 12:59:24 +0900 Subject: [PATCH 09/11] Add "newtype deriving" entry to RELEASES --- RELEASES.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/RELEASES.md b/RELEASES.md index 17f97e3..fc9a10d 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -1,3 +1,10 @@ +# Unreleased + +- [Added newtype deriving][17] for `FromPrimitive`, `ToPrimitive`, + `NumOps`, `NumCast`, `Zero`, `One`, `Num`, and `Float`. + +[17]: https://github.com/rust-num/num-derive/pull/17 + # Release 0.2.2 (2018-05-22) - [Updated dependencies][14]. From 203a3db0280256eee60925e535df2a57e930eca2 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Wed, 3 Oct 2018 09:58:05 -0700 Subject: [PATCH 10/11] Explicitly use build.rs in Cargo.toml This is needed for older compilers, even though we know they won't have i128 support anyway... --- Cargo.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/Cargo.toml b/Cargo.toml index a2c7a7d..204ff58 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,7 @@ name = "num-derive" repository = "https://github.com/rust-num/num-derive" version = "0.2.2" readme = "README.md" +build = "build.rs" [dependencies] num-traits = "0.2" From 706ea88d1459ea9e803249eff5a3790295b302c4 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Wed, 3 Oct 2018 09:59:51 -0700 Subject: [PATCH 11/11] Add explicit tests of has_i128-derived methods --- tests/newtype.rs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/newtype.rs b/tests/newtype.rs index c08aec7..98d77c8 100644 --- a/tests/newtype.rs +++ b/tests/newtype.rs @@ -34,11 +34,25 @@ fn test_from_primitive() { assert_eq!(MyFloat::from_u32(25), Some(MyFloat(25.0))); } +#[test] +#[cfg(has_i128)] +fn test_from_primitive_128() { + assert_eq!(MyFloat::from_i128(std::i128::MIN), Some(MyFloat(-2.0.powi(127)))); +} + #[test] fn test_to_primitive() { assert_eq!(MyFloat(25.0).to_u32(), Some(25)); } +#[test] +#[cfg(has_i128)] +fn test_to_primitive_128() { + let f = MyFloat::from_f32(std::f32::MAX).unwrap(); + assert_eq!(f.to_i128(), None); + assert_eq!(f.to_u128(), Some(0xffff_ff00_0000_0000_0000_0000_0000_0000)); +} + #[test] fn test_num_ops() { assert_eq!(MyFloat(25.0) + MyFloat(10.0), MyFloat(35.0));