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