|
| 1 | +// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT |
| 2 | +// file at the top-level directory of this distribution and at |
| 3 | +// http://rust-lang.org/COPYRIGHT. |
| 4 | +// |
| 5 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 6 | +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 7 | +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your |
| 8 | +// option. This file may not be copied, modified, or distributed |
| 9 | +// except according to those terms. |
| 10 | + |
| 11 | +#![crate_type = "rustc-macro"] |
| 12 | +#![feature(rustc_macro, rustc_macro_lib)] |
| 13 | + |
| 14 | +extern crate syn; |
| 15 | +#[macro_use] |
| 16 | +extern crate quote; |
| 17 | +extern crate rustc_macro; |
| 18 | + |
| 19 | +use rustc_macro::TokenStream; |
| 20 | + |
| 21 | +use syn::Body::Enum; |
| 22 | +use syn::VariantData::Unit; |
| 23 | + |
| 24 | +#[rustc_macro_derive(FromPrimitive)] |
| 25 | +pub fn from_primitive(input: TokenStream) -> TokenStream { |
| 26 | + let source = input.to_string(); |
| 27 | + |
| 28 | + let ast = syn::parse_macro_input(&source).unwrap(); |
| 29 | + let name = &ast.ident; |
| 30 | + |
| 31 | + let variants = match ast.body { |
| 32 | + Enum(ref variants) => variants, |
| 33 | + _ => { |
| 34 | + panic!("`FromPrimitive` can be applied only to the enums, {} is not an enum", |
| 35 | + name) |
| 36 | + } |
| 37 | + }; |
| 38 | + |
| 39 | + let mut idx = 0; |
| 40 | + let variants: Vec<_> = variants.iter() |
| 41 | + .map(|variant| { |
| 42 | + let ident = &variant.ident; |
| 43 | + match variant.data { |
| 44 | + Unit => (), |
| 45 | + _ => { |
| 46 | + panic!("`FromPrimitive` can be applied only to unitary enums, {}::{} is either struct or tuple", name, ident) |
| 47 | + }, |
| 48 | + } |
| 49 | + if let Some(val) = variant.discriminant { |
| 50 | + idx = val.value; |
| 51 | + } |
| 52 | + let tt = quote!(#idx => Some(#name::#ident)); |
| 53 | + idx += 1; |
| 54 | + tt |
| 55 | + }) |
| 56 | + .collect(); |
| 57 | + |
| 58 | + let res = quote! { |
| 59 | + #ast |
| 60 | + |
| 61 | + impl ::num::traits::FromPrimitive for #name { |
| 62 | + fn from_i64(n: i64) -> Option<Self> { |
| 63 | + Self::from_u64(n as u64) |
| 64 | + } |
| 65 | + |
| 66 | + fn from_u64(n: u64) -> Option<Self> { |
| 67 | + match n { |
| 68 | + #(variants,)* |
| 69 | + _ => None, |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | + }; |
| 74 | + |
| 75 | + res.to_string().parse().unwrap() |
| 76 | +} |
0 commit comments