lib.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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. #![feature(plugin_registrar, rustc_private)]
  11. #![doc(html_logo_url = "https://rust-num.github.io/num/rust-logo-128x128-blk-v2.png",
  12. html_favicon_url = "https://rust-num.github.io/num/favicon.ico",
  13. html_root_url = "https://rust-num.github.io/num/",
  14. html_playground_url = "http://play.integer32.com/")]
  15. extern crate syntax;
  16. extern crate syntax_ext;
  17. extern crate rustc_plugin;
  18. use syntax::ast::{MetaItem, Expr, BinOpKind};
  19. use syntax::ast;
  20. use syntax::codemap::Span;
  21. use syntax::ext::base::{ExtCtxt, Annotatable};
  22. use syntax::ext::build::AstBuilder;
  23. use syntax_ext::deriving::generic::*;
  24. use syntax_ext::deriving::generic::ty::*;
  25. use syntax::symbol::Symbol;
  26. use syntax::ptr::P;
  27. use syntax::ext::base::MultiDecorator;
  28. use rustc_plugin::Registry;
  29. macro_rules! pathvec {
  30. ($($x:ident)::+) => (
  31. vec![ $( stringify!($x) ),+ ]
  32. )
  33. }
  34. macro_rules! path {
  35. ($($x:tt)*) => (
  36. ::syntax_ext::deriving::generic::ty::Path::new( pathvec!( $($x)* ) )
  37. )
  38. }
  39. macro_rules! path_local {
  40. ($x:ident) => (
  41. ::syntax_ext::deriving::generic::ty::Path::new_local(stringify!($x))
  42. )
  43. }
  44. macro_rules! pathvec_std {
  45. ($cx:expr, $first:ident :: $($rest:ident)::+) => ({
  46. let mut v = pathvec!($($rest)::+);
  47. if let Some(s) = $cx.crate_root {
  48. v.insert(0, s);
  49. }
  50. v
  51. })
  52. }
  53. pub fn expand_deriving_from_primitive(cx: &mut ExtCtxt,
  54. span: Span,
  55. mitem: &MetaItem,
  56. item: &Annotatable,
  57. push: &mut FnMut(Annotatable))
  58. {
  59. let inline = cx.meta_word(span, Symbol::intern("inline"));
  60. let attrs = vec!(cx.attribute(span, inline));
  61. let trait_def = TraitDef {
  62. is_unsafe: false,
  63. span: span,
  64. attributes: Vec::new(),
  65. path: path!(num::FromPrimitive),
  66. additional_bounds: Vec::new(),
  67. generics: LifetimeBounds::empty(),
  68. methods: vec!(
  69. MethodDef {
  70. name: "from_i64",
  71. is_unsafe: false,
  72. unify_fieldless_variants: false,
  73. generics: LifetimeBounds::empty(),
  74. explicit_self: None,
  75. args: vec!(Literal(path_local!(i64))),
  76. ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
  77. None,
  78. vec!(Box::new(Self_)),
  79. true)),
  80. // #[inline] liable to cause code-bloat
  81. attributes: attrs.clone(),
  82. combine_substructure: combine_substructure(Box::new(|c, s, sub| {
  83. cs_from("i64", c, s, sub)
  84. })),
  85. },
  86. MethodDef {
  87. name: "from_u64",
  88. is_unsafe: false,
  89. unify_fieldless_variants: false,
  90. generics: LifetimeBounds::empty(),
  91. explicit_self: None,
  92. args: vec!(Literal(path_local!(u64))),
  93. ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
  94. None,
  95. vec!(Box::new(Self_)),
  96. true)),
  97. // #[inline] liable to cause code-bloat
  98. attributes: attrs,
  99. combine_substructure: combine_substructure(Box::new(|c, s, sub| {
  100. cs_from("u64", c, s, sub)
  101. })),
  102. }
  103. ),
  104. associated_types: Vec::new(),
  105. supports_unions: false,
  106. };
  107. trait_def.expand(cx, mitem, &item, push)
  108. }
  109. fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
  110. if substr.nonself_args.len() != 1 {
  111. cx.span_bug(trait_span, "incorrect number of arguments in `derive(FromPrimitive)`")
  112. }
  113. let n = &substr.nonself_args[0];
  114. match *substr.fields {
  115. StaticStruct(..) => {
  116. cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
  117. return cx.expr_fail(trait_span, Symbol::intern(""));
  118. }
  119. StaticEnum(enum_def, _) => {
  120. if enum_def.variants.is_empty() {
  121. cx.span_err(trait_span,
  122. "`FromPrimitive` cannot be derived for enums with no variants");
  123. return cx.expr_fail(trait_span, Symbol::intern(""));
  124. }
  125. let mut arms = Vec::new();
  126. for variant in &enum_def.variants {
  127. match variant.node.data {
  128. ast::VariantData::Unit(..) => {
  129. let span = variant.span;
  130. // expr for `$n == $variant as $name`
  131. let path = cx.path(span, vec![substr.type_ident, variant.node.name]);
  132. let variant = cx.expr_path(path);
  133. let ty = cx.ty_ident(span, cx.ident_of(name));
  134. let cast = cx.expr_cast(span, variant.clone(), ty);
  135. let guard = cx.expr_binary(span, BinOpKind::Eq, n.clone(), cast);
  136. // expr for `Some($variant)`
  137. let body = cx.expr_some(span, variant);
  138. // arm for `_ if $guard => $body`
  139. let arm = ast::Arm {
  140. attrs: vec!(),
  141. pats: vec!(cx.pat_wild(span)),
  142. guard: Some(guard),
  143. body: body,
  144. };
  145. arms.push(arm);
  146. }
  147. ast::VariantData::Tuple(..) => {
  148. cx.span_err(trait_span,
  149. "`FromPrimitive` cannot be derived for \
  150. enum variants with arguments");
  151. return cx.expr_fail(trait_span,
  152. Symbol::intern(""));
  153. }
  154. ast::VariantData::Struct(..) => {
  155. cx.span_err(trait_span,
  156. "`FromPrimitive` cannot be derived for enums \
  157. with struct variants");
  158. return cx.expr_fail(trait_span,
  159. Symbol::intern(""));
  160. }
  161. }
  162. }
  163. // arm for `_ => None`
  164. let arm = ast::Arm {
  165. attrs: vec!(),
  166. pats: vec!(cx.pat_wild(trait_span)),
  167. guard: None,
  168. body: cx.expr_none(trait_span),
  169. };
  170. arms.push(arm);
  171. cx.expr_match(trait_span, n.clone(), arms)
  172. }
  173. _ => cx.span_bug(trait_span, "expected StaticEnum in derive(FromPrimitive)")
  174. }
  175. }
  176. #[plugin_registrar]
  177. #[doc(hidden)]
  178. pub fn plugin_registrar(reg: &mut Registry) {
  179. reg.register_syntax_extension(
  180. Symbol::intern("derive_NumFromPrimitive"),
  181. MultiDecorator(Box::new(expand_deriving_from_primitive)));
  182. }