lib.rs 7.3 KB

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