1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
//! This crate provides helper methods for matching against enum variants, and //! extracting bindings to each of the fields in the deriving Struct or Enum in //! a generic way. //! //! If you are writing a `#[derive]` which needs to perform some operation on every //! field, then you have come to the right place! //! //! # Example //! //! ``` //! extern crate syn; //! extern crate synstructure; //! #[macro_use] //! extern crate quote; //! use synstructure::{each_field, BindStyle}; //! //! type TokenStream = String; // XXX: Dummy to not depend on rustc_macro //! //! fn sum_fields_derive(input: TokenStream) -> TokenStream { //! let source = input.to_string(); //! let mut ast = syn::parse_macro_input(&source).unwrap(); //! //! let match_body = each_field(&mut ast, BindStyle::Ref, |bi| quote! { //! sum += #bi as i64; //! }); //! //! let name = &ast.ident; //! let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); //! let result = quote! { //! // Original struct unmodified //! #ast //! //! impl #impl_generics ::sum_fields::SumFields for #name #ty_generics #where_clause { //! fn sum_fields(&self) -> i64 { //! let mut sum = 0i64; //! match *self { #match_body } //! sum //! } //! } //! }; //! //! result.to_string().parse().unwrap() //! } //! //! fn main() {} //! ``` //! //! For more example usage, consider investigating the `abomonation_derive` crate, //! which makes use of this crate, and is fairly simple. extern crate syn; #[macro_use] extern crate quote; use syn::{Body, Field, Ident, MacroInput, VariantData}; use quote::{Tokens, ToTokens}; /// The type of binding to use when generating a pattern. #[derive(Debug, Copy, Clone)] pub enum BindStyle { /// `x` Move, /// `mut x` MoveMut, /// `ref x` Ref, /// `ref mut x` RefMut, } /// Information about a specific binding. This contains both an `Ident` /// reference to the given field, and the syn `&'a Field` descriptor for that /// field. /// /// This type supports `quote::ToTokens`, so can be directly used within the /// `quote!` macro. It expands to a reference to the matched field. #[derive(Debug)] pub struct BindingInfo<'a> { pub ident: Ident, pub field: &'a mut Field, } impl<'a> ToTokens for BindingInfo<'a> { fn to_tokens(&self, tokens: &mut Tokens) { self.ident.to_tokens(tokens); } } /// Generate a match pattern for binding to the given VariantData This function /// returns a tuple of the tokens which make up that match pattern, and a /// `BindingInfo` object for each of the bindings which were made. The `bind` /// parameter controls the type of binding which is made. /// /// The `BindingInfo` object holds a mutable reference into the original /// `VariantData`, which means that mutations will be reflected in the source /// object. This can be useful for removing attributes as they are used. /// /// # Example /// /// ``` /// extern crate syn; /// extern crate synstructure; /// use synstructure::{match_pattern, BindStyle}; /// /// fn main() { /// let mut ast = syn::parse_macro_input("struct A { a: i32, b: i32 }").unwrap(); /// let vd = if let syn::Body::Struct(ref mut vd) = ast.body { /// vd /// } else { unreachable!() }; /// /// let (tokens, bindings) = match_pattern(&ast.ident, vd, BindStyle::Ref); /// assert_eq!(&tokens.to_string(), /// "A { a : ref __binding_0 , b : ref __binding_1 , } "); /// assert_eq!(bindings.len(), 2); /// assert_eq!(&bindings[0].ident.to_string(), "__binding_0"); /// assert_eq!(&bindings[1].ident.to_string(), "__binding_1"); /// } /// ``` pub fn match_pattern<'a, N: ToTokens>(name: &N, vd: &'a mut VariantData, bind: BindStyle) -> (Tokens, Vec<BindingInfo<'a>>) { let mut t = Tokens::new(); let mut matches = Vec::new(); let prefix = match bind { BindStyle::Move => Tokens::new(), BindStyle::MoveMut => quote!(mut), BindStyle::Ref => quote!(ref), BindStyle::RefMut => quote!(ref mut), }; name.to_tokens(&mut t); match *vd { VariantData::Unit => {} VariantData::Tuple(ref mut fields) => { t.append("("); for (i, field) in fields.iter_mut().enumerate() { let ident: Ident = format!("__binding_{}", i).into(); quote!(#prefix #ident ,).to_tokens(&mut t); matches.push(BindingInfo { ident: ident, field: field, }); } t.append(")"); } VariantData::Struct(ref mut fields) => { t.append("{"); for (i, field) in fields.iter_mut().enumerate() { let ident: Ident = format!("__binding_{}", i).into(); { let field_name = field.ident.as_ref().unwrap(); quote!(#field_name : #prefix #ident ,).to_tokens(&mut t); } matches.push(BindingInfo { ident: ident, field: field, }); } t.append("}"); } } (t, matches) } /// This method generates a match branch for each of the substructures of the /// given `MacroInput`. It will call `func` for each of these substructures, /// passing in the bindings which were made for each of the fields in the /// substructure. The return value of `func` is then used as the value of each /// branch /// /// The `BindingInfo` object holds a mutable reference into the original /// `MacroInput`, which means that mutations will be reflected in the source /// object. This can be useful for removing attributes as they are used. /// /// # Example /// /// ``` /// extern crate syn; /// extern crate synstructure; /// #[macro_use] /// extern crate quote; /// use synstructure::{match_substructs, BindStyle}; /// /// fn main() { /// let mut ast = syn::parse_macro_input("struct A { a: i32, b: i32 }").unwrap(); /// /// let tokens = match_substructs(&mut ast, BindStyle::Ref, |bindings| { /// assert_eq!(bindings.len(), 2); /// assert_eq!(bindings[0].ident.as_ref(), "__binding_0"); /// assert_eq!(bindings[1].ident.as_ref(), "__binding_1"); /// quote!("some_random_string") /// }); /// let e = concat!("A { a : ref __binding_0 , b : ref __binding_1 , }", /// " => { \"some_random_string\" } "); /// assert_eq!(&tokens.to_string(), e); /// } /// ``` pub fn match_substructs<F, T: ToTokens>(input: &mut MacroInput, bind: BindStyle, func: F) -> Tokens where F: Fn(Vec<BindingInfo>) -> T { let ident = &input.ident; // Generate patterns for matching against all of the variants let variants = match input.body { Body::Enum(ref mut variants) => { variants.iter_mut() .map(|variant| { let variant_ident = &variant.ident; match_pattern("e!(#ident :: #variant_ident), &mut variant.data, bind) }) .collect() } Body::Struct(ref mut vd) => vec![match_pattern(&ident, vd, bind)], }; // Now that we have the patterns, generate the actual branches of the match // expression let mut t = Tokens::new(); for (pat, bindings) in variants { let body = func(bindings); quote!(#pat => { #body }).to_tokens(&mut t); } t } /// This method calls `func` once per field in the struct or enum, and generates /// a series of match branches which will destructure match argument, and run /// the result of `func` once on each of the bindings. /// /// The `BindingInfo` object holds a mutable reference into the original /// `MacroInput`, which means that mutations will be reflected in the source /// object. This can be useful for removing attributes as they are used. /// /// # Example /// /// ``` /// extern crate syn; /// extern crate synstructure; /// #[macro_use] /// extern crate quote; /// use synstructure::{each_field, BindStyle}; /// /// fn main() { /// let mut ast = syn::parse_macro_input("struct A { a: i32, b: i32 }").unwrap(); /// /// let tokens = each_field(&mut ast, BindStyle::Ref, |bi| quote! { /// println!("Saw: {:?}", #bi); /// }); /// let e = concat!("A { a : ref __binding_0 , b : ref __binding_1 , } ", /// "=> { ", /// "{ println ! ( \"Saw: {:?}\" , __binding_0 ) ; } ", /// "{ println ! ( \"Saw: {:?}\" , __binding_1 ) ; } ", /// "( ) } "); /// assert_eq!(&tokens.to_string(), e); /// } /// ``` pub fn each_field<F, T: ToTokens>(input: &mut MacroInput, bind: BindStyle, func: F) -> Tokens where F: Fn(BindingInfo) -> T { match_substructs(input, bind, |infos| { let mut t = Tokens::new(); for info in infos { t.append("{"); func(info).to_tokens(&mut t); t.append("}"); } quote!(()).to_tokens(&mut t); t }) }