From 1da2450817ddf6b29776a2f5268402b17c5e5b6e Mon Sep 17 00:00:00 2001 From: jean-airoldie <25088801+jean-airoldie@users.noreply.github.com> Date: Sun, 3 Nov 2019 16:29:27 -0500 Subject: [PATCH 1/9] Add `num_traits` proc_macro helper for explicit import This allows the user to specify a identifier for the `num_traits` crate so that the proc_macro can directly depend in it. This is usefull when reexporting `num-derive` and using `num-trait` as a transitive import. Fixes https://github.com/rust-num/num-derive/issues/34. --- ci/test_full.sh | 3 + import/Cargo.toml | 10 + import/src/lib.rs | 19 ++ import/src/main.rs | 3 + src/lib.rs | 692 +++++++++++++++++++++++++++------------------ 5 files changed, 459 insertions(+), 268 deletions(-) create mode 100644 import/Cargo.toml create mode 100644 import/src/lib.rs create mode 100644 import/src/main.rs diff --git a/ci/test_full.sh b/ci/test_full.sh index 08b1e27..5f35ca8 100755 --- a/ci/test_full.sh +++ b/ci/test_full.sh @@ -45,3 +45,6 @@ done # test all supported features cargo build --features="${FEATURES[*]}" cargo test --features="${FEATURES[*]}" + +cd check; cargo test --verbose check; cd .. +cd import; cargo test --verbose import; cd .. diff --git a/import/Cargo.toml b/import/Cargo.toml new file mode 100644 index 0000000..2a737c1 --- /dev/null +++ b/import/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "import" +version = "0.0.1" +authors = ["jean-airoldie <25088801+jean-airoldie@users.noreply.github.com>"] +edition = "2018" +publish = false + +[dependencies] +num-derive = { path = "../" } +num = { version = "0.2", default-features = false } diff --git a/import/src/lib.rs b/import/src/lib.rs new file mode 100644 index 0000000..9e8bbcb --- /dev/null +++ b/import/src/lib.rs @@ -0,0 +1,19 @@ +#[macro_use] +extern crate num_derive; + +#[derive( + Debug, + Clone, + Copy, + PartialEq, + PartialOrd, + ToPrimitive, + FromPrimitive, +)] +#[num_traits = "num"] +#[repr(u8)] +enum Rgb { + Red = 0, + Green = 1, + Black = 2, +} diff --git a/import/src/main.rs b/import/src/main.rs new file mode 100644 index 0000000..e7a11a9 --- /dev/null +++ b/import/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/src/lib.rs b/src/lib.rs index be77fb5..6017f07 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -38,13 +38,73 @@ //! } //! # fn main() {} //! ``` +//! +//! ## Explicit import +//! +//! By default the `num_derive` procedural macros assume that the +//! `num_traits` crate is a direct dependency. If `num_traits` is instead +//! a transitive dependency, the `num_traits` helper attribute can be +//! used to tell `num_derive` to use a specific identifier for its imports. +//! +//! ```rust +//! #[macro_use] +//! extern crate num_derive; +//! // Lets pretend this is a transitive dependency from another crate +//! // reexported as `some_other_ident`. +//! extern crate num_traits as some_other_ident; +//! +//! #[derive(FromPrimitive, ToPrimitive)] +//! #[num_traits = "some_other_ident"] +//! enum Color { +//! Red, +//! Blue, +//! Green, +//! } +//! # fn main() {} +//! ``` extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::Span; use quote::quote; -use syn::{Data, Fields, Ident}; +use std::fmt; +use syn::{Data, Fields, Ident, Path}; + +#[derive(Copy, Clone)] +struct Symbol(&'static str); + +const NUM_TRAITS: Symbol = Symbol("num_traits"); + +impl PartialEq for Ident { + fn eq(&self, word: &Symbol) -> bool { + self == word.0 + } +} + +impl<'a> PartialEq for &'a Ident { + fn eq(&self, word: &Symbol) -> bool { + *self == word.0 + } +} + +impl PartialEq for Path { + fn eq(&self, word: &Symbol) -> bool { + self.is_ident(word.0) + } +} + +impl<'a> PartialEq for &'a Path { + fn eq(&self, word: &Symbol) -> bool { + self.is_ident(word.0) + } +} + +impl fmt::Display for Symbol { + fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + formatter.write_str(self.0) + } +} // Within `exp`, you can bring things into scope with `extern crate`. // @@ -52,7 +112,7 @@ use syn::{Data, Fields, Ident}; // 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 +// 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. // @@ -113,6 +173,28 @@ fn newtype_inner(data: &syn::Data) -> Option { } } +// If there as `num_traits` MetaNameValue attribute within the slice, +// retreive its value, and use it to create a Ident to be used to import +// the `num_traits` crate. +fn find_explicit_import_ident(attrs: &[syn::Attribute]) -> Option { + for attr in attrs { + if let Ok(syn::Meta::NameValue(mnv)) = attr.parse_meta() { + if mnv.path == NUM_TRAITS { + match mnv.lit { + syn::Lit::Str(lit_str) => { + let import_str = &lit_str.value(); + let span = proc_macro2::Span::call_site(); + let import_ident = syn::Ident::new(import_str, span); + return Some(import_ident); + } + _ => panic!("#[{}] attribute value must be a str", NUM_TRAITS), + } + } + } + } + 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 @@ -161,55 +243,63 @@ fn newtype_inner(data: &syn::Data) -> Option { /// } /// # fn main() {} /// ``` -#[proc_macro_derive(FromPrimitive)] +#[proc_macro_derive(FromPrimitive, attributes(num_traits))] pub fn from_primitive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; + let explicit_import = find_explicit_import_ident(&ast.attrs); + let is_explicit_import = explicit_import.is_some(); + + let import = match explicit_import { + Some(ident) => ident, + None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), + }; + let impl_ = if let Some(inner_ty) = newtype_inner(&ast.data) { quote! { - impl _num_traits::FromPrimitive for #name { + impl #import::FromPrimitive for #name { fn from_i64(n: i64) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_i64(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_i64(n).map(#name) } fn from_u64(n: u64) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_u64(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_u64(n).map(#name) } fn from_isize(n: isize) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_isize(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_isize(n).map(#name) } fn from_i8(n: i8) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_i8(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_i8(n).map(#name) } fn from_i16(n: i16) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_i16(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_i16(n).map(#name) } fn from_i32(n: i32) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_i32(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_i32(n).map(#name) } fn from_i128(n: i128) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_i128(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_i128(n).map(#name) } fn from_usize(n: usize) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_usize(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_usize(n).map(#name) } fn from_u8(n: u8) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_u8(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_u8(n).map(#name) } fn from_u16(n: u16) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_u16(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_u16(n).map(#name) } fn from_u32(n: u32) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_u32(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_u32(n).map(#name) } fn from_u128(n: u128) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_u128(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_u128(n).map(#name) } fn from_f32(n: f32) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_f32(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_f32(n).map(#name) } fn from_f64(n: f64) -> Option { - <#inner_ty as _num_traits::FromPrimitive>::from_f64(n).map(#name) + <#inner_ty as #import::FromPrimitive>::from_f64(n).map(#name) } } } @@ -251,7 +341,7 @@ pub fn from_primitive(input: TokenStream) -> TokenStream { }; quote! { - impl _num_traits::FromPrimitive for #name { + impl #import::FromPrimitive for #name { #[allow(trivial_numeric_casts)] fn from_i64(#from_i64_var: i64) -> Option { #(#clauses else)* { @@ -266,7 +356,11 @@ pub fn from_primitive(input: TokenStream) -> TokenStream { } }; - dummy_const_trick("FromPrimitive", &name, impl_).into() + if is_explicit_import { + impl_.into() + } else { + dummy_const_trick("FromPrimitive", &name, impl_).into() + } } /// Derives [`num_traits::ToPrimitive`][to] for simple enums and newtypes. @@ -322,50 +416,58 @@ pub fn to_primitive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; + let explicit_import = find_explicit_import_ident(&ast.attrs); + let is_explicit_import = explicit_import.is_some(); + + let import = match explicit_import { + Some(ident) => ident, + None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), + }; + let impl_ = if let Some(inner_ty) = newtype_inner(&ast.data) { quote! { - impl _num_traits::ToPrimitive for #name { + impl #import::ToPrimitive for #name { fn to_i64(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_i64(&self.0) + <#inner_ty as #import::ToPrimitive>::to_i64(&self.0) } fn to_u64(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_u64(&self.0) + <#inner_ty as #import::ToPrimitive>::to_u64(&self.0) } fn to_isize(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_isize(&self.0) + <#inner_ty as #import::ToPrimitive>::to_isize(&self.0) } fn to_i8(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_i8(&self.0) + <#inner_ty as #import::ToPrimitive>::to_i8(&self.0) } fn to_i16(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_i16(&self.0) + <#inner_ty as #import::ToPrimitive>::to_i16(&self.0) } fn to_i32(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_i32(&self.0) + <#inner_ty as #import::ToPrimitive>::to_i32(&self.0) } fn to_i128(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_i128(&self.0) + <#inner_ty as #import::ToPrimitive>::to_i128(&self.0) } fn to_usize(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_usize(&self.0) + <#inner_ty as #import::ToPrimitive>::to_usize(&self.0) } fn to_u8(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_u8(&self.0) + <#inner_ty as #import::ToPrimitive>::to_u8(&self.0) } fn to_u16(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_u16(&self.0) + <#inner_ty as #import::ToPrimitive>::to_u16(&self.0) } fn to_u32(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_u32(&self.0) + <#inner_ty as #import::ToPrimitive>::to_u32(&self.0) } fn to_u128(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_u128(&self.0) + <#inner_ty as #import::ToPrimitive>::to_u128(&self.0) } fn to_f32(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_f32(&self.0) + <#inner_ty as #import::ToPrimitive>::to_f32(&self.0) } fn to_f64(&self) -> Option { - <#inner_ty as _num_traits::ToPrimitive>::to_f64(&self.0) + <#inner_ty as #import::ToPrimitive>::to_f64(&self.0) } } } @@ -410,7 +512,7 @@ pub fn to_primitive(input: TokenStream) -> TokenStream { }; quote! { - impl _num_traits::ToPrimitive for #name { + impl #import::ToPrimitive for #name { #[allow(trivial_numeric_casts)] fn to_i64(&self) -> Option { #match_expr @@ -423,7 +525,11 @@ pub fn to_primitive(input: TokenStream) -> TokenStream { } }; - dummy_const_trick("ToPrimitive", &name, impl_).into() + if is_explicit_import { + impl_.into() + } else { + dummy_const_trick("ToPrimitive", &name, impl_).into() + } } const NEWTYPE_ONLY: &str = "This trait can only be derived for newtypes"; @@ -489,18 +595,28 @@ 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! { - impl _num_traits::NumCast for #name { - fn from(n: T) -> Option { - <#inner_ty as _num_traits::NumCast>::from(n).map(#name) - } + + let explicit_import = find_explicit_import_ident(&ast.attrs); + let is_explicit_import = explicit_import.is_some(); + + let import = match explicit_import { + Some(ident) => ident, + None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), + }; + + let impl_ = quote! { + impl #import::NumCast for #name { + fn from(n: T) -> Option { + <#inner_ty as #import::NumCast>::from(n).map(#name) } - }, - ) - .into() + } + }; + + if is_explicit_import { + impl_.into() + } else { + dummy_const_trick("NumCast", &name, impl_).into() + } } /// Derives [`num_traits::Zero`][zero] for newtypes. The inner type must already implement `Zero`. @@ -511,21 +627,31 @@ 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! { - 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) - } + + let explicit_import = find_explicit_import_ident(&ast.attrs); + let is_explicit_import = explicit_import.is_some(); + + let import = match explicit_import { + Some(ident) => ident, + None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), + }; + + let impl_ = quote! { + impl #import::Zero for #name { + fn zero() -> Self { + #name(<#inner_ty as #import::Zero>::zero()) } - }, - ) - .into() + fn is_zero(&self) -> bool { + <#inner_ty as #import::Zero>::is_zero(&self.0) + } + } + }; + + if is_explicit_import { + impl_.into() + } else { + dummy_const_trick("Zero", &name, impl_).into() + } } /// Derives [`num_traits::One`][one] for newtypes. The inner type must already implement `One`. @@ -536,21 +662,31 @@ 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! { - 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) - } + + let explicit_import = find_explicit_import_ident(&ast.attrs); + let is_explicit_import = explicit_import.is_some(); + + let import = match explicit_import { + Some(ident) => ident, + None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), + }; + + let impl_ = quote! { + impl #import::One for #name { + fn one() -> Self { + #name(<#inner_ty as #import::One>::one()) } - }, - ) - .into() + fn is_one(&self) -> bool { + <#inner_ty as #import::One>::is_one(&self.0) + } + } + }; + + if is_explicit_import { + impl_.into() + } else { + dummy_const_trick("One", &name, impl_).into() + } } /// Derives [`num_traits::Num`][num] for newtypes. The inner type must already implement `Num`. @@ -561,19 +697,29 @@ 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! { - 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) - } + + let explicit_import = find_explicit_import_ident(&ast.attrs); + let is_explicit_import = explicit_import.is_some(); + + let import = match explicit_import { + Some(ident) => ident, + None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), + }; + + let impl_ = quote! { + impl #import::Num for #name { + type FromStrRadixErr = <#inner_ty as #import::Num>::FromStrRadixErr; + fn from_str_radix(s: &str, radix: u32) -> Result { + <#inner_ty as #import::Num>::from_str_radix(s, radix).map(#name) } - }, - ) - .into() + } + }; + + if is_explicit_import { + impl_.into() + } else { + dummy_const_trick("Num", &name, impl_).into() + } } /// Derives [`num_traits::Float`][float] for newtypes. The inner type must already implement @@ -585,185 +731,195 @@ 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! { - 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)) - } + + let explicit_import = find_explicit_import_ident(&ast.attrs); + let is_explicit_import = explicit_import.is_some(); + + let import = match explicit_import { + Some(ident) => ident, + None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), + }; + + let impl_ = quote! { + impl #import::Float for #name { + fn nan() -> Self { + #name(<#inner_ty as #import::Float>::nan()) } - }, - ) - .into() + fn infinity() -> Self { + #name(<#inner_ty as #import::Float>::infinity()) + } + fn neg_infinity() -> Self { + #name(<#inner_ty as #import::Float>::neg_infinity()) + } + fn neg_zero() -> Self { + #name(<#inner_ty as #import::Float>::neg_zero()) + } + fn min_value() -> Self { + #name(<#inner_ty as #import::Float>::min_value()) + } + fn min_positive_value() -> Self { + #name(<#inner_ty as #import::Float>::min_positive_value()) + } + fn max_value() -> Self { + #name(<#inner_ty as #import::Float>::max_value()) + } + fn is_nan(self) -> bool { + <#inner_ty as #import::Float>::is_nan(self.0) + } + fn is_infinite(self) -> bool { + <#inner_ty as #import::Float>::is_infinite(self.0) + } + fn is_finite(self) -> bool { + <#inner_ty as #import::Float>::is_finite(self.0) + } + fn is_normal(self) -> bool { + <#inner_ty as #import::Float>::is_normal(self.0) + } + fn classify(self) -> ::std::num::FpCategory { + <#inner_ty as #import::Float>::classify(self.0) + } + fn floor(self) -> Self { + #name(<#inner_ty as #import::Float>::floor(self.0)) + } + fn ceil(self) -> Self { + #name(<#inner_ty as #import::Float>::ceil(self.0)) + } + fn round(self) -> Self { + #name(<#inner_ty as #import::Float>::round(self.0)) + } + fn trunc(self) -> Self { + #name(<#inner_ty as #import::Float>::trunc(self.0)) + } + fn fract(self) -> Self { + #name(<#inner_ty as #import::Float>::fract(self.0)) + } + fn abs(self) -> Self { + #name(<#inner_ty as #import::Float>::abs(self.0)) + } + fn signum(self) -> Self { + #name(<#inner_ty as #import::Float>::signum(self.0)) + } + fn is_sign_positive(self) -> bool { + <#inner_ty as #import::Float>::is_sign_positive(self.0) + } + fn is_sign_negative(self) -> bool { + <#inner_ty as #import::Float>::is_sign_negative(self.0) + } + fn mul_add(self, a: Self, b: Self) -> Self { + #name(<#inner_ty as #import::Float>::mul_add(self.0, a.0, b.0)) + } + fn recip(self) -> Self { + #name(<#inner_ty as #import::Float>::recip(self.0)) + } + fn powi(self, n: i32) -> Self { + #name(<#inner_ty as #import::Float>::powi(self.0, n)) + } + fn powf(self, n: Self) -> Self { + #name(<#inner_ty as #import::Float>::powf(self.0, n.0)) + } + fn sqrt(self) -> Self { + #name(<#inner_ty as #import::Float>::sqrt(self.0)) + } + fn exp(self) -> Self { + #name(<#inner_ty as #import::Float>::exp(self.0)) + } + fn exp2(self) -> Self { + #name(<#inner_ty as #import::Float>::exp2(self.0)) + } + fn ln(self) -> Self { + #name(<#inner_ty as #import::Float>::ln(self.0)) + } + fn log(self, base: Self) -> Self { + #name(<#inner_ty as #import::Float>::log(self.0, base.0)) + } + fn log2(self) -> Self { + #name(<#inner_ty as #import::Float>::log2(self.0)) + } + fn log10(self) -> Self { + #name(<#inner_ty as #import::Float>::log10(self.0)) + } + fn max(self, other: Self) -> Self { + #name(<#inner_ty as #import::Float>::max(self.0, other.0)) + } + fn min(self, other: Self) -> Self { + #name(<#inner_ty as #import::Float>::min(self.0, other.0)) + } + fn abs_sub(self, other: Self) -> Self { + #name(<#inner_ty as #import::Float>::abs_sub(self.0, other.0)) + } + fn cbrt(self) -> Self { + #name(<#inner_ty as #import::Float>::cbrt(self.0)) + } + fn hypot(self, other: Self) -> Self { + #name(<#inner_ty as #import::Float>::hypot(self.0, other.0)) + } + fn sin(self) -> Self { + #name(<#inner_ty as #import::Float>::sin(self.0)) + } + fn cos(self) -> Self { + #name(<#inner_ty as #import::Float>::cos(self.0)) + } + fn tan(self) -> Self { + #name(<#inner_ty as #import::Float>::tan(self.0)) + } + fn asin(self) -> Self { + #name(<#inner_ty as #import::Float>::asin(self.0)) + } + fn acos(self) -> Self { + #name(<#inner_ty as #import::Float>::acos(self.0)) + } + fn atan(self) -> Self { + #name(<#inner_ty as #import::Float>::atan(self.0)) + } + fn atan2(self, other: Self) -> Self { + #name(<#inner_ty as #import::Float>::atan2(self.0, other.0)) + } + fn sin_cos(self) -> (Self, Self) { + let (x, y) = <#inner_ty as #import::Float>::sin_cos(self.0); + (#name(x), #name(y)) + } + fn exp_m1(self) -> Self { + #name(<#inner_ty as #import::Float>::exp_m1(self.0)) + } + fn ln_1p(self) -> Self { + #name(<#inner_ty as #import::Float>::ln_1p(self.0)) + } + fn sinh(self) -> Self { + #name(<#inner_ty as #import::Float>::sinh(self.0)) + } + fn cosh(self) -> Self { + #name(<#inner_ty as #import::Float>::cosh(self.0)) + } + fn tanh(self) -> Self { + #name(<#inner_ty as #import::Float>::tanh(self.0)) + } + fn asinh(self) -> Self { + #name(<#inner_ty as #import::Float>::asinh(self.0)) + } + fn acosh(self) -> Self { + #name(<#inner_ty as #import::Float>::acosh(self.0)) + } + fn atanh(self) -> Self { + #name(<#inner_ty as #import::Float>::atanh(self.0)) + } + fn integer_decode(self) -> (u64, i16, i8) { + <#inner_ty as #import::Float>::integer_decode(self.0) + } + fn epsilon() -> Self { + #name(<#inner_ty as #import::Float>::epsilon()) + } + fn to_degrees(self) -> Self { + #name(<#inner_ty as #import::Float>::to_degrees(self.0)) + } + fn to_radians(self) -> Self { + #name(<#inner_ty as #import::Float>::to_radians(self.0)) + } + } + }; + + if is_explicit_import { + impl_.into() + } else { + dummy_const_trick("Float", &name, impl_).into() + } } From ffcae8dfc78a56c95a94f6b3bd51f69ec91c9530 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 26 Jun 2020 16:02:27 -0700 Subject: [PATCH 2/9] Remove a stray backquote --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 6017f07..36f7d7f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -112,7 +112,7 @@ impl fmt::Display for Symbol { // 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 +// 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. // From 824074f2d9350455aaef3bbf22ed531f98309c8f Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 26 Jun 2020 16:04:01 -0700 Subject: [PATCH 3/9] Spelling fix --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 36f7d7f..6ed6c85 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -174,7 +174,7 @@ fn newtype_inner(data: &syn::Data) -> Option { } // If there as `num_traits` MetaNameValue attribute within the slice, -// retreive its value, and use it to create a Ident to be used to import +// retrieve its value, and use it to create an `Ident` to be used to import // the `num_traits` crate. fn find_explicit_import_ident(attrs: &[syn::Attribute]) -> Option { for attr in attrs { From d4cf5d834feec01a5606033c2bf226de56199cfa Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 26 Jun 2020 16:08:07 -0700 Subject: [PATCH 4/9] remove Symbol, just compare `is_ident` directly --- src/lib.rs | 42 +++--------------------------------------- 1 file changed, 3 insertions(+), 39 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 6ed6c85..d3fe6aa 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -68,43 +68,7 @@ extern crate proc_macro; use proc_macro::TokenStream; use proc_macro2::Span; use quote::quote; -use std::fmt; -use syn::{Data, Fields, Ident, Path}; - -#[derive(Copy, Clone)] -struct Symbol(&'static str); - -const NUM_TRAITS: Symbol = Symbol("num_traits"); - -impl PartialEq for Ident { - fn eq(&self, word: &Symbol) -> bool { - self == word.0 - } -} - -impl<'a> PartialEq for &'a Ident { - fn eq(&self, word: &Symbol) -> bool { - *self == word.0 - } -} - -impl PartialEq for Path { - fn eq(&self, word: &Symbol) -> bool { - self.is_ident(word.0) - } -} - -impl<'a> PartialEq for &'a Path { - fn eq(&self, word: &Symbol) -> bool { - self.is_ident(word.0) - } -} - -impl fmt::Display for Symbol { - fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { - formatter.write_str(self.0) - } -} +use syn::{Data, Fields, Ident}; // Within `exp`, you can bring things into scope with `extern crate`. // @@ -179,7 +143,7 @@ fn newtype_inner(data: &syn::Data) -> Option { fn find_explicit_import_ident(attrs: &[syn::Attribute]) -> Option { for attr in attrs { if let Ok(syn::Meta::NameValue(mnv)) = attr.parse_meta() { - if mnv.path == NUM_TRAITS { + if mnv.path.is_ident("num_traits") { match mnv.lit { syn::Lit::Str(lit_str) => { let import_str = &lit_str.value(); @@ -187,7 +151,7 @@ fn find_explicit_import_ident(attrs: &[syn::Attribute]) -> Option { let import_ident = syn::Ident::new(import_str, span); return Some(import_ident); } - _ => panic!("#[{}] attribute value must be a str", NUM_TRAITS), + _ => panic!("#[num_traits] attribute value must be a str"), } } } From 864a99a52e32d80d581087ce0ac0d899a15cc38b Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 26 Jun 2020 16:09:25 -0700 Subject: [PATCH 5/9] Add attributes(num_traits) on everything that tries to use it --- src/lib.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index d3fe6aa..11d48b2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -375,7 +375,7 @@ pub fn from_primitive(input: TokenStream) -> TokenStream { /// } /// # fn main() {} /// ``` -#[proc_macro_derive(ToPrimitive)] +#[proc_macro_derive(ToPrimitive, attributes(num_traits))] pub fn to_primitive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; @@ -554,7 +554,7 @@ pub fn num_ops(input: TokenStream) -> TokenStream { /// `NumCast`. /// /// [num_cast]: https://docs.rs/num-traits/0.2/num_traits/cast/trait.NumCast.html -#[proc_macro_derive(NumCast)] +#[proc_macro_derive(NumCast, attributes(num_traits))] pub fn num_cast(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; @@ -586,7 +586,7 @@ pub fn num_cast(input: TokenStream) -> TokenStream { /// 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)] +#[proc_macro_derive(Zero, attributes(num_traits))] pub fn zero(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; @@ -621,7 +621,7 @@ pub fn zero(input: TokenStream) -> TokenStream { /// 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)] +#[proc_macro_derive(One, attributes(num_traits))] pub fn one(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; @@ -656,7 +656,7 @@ pub fn one(input: TokenStream) -> TokenStream { /// 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)] +#[proc_macro_derive(Num, attributes(num_traits))] pub fn num(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; @@ -690,7 +690,7 @@ pub fn num(input: TokenStream) -> TokenStream { /// `Float`. /// /// [float]: https://docs.rs/num-traits/0.2/num_traits/float/trait.Float.html -#[proc_macro_derive(Float)] +#[proc_macro_derive(Float, attributes(num_traits))] pub fn float(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; From 3733a7f5845c8708d402c59be65966553f0ff6c0 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 26 Jun 2020 16:14:30 -0700 Subject: [PATCH 6/9] Update to num 0.3 --- Cargo.toml | 2 +- import/Cargo.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 6b71c8b..be4586a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,7 +19,7 @@ quote = "1" syn = "1" [dev-dependencies] -num = "0.2" +num = "0.3" num-traits = "0.2" [features] diff --git a/import/Cargo.toml b/import/Cargo.toml index 2a737c1..d23f91e 100644 --- a/import/Cargo.toml +++ b/import/Cargo.toml @@ -7,4 +7,4 @@ publish = false [dependencies] num-derive = { path = "../" } -num = { version = "0.2", default-features = false } +num = { version = "0.3", default-features = false } From 4ac994e64f3429084e2f182f40f5cb12c328a4c9 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 26 Jun 2020 16:19:13 -0700 Subject: [PATCH 7/9] move CI crates to ci/ --- .github/workflows/ci.yaml | 2 +- {check => ci/check}/Cargo.toml | 2 +- {check => ci/check}/src/lib.rs | 0 {import => ci/import}/Cargo.toml | 2 +- {import => ci/import}/src/lib.rs | 0 ci/test_full.sh | 5 +++-- import/src/main.rs | 3 --- 7 files changed, 6 insertions(+), 8 deletions(-) rename {check => ci/check}/Cargo.toml (93%) rename {check => ci/check}/src/lib.rs (100%) rename {import => ci/import}/Cargo.toml (87%) rename {import => ci/import}/src/lib.rs (100%) delete mode 100644 import/src/main.rs diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 546b4ab..4ee4655 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -49,7 +49,7 @@ jobs: command: build # This test crate is intentionally separate, because we need # independent features for no-std. (rust-lang/cargo#2589) - args: --target thumbv6m-none-eabi --manifest-path check/Cargo.toml + args: --target thumbv6m-none-eabi --manifest-path ci/check/Cargo.toml fmt: name: Format diff --git a/check/Cargo.toml b/ci/check/Cargo.toml similarity index 93% rename from check/Cargo.toml rename to ci/check/Cargo.toml index 854bf7c..12f31d2 100644 --- a/check/Cargo.toml +++ b/ci/check/Cargo.toml @@ -5,7 +5,7 @@ authors = ["Josh Stone "] edition = "2018" [dependencies.num-derive] -path = ".." +path = "../.." [dependencies.num-traits] version = "0.2" diff --git a/check/src/lib.rs b/ci/check/src/lib.rs similarity index 100% rename from check/src/lib.rs rename to ci/check/src/lib.rs diff --git a/import/Cargo.toml b/ci/import/Cargo.toml similarity index 87% rename from import/Cargo.toml rename to ci/import/Cargo.toml index d23f91e..48f5818 100644 --- a/import/Cargo.toml +++ b/ci/import/Cargo.toml @@ -6,5 +6,5 @@ edition = "2018" publish = false [dependencies] -num-derive = { path = "../" } +num-derive = { path = "../.." } num = { version = "0.3", default-features = false } diff --git a/import/src/lib.rs b/ci/import/src/lib.rs similarity index 100% rename from import/src/lib.rs rename to ci/import/src/lib.rs diff --git a/ci/test_full.sh b/ci/test_full.sh index 5f35ca8..513fbc4 100755 --- a/ci/test_full.sh +++ b/ci/test_full.sh @@ -46,5 +46,6 @@ done cargo build --features="${FEATURES[*]}" cargo test --features="${FEATURES[*]}" -cd check; cargo test --verbose check; cd .. -cd import; cargo test --verbose import; cd .. +# these CI crates keep tighter control over dependencies +cargo check --verbose --manifest-path ci/check/Cargo.toml +cargo check --verbose --manifest-path ci/import/Cargo.toml diff --git a/import/src/main.rs b/import/src/main.rs deleted file mode 100644 index e7a11a9..0000000 --- a/import/src/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - println!("Hello, world!"); -} From d4cc8f7e37e3af9ba4a80c071a8facf2f945f518 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 26 Jun 2020 17:44:58 -0700 Subject: [PATCH 8/9] Consolidate the code to find num_traits --- src/lib.rs | 163 +++++++++++++++++++---------------------------------- 1 file changed, 57 insertions(+), 106 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 11d48b2..5901fbc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -66,7 +66,7 @@ extern crate proc_macro; use proc_macro::TokenStream; -use proc_macro2::Span; +use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; use syn::{Data, Fields, Ident}; @@ -87,11 +87,7 @@ use syn::{Data, Fields, Ident}; // // 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 { +fn dummy_const_trick(trait_: &str, name: &Ident, exp: TokenStream2) -> TokenStream2 { let dummy_const = Ident::new( &format!("_IMPL_NUM_{}_FOR_{}", trait_, unraw(name)), Span::call_site(), @@ -107,7 +103,7 @@ fn dummy_const_trick( } } -fn unraw(ident: &proc_macro2::Ident) -> String { +fn unraw(ident: &Ident) -> String { ident.to_string().trim_start_matches("r#").to_owned() } @@ -137,26 +133,51 @@ fn newtype_inner(data: &syn::Data) -> Option { } } -// If there as `num_traits` MetaNameValue attribute within the slice, -// retrieve its value, and use it to create an `Ident` to be used to import -// the `num_traits` crate. -fn find_explicit_import_ident(attrs: &[syn::Attribute]) -> Option { - for attr in attrs { - if let Ok(syn::Meta::NameValue(mnv)) = attr.parse_meta() { - if mnv.path.is_ident("num_traits") { - match mnv.lit { - syn::Lit::Str(lit_str) => { - let import_str = &lit_str.value(); - let span = proc_macro2::Span::call_site(); - let import_ident = syn::Ident::new(import_str, span); - return Some(import_ident); +struct NumTraits { + import: Ident, + explicit: bool, +} + +impl quote::ToTokens for NumTraits { + fn to_tokens(&self, tokens: &mut TokenStream2) { + self.import.to_tokens(tokens); + } +} + +impl NumTraits { + fn new(ast: &syn::DeriveInput) -> Self { + // If there is a `num_traits` MetaNameValue attribute on the input, + // retrieve its value, and use it to create an `Ident` to be used + // to import the `num_traits` crate. + for attr in &ast.attrs { + if let Ok(syn::Meta::NameValue(mnv)) = attr.parse_meta() { + if mnv.path.is_ident("num_traits") { + if let syn::Lit::Str(lit_str) = mnv.lit { + return NumTraits { + import: syn::Ident::new(&lit_str.value(), lit_str.span()), + explicit: true, + }; + } else { + panic!("#[num_traits] attribute value must be a str"); } - _ => panic!("#[num_traits] attribute value must be a str"), } } } + + // Otherwise, we'll implicitly import our own. + NumTraits { + import: Ident::new("_num_traits", Span::call_site()), + explicit: false, + } + } + + fn wrap(&self, trait_: &str, name: &Ident, output: TokenStream2) -> TokenStream2 { + if self.explicit { + output + } else { + dummy_const_trick(trait_, &name, output) + } } - None } /// Derives [`num_traits::FromPrimitive`][from] for simple enums and newtypes. @@ -212,13 +233,7 @@ pub fn from_primitive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; - let explicit_import = find_explicit_import_ident(&ast.attrs); - let is_explicit_import = explicit_import.is_some(); - - let import = match explicit_import { - Some(ident) => ident, - None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), - }; + let import = NumTraits::new(&ast); let impl_ = if let Some(inner_ty) = newtype_inner(&ast.data) { quote! { @@ -320,11 +335,7 @@ pub fn from_primitive(input: TokenStream) -> TokenStream { } }; - if is_explicit_import { - impl_.into() - } else { - dummy_const_trick("FromPrimitive", &name, impl_).into() - } + import.wrap("FromPrimitive", &name, impl_).into() } /// Derives [`num_traits::ToPrimitive`][to] for simple enums and newtypes. @@ -380,13 +391,7 @@ pub fn to_primitive(input: TokenStream) -> TokenStream { let ast: syn::DeriveInput = syn::parse(input).unwrap(); let name = &ast.ident; - let explicit_import = find_explicit_import_ident(&ast.attrs); - let is_explicit_import = explicit_import.is_some(); - - let import = match explicit_import { - Some(ident) => ident, - None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), - }; + let import = NumTraits::new(&ast); let impl_ = if let Some(inner_ty) = newtype_inner(&ast.data) { quote! { @@ -489,11 +494,7 @@ pub fn to_primitive(input: TokenStream) -> TokenStream { } }; - if is_explicit_import { - impl_.into() - } else { - dummy_const_trick("ToPrimitive", &name, impl_).into() - } + import.wrap("ToPrimitive", &name, impl_).into() } const NEWTYPE_ONLY: &str = "This trait can only be derived for newtypes"; @@ -560,13 +561,7 @@ pub fn num_cast(input: TokenStream) -> TokenStream { let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); - let explicit_import = find_explicit_import_ident(&ast.attrs); - let is_explicit_import = explicit_import.is_some(); - - let import = match explicit_import { - Some(ident) => ident, - None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), - }; + let import = NumTraits::new(&ast); let impl_ = quote! { impl #import::NumCast for #name { @@ -576,11 +571,7 @@ pub fn num_cast(input: TokenStream) -> TokenStream { } }; - if is_explicit_import { - impl_.into() - } else { - dummy_const_trick("NumCast", &name, impl_).into() - } + import.wrap("NumCast", &name, impl_).into() } /// Derives [`num_traits::Zero`][zero] for newtypes. The inner type must already implement `Zero`. @@ -592,13 +583,7 @@ pub fn zero(input: TokenStream) -> TokenStream { let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); - let explicit_import = find_explicit_import_ident(&ast.attrs); - let is_explicit_import = explicit_import.is_some(); - - let import = match explicit_import { - Some(ident) => ident, - None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), - }; + let import = NumTraits::new(&ast); let impl_ = quote! { impl #import::Zero for #name { @@ -611,11 +596,7 @@ pub fn zero(input: TokenStream) -> TokenStream { } }; - if is_explicit_import { - impl_.into() - } else { - dummy_const_trick("Zero", &name, impl_).into() - } + import.wrap("Zero", &name, impl_).into() } /// Derives [`num_traits::One`][one] for newtypes. The inner type must already implement `One`. @@ -627,13 +608,7 @@ pub fn one(input: TokenStream) -> TokenStream { let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); - let explicit_import = find_explicit_import_ident(&ast.attrs); - let is_explicit_import = explicit_import.is_some(); - - let import = match explicit_import { - Some(ident) => ident, - None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), - }; + let import = NumTraits::new(&ast); let impl_ = quote! { impl #import::One for #name { @@ -646,11 +621,7 @@ pub fn one(input: TokenStream) -> TokenStream { } }; - if is_explicit_import { - impl_.into() - } else { - dummy_const_trick("One", &name, impl_).into() - } + import.wrap("One", &name, impl_).into() } /// Derives [`num_traits::Num`][num] for newtypes. The inner type must already implement `Num`. @@ -662,13 +633,7 @@ pub fn num(input: TokenStream) -> TokenStream { let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); - let explicit_import = find_explicit_import_ident(&ast.attrs); - let is_explicit_import = explicit_import.is_some(); - - let import = match explicit_import { - Some(ident) => ident, - None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), - }; + let import = NumTraits::new(&ast); let impl_ = quote! { impl #import::Num for #name { @@ -679,11 +644,7 @@ pub fn num(input: TokenStream) -> TokenStream { } }; - if is_explicit_import { - impl_.into() - } else { - dummy_const_trick("Num", &name, impl_).into() - } + import.wrap("Num", &name, impl_).into() } /// Derives [`num_traits::Float`][float] for newtypes. The inner type must already implement @@ -696,13 +657,7 @@ pub fn float(input: TokenStream) -> TokenStream { let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); - let explicit_import = find_explicit_import_ident(&ast.attrs); - let is_explicit_import = explicit_import.is_some(); - - let import = match explicit_import { - Some(ident) => ident, - None => syn::Ident::new("_num_traits", proc_macro2::Span::call_site()), - }; + let import = NumTraits::new(&ast); let impl_ = quote! { impl #import::Float for #name { @@ -881,9 +836,5 @@ pub fn float(input: TokenStream) -> TokenStream { } }; - if is_explicit_import { - impl_.into() - } else { - dummy_const_trick("Float", &name, impl_).into() - } + import.wrap("Float", &name, impl_).into() } From 90c8ad8147aa09161a5c07413f203dee695ca8f0 Mon Sep 17 00:00:00 2001 From: Josh Stone Date: Fri, 26 Jun 2020 17:47:49 -0700 Subject: [PATCH 9/9] Don't use dummy_const_trick for NumOps --- src/lib.rs | 60 +++++++++++++++++++++++++----------------------------- 1 file changed, 28 insertions(+), 32 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5901fbc..138b752 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -512,43 +512,39 @@ 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)) - } + let impl_ = 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::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::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::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)) - } + } + 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() + } + }; + impl_.into() } /// Derives [`num_traits::NumCast`][num_cast] for newtypes. The inner type must already implement