lib.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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. let mut v = pathvec!($($rest)::+);
  43. if let Some(s) = $cx.crate_root {
  44. v.insert(0, s);
  45. }
  46. v
  47. })
  48. }
  49. pub fn expand_deriving_from_primitive(cx: &mut ExtCtxt,
  50. span: Span,
  51. mitem: &MetaItem,
  52. item: &Annotatable,
  53. push: &mut FnMut(Annotatable))
  54. {
  55. let inline = cx.meta_word(span, InternedString::new("inline"));
  56. let attrs = vec!(cx.attribute(span, inline));
  57. let trait_def = TraitDef {
  58. is_unsafe: false,
  59. span: span,
  60. attributes: Vec::new(),
  61. path: path!(num::FromPrimitive),
  62. additional_bounds: Vec::new(),
  63. generics: LifetimeBounds::empty(),
  64. methods: vec!(
  65. MethodDef {
  66. name: "from_i64",
  67. is_unsafe: false,
  68. generics: LifetimeBounds::empty(),
  69. explicit_self: None,
  70. args: vec!(Literal(path_local!(i64))),
  71. ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
  72. None,
  73. vec!(Box::new(Self_)),
  74. true)),
  75. // #[inline] liable to cause code-bloat
  76. attributes: attrs.clone(),
  77. combine_substructure: combine_substructure(Box::new(|c, s, sub| {
  78. cs_from("i64", c, s, sub)
  79. })),
  80. },
  81. MethodDef {
  82. name: "from_u64",
  83. is_unsafe: false,
  84. generics: LifetimeBounds::empty(),
  85. explicit_self: None,
  86. args: vec!(Literal(path_local!(u64))),
  87. ret_ty: Literal(Path::new_(pathvec_std!(cx, core::option::Option),
  88. None,
  89. vec!(Box::new(Self_)),
  90. true)),
  91. // #[inline] liable to cause code-bloat
  92. attributes: attrs,
  93. combine_substructure: combine_substructure(Box::new(|c, s, sub| {
  94. cs_from("u64", c, s, sub)
  95. })),
  96. }
  97. ),
  98. associated_types: Vec::new(),
  99. };
  100. trait_def.expand(cx, mitem, &item, push)
  101. }
  102. fn cs_from(name: &str, cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> {
  103. if substr.nonself_args.len() != 1 {
  104. cx.span_bug(trait_span, "incorrect number of arguments in `derive(FromPrimitive)`")
  105. }
  106. let n = &substr.nonself_args[0];
  107. match *substr.fields {
  108. StaticStruct(..) => {
  109. cx.span_err(trait_span, "`FromPrimitive` cannot be derived for structs");
  110. return cx.expr_fail(trait_span, InternedString::new(""));
  111. }
  112. StaticEnum(enum_def, _) => {
  113. if enum_def.variants.is_empty() {
  114. cx.span_err(trait_span,
  115. "`FromPrimitive` cannot be derived for enums with no variants");
  116. return cx.expr_fail(trait_span, InternedString::new(""));
  117. }
  118. let mut arms = Vec::new();
  119. for variant in &enum_def.variants {
  120. match variant.node.kind {
  121. ast::TupleVariantKind(ref args) => {
  122. if !args.is_empty() {
  123. cx.span_err(trait_span,
  124. "`FromPrimitive` cannot be derived for \
  125. enum variants with arguments");
  126. return cx.expr_fail(trait_span,
  127. InternedString::new(""));
  128. }
  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, ast::BiEq, 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::StructVariantKind(_) => {
  148. cx.span_err(trait_span,
  149. "`FromPrimitive` cannot be derived for enums \
  150. with struct variants");
  151. return cx.expr_fail(trait_span,
  152. InternedString::new(""));
  153. }
  154. }
  155. }
  156. // arm for `_ => None`
  157. let arm = ast::Arm {
  158. attrs: vec!(),
  159. pats: vec!(cx.pat_wild(trait_span)),
  160. guard: None,
  161. body: cx.expr_none(trait_span),
  162. };
  163. arms.push(arm);
  164. cx.expr_match(trait_span, n.clone(), arms)
  165. }
  166. _ => cx.span_bug(trait_span, "expected StaticEnum in derive(FromPrimitive)")
  167. }
  168. }
  169. #[plugin_registrar]
  170. #[doc(hidden)]
  171. pub fn plugin_registrar(reg: &mut Registry) {
  172. reg.register_syntax_extension(
  173. token::intern("derive_NumFromPrimitive"),
  174. MultiDecorator(Box::new(expand_deriving_from_primitive)));
  175. }