lib.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. generics: LifetimeBounds::empty(),
  70. explicit_self: None,
  71. args: vec!(Literal(path_local!(i64))),
  72. ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
  73. None,
  74. vec!(Box::new(Self_)),
  75. true)),
  76. // #[inline] liable to cause code-bloat
  77. attributes: attrs.clone(),
  78. combine_substructure: combine_substructure(Box::new(|c, s, sub| {
  79. cs_from("i64", c, s, sub)
  80. })),
  81. },
  82. MethodDef {
  83. name: "from_u64",
  84. is_unsafe: false,
  85. generics: LifetimeBounds::empty(),
  86. explicit_self: None,
  87. args: vec!(Literal(path_local!(u64))),
  88. ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
  89. None,
  90. vec!(Box::new(Self_)),
  91. true)),
  92. // #[inline] liable to cause code-bloat
  93. attributes: attrs,
  94. combine_substructure: combine_substructure(Box::new(|c, s, sub| {
  95. cs_from("u64", c, s, sub)
  96. })),
  97. }
  98. ),
  99. associated_types: Vec::new(),
  100. };
  101. trait_def.expand(cx, mitem, &item, push)
  102. }
  103. fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
  104. if substr.nonself_args.len() != 1 {
  105. cx.span_bug(trait_span, "incorrect number of arguments in `derive(FromPrimitive)`")
  106. }
  107. let n = &substr.nonself_args[0];
  108. match *substr.fields {
  109. StaticStruct(..) => {
  110. cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
  111. return cx.expr_fail(trait_span, InternedString::new(""));
  112. }
  113. StaticEnum(enum_def, _) => {
  114. if enum_def.variants.is_empty() {
  115. cx.span_err(trait_span,
  116. "`FromPrimitive` cannot be derived for enums with no variants");
  117. return cx.expr_fail(trait_span, InternedString::new(""));
  118. }
  119. let mut arms = Vec::new();
  120. for variant in &enum_def.variants {
  121. match variant.node.data {
  122. ast::VariantData::Unit(..) => {
  123. let span = variant.span;
  124. // expr for `$n == $variant as $name`
  125. let path = cx.path(span, vec![substr.type_ident, variant.node.name]);
  126. let variant = cx.expr_path(path);
  127. let ty = cx.ty_ident(span, cx.ident_of(name));
  128. let cast = cx.expr_cast(span, variant.clone(), ty);
  129. let guard = cx.expr_binary(span, BinOpKind::Eq, n.clone(), cast);
  130. // expr for `Some($variant)`
  131. let body = cx.expr_some(span, variant);
  132. // arm for `_ if $guard => $body`
  133. let arm = ast::Arm {
  134. attrs: vec!(),
  135. pats: vec!(cx.pat_wild(span)),
  136. guard: Some(guard),
  137. body: body,
  138. };
  139. arms.push(arm);
  140. }
  141. ast::VariantData::Tuple(..) => {
  142. cx.span_err(trait_span,
  143. "`FromPrimitive` cannot be derived for \
  144. enum variants with arguments");
  145. return cx.expr_fail(trait_span,
  146. InternedString::new(""));
  147. }
  148. ast::VariantData::Struct(..) => {
  149. cx.span_err(trait_span,
  150. "`FromPrimitive` cannot be derived for enums \
  151. with struct variants");
  152. return cx.expr_fail(trait_span,
  153. InternedString::new(""));
  154. }
  155. }
  156. }
  157. // arm for `_ => None`
  158. let arm = ast::Arm {
  159. attrs: vec!(),
  160. pats: vec!(cx.pat_wild(trait_span)),
  161. guard: None,
  162. body: cx.expr_none(trait_span),
  163. };
  164. arms.push(arm);
  165. cx.expr_match(trait_span, n.clone(), arms)
  166. }
  167. _ => cx.span_bug(trait_span, "expected StaticEnum in derive(FromPrimitive)")
  168. }
  169. }
  170. #[plugin_registrar]
  171. #[doc(hidden)]
  172. pub fn plugin_registrar(reg: &mut Registry) {
  173. reg.register_syntax_extension(
  174. token::intern("derive_NumFromPrimitive"),
  175. MultiDecorator(Box::new(expand_deriving_from_primitive)));
  176. }