lib.rs 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  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. };
  103. trait_def.expand(cx, mitem, &item, push)
  104. }
  105. fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
  106. if substr.nonself_args.len() != 1 {
  107. cx.span_bug(trait_span, "incorrect number of arguments in `derive(FromPrimitive)`")
  108. }
  109. let n = &substr.nonself_args[0];
  110. match *substr.fields {
  111. StaticStruct(..) => {
  112. cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
  113. return cx.expr_fail(trait_span, InternedString::new(""));
  114. }
  115. StaticEnum(enum_def, _) => {
  116. if enum_def.variants.is_empty() {
  117. cx.span_err(trait_span,
  118. "`FromPrimitive` cannot be derived for enums with no variants");
  119. return cx.expr_fail(trait_span, InternedString::new(""));
  120. }
  121. let mut arms = Vec::new();
  122. for variant in &enum_def.variants {
  123. match variant.node.data {
  124. ast::VariantData::Unit(..) => {
  125. let span = variant.span;
  126. // expr for `$n == $variant as $name`
  127. let path = cx.path(span, vec![substr.type_ident, variant.node.name]);
  128. let variant = cx.expr_path(path);
  129. let ty = cx.ty_ident(span, cx.ident_of(name));
  130. let cast = cx.expr_cast(span, variant.clone(), ty);
  131. let guard = cx.expr_binary(span, BinOpKind::Eq, n.clone(), cast);
  132. // expr for `Some($variant)`
  133. let body = cx.expr_some(span, variant);
  134. // arm for `_ if $guard => $body`
  135. let arm = ast::Arm {
  136. attrs: vec!(),
  137. pats: vec!(cx.pat_wild(span)),
  138. guard: Some(guard),
  139. body: body,
  140. };
  141. arms.push(arm);
  142. }
  143. ast::VariantData::Tuple(..) => {
  144. cx.span_err(trait_span,
  145. "`FromPrimitive` cannot be derived for \
  146. enum variants with arguments");
  147. return cx.expr_fail(trait_span,
  148. InternedString::new(""));
  149. }
  150. ast::VariantData::Struct(..) => {
  151. cx.span_err(trait_span,
  152. "`FromPrimitive` cannot be derived for enums \
  153. with struct variants");
  154. return cx.expr_fail(trait_span,
  155. InternedString::new(""));
  156. }
  157. }
  158. }
  159. // arm for `_ => None`
  160. let arm = ast::Arm {
  161. attrs: vec!(),
  162. pats: vec!(cx.pat_wild(trait_span)),
  163. guard: None,
  164. body: cx.expr_none(trait_span),
  165. };
  166. arms.push(arm);
  167. cx.expr_match(trait_span, n.clone(), arms)
  168. }
  169. _ => cx.span_bug(trait_span, "expected StaticEnum in derive(FromPrimitive)")
  170. }
  171. }
  172. #[plugin_registrar]
  173. #[doc(hidden)]
  174. pub fn plugin_registrar(reg: &mut Registry) {
  175. reg.register_syntax_extension(
  176. token::intern("derive_NumFromPrimitive"),
  177. MultiDecorator(Box::new(expand_deriving_from_primitive)));
  178. }