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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
//! 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 ast = syn::parse_macro_input(&source).unwrap(); //! //! let match_body = each_field(&ast, &BindStyle::Ref.into(), |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! { //! 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 std::borrow::Cow; 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, } impl ToTokens for BindStyle { fn to_tokens(&self, tokens: &mut Tokens) { match *self { BindStyle::Move => {} BindStyle::MoveMut => tokens.append("mut"), BindStyle::Ref => tokens.append("ref"), BindStyle::RefMut => { tokens.append("ref"); tokens.append("mut"); } } } } /// Binding options to use when generating a pattern. /// Configuration options used for generating binding patterns. /// /// `bind_style` controls the type of binding performed in the pattern, for /// example: `ref` or `ref mut`. /// /// `prefix` controls the name which is used for the binding. This can be used /// to avoid name conflicts with nested match patterns. #[derive(Debug, Clone)] pub struct BindOpts { bind_style: BindStyle, prefix: Cow<'static, str>, } impl BindOpts { /// Create a BindOpts with the given style, and the default prefix: "__binding". pub fn new(bind_style: BindStyle) -> BindOpts { BindOpts { bind_style: bind_style, prefix: "__binding".into(), } } /// Create a BindOpts with the given style and prefix. pub fn with_prefix(bind_style: BindStyle, prefix: String) -> BindOpts { BindOpts { bind_style: bind_style, prefix: prefix.into(), } } } impl From<BindStyle> for BindOpts { fn from(style: BindStyle) -> Self { BindOpts::new(style) } } /// 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 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; /// #[macro_use] /// extern crate quote; /// use synstructure::{match_pattern, BindStyle}; /// /// fn main() { /// let ast = syn::parse_macro_input("struct A { a: i32, b: i32 }").unwrap(); /// let vd = if let syn::Body::Struct(ref vd) = ast.body { /// vd /// } else { unreachable!() }; /// /// let (tokens, bindings) = match_pattern(&ast.ident, vd, &BindStyle::Ref.into()); /// assert_eq!(tokens.to_string(), quote! { /// A{ a: ref __binding_0, b: ref __binding_1, } /// }.to_string()); /// 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 VariantData, options: &BindOpts) -> (Tokens, Vec<BindingInfo<'a>>) { let mut t = Tokens::new(); let mut matches = Vec::new(); let binding = options.bind_style; name.to_tokens(&mut t); match *vd { VariantData::Unit => {} VariantData::Tuple(ref fields) => { t.append("("); for (i, field) in fields.iter().enumerate() { let ident: Ident = format!("{}_{}", options.prefix, i).into(); quote!(#binding #ident ,).to_tokens(&mut t); matches.push(BindingInfo { ident: ident, field: field, }); } t.append(")"); } VariantData::Struct(ref fields) => { t.append("{"); for (i, field) in fields.iter().enumerate() { let ident: Ident = format!("{}_{}", options.prefix, i).into(); { let field_name = field.ident.as_ref().unwrap(); quote!(#field_name : #binding #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.into(), |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") /// }); /// assert_eq!(tokens.to_string(), quote! { /// A { a: ref __binding_0, b: ref __binding_1, } => { "some_random_string" } /// }.to_string()); /// } /// ``` pub fn match_substructs<F, T: ToTokens>(input: &MacroInput, options: &BindOpts, 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 variants) => { variants.iter() .map(|variant| { let variant_ident = &variant.ident; match_pattern("e!(#ident :: #variant_ident), &variant.data, options) }) .collect() } Body::Struct(ref vd) => vec![match_pattern(&ident, vd, options)], }; // 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.into(), |bi| quote! { /// println!("Saw: {:?}", #bi); /// }); /// assert_eq!(tokens.to_string(), quote! { /// A{ a: ref __binding_0, b: ref __binding_1, } => { /// { println!("Saw: {:?}", __binding_0); } /// { println!("Saw: {:?}", __binding_1); } /// () /// } /// }.to_string()); /// } /// ``` pub fn each_field<F, T: ToTokens>(input: &MacroInput, options: &BindOpts, func: F) -> Tokens where F: Fn(BindingInfo) -> T { match_substructs(input, options, |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 }) }