// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
//! Procedural macros to derive numeric traits in Rust. //! //! ## Usage //! //! Add this to your `Cargo.toml`: //! //! ```toml //! [dependencies] //! num-traits = "0.2" //! num-derive = "0.3" //! ``` //! //! Then you can derive traits on your own types: //! //! ```rust //! #[macro_use] //! extern crate num_derive; //! //! #[derive(FromPrimitive, ToPrimitive)] //! enum Color { //! Red, //! Blue, //! Green, //! } //! # 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() {} //! ```
externcrate proc_macro;
use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; use syn::{Data, Fields, Ident};
/// Try to parse the tokens, or else return a compilation error
macro_rules! parse {
($tokens:ident as $type:ty) => { match syn::parse::<$type>($tokens) {
Ok(parsed) => parsed,
Err(error) => { return TokenStream::from(error.to_compile_error());
}
}
};
}
// 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 anonymous 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 anon_const_trick(exp: TokenStream2) -> TokenStream2 {
quote! { #[allow(non_upper_case_globals, unused_qualifications)] const _: () = { #[allow(clippy::useless_attribute)] #[allow(rust_2018_idioms)] externcrate num_traits as _num_traits; #exp
};
}
}
// If `data` is a newtype, return the type it's wrapping. fn newtype_inner(data: &syn::Data) -> Option<syn::Type> { 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,
}
}
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 attr.path().is_ident("num_traits") { iflet Ok(syn::MetaNameValue {
value:
syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(ref lit_str),
..
}),
..
}) = attr.meta.require_name_value()
{ return NumTraits {
import: syn::Ident::new(&lit_str.value(), lit_str.span()),
explicit: true,
};
} else {
panic!("#[num_traits] attribute value must be a str");
}
}
}
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
),
}
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)
},
}
// 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::#identas 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! {
::core::option::Option::Some(match *self { #(#variants,)*
})
}
};
#[inline] fn to_u64(&self) -> ::core::option::Option<u64> { self.to_i64().map(|x| x as u64)
}
}
}
};
import.wrap(impl_).into()
}
const NEWTYPE_ONLY: &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)] pubfn num_ops(input: TokenStream) -> TokenStream { let ast = parse!(input as syn::DeriveInput); let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY); let impl_ = quote! { impl ::core::ops::Add for#name { type Output = Self; #[inline] fn add(self, other: Self) -> Self { #name(<#inner_tyas ::core::ops::Add>::add(self.0, other.0))
}
} impl ::core::ops::Sub for#name { type Output = Self; #[inline] fn sub(self, other: Self) -> Self { #name(<#inner_tyas ::core::ops::Sub>::sub(self.0, other.0))
}
} impl ::core::ops::Mul for#name { type Output = Self; #[inline] fn mul(self, other: Self) -> Self { #name(<#inner_tyas ::core::ops::Mul>::mul(self.0, other.0))
}
} impl ::core::ops::Div for#name { type Output = Self; #[inline] fn div(self, other: Self) -> Self { #name(<#inner_tyas ::core::ops::Div>::div(self.0, other.0))
}
} impl ::core::ops::Rem for#name { type Output = Self; #[inline] fn rem(self, other: Self) -> Self { #name(<#inner_tyas ::core::ops::Rem>::rem(self.0, other.0))
}
}
};
impl_.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, attributes(num_traits))] pubfn num_cast(input: TokenStream) -> TokenStream { let ast = parse!(input as syn::DeriveInput); let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY);
/// 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, attributes(num_traits))] pubfn zero(input: TokenStream) -> TokenStream { let ast = parse!(input as syn::DeriveInput); let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY);
/// 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, attributes(num_traits))] pubfn one(input: TokenStream) -> TokenStream { let ast = parse!(input as syn::DeriveInput); let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY);
/// 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, attributes(num_traits))] pubfn num(input: TokenStream) -> TokenStream { let ast = parse!(input as syn::DeriveInput); let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY);
/// 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, attributes(num_traits))] pubfn float(input: TokenStream) -> TokenStream { let ast = parse!(input as syn::DeriveInput); let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY);
/// Derives [`num_traits::Signed`][signed] for newtypes. The inner type must already implement /// `Signed`. /// /// [signed]: https://docs.rs/num-traits/0.2/num_traits/sign/trait.Signed.html #[proc_macro_derive(Signed, attributes(num_traits))] pubfn signed(input: TokenStream) -> TokenStream { let ast = parse!(input as syn::DeriveInput); let name = &ast.ident; let inner_ty = newtype_inner(&ast.data).expect(NEWTYPE_ONLY);
/// Derives [`num_traits::Unsigned`][unsigned]. The inner type must already implement /// `Unsigned`. /// /// [unsigned]: https://docs.rs/num/latest/num/traits/trait.Unsigned.html #[proc_macro_derive(Unsigned, attributes(num_traits))] pubfn unsigned(input: TokenStream) -> TokenStream { let ast = parse!(input as syn::DeriveInput); let name = &ast.ident;
let import = NumTraits::new(&ast);
let impl_ = quote! { impl#import::Unsigned for#name {}
};
import.wrap(impl_).into()
}
Messung V0.5 in Prozent
¤ Diese beiden folgenden Angebotsgruppen bietet das Unternehmen0.32Angebot
(Wie Sie bei der Firma Beratungs- und Dienstleistungen beauftragen können 2026-06-18)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.