blob: 626049dac06e8ea55f83410aa67a7ed37ea0d231 [file] [log] [blame]
David Tolnay4b4c4b62018-01-06 13:48:05 -08001//! This crate automatically generates the definition of the `Visit`,
2//! `VisitMut`, and `Fold` traits in `syn` based on the `syn` source. It
Nika Layzell27726662017-10-24 23:16:35 -04003//! discovers structs and enums declared with the `ast_*` macros and generates
4//! the functions for those types.
5//!
6//! It makes a few assumptions about the target crate:
7//! 1. All structs which are discovered must be re-exported in the root of the
8//! crate, even if they were declared in a submodule.
9//! 2. This code cannot discover submodules which are located in subdirectories
10//! - only submodules located in the same directory.
11//! 3. The path to `syn` is hardcoded.
12
David Tolnayea9ae892017-12-26 01:44:32 -050013#![cfg_attr(feature = "cargo-clippy", allow(redundant_closure))]
14
David Tolnayd67fb752017-12-27 13:50:29 -050015#[macro_use]
16extern crate failure;
Nika Layzell27726662017-10-24 23:16:35 -040017extern crate inflections;
David Tolnay2e0dba12017-12-27 01:54:40 -050018extern crate proc_macro2;
David Tolnayd67fb752017-12-27 13:50:29 -050019#[macro_use]
20extern crate quote;
David Tolnay5c4c0b52017-12-28 17:58:54 -050021#[macro_use]
David Tolnayd67fb752017-12-27 13:50:29 -050022extern crate syn;
Nika Layzell27726662017-10-24 23:16:35 -040023
David Tolnayd67fb752017-12-27 13:50:29 -050024use quote::{ToTokens, Tokens};
Alex Crichtona74a1c82018-05-16 10:20:44 -070025use syn::{Attribute, Data, DataStruct, DeriveInput, Item};
David Tolnayd67fb752017-12-27 13:50:29 -050026use failure::{err_msg, Error};
Alex Crichtona74a1c82018-05-16 10:20:44 -070027use proc_macro2::{Ident, Span};
Nika Layzell27726662017-10-24 23:16:35 -040028
David Tolnay8ed806a2017-12-26 01:28:28 -050029use std::io::{Read, Write};
David Tolnayf0d63bf2017-12-26 12:29:47 -050030use std::fmt::{self, Debug};
Nika Layzell27726662017-10-24 23:16:35 -040031use std::fs::File;
32use std::path::Path;
33use std::collections::BTreeMap;
34
35const SYN_CRATE_ROOT: &str = "../src/lib.rs";
36
37const FOLD_SRC: &str = "../src/gen/fold.rs";
38const VISIT_SRC: &str = "../src/gen/visit.rs";
39const VISIT_MUT_SRC: &str = "../src/gen/visit_mut.rs";
40
David Tolnayd67fb752017-12-27 13:50:29 -050041const IGNORED_MODS: &[&str] = &["fold", "visit", "visit_mut"];
Nika Layzell27726662017-10-24 23:16:35 -040042
David Tolnay360efd22018-01-04 23:35:26 -080043const EXTRA_TYPES: &[&str] = &["Ident", "Lifetime"];
David Tolnay4ba63a02017-12-28 15:53:05 -050044
45const TERMINAL_TYPES: &[&str] = &["Span"];
Nika Layzellefb83ba2017-12-19 18:23:55 -050046
Alex Crichtona74a1c82018-05-16 10:20:44 -070047fn path_eq(a: &syn::Path, b: &str) -> bool {
48 if a.global() {
49 return false
Nika Layzell27726662017-10-24 23:16:35 -040050 }
Alex Crichtona74a1c82018-05-16 10:20:44 -070051 if a.segments.len() != 1 {
52 return false
53 }
54 a.segments[0].ident.to_string() == b
Nika Layzell27726662017-10-24 23:16:35 -040055}
56
57fn get_features(attrs: &[Attribute], mut features: Tokens) -> Tokens {
58 for attr in attrs {
Alex Crichtona74a1c82018-05-16 10:20:44 -070059 if path_eq(&attr.path, "cfg") {
Nika Layzell27726662017-10-24 23:16:35 -040060 attr.to_tokens(&mut features);
61 }
62 }
63 features
64}
65
66#[derive(Clone)]
67pub struct AstItem {
David Tolnay3d772182017-12-28 17:18:53 -050068 ast: DeriveInput,
Nika Layzell27726662017-10-24 23:16:35 -040069 features: Tokens,
70 // True if this is an ast_enum_of_structs! item with a #full annotation.
71 eos_full: bool,
72}
73
David Tolnayf0d63bf2017-12-26 12:29:47 -050074impl Debug for AstItem {
Nika Layzell27726662017-10-24 23:16:35 -040075 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
76 f.debug_struct("AstItem")
David Tolnay3d772182017-12-28 17:18:53 -050077 .field("ast", &self.ast)
Nika Layzell27726662017-10-24 23:16:35 -040078 .field("features", &self.features.to_string())
79 .finish()
80 }
81}
82
83// NOTE: BTreeMap is used here instead of HashMap to have deterministic output.
David Tolnayc47f8422017-12-28 17:30:46 -050084type Lookup = BTreeMap<Ident, AstItem>;
Nika Layzell27726662017-10-24 23:16:35 -040085
David Tolnayd67fb752017-12-27 13:50:29 -050086fn load_file<P: AsRef<Path>>(name: P, features: &Tokens, lookup: &mut Lookup) -> Result<(), Error> {
Nika Layzell27726662017-10-24 23:16:35 -040087 let name = name.as_ref();
David Tolnayea9ae892017-12-26 01:44:32 -050088 let parent = name.parent().ok_or_else(|| err_msg("no parent path"))?;
Nika Layzell27726662017-10-24 23:16:35 -040089
90 let mut f = File::open(name)?;
91 let mut src = String::new();
92 f.read_to_string(&mut src)?;
93
94 // Parse the file
David Tolnayd67fb752017-12-27 13:50:29 -050095 let file =
96 syn::parse_file(&src).map_err(|_| format_err!("failed to parse {}", name.display()))?;
Nika Layzell27726662017-10-24 23:16:35 -040097
98 // Collect all of the interesting AstItems declared in this file or submodules.
David Tolnay4ba63a02017-12-28 15:53:05 -050099 'items: for item in file.items {
100 match item {
101 Item::Mod(item) => {
Nika Layzell27726662017-10-24 23:16:35 -0400102 // Don't inspect inline modules.
David Tolnayc6b55bc2017-11-09 22:48:38 -0800103 if item.content.is_some() {
Nika Layzell27726662017-10-24 23:16:35 -0400104 continue;
105 }
106
107 // We don't want to try to load the generated rust files and
108 // parse them, so we ignore them here.
109 for name in IGNORED_MODS {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700110 if item.ident.to_string() == *name {
Nika Layzell27726662017-10-24 23:16:35 -0400111 continue 'items;
112 }
113 }
114
115 // Lookup any #[cfg()] attributes on the module and add them to
116 // the feature set.
David Tolnay0a0d78c2018-01-05 15:24:01 -0800117 //
118 // The derive module is weird because it is built with either
119 // `full` or `derive` but exported only under `derive`.
Alex Crichtona74a1c82018-05-16 10:20:44 -0700120 let features = if item.ident.to_string() == "derive" {
David Tolnay0a0d78c2018-01-05 15:24:01 -0800121 quote!(#[cfg(feature = "derive")])
122 } else {
123 get_features(&item.attrs, features.clone())
124 };
Nika Layzell27726662017-10-24 23:16:35 -0400125
126 // Look up the submodule file, and recursively parse it.
127 // XXX: Only handles same-directory .rs file submodules.
Alex Crichtona74a1c82018-05-16 10:20:44 -0700128 let path = parent.join(&format!("{}.rs", item.ident));
David Tolnayea9ae892017-12-26 01:44:32 -0500129 load_file(path, &features, lookup)?;
Nika Layzell27726662017-10-24 23:16:35 -0400130 }
David Tolnay4ba63a02017-12-28 15:53:05 -0500131 Item::Macro(item) => {
Nika Layzell27726662017-10-24 23:16:35 -0400132 // Lookip any #[cfg()] attributes directly on the macro
133 // invocation, and add them to the feature set.
134 let features = get_features(&item.attrs, features.clone());
135
136 // Try to parse the AstItem declaration out of the item.
David Tolnay01a77582018-01-01 20:00:51 -0800137 let tts = &item.mac.tts;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700138 let found = if path_eq(&item.mac.path, "ast_struct") {
David Tolnay01a77582018-01-01 20:00:51 -0800139 syn::parse_str::<parsing::AstStruct>(&quote!(#tts).to_string())
David Tolnayd67fb752017-12-27 13:50:29 -0500140 .map_err(|_| err_msg("failed to parse ast_struct"))?
141 .0
Alex Crichtona74a1c82018-05-16 10:20:44 -0700142 } else if path_eq(&item.mac.path, "ast_enum") {
David Tolnay01a77582018-01-01 20:00:51 -0800143 syn::parse_str::<parsing::AstEnum>(&quote!(#tts).to_string())
David Tolnayd67fb752017-12-27 13:50:29 -0500144 .map_err(|_| err_msg("failed to parse ast_enum"))?
145 .0
Alex Crichtona74a1c82018-05-16 10:20:44 -0700146 } else if path_eq(&item.mac.path, "ast_enum_of_structs") {
David Tolnay01a77582018-01-01 20:00:51 -0800147 syn::parse_str::<parsing::AstEnumOfStructs>(&quote!(#tts).to_string())
David Tolnay1cf80912017-12-31 18:35:12 -0500148 .map_err(|_| err_msg("failed to parse ast_enum_of_structs"))?
David Tolnayd67fb752017-12-27 13:50:29 -0500149 .0
Nika Layzell27726662017-10-24 23:16:35 -0400150 } else {
David Tolnayd67fb752017-12-27 13:50:29 -0500151 continue;
Nika Layzell27726662017-10-24 23:16:35 -0400152 };
153
154 // Record our features on the parsed AstItems.
155 for mut item in found {
156 features.to_tokens(&mut item.features);
Alex Crichtona74a1c82018-05-16 10:20:44 -0700157 lookup.insert(item.ast.ident.clone(), item);
Nika Layzell27726662017-10-24 23:16:35 -0400158 }
159 }
David Tolnay4ba63a02017-12-28 15:53:05 -0500160 Item::Struct(item) => {
161 let ident = item.ident;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700162 if EXTRA_TYPES.contains(&&ident.to_string()[..]) {
163 lookup.insert(ident.clone(), AstItem {
David Tolnay3d772182017-12-28 17:18:53 -0500164 ast: DeriveInput {
David Tolnay4ba63a02017-12-28 15:53:05 -0500165 ident: ident,
166 vis: item.vis,
167 attrs: item.attrs,
168 generics: item.generics,
David Tolnaye3d41b72017-12-31 15:24:00 -0500169 data: Data::Struct(DataStruct {
170 fields: item.fields,
David Tolnay4ba63a02017-12-28 15:53:05 -0500171 struct_token: item.struct_token,
172 semi_token: item.semi_token,
173 }),
174 },
175 features: features.clone(),
176 eos_full: false,
177 });
178 }
179 }
Nika Layzell27726662017-10-24 23:16:35 -0400180 _ => {}
181 }
182 }
183 Ok(())
184}
185
186mod parsing {
187 use super::AstItem;
188
David Tolnay1cf80912017-12-31 18:35:12 -0500189 use syn;
David Tolnayc5ab8c62017-12-26 16:43:39 -0500190 use syn::synom::*;
Nika Layzell27726662017-10-24 23:16:35 -0400191 use syn::*;
Nika Layzell27726662017-10-24 23:16:35 -0400192 use quote::Tokens;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700193 use proc_macro2::{TokenStream, Ident};
Nika Layzell27726662017-10-24 23:16:35 -0400194
195 // Parses #full - returns #[cfg(feature = "full")] if it is present, and
196 // nothing otherwise.
197 named!(full -> (Tokens, bool), map!(option!(do_parse!(
David Tolnayf8db7ba2017-11-11 22:52:16 -0800198 punct!(#) >>
Nika Layzell27726662017-10-24 23:16:35 -0400199 id: syn!(Ident) >>
Alex Crichtona74a1c82018-05-16 10:20:44 -0700200 cond_reduce!(id.to_string() == "full") >>
David Tolnayea9ae892017-12-26 01:44:32 -0500201 ()
Nika Layzell27726662017-10-24 23:16:35 -0400202 )), |s| if s.is_some() {
203 (quote!(#[cfg(feature = "full")]), true)
204 } else {
205 (quote!(), false)
206 }));
207
David Tolnay28c5a462017-12-27 01:59:30 -0500208 named!(manual_extra_traits -> (), do_parse!(
209 punct!(#) >>
210 id: syn!(Ident) >>
Alex Crichtona74a1c82018-05-16 10:20:44 -0700211 cond_reduce!(id.to_string() == "manual_extra_traits") >>
David Tolnay28c5a462017-12-27 01:59:30 -0500212 ()
213 ));
214
Nika Layzell27726662017-10-24 23:16:35 -0400215 // Parses a simple AstStruct without the `pub struct` prefix.
216 named!(ast_struct_inner -> AstItem, do_parse!(
217 id: syn!(Ident) >>
218 features: full >>
David Tolnay28c5a462017-12-27 01:59:30 -0500219 option!(manual_extra_traits) >>
David Tolnay2e0dba12017-12-27 01:54:40 -0500220 rest: syn!(TokenStream) >>
Nika Layzell27726662017-10-24 23:16:35 -0400221 (AstItem {
David Tolnay01a77582018-01-01 20:00:51 -0800222 ast: syn::parse_str(&quote! {
David Tolnay2e0dba12017-12-27 01:54:40 -0500223 pub struct #id #rest
David Tolnay01a77582018-01-01 20:00:51 -0800224 }.to_string())?,
Nika Layzell27726662017-10-24 23:16:35 -0400225 features: features.0,
226 eos_full: features.1,
227 })
228 ));
229
230 // ast_struct! parsing
231 pub struct AstStruct(pub Vec<AstItem>);
232 impl Synom for AstStruct {
David Tolnayab919512017-12-30 23:31:51 -0500233 named!(parse -> Self, do_parse!(
David Tolnay2c136452017-12-27 14:13:32 -0500234 many0!(Attribute::parse_outer) >>
David Tolnayf8db7ba2017-11-11 22:52:16 -0800235 keyword!(pub) >>
236 keyword!(struct) >>
Nika Layzell27726662017-10-24 23:16:35 -0400237 res: call!(ast_struct_inner) >>
David Tolnayab919512017-12-30 23:31:51 -0500238 (AstStruct(vec![res]))
239 ));
Nika Layzell27726662017-10-24 23:16:35 -0400240 }
241
David Tolnay360efd22018-01-04 23:35:26 -0800242 named!(no_visit -> (), do_parse!(
243 punct!(#) >>
244 id: syn!(Ident) >>
Alex Crichtona74a1c82018-05-16 10:20:44 -0700245 cond_reduce!(id.to_string() == "no_visit") >>
David Tolnay360efd22018-01-04 23:35:26 -0800246 ()
247 ));
248
Nika Layzell27726662017-10-24 23:16:35 -0400249 // ast_enum! parsing
250 pub struct AstEnum(pub Vec<AstItem>);
251 impl Synom for AstEnum {
David Tolnay360efd22018-01-04 23:35:26 -0800252 named!(parse -> Self, do_parse!(
253 many0!(Attribute::parse_outer) >>
254 keyword!(pub) >>
255 keyword!(enum) >>
256 id: syn!(Ident) >>
257 no_visit: option!(no_visit) >>
258 rest: syn!(TokenStream) >>
259 (AstEnum(if no_visit.is_some() {
260 vec![]
261 } else {
262 vec![AstItem {
263 ast: syn::parse_str(&quote! {
264 pub enum #id #rest
265 }.to_string())?,
266 features: quote!(),
267 eos_full: false,
268 }]
269 }))
270 ));
Nika Layzell27726662017-10-24 23:16:35 -0400271 }
272
273 // A single variant of an ast_enum_of_structs!
274 struct EosVariant {
275 name: Ident,
David Tolnayfcfb9002017-12-28 22:04:29 -0500276 member: Option<Path>,
Nika Layzell27726662017-10-24 23:16:35 -0400277 inner: Option<AstItem>,
278 }
279 named!(eos_variant -> EosVariant, do_parse!(
David Tolnay2c136452017-12-27 14:13:32 -0500280 many0!(Attribute::parse_outer) >>
David Tolnayf8db7ba2017-11-11 22:52:16 -0800281 keyword!(pub) >>
Nika Layzell27726662017-10-24 23:16:35 -0400282 variant: syn!(Ident) >>
David Tolnayfcfb9002017-12-28 22:04:29 -0500283 member: option!(map!(parens!(alt!(
Alex Crichtona74a1c82018-05-16 10:20:44 -0700284 call!(ast_struct_inner) => { |x: AstItem| (Path::from(x.ast.ident.clone()), Some(x)) }
Nika Layzell27726662017-10-24 23:16:35 -0400285 |
286 syn!(Path) => { |x| (x, None) }
David Tolnay8875fca2017-12-31 13:52:37 -0500287 )), |x| x.1)) >>
David Tolnayf8db7ba2017-11-11 22:52:16 -0800288 punct!(,) >>
Nika Layzell27726662017-10-24 23:16:35 -0400289 (EosVariant {
290 name: variant,
David Tolnayfcfb9002017-12-28 22:04:29 -0500291 member: member.clone().map(|x| x.0),
292 inner: member.map(|x| x.1).unwrap_or_default(),
Nika Layzell27726662017-10-24 23:16:35 -0400293 })
294 ));
295
296 // ast_enum_of_structs! parsing
297 pub struct AstEnumOfStructs(pub Vec<AstItem>);
298 impl Synom for AstEnumOfStructs {
David Tolnayab919512017-12-30 23:31:51 -0500299 named!(parse -> Self, do_parse!(
David Tolnay2c136452017-12-27 14:13:32 -0500300 many0!(Attribute::parse_outer) >>
David Tolnayf8db7ba2017-11-11 22:52:16 -0800301 keyword!(pub) >>
302 keyword!(enum) >>
Nika Layzell27726662017-10-24 23:16:35 -0400303 id: syn!(Ident) >>
David Tolnaye3d41b72017-12-31 15:24:00 -0500304 variants: braces!(many0!(eos_variant)) >>
Nika Layzell27726662017-10-24 23:16:35 -0400305 option!(syn!(Ident)) >> // do_not_generate_to_tokens
306 ({
307 // XXX: This is really gross - we shouldn't have to convert the
308 // tokens to strings to re-parse them.
309 let enum_item = {
David Tolnaye3d41b72017-12-31 15:24:00 -0500310 let variants = variants.1.iter().map(|v| {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700311 let name = v.name.clone();
David Tolnayfcfb9002017-12-28 22:04:29 -0500312 match v.member {
313 Some(ref member) => quote!(#name(#member)),
314 None => quote!(#name),
315 }
Nika Layzell27726662017-10-24 23:16:35 -0400316 });
David Tolnay01a77582018-01-01 20:00:51 -0800317 syn::parse_str(&quote! {
Nika Layzell27726662017-10-24 23:16:35 -0400318 pub enum #id { #(#variants),* }
David Tolnay01a77582018-01-01 20:00:51 -0800319 }.to_string())?
Nika Layzell27726662017-10-24 23:16:35 -0400320 };
321 let mut items = vec![AstItem {
David Tolnay3d772182017-12-28 17:18:53 -0500322 ast: enum_item,
Nika Layzell27726662017-10-24 23:16:35 -0400323 features: quote!(),
324 eos_full: false,
325 }];
David Tolnaye3d41b72017-12-31 15:24:00 -0500326 items.extend(variants.1.into_iter().filter_map(|v| v.inner));
Nika Layzell27726662017-10-24 23:16:35 -0400327 AstEnumOfStructs(items)
328 })
David Tolnayab919512017-12-30 23:31:51 -0500329 ));
Nika Layzell27726662017-10-24 23:16:35 -0400330 }
331}
332
333mod codegen {
334 use super::{AstItem, Lookup};
335 use syn::*;
David Tolnayf2cfd722017-12-31 18:02:51 -0500336 use syn::punctuated::Punctuated;
David Tolnayd67fb752017-12-27 13:50:29 -0500337 use quote::{ToTokens, Tokens};
David Tolnayf0d63bf2017-12-26 12:29:47 -0500338 use std::fmt::{self, Display};
Alex Crichtona74a1c82018-05-16 10:20:44 -0700339 use proc_macro2::{Ident, Span};
Nika Layzell27726662017-10-24 23:16:35 -0400340
341 #[derive(Default)]
342 pub struct State {
343 pub visit_trait: String,
344 pub visit_impl: String,
345 pub visit_mut_trait: String,
346 pub visit_mut_impl: String,
347 pub fold_trait: String,
348 pub fold_impl: String,
349 }
350
David Tolnay4a918742017-12-28 16:54:41 -0500351 fn under_name(name: Ident) -> Ident {
Nika Layzell27726662017-10-24 23:16:35 -0400352 use inflections::Inflect;
Alex Crichtona74a1c82018-05-16 10:20:44 -0700353 Ident::new(&name.to_string().to_snake_case(), Span::call_site())
Nika Layzell27726662017-10-24 23:16:35 -0400354 }
355
David Tolnay3d772182017-12-28 17:18:53 -0500356 enum RelevantType<'a> {
357 Box(&'a Type),
358 Vec(&'a Type),
David Tolnayf2cfd722017-12-31 18:02:51 -0500359 Punctuated(&'a Type),
David Tolnay3d772182017-12-28 17:18:53 -0500360 Option(&'a Type),
David Tolnayf2cfd722017-12-31 18:02:51 -0500361 Tuple(&'a Punctuated<Type, Token![,]>),
David Tolnay3d772182017-12-28 17:18:53 -0500362 Simple(&'a AstItem),
David Tolnay1e01f9c2017-12-28 20:16:19 -0500363 Token(Tokens),
David Tolnay3d772182017-12-28 17:18:53 -0500364 Pass,
365 }
Nika Layzell27726662017-10-24 23:16:35 -0400366
David Tolnay3d772182017-12-28 17:18:53 -0500367 fn classify<'a>(ty: &'a Type, lookup: &'a Lookup) -> RelevantType<'a> {
368 match *ty {
369 Type::Path(TypePath { qself: None, ref path }) => {
David Tolnay56080682018-01-06 14:01:52 -0800370 let last = path.segments.last().unwrap().into_value();
Alex Crichtona74a1c82018-05-16 10:20:44 -0700371 match &last.ident.to_string()[..] {
David Tolnay3d772182017-12-28 17:18:53 -0500372 "Box" => RelevantType::Box(first_arg(&last.arguments)),
373 "Vec" => RelevantType::Vec(first_arg(&last.arguments)),
David Tolnayf2cfd722017-12-31 18:02:51 -0500374 "Punctuated" => RelevantType::Punctuated(first_arg(&last.arguments)),
David Tolnay3d772182017-12-28 17:18:53 -0500375 "Option" => RelevantType::Option(first_arg(&last.arguments)),
David Tolnay1e01f9c2017-12-28 20:16:19 -0500376 "Brace" | "Bracket" | "Paren" | "Group" => {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700377 RelevantType::Token(last.ident.clone().into_tokens())
David Tolnay1e01f9c2017-12-28 20:16:19 -0500378 }
David Tolnay3d772182017-12-28 17:18:53 -0500379 _ => {
380 if let Some(item) = lookup.get(&last.ident) {
381 RelevantType::Simple(item)
382 } else {
383 RelevantType::Pass
384 }
385 }
386 }
Nika Layzell27726662017-10-24 23:16:35 -0400387 }
David Tolnayeadbda32017-12-29 02:33:47 -0500388 Type::Tuple(TypeTuple { ref elems, .. }) => {
389 RelevantType::Tuple(elems)
David Tolnay5c4c0b52017-12-28 17:58:54 -0500390 }
Alex Crichtona74a1c82018-05-16 10:20:44 -0700391 Type::Macro(TypeMacro { ref mac }) if mac.path.segments.last().unwrap().into_value().ident.to_string() == "Token" => {
David Tolnay1e01f9c2017-12-28 20:16:19 -0500392 RelevantType::Token(mac.into_tokens())
David Tolnaycc0f0372017-12-28 19:11:04 -0500393 }
David Tolnay3d772182017-12-28 17:18:53 -0500394 _ => RelevantType::Pass,
Nika Layzell27726662017-10-24 23:16:35 -0400395 }
396 }
397
398 #[derive(Debug, Eq, PartialEq, Copy, Clone)]
399 enum Kind {
400 Visit,
401 VisitMut,
402 Fold,
403 }
404
David Tolnayf0d63bf2017-12-26 12:29:47 -0500405 enum Operand {
406 Borrowed(Tokens),
407 Owned(Tokens),
408 }
409
David Tolnay83db9272017-12-28 17:02:31 -0500410 use self::Operand::*;
411 use self::Kind::*;
412
David Tolnayf0d63bf2017-12-26 12:29:47 -0500413 impl Operand {
414 fn tokens(&self) -> &Tokens {
415 match *self {
David Tolnay83db9272017-12-28 17:02:31 -0500416 Borrowed(ref n) | Owned(ref n) => n,
David Tolnayf0d63bf2017-12-26 12:29:47 -0500417 }
418 }
419
420 fn ref_tokens(&self) -> Tokens {
421 match *self {
David Tolnay83db9272017-12-28 17:02:31 -0500422 Borrowed(ref n) => n.clone(),
423 Owned(ref n) => quote!(&#n),
David Tolnayf0d63bf2017-12-26 12:29:47 -0500424 }
425 }
426
427 fn ref_mut_tokens(&self) -> Tokens {
428 match *self {
David Tolnay83db9272017-12-28 17:02:31 -0500429 Borrowed(ref n) => n.clone(),
430 Owned(ref n) => quote!(&mut #n),
David Tolnayf0d63bf2017-12-26 12:29:47 -0500431 }
432 }
433
434 fn owned_tokens(&self) -> Tokens {
435 match *self {
David Tolnay83db9272017-12-28 17:02:31 -0500436 Borrowed(ref n) => quote!(*#n),
437 Owned(ref n) => n.clone(),
David Tolnayf0d63bf2017-12-26 12:29:47 -0500438 }
439 }
440 }
441
442 impl Display for Operand {
443 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
David Tolnay4e52d8a2017-12-28 15:54:50 -0500444 Display::fmt(self.tokens(), formatter)
David Tolnayf0d63bf2017-12-26 12:29:47 -0500445 }
446 }
447
Nika Layzellc08227a2017-12-04 16:30:17 -0500448 fn first_arg(params: &PathArguments) -> &Type {
Nika Layzell27726662017-10-24 23:16:35 -0400449 let data = match *params {
Nika Layzellc08227a2017-12-04 16:30:17 -0500450 PathArguments::AngleBracketed(ref data) => data,
451 _ => panic!("Expected at least 1 type argument here"),
Nika Layzell27726662017-10-24 23:16:35 -0400452 };
453
David Tolnayd67fb752017-12-27 13:50:29 -0500454 match **data.args
455 .first()
456 .expect("Expected at least 1 type argument here")
David Tolnay56080682018-01-06 14:01:52 -0800457 .value()
David Tolnayd67fb752017-12-27 13:50:29 -0500458 {
David Tolnayea9ae892017-12-26 01:44:32 -0500459 GenericArgument::Type(ref ty) => ty,
Nika Layzellc08227a2017-12-04 16:30:17 -0500460 _ => panic!("Expected at least 1 type argument here"),
Nika Layzell357885a2017-12-04 15:47:07 -0500461 }
Nika Layzell27726662017-10-24 23:16:35 -0400462 }
463
464 fn simple_visit(
David Tolnay3d772182017-12-28 17:18:53 -0500465 item: &AstItem,
Nika Layzell27726662017-10-24 23:16:35 -0400466 kind: Kind,
David Tolnayf0d63bf2017-12-26 12:29:47 -0500467 name: &Operand,
David Tolnay4a918742017-12-28 16:54:41 -0500468 ) -> String {
469 match kind {
David Tolnay83db9272017-12-28 17:02:31 -0500470 Visit => format!(
David Tolnay4a918742017-12-28 16:54:41 -0500471 "_visitor.visit_{under_name}({name})",
Alex Crichtona74a1c82018-05-16 10:20:44 -0700472 under_name = under_name(item.ast.ident.clone()),
David Tolnay4a918742017-12-28 16:54:41 -0500473 name = name.ref_tokens(),
474 ),
David Tolnay83db9272017-12-28 17:02:31 -0500475 VisitMut => format!(
David Tolnay4a918742017-12-28 16:54:41 -0500476 "_visitor.visit_{under_name}_mut({name})",
Alex Crichtona74a1c82018-05-16 10:20:44 -0700477 under_name = under_name(item.ast.ident.clone()),
David Tolnay4a918742017-12-28 16:54:41 -0500478 name = name.ref_mut_tokens(),
479 ),
David Tolnay83db9272017-12-28 17:02:31 -0500480 Fold => format!(
David Tolnay4a918742017-12-28 16:54:41 -0500481 "_visitor.fold_{under_name}({name})",
Alex Crichtona74a1c82018-05-16 10:20:44 -0700482 under_name = under_name(item.ast.ident.clone()),
David Tolnay4a918742017-12-28 16:54:41 -0500483 name = name.owned_tokens(),
484 ),
Nika Layzell27726662017-10-24 23:16:35 -0400485 }
486 }
487
488 fn box_visit(
David Tolnay3d772182017-12-28 17:18:53 -0500489 elem: &Type,
Nika Layzell27726662017-10-24 23:16:35 -0400490 lookup: &Lookup,
491 kind: Kind,
David Tolnayf0d63bf2017-12-26 12:29:47 -0500492 name: &Operand,
Nika Layzell27726662017-10-24 23:16:35 -0400493 ) -> Option<String> {
David Tolnay4a918742017-12-28 16:54:41 -0500494 let name = name.owned_tokens();
David Tolnay39d0a202017-12-28 18:19:00 -0500495 let res = visit(elem, lookup, kind, &Owned(quote!(*#name)))?;
David Tolnay4a918742017-12-28 16:54:41 -0500496 Some(match kind {
David Tolnay83db9272017-12-28 17:02:31 -0500497 Fold => format!("Box::new({})", res),
498 Visit | VisitMut => res,
David Tolnay4a918742017-12-28 16:54:41 -0500499 })
Nika Layzell27726662017-10-24 23:16:35 -0400500 }
501
502 fn vec_visit(
David Tolnay3d772182017-12-28 17:18:53 -0500503 elem: &Type,
Nika Layzell27726662017-10-24 23:16:35 -0400504 lookup: &Lookup,
505 kind: Kind,
David Tolnayf0d63bf2017-12-26 12:29:47 -0500506 name: &Operand,
Nika Layzell27726662017-10-24 23:16:35 -0400507 ) -> Option<String> {
David Tolnay4a918742017-12-28 16:54:41 -0500508 let operand = match kind {
David Tolnay83db9272017-12-28 17:02:31 -0500509 Visit | VisitMut => Borrowed(quote!(it)),
510 Fold => Owned(quote!(it)),
David Tolnay4a918742017-12-28 16:54:41 -0500511 };
David Tolnay39d0a202017-12-28 18:19:00 -0500512 let val = visit(elem, lookup, kind, &operand)?;
David Tolnay4a918742017-12-28 16:54:41 -0500513 Some(match kind {
David Tolnay83db9272017-12-28 17:02:31 -0500514 Visit => {
David Tolnay3d772182017-12-28 17:18:53 -0500515 format!(
516 "for it in {name} {{ {val} }}",
517 name = name.ref_tokens(),
518 val = val,
519 )
Nika Layzell27726662017-10-24 23:16:35 -0400520 }
David Tolnay83db9272017-12-28 17:02:31 -0500521 VisitMut => {
David Tolnay3d772182017-12-28 17:18:53 -0500522 format!(
523 "for it in {name} {{ {val} }}",
524 name = name.ref_mut_tokens(),
525 val = val,
526 )
527 }
528 Fold => format!(
529 "FoldHelper::lift({name}, |it| {{ {val} }})",
530 name = name.owned_tokens(),
531 val = val,
532 ),
533 })
534 }
535
David Tolnay6eff4da2018-01-01 20:27:45 -0800536 fn punctuated_visit(
David Tolnay3d772182017-12-28 17:18:53 -0500537 elem: &Type,
538 lookup: &Lookup,
539 kind: Kind,
540 name: &Operand,
541 ) -> Option<String> {
542 let operand = match kind {
543 Visit | VisitMut => Borrowed(quote!(it)),
544 Fold => Owned(quote!(it)),
545 };
David Tolnay39d0a202017-12-28 18:19:00 -0500546 let val = visit(elem, lookup, kind, &operand)?;
David Tolnay3d772182017-12-28 17:18:53 -0500547 Some(match kind {
548 Visit => {
549 format!(
David Tolnay56080682018-01-06 14:01:52 -0800550 "for el in Punctuated::pairs({name}) {{ \
551 let it = el.value(); \
David Tolnay3d772182017-12-28 17:18:53 -0500552 {val} \
553 }}",
554 name = name.ref_tokens(),
555 val = val,
556 )
557 }
558 VisitMut => {
559 format!(
David Tolnay56080682018-01-06 14:01:52 -0800560 "for mut el in Punctuated::pairs_mut({name}) {{ \
561 let it = el.value_mut(); \
David Tolnay3d772182017-12-28 17:18:53 -0500562 {val} \
563 }}",
564 name = name.ref_mut_tokens(),
565 val = val,
566 )
David Tolnay4a918742017-12-28 16:54:41 -0500567 }
David Tolnay83db9272017-12-28 17:02:31 -0500568 Fold => format!(
David Tolnay4a918742017-12-28 16:54:41 -0500569 "FoldHelper::lift({name}, |it| {{ {val} }})",
570 name = name.owned_tokens(),
571 val = val,
572 ),
573 })
Nika Layzell27726662017-10-24 23:16:35 -0400574 }
575
Nika Layzell4ab8d6e2017-10-26 09:45:49 -0400576 fn option_visit(
David Tolnay3d772182017-12-28 17:18:53 -0500577 elem: &Type,
Nika Layzell4ab8d6e2017-10-26 09:45:49 -0400578 lookup: &Lookup,
579 kind: Kind,
David Tolnayf0d63bf2017-12-26 12:29:47 -0500580 name: &Operand,
Nika Layzell4ab8d6e2017-10-26 09:45:49 -0400581 ) -> Option<String> {
David Tolnay4a918742017-12-28 16:54:41 -0500582 let it = match kind {
David Tolnay83db9272017-12-28 17:02:31 -0500583 Visit | VisitMut => Borrowed(quote!(it)),
584 Fold => Owned(quote!(it)),
David Tolnay4a918742017-12-28 16:54:41 -0500585 };
David Tolnay39d0a202017-12-28 18:19:00 -0500586 let val = visit(elem, lookup, kind, &it)?;
David Tolnay4a918742017-12-28 16:54:41 -0500587 Some(match kind {
David Tolnay83db9272017-12-28 17:02:31 -0500588 Visit => format!(
David Tolnay4a918742017-12-28 16:54:41 -0500589 "if let Some(ref it) = {name} {{ {val} }}",
590 name = name.owned_tokens(),
591 val = val,
592 ),
David Tolnay83db9272017-12-28 17:02:31 -0500593 VisitMut => format!(
David Tolnay4a918742017-12-28 16:54:41 -0500594 "if let Some(ref mut it) = {name} {{ {val} }}",
595 name = name.owned_tokens(),
596 val = val,
597 ),
David Tolnay83db9272017-12-28 17:02:31 -0500598 Fold => format!(
David Tolnay4a918742017-12-28 16:54:41 -0500599 "({name}).map(|it| {{ {val} }})",
600 name = name.owned_tokens(),
601 val = val,
602 ),
603 })
Nika Layzell4ab8d6e2017-10-26 09:45:49 -0400604 }
605
David Tolnay5c4c0b52017-12-28 17:58:54 -0500606 fn tuple_visit(
David Tolnayf2cfd722017-12-31 18:02:51 -0500607 elems: &Punctuated<Type, Token![,]>,
David Tolnay5c4c0b52017-12-28 17:58:54 -0500608 lookup: &Lookup,
609 kind: Kind,
610 name: &Operand,
611 ) -> Option<String> {
612 let mut code = String::new();
David Tolnayf047c7a2017-12-31 02:29:04 -0500613 for (i, elem) in elems.iter().enumerate() {
David Tolnay5c4c0b52017-12-28 17:58:54 -0500614 let name = name.tokens();
David Tolnay14982012017-12-29 00:49:51 -0500615 let i = Index::from(i);
David Tolnay5c4c0b52017-12-28 17:58:54 -0500616 let it = Owned(quote!((#name).#i));
David Tolnay6eff4da2018-01-01 20:27:45 -0800617 let val = visit(elem, lookup, kind, &it)
David Tolnay5c4c0b52017-12-28 17:58:54 -0500618 .unwrap_or_else(|| noop_visit(kind, &it));
619 code.push_str(&format!(" {}", val));
620 match kind {
621 Fold => code.push(','),
622 Visit | VisitMut => code.push(';'),
623 }
624 code.push('\n');
625 }
626 if code.is_empty() {
627 None
628 } else {
629 Some(match kind {
630 Fold => {
631 format!("(\n{} )", code)
632 }
633 Visit | VisitMut => {
634 format!("\n{} ", code)
635 }
636 })
637 }
638 }
639
David Tolnay1e01f9c2017-12-28 20:16:19 -0500640 fn token_visit(ty: Tokens, kind: Kind, name: &Operand) -> String {
David Tolnaycc0f0372017-12-28 19:11:04 -0500641 match kind {
642 Fold => format!(
David Tolnay1e01f9c2017-12-28 20:16:19 -0500643 "{ty}(tokens_helper(_visitor, &({name}).0))",
644 ty = ty,
David Tolnaycc0f0372017-12-28 19:11:04 -0500645 name = name.owned_tokens(),
646 ),
647 Visit => format!(
648 "tokens_helper(_visitor, &({name}).0)",
649 name = name.ref_tokens(),
650 ),
651 VisitMut => format!(
652 "tokens_helper(_visitor, &mut ({name}).0)",
653 name = name.ref_mut_tokens(),
654 ),
655 }
656 }
657
David Tolnay4a918742017-12-28 16:54:41 -0500658 fn noop_visit(kind: Kind, name: &Operand) -> String {
659 match kind {
David Tolnay83db9272017-12-28 17:02:31 -0500660 Fold => name.owned_tokens().to_string(),
661 Visit | VisitMut => format!("// Skipped field {}", name),
David Tolnay4a918742017-12-28 16:54:41 -0500662 }
663 }
664
665 fn visit(ty: &Type, lookup: &Lookup, kind: Kind, name: &Operand) -> Option<String> {
David Tolnay3d772182017-12-28 17:18:53 -0500666 match classify(ty, lookup) {
667 RelevantType::Box(elem) => {
668 box_visit(elem, lookup, kind, name)
David Tolnay4a918742017-12-28 16:54:41 -0500669 }
David Tolnay3d772182017-12-28 17:18:53 -0500670 RelevantType::Vec(elem) => {
671 vec_visit(elem, lookup, kind, name)
David Tolnay4a918742017-12-28 16:54:41 -0500672 }
David Tolnayf2cfd722017-12-31 18:02:51 -0500673 RelevantType::Punctuated(elem) => {
David Tolnay6eff4da2018-01-01 20:27:45 -0800674 punctuated_visit(elem, lookup, kind, name)
David Tolnay4a918742017-12-28 16:54:41 -0500675 }
David Tolnay3d772182017-12-28 17:18:53 -0500676 RelevantType::Option(elem) => {
677 option_visit(elem, lookup, kind, name)
678 }
David Tolnay5c4c0b52017-12-28 17:58:54 -0500679 RelevantType::Tuple(elems) => {
680 tuple_visit(elems, lookup, kind, name)
681 }
David Tolnay3d772182017-12-28 17:18:53 -0500682 RelevantType::Simple(item) => {
683 let mut res = simple_visit(item, kind, name);
684 Some(if item.eos_full {
685 format!("full!({res})", res = res)
686 } else {
687 res
688 })
689 }
David Tolnay1e01f9c2017-12-28 20:16:19 -0500690 RelevantType::Token(ty) => {
691 Some(token_visit(ty, kind, name))
David Tolnaycc0f0372017-12-28 19:11:04 -0500692 }
David Tolnay3d772182017-12-28 17:18:53 -0500693 RelevantType::Pass => {
694 None
Nika Layzell27726662017-10-24 23:16:35 -0400695 }
696 }
Nika Layzell27726662017-10-24 23:16:35 -0400697 }
698
699 pub fn generate(state: &mut State, lookup: &Lookup, s: &AstItem) {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700700 let under_name = under_name(s.ast.ident.clone());
Nika Layzell27726662017-10-24 23:16:35 -0400701
702 state.visit_trait.push_str(&format!(
703 "{features}\n\
Nika Layzellc86173a2017-11-18 13:55:22 -0500704 fn visit_{under_name}(&mut self, i: &'ast {ty}) {{ \
David Tolnayd67fb752017-12-27 13:50:29 -0500705 visit_{under_name}(self, i) \
Nika Layzell27726662017-10-24 23:16:35 -0400706 }}\n",
707 features = s.features,
708 under_name = under_name,
David Tolnay3d772182017-12-28 17:18:53 -0500709 ty = s.ast.ident,
Nika Layzell27726662017-10-24 23:16:35 -0400710 ));
711 state.visit_mut_trait.push_str(&format!(
712 "{features}\n\
Nika Layzella6f46c42017-10-26 15:26:16 -0400713 fn visit_{under_name}_mut(&mut self, i: &mut {ty}) {{ \
David Tolnayd67fb752017-12-27 13:50:29 -0500714 visit_{under_name}_mut(self, i) \
Nika Layzell27726662017-10-24 23:16:35 -0400715 }}\n",
716 features = s.features,
717 under_name = under_name,
David Tolnay3d772182017-12-28 17:18:53 -0500718 ty = s.ast.ident,
Nika Layzell27726662017-10-24 23:16:35 -0400719 ));
720 state.fold_trait.push_str(&format!(
721 "{features}\n\
722 fn fold_{under_name}(&mut self, i: {ty}) -> {ty} {{ \
David Tolnayd67fb752017-12-27 13:50:29 -0500723 fold_{under_name}(self, i) \
Nika Layzell27726662017-10-24 23:16:35 -0400724 }}\n",
725 features = s.features,
726 under_name = under_name,
David Tolnay3d772182017-12-28 17:18:53 -0500727 ty = s.ast.ident,
Nika Layzell27726662017-10-24 23:16:35 -0400728 ));
729
730 state.visit_impl.push_str(&format!(
731 "{features}\n\
David Tolnay4b4c4b62018-01-06 13:48:05 -0800732 pub fn visit_{under_name}<'ast, V: Visit<'ast> + ?Sized>(\
David Tolnayd67fb752017-12-27 13:50:29 -0500733 _visitor: &mut V, _i: &'ast {ty}) {{\n",
Nika Layzell27726662017-10-24 23:16:35 -0400734 features = s.features,
735 under_name = under_name,
David Tolnay3d772182017-12-28 17:18:53 -0500736 ty = s.ast.ident,
Nika Layzell27726662017-10-24 23:16:35 -0400737 ));
738 state.visit_mut_impl.push_str(&format!(
739 "{features}\n\
David Tolnay4b4c4b62018-01-06 13:48:05 -0800740 pub fn visit_{under_name}_mut<V: VisitMut + ?Sized>(\
David Tolnayd67fb752017-12-27 13:50:29 -0500741 _visitor: &mut V, _i: &mut {ty}) {{\n",
Nika Layzell27726662017-10-24 23:16:35 -0400742 features = s.features,
743 under_name = under_name,
David Tolnay3d772182017-12-28 17:18:53 -0500744 ty = s.ast.ident,
Nika Layzell27726662017-10-24 23:16:35 -0400745 ));
David Tolnayd0adf522017-12-29 01:30:07 -0500746 let before_fold_impl_len = state.fold_impl.len();
Nika Layzell27726662017-10-24 23:16:35 -0400747 state.fold_impl.push_str(&format!(
748 "{features}\n\
David Tolnay4b4c4b62018-01-06 13:48:05 -0800749 pub fn fold_{under_name}<V: Fold + ?Sized>(\
David Tolnayd67fb752017-12-27 13:50:29 -0500750 _visitor: &mut V, _i: {ty}) -> {ty} {{\n",
Nika Layzell27726662017-10-24 23:16:35 -0400751 features = s.features,
752 under_name = under_name,
David Tolnay3d772182017-12-28 17:18:53 -0500753 ty = s.ast.ident,
Nika Layzell27726662017-10-24 23:16:35 -0400754 ));
755
756 // XXX: This part is a disaster - I'm not sure how to make it cleaner though :'(
David Tolnaye3d41b72017-12-31 15:24:00 -0500757 match s.ast.data {
758 Data::Enum(ref e) => {
Nika Layzell27726662017-10-24 23:16:35 -0400759 state.visit_impl.push_str(" match *_i {\n");
760 state.visit_mut_impl.push_str(" match *_i {\n");
761 state.fold_impl.push_str(" match _i {\n");
762 for variant in &e.variants {
David Tolnay6eff4da2018-01-01 20:27:45 -0800763 let fields: Vec<(&Field, Tokens)> = match variant.fields {
David Tolnaye3d41b72017-12-31 15:24:00 -0500764 Fields::Named(..) => panic!("Doesn't support enum struct variants"),
765 Fields::Unnamed(ref fields) => {
David Tolnay6eff4da2018-01-01 20:27:45 -0800766 let binding = format!(" {}::{}(", s.ast.ident, variant.ident);
Nika Layzell27726662017-10-24 23:16:35 -0400767 state.visit_impl.push_str(&binding);
768 state.visit_mut_impl.push_str(&binding);
769 state.fold_impl.push_str(&binding);
770
David Tolnaybdafb102018-01-01 19:39:10 -0800771 let res = fields.unnamed
David Tolnayd67fb752017-12-27 13:50:29 -0500772 .iter()
773 .enumerate()
774 .map(|(idx, el)| {
775 let name = format!("_binding_{}", idx);
Nika Layzell27726662017-10-24 23:16:35 -0400776
David Tolnayd67fb752017-12-27 13:50:29 -0500777 state.visit_impl.push_str("ref ");
778 state.visit_mut_impl.push_str("ref mut ");
Nika Layzell27726662017-10-24 23:16:35 -0400779
David Tolnayd67fb752017-12-27 13:50:29 -0500780 state.visit_impl.push_str(&name);
781 state.visit_mut_impl.push_str(&name);
782 state.fold_impl.push_str(&name);
783 state.visit_impl.push_str(", ");
784 state.visit_mut_impl.push_str(", ");
785 state.fold_impl.push_str(", ");
Nika Layzell27726662017-10-24 23:16:35 -0400786
David Tolnayd67fb752017-12-27 13:50:29 -0500787 let mut tokens = quote!();
Alex Crichtona74a1c82018-05-16 10:20:44 -0700788 Ident::new(&name, Span::call_site()).to_tokens(&mut tokens);
Nika Layzell27726662017-10-24 23:16:35 -0400789
David Tolnay6eff4da2018-01-01 20:27:45 -0800790 (el, tokens)
David Tolnayd67fb752017-12-27 13:50:29 -0500791 })
792 .collect();
Nika Layzell27726662017-10-24 23:16:35 -0400793
794 state.visit_impl.push_str(") => {\n");
795 state.visit_mut_impl.push_str(") => {\n");
796 state.fold_impl.push_str(") => {\n");
797
798 res
799 }
David Tolnaye3d41b72017-12-31 15:24:00 -0500800 Fields::Unit => {
David Tolnayd67fb752017-12-27 13:50:29 -0500801 state
802 .visit_impl
David Tolnay6eff4da2018-01-01 20:27:45 -0800803 .push_str(&format!(" {0}::{1} => {{ }}\n", s.ast.ident, variant.ident));
David Tolnayd67fb752017-12-27 13:50:29 -0500804 state
805 .visit_mut_impl
David Tolnay6eff4da2018-01-01 20:27:45 -0800806 .push_str(&format!(" {0}::{1} => {{ }}\n", s.ast.ident, variant.ident));
Nika Layzell27726662017-10-24 23:16:35 -0400807 state.fold_impl.push_str(&format!(
David Tolnay6702ade2017-12-30 23:38:15 -0500808 " {0}::{1} => {{ {0}::{1} }}\n",
809 s.ast.ident,
David Tolnay6eff4da2018-01-01 20:27:45 -0800810 variant.ident
Nika Layzell27726662017-10-24 23:16:35 -0400811 ));
David Tolnayd67fb752017-12-27 13:50:29 -0500812 continue;
Nika Layzell27726662017-10-24 23:16:35 -0400813 }
814 };
815
816 if fields.is_empty() {
817 state.visit_impl.push_str(" {}");
818 state.visit_mut_impl.push_str(") => {\n");
819 state.fold_impl.push_str(") => {\n");
820 }
David Tolnayd67fb752017-12-27 13:50:29 -0500821 state
822 .fold_impl
David Tolnay6eff4da2018-01-01 20:27:45 -0800823 .push_str(&format!(" {}::{} (\n", s.ast.ident, variant.ident,));
Nika Layzell27726662017-10-24 23:16:35 -0400824 for (field, binding) in fields {
825 state.visit_impl.push_str(&format!(
826 " {};\n",
David Tolnayd67fb752017-12-27 13:50:29 -0500827 visit(
828 &field.ty,
829 lookup,
David Tolnay83db9272017-12-28 17:02:31 -0500830 Visit,
831 &Borrowed(binding.clone())
David Tolnay4a918742017-12-28 16:54:41 -0500832 ).unwrap_or_else(|| noop_visit(
David Tolnay83db9272017-12-28 17:02:31 -0500833 Visit,
834 &Borrowed(binding.clone())
David Tolnay4a918742017-12-28 16:54:41 -0500835 )),
Nika Layzell27726662017-10-24 23:16:35 -0400836 ));
837 state.visit_mut_impl.push_str(&format!(
838 " {};\n",
David Tolnayd67fb752017-12-27 13:50:29 -0500839 visit(
840 &field.ty,
841 lookup,
David Tolnay83db9272017-12-28 17:02:31 -0500842 VisitMut,
843 &Borrowed(binding.clone())
David Tolnay4a918742017-12-28 16:54:41 -0500844 ).unwrap_or_else(|| noop_visit(
David Tolnay83db9272017-12-28 17:02:31 -0500845 VisitMut,
846 &Borrowed(binding.clone())
David Tolnay4a918742017-12-28 16:54:41 -0500847 )),
Nika Layzell27726662017-10-24 23:16:35 -0400848 ));
849 state.fold_impl.push_str(&format!(
850 " {},\n",
David Tolnay83db9272017-12-28 17:02:31 -0500851 visit(&field.ty, lookup, Fold, &Owned(binding.clone()))
David Tolnay4a918742017-12-28 16:54:41 -0500852 .unwrap_or_else(|| noop_visit(
David Tolnay83db9272017-12-28 17:02:31 -0500853 Fold,
854 &Owned(binding)
David Tolnay4a918742017-12-28 16:54:41 -0500855 )),
Nika Layzell27726662017-10-24 23:16:35 -0400856 ));
857 }
858 state.fold_impl.push_str(" )\n");
859
860 state.visit_impl.push_str(" }\n");
861 state.visit_mut_impl.push_str(" }\n");
862 state.fold_impl.push_str(" }\n");
863 }
864 state.visit_impl.push_str(" }\n");
865 state.visit_mut_impl.push_str(" }\n");
866 state.fold_impl.push_str(" }\n");
867 }
David Tolnaye3d41b72017-12-31 15:24:00 -0500868 Data::Struct(ref v) => {
869 let fields: Vec<(&Field, Tokens)> = match v.fields {
870 Fields::Named(ref fields) => {
David Tolnayd67fb752017-12-27 13:50:29 -0500871 state
872 .fold_impl
David Tolnay3d772182017-12-28 17:18:53 -0500873 .push_str(&format!(" {} {{\n", s.ast.ident));
David Tolnaybdafb102018-01-01 19:39:10 -0800874 fields.named
David Tolnayd67fb752017-12-27 13:50:29 -0500875 .iter()
876 .map(|el| {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700877 let id = el.ident.clone();
David Tolnay6eff4da2018-01-01 20:27:45 -0800878 (el, quote!(_i.#id))
David Tolnayd67fb752017-12-27 13:50:29 -0500879 })
880 .collect()
Nika Layzell27726662017-10-24 23:16:35 -0400881 }
David Tolnaye3d41b72017-12-31 15:24:00 -0500882 Fields::Unnamed(ref fields) => {
David Tolnayd67fb752017-12-27 13:50:29 -0500883 state
884 .fold_impl
David Tolnay3d772182017-12-28 17:18:53 -0500885 .push_str(&format!(" {} (\n", s.ast.ident));
David Tolnaybdafb102018-01-01 19:39:10 -0800886 fields.unnamed
David Tolnayd67fb752017-12-27 13:50:29 -0500887 .iter()
888 .enumerate()
889 .map(|(idx, el)| {
David Tolnay14982012017-12-29 00:49:51 -0500890 let id = Index::from(idx);
David Tolnay6eff4da2018-01-01 20:27:45 -0800891 (el, quote!(_i.#id))
David Tolnayd67fb752017-12-27 13:50:29 -0500892 })
893 .collect()
Nika Layzell27726662017-10-24 23:16:35 -0400894 }
David Tolnaye3d41b72017-12-31 15:24:00 -0500895 Fields::Unit => {
Nika Layzellefb83ba2017-12-19 18:23:55 -0500896 state.fold_impl.push_str(" _i\n");
897 vec![]
898 }
Nika Layzell27726662017-10-24 23:16:35 -0400899 };
900
901 for (field, ref_toks) in fields {
David Tolnay83db9272017-12-28 17:02:31 -0500902 let ref_toks = Owned(ref_toks);
Nika Layzell27726662017-10-24 23:16:35 -0400903 state.visit_impl.push_str(&format!(
David Tolnayd67fb752017-12-27 13:50:29 -0500904 " {};\n",
David Tolnay83db9272017-12-28 17:02:31 -0500905 visit(&field.ty, lookup, Visit, &ref_toks)
David Tolnay4a918742017-12-28 16:54:41 -0500906 .unwrap_or_else(|| noop_visit(
David Tolnay83db9272017-12-28 17:02:31 -0500907 Visit,
David Tolnay4a918742017-12-28 16:54:41 -0500908 &ref_toks,
909 ))
Nika Layzell27726662017-10-24 23:16:35 -0400910 ));
911 state.visit_mut_impl.push_str(&format!(
David Tolnayd67fb752017-12-27 13:50:29 -0500912 " {};\n",
David Tolnay83db9272017-12-28 17:02:31 -0500913 visit(&field.ty, lookup, VisitMut, &ref_toks)
David Tolnay4a918742017-12-28 16:54:41 -0500914 .unwrap_or_else(|| noop_visit(
David Tolnay83db9272017-12-28 17:02:31 -0500915 VisitMut,
David Tolnay4a918742017-12-28 16:54:41 -0500916 &ref_toks,
917 ))
Nika Layzell27726662017-10-24 23:16:35 -0400918 ));
David Tolnay83db9272017-12-28 17:02:31 -0500919 let fold = visit(&field.ty, lookup, Fold, &ref_toks)
David Tolnay4a918742017-12-28 16:54:41 -0500920 .unwrap_or_else(|| noop_visit(
David Tolnay83db9272017-12-28 17:02:31 -0500921 Fold,
David Tolnay4a918742017-12-28 16:54:41 -0500922 &ref_toks,
923 ));
Nika Layzell27726662017-10-24 23:16:35 -0400924 if let Some(ref name) = field.ident {
David Tolnayd67fb752017-12-27 13:50:29 -0500925 state
926 .fold_impl
927 .push_str(&format!(" {}: {},\n", name, fold));
Nika Layzell27726662017-10-24 23:16:35 -0400928 } else {
929 state.fold_impl.push_str(&format!(" {},\n", fold));
930 }
931 }
932
David Tolnaye3d41b72017-12-31 15:24:00 -0500933 match v.fields {
934 Fields::Named(..) => state.fold_impl.push_str(" }\n"),
935 Fields::Unnamed(..) => state.fold_impl.push_str(" )\n"),
936 Fields::Unit => {}
Nika Layzell27726662017-10-24 23:16:35 -0400937 };
938 }
David Tolnaye3d41b72017-12-31 15:24:00 -0500939 Data::Union(..) => panic!("Union not supported"),
Nika Layzell27726662017-10-24 23:16:35 -0400940 }
941
942 // Close the impl body
943 state.visit_impl.push_str("}\n");
944 state.visit_mut_impl.push_str("}\n");
945 state.fold_impl.push_str("}\n");
David Tolnayd0adf522017-12-29 01:30:07 -0500946
David Tolnay360efd22018-01-04 23:35:26 -0800947 if let Data::Struct(ref data) = s.ast.data {
948 if let Fields::Named(ref fields) = data.fields {
949 if fields.named.iter().any(|field| field.vis == Visibility::Inherited) {
950 // Discard the generated impl if there are private fields.
951 // These have to be handwritten.
952 state.fold_impl.truncate(before_fold_impl_len);
953 }
954 }
David Tolnayd0adf522017-12-29 01:30:07 -0500955 }
Nika Layzell27726662017-10-24 23:16:35 -0400956 }
957}
958
959fn main() {
960 let mut lookup = BTreeMap::new();
David Tolnayea9ae892017-12-26 01:44:32 -0500961 load_file(SYN_CRATE_ROOT, &quote!(), &mut lookup).unwrap();
Nika Layzell27726662017-10-24 23:16:35 -0400962
Nika Layzellefb83ba2017-12-19 18:23:55 -0500963 // Load in any terminal types
964 for &tt in TERMINAL_TYPES {
965 use syn::*;
David Tolnayd67fb752017-12-27 13:50:29 -0500966 lookup.insert(
Alex Crichtona74a1c82018-05-16 10:20:44 -0700967 Ident::new(&tt, Span::call_site()),
David Tolnayd67fb752017-12-27 13:50:29 -0500968 AstItem {
David Tolnay3d772182017-12-28 17:18:53 -0500969 ast: DeriveInput {
Alex Crichtona74a1c82018-05-16 10:20:44 -0700970 ident: Ident::new(tt, Span::call_site()),
David Tolnayd67fb752017-12-27 13:50:29 -0500971 vis: Visibility::Public(VisPublic {
972 pub_token: Default::default(),
973 }),
974 attrs: vec![],
975 generics: Default::default(),
David Tolnaye3d41b72017-12-31 15:24:00 -0500976 data: Data::Struct(DataStruct {
977 fields: Fields::Unit,
David Tolnayd67fb752017-12-27 13:50:29 -0500978 struct_token: Default::default(),
979 semi_token: None,
980 }),
981 },
982 features: Default::default(),
983 eos_full: false,
Nika Layzellefb83ba2017-12-19 18:23:55 -0500984 },
David Tolnayd67fb752017-12-27 13:50:29 -0500985 );
Nika Layzellefb83ba2017-12-19 18:23:55 -0500986 }
987
Nika Layzell27726662017-10-24 23:16:35 -0400988 let mut state = Default::default();
989 for s in lookup.values() {
990 codegen::generate(&mut state, &lookup, s);
991 }
992
Nika Layzell4ab8d6e2017-10-26 09:45:49 -0400993 let full_macro = "
994#[cfg(feature = \"full\")]
995macro_rules! full {
996 ($e:expr) => { $e }
997}
998
David Tolnay0a0d78c2018-01-05 15:24:01 -0800999#[cfg(all(feature = \"derive\", not(feature = \"full\")))]
Nika Layzell4ab8d6e2017-10-26 09:45:49 -04001000macro_rules! full {
1001 ($e:expr) => { unreachable!() }
1002}
1003";
1004
Nika Layzell27726662017-10-24 23:16:35 -04001005 let mut fold_file = File::create(FOLD_SRC).unwrap();
David Tolnayd67fb752017-12-27 13:50:29 -05001006 write!(
1007 fold_file,
1008 "\
Nika Layzell27726662017-10-24 23:16:35 -04001009// THIS FILE IS AUTOMATICALLY GENERATED; DO NOT EDIT
1010
David Tolnay0afc9b32017-12-27 13:38:24 -05001011#![cfg_attr(rustfmt, rustfmt_skip)]
1012
Nika Layzell27726662017-10-24 23:16:35 -04001013// Unreachable code is generated sometimes without the full feature.
1014#![allow(unreachable_code)]
David Tolnayf0d63bf2017-12-26 12:29:47 -05001015#![cfg_attr(feature = \"cargo-clippy\", allow(needless_pass_by_value))]
Nika Layzell27726662017-10-24 23:16:35 -04001016
Nika Layzella6f46c42017-10-26 15:26:16 -04001017use *;
David Tolnay0a0d78c2018-01-05 15:24:01 -08001018#[cfg(any(feature = \"full\", feature = \"derive\"))]
David Tolnay1e01f9c2017-12-28 20:16:19 -05001019use token::{{Brace, Bracket, Paren, Group}};
Alex Crichtona74a1c82018-05-16 10:20:44 -07001020use proc_macro2::{{Span, Ident}};
David Tolnay0a0d78c2018-01-05 15:24:01 -08001021#[cfg(any(feature = \"full\", feature = \"derive\"))]
David Tolnayf60f4262017-12-28 19:17:58 -05001022use gen::helper::fold::*;
Nika Layzell27726662017-10-24 23:16:35 -04001023
Nika Layzell4ab8d6e2017-10-26 09:45:49 -04001024{full_macro}
1025
David Tolnayded2d682018-01-06 18:53:53 -08001026/// Syntax tree traversal to transform the nodes of an owned syntax tree.
Nika Layzell27726662017-10-24 23:16:35 -04001027///
David Tolnayded2d682018-01-06 18:53:53 -08001028/// See the [module documentation] for details.
Nika Layzell27726662017-10-24 23:16:35 -04001029///
David Tolnayded2d682018-01-06 18:53:53 -08001030/// [module documentation]: index.html
David Tolnay461d98e2018-01-07 11:07:19 -08001031///
1032/// *This trait is available if Syn is built with the `\"fold\"` feature.*
David Tolnay4b4c4b62018-01-06 13:48:05 -08001033pub trait Fold {{
Nika Layzell27726662017-10-24 23:16:35 -04001034{fold_trait}
1035}}
1036
David Tolnay360efd22018-01-04 23:35:26 -08001037macro_rules! fold_span_only {{
1038 ($f:ident : $t:ident) => {{
David Tolnay4b4c4b62018-01-06 13:48:05 -08001039 pub fn $f<V: Fold + ?Sized>(_visitor: &mut V, mut _i: $t) -> $t {{
Alex Crichton9a4dca22018-03-28 06:32:19 -07001040 let span = _visitor.fold_span(_i.span());
1041 _i.set_span(span);
David Tolnay360efd22018-01-04 23:35:26 -08001042 _i
1043 }}
1044 }}
David Tolnayd0adf522017-12-29 01:30:07 -05001045}}
1046
David Tolnay360efd22018-01-04 23:35:26 -08001047fold_span_only!(fold_ident: Ident);
David Tolnay0a0d78c2018-01-05 15:24:01 -08001048#[cfg(any(feature = \"full\", feature = \"derive\"))]
David Tolnay360efd22018-01-04 23:35:26 -08001049fold_span_only!(fold_lifetime: Lifetime);
1050#[cfg(any(feature = \"full\", feature = \"derive\"))]
1051fold_span_only!(fold_lit_byte: LitByte);
1052#[cfg(any(feature = \"full\", feature = \"derive\"))]
1053fold_span_only!(fold_lit_byte_str: LitByteStr);
1054#[cfg(any(feature = \"full\", feature = \"derive\"))]
1055fold_span_only!(fold_lit_char: LitChar);
1056#[cfg(any(feature = \"full\", feature = \"derive\"))]
1057fold_span_only!(fold_lit_float: LitFloat);
1058#[cfg(any(feature = \"full\", feature = \"derive\"))]
1059fold_span_only!(fold_lit_int: LitInt);
1060#[cfg(any(feature = \"full\", feature = \"derive\"))]
1061fold_span_only!(fold_lit_str: LitStr);
David Tolnayd0adf522017-12-29 01:30:07 -05001062
Nika Layzell27726662017-10-24 23:16:35 -04001063{fold_impl}
1064",
David Tolnayd67fb752017-12-27 13:50:29 -05001065 full_macro = full_macro,
1066 fold_trait = state.fold_trait,
1067 fold_impl = state.fold_impl
1068 ).unwrap();
Nika Layzell27726662017-10-24 23:16:35 -04001069
1070 let mut visit_file = File::create(VISIT_SRC).unwrap();
David Tolnayd67fb752017-12-27 13:50:29 -05001071 write!(
1072 visit_file,
1073 "\
Nika Layzell27726662017-10-24 23:16:35 -04001074// THIS FILE IS AUTOMATICALLY GENERATED; DO NOT EDIT
1075
David Tolnay0afc9b32017-12-27 13:38:24 -05001076#![cfg_attr(rustfmt, rustfmt_skip)]
1077
David Tolnayf0d63bf2017-12-26 12:29:47 -05001078#![cfg_attr(feature = \"cargo-clippy\", allow(match_same_arms))]
1079
Nika Layzella6f46c42017-10-26 15:26:16 -04001080use *;
David Tolnay0a0d78c2018-01-05 15:24:01 -08001081#[cfg(any(feature = \"full\", feature = \"derive\"))]
David Tolnay6eff4da2018-01-01 20:27:45 -08001082use punctuated::Punctuated;
David Tolnay98942562017-12-26 21:24:35 -05001083use proc_macro2::Span;
David Tolnay0a0d78c2018-01-05 15:24:01 -08001084#[cfg(any(feature = \"full\", feature = \"derive\"))]
David Tolnaycc0f0372017-12-28 19:11:04 -05001085use gen::helper::visit::*;
Nika Layzell27726662017-10-24 23:16:35 -04001086
Nika Layzell4ab8d6e2017-10-26 09:45:49 -04001087{full_macro}
1088
David Tolnayded2d682018-01-06 18:53:53 -08001089/// Syntax tree traversal to walk a shared borrow of a syntax tree.
Nika Layzell27726662017-10-24 23:16:35 -04001090///
David Tolnayded2d682018-01-06 18:53:53 -08001091/// See the [module documentation] for details.
1092///
1093/// [module documentation]: index.html
David Tolnay461d98e2018-01-07 11:07:19 -08001094///
1095/// *This trait is available if Syn is built with the `\"visit\"` feature.*
David Tolnay4b4c4b62018-01-06 13:48:05 -08001096pub trait Visit<'ast> {{
Nika Layzell27726662017-10-24 23:16:35 -04001097{visit_trait}
1098}}
1099
1100{visit_impl}
1101",
David Tolnayd67fb752017-12-27 13:50:29 -05001102 full_macro = full_macro,
1103 visit_trait = state.visit_trait,
1104 visit_impl = state.visit_impl
1105 ).unwrap();
Nika Layzell27726662017-10-24 23:16:35 -04001106
1107 let mut visit_mut_file = File::create(VISIT_MUT_SRC).unwrap();
David Tolnayd67fb752017-12-27 13:50:29 -05001108 write!(
1109 visit_mut_file,
1110 "\
Nika Layzell27726662017-10-24 23:16:35 -04001111// THIS FILE IS AUTOMATICALLY GENERATED; DO NOT EDIT
1112
David Tolnay0afc9b32017-12-27 13:38:24 -05001113#![cfg_attr(rustfmt, rustfmt_skip)]
1114
David Tolnayf0d63bf2017-12-26 12:29:47 -05001115#![cfg_attr(feature = \"cargo-clippy\", allow(match_same_arms))]
1116
Nika Layzella6f46c42017-10-26 15:26:16 -04001117use *;
David Tolnay0a0d78c2018-01-05 15:24:01 -08001118#[cfg(any(feature = \"full\", feature = \"derive\"))]
David Tolnay6eff4da2018-01-01 20:27:45 -08001119use punctuated::Punctuated;
David Tolnay98942562017-12-26 21:24:35 -05001120use proc_macro2::Span;
David Tolnay0a0d78c2018-01-05 15:24:01 -08001121#[cfg(any(feature = \"full\", feature = \"derive\"))]
David Tolnaycc0f0372017-12-28 19:11:04 -05001122use gen::helper::visit_mut::*;
Nika Layzell27726662017-10-24 23:16:35 -04001123
Nika Layzell4ab8d6e2017-10-26 09:45:49 -04001124{full_macro}
1125
David Tolnayded2d682018-01-06 18:53:53 -08001126/// Syntax tree traversal to mutate an exclusive borrow of a syntax tree in
1127/// place.
Nika Layzell27726662017-10-24 23:16:35 -04001128///
David Tolnayded2d682018-01-06 18:53:53 -08001129/// See the [module documentation] for details.
1130///
1131/// [module documentation]: index.html
David Tolnay461d98e2018-01-07 11:07:19 -08001132///
1133/// *This trait is available if Syn is built with the `\"visit-mut\"` feature.*
David Tolnay4b4c4b62018-01-06 13:48:05 -08001134pub trait VisitMut {{
Nika Layzell27726662017-10-24 23:16:35 -04001135{visit_mut_trait}
1136}}
1137
1138{visit_mut_impl}
1139",
David Tolnayd67fb752017-12-27 13:50:29 -05001140 full_macro = full_macro,
1141 visit_mut_trait = state.visit_mut_trait,
1142 visit_mut_impl = state.visit_mut_impl
1143 ).unwrap();
Nika Layzell27726662017-10-24 23:16:35 -04001144}