blob: f4578104d774b61ad3befbb7a0637303397abad8 [file] [log] [blame]
David Tolnay3c3c7d12019-05-08 14:54:12 -07001use crate::error::Result;
2use crate::file;
3use proc_macro2::{Ident, Span, TokenStream};
4use quote::quote;
5use syn::Index;
6use syn_codegen::{Data, Definitions, Node, Type};
7
8const DEBUG_SRC: &str = "../tests/debug/gen.rs";
9
10fn rust_type(ty: &Type) -> TokenStream {
11 match ty {
12 Type::Syn(ty) => {
13 let ident = Ident::new(ty, Span::call_site());
14 quote!(syn::#ident)
15 }
16 Type::Std(ty) => {
17 let ident = Ident::new(ty, Span::call_site());
18 quote!(#ident)
19 }
20 Type::Ext(ty) => {
21 let ident = Ident::new(ty, Span::call_site());
22 quote!(proc_macro2::#ident)
23 }
24 Type::Token(ty) | Type::Group(ty) => {
25 let ident = Ident::new(ty, Span::call_site());
26 quote!(syn::token::#ident)
27 }
28 Type::Punctuated(ty) => {
29 let element = rust_type(&ty.element);
30 let punct = Ident::new(&ty.punct, Span::call_site());
31 quote!(syn::punctuated::Punctuated<#element, #punct>)
32 }
33 Type::Option(ty) => {
34 let inner = rust_type(ty);
35 quote!(Option<#inner>)
36 }
37 Type::Box(ty) => {
38 let inner = rust_type(ty);
39 quote!(Box<#inner>)
40 }
41 Type::Vec(ty) => {
42 let inner = rust_type(ty);
43 quote!(Vec<#inner>)
44 }
45 Type::Tuple(ty) => {
46 let inner = ty.iter().map(rust_type);
47 quote!((#(#inner,)*))
48 }
49 }
50}
51
52fn is_printable(ty: &Type) -> bool {
53 match ty {
54 Type::Ext(name) => name != "Span",
55 Type::Box(ty) => is_printable(ty),
56 Type::Tuple(ty) => ty.iter().any(is_printable),
57 Type::Token(_) | Type::Group(_) => false,
58 Type::Syn(_) | Type::Std(_) | Type::Punctuated(_) | Type::Option(_) | Type::Vec(_) => true,
59 }
60}
61
62fn format_field(val: &TokenStream, ty: &Type) -> Option<TokenStream> {
63 if !is_printable(ty) {
64 return None;
65 }
66 let format = match ty {
67 Type::Option(ty) => {
68 let inner = quote!(_val);
69 let format = format_field(&inner, ty).map(|format| {
70 quote! {
71 formatter.write_str("(")?;
72 Debug::fmt(#format, formatter)?;
73 formatter.write_str(")")?;
74 }
75 });
76 let ty = rust_type(ty);
77 quote!({
78 #[derive(RefCast)]
79 #[repr(transparent)]
80 struct Print(Option<#ty>);
81 impl Debug for Print {
82 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
83 match &self.0 {
84 Some(#inner) => {
85 formatter.write_str("Some")?;
86 #format
87 Ok(())
88 }
89 None => formatter.write_str("None"),
90 }
91 }
92 }
93 Print::ref_cast(#val)
94 })
95 }
96 Type::Tuple(ty) => {
97 let printable: Vec<TokenStream> = ty
98 .iter()
99 .enumerate()
100 .filter_map(|(i, ty)| {
101 let index = Index::from(i);
102 let val = quote!(&#val.#index);
103 format_field(&val, ty)
104 })
105 .collect();
106 if printable.len() == 1 {
107 printable.into_iter().next().unwrap()
108 } else {
109 quote! {
110 &(#(#printable),*)
111 }
112 }
113 }
114 _ => quote! { Lite(#val) },
115 };
116 Some(format)
117}
118
David Tolnay5302f0e2019-05-08 23:26:18 -0700119fn syntax_tree_enum<'a>(outer: &str, inner: &str, fields: &'a [Type]) -> Option<&'a str> {
120 if fields.len() != 1 {
121 return None;
122 }
David Tolnay6d16fa82019-05-09 12:17:19 -0700123 const WHITELIST: &[&str] = &["PathArguments", "Visibility"];
David Tolnay5302f0e2019-05-08 23:26:18 -0700124 match &fields[0] {
David Tolnay6d16fa82019-05-09 12:17:19 -0700125 Type::Syn(ty) if WHITELIST.contains(&outer) || outer.to_owned() + inner == *ty => Some(ty),
126 _ => None,
David Tolnay5302f0e2019-05-08 23:26:18 -0700127 }
128}
129
130fn lookup<'a>(defs: &'a Definitions, name: &str) -> &'a Node {
131 for node in &defs.types {
132 if node.ident == name {
133 return node;
134 }
135 }
136 panic!("not found: {}", name)
137}
138
139fn expand_impl_body(defs: &Definitions, node: &Node, name: &str) -> TokenStream {
David Tolnay3c3c7d12019-05-08 14:54:12 -0700140 let ident = Ident::new(&node.ident, Span::call_site());
141
David Tolnay5302f0e2019-05-08 23:26:18 -0700142 match &node.data {
David Tolnay3c3c7d12019-05-08 14:54:12 -0700143 Data::Enum(variants) => {
144 let arms = variants.iter().map(|(v, fields)| {
145 let variant = Ident::new(v, Span::call_site());
146 if fields.is_empty() {
147 quote! {
148 syn::#ident::#variant => formatter.write_str(#v),
149 }
David Tolnay5302f0e2019-05-08 23:26:18 -0700150 } else if let Some(inner) = syntax_tree_enum(name, v, fields) {
151 let path = format!("{}::{}", name, v);
152 let format = expand_impl_body(defs, lookup(defs, inner), &path);
153 quote! {
154 syn::#ident::#variant(_val) => {
155 #format
156 }
157 }
David Tolnay32245a92019-05-09 12:32:15 -0700158 } else if fields.len() == 1 {
159 let ty = &fields[0];
160 let val = quote!(_val);
161 let format = format_field(&val, ty).map(|format| {
162 quote! {
163 formatter.write_str("(")?;
164 Debug::fmt(#format, formatter)?;
165 formatter.write_str(")")?;
166 }
167 });
168 quote! {
169 syn::#ident::#variant(_val) => {
170 formatter.write_str(#v)?;
171 #format
172 Ok(())
173 }
174 }
David Tolnay3c3c7d12019-05-08 14:54:12 -0700175 } else {
176 let pats = (0..fields.len())
177 .map(|i| Ident::new(&format!("_v{}", i), Span::call_site()));
178 let fields = fields.iter().enumerate().filter_map(|(i, ty)| {
179 let index = Ident::new(&format!("_v{}", i), Span::call_site());
180 let val = quote!(#index);
181 let format = format_field(&val, ty)?;
182 Some(quote! {
183 formatter.field(#format);
184 })
185 });
186 quote! {
187 syn::#ident::#variant(#(#pats),*) => {
188 let mut formatter = formatter.debug_tuple(#v);
189 #(#fields)*
190 formatter.finish()
191 }
192 }
193 }
194 });
195 quote! {
David Tolnay5302f0e2019-05-08 23:26:18 -0700196 match _val {
David Tolnay3c3c7d12019-05-08 14:54:12 -0700197 #(#arms)*
198 }
199 }
200 }
201 Data::Struct(fields) => {
202 let fields = fields.iter().filter_map(|(f, ty)| {
203 let ident = Ident::new(f, Span::call_site());
David Tolnay644246b2019-05-08 23:02:46 -0700204 if let Type::Option(ty) = ty {
205 let inner = quote!(_val);
206 let format = format_field(&inner, ty).map(|format| {
207 quote! {
208 let #inner = &self.0;
209 formatter.write_str("(")?;
210 Debug::fmt(#format, formatter)?;
211 formatter.write_str(")")?;
212 }
213 });
214 let ty = rust_type(ty);
215 Some(quote! {
David Tolnay5302f0e2019-05-08 23:26:18 -0700216 if let Some(val) = &_val.#ident {
David Tolnay644246b2019-05-08 23:02:46 -0700217 #[derive(RefCast)]
218 #[repr(transparent)]
219 struct Print(#ty);
220 impl Debug for Print {
221 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
222 formatter.write_str("Some")?;
223 #format
224 Ok(())
225 }
226 }
227 formatter.field(#f, Print::ref_cast(val));
228 }
229 })
230 } else {
David Tolnay5302f0e2019-05-08 23:26:18 -0700231 let val = quote!(&_val.#ident);
David Tolnay644246b2019-05-08 23:02:46 -0700232 let format = format_field(&val, ty)?;
David Tolnaycaac6272019-05-09 11:26:37 -0700233 let mut call = quote! {
David Tolnay644246b2019-05-08 23:02:46 -0700234 formatter.field(#f, #format);
David Tolnaycaac6272019-05-09 11:26:37 -0700235 };
236 if let Type::Vec(_) | Type::Punctuated(_) = ty {
237 call = quote! {
238 if !_val.#ident.is_empty() {
239 #call
240 }
241 };
242 }
243 Some(call)
David Tolnay644246b2019-05-08 23:02:46 -0700244 }
David Tolnay3c3c7d12019-05-08 14:54:12 -0700245 });
246 quote! {
247 let mut formatter = formatter.debug_struct(#name);
248 #(#fields)*
249 formatter.finish()
250 }
251 }
252 Data::Private => {
253 quote! {
David Tolnay5302f0e2019-05-08 23:26:18 -0700254 write!(formatter, "{:?}", _val.value())
David Tolnay3c3c7d12019-05-08 14:54:12 -0700255 }
256 }
David Tolnay5302f0e2019-05-08 23:26:18 -0700257 }
258}
259
260fn expand_impl(defs: &Definitions, node: &Node) -> TokenStream {
261 let ident = Ident::new(&node.ident, Span::call_site());
262 let body = expand_impl_body(defs, node, &node.ident);
David Tolnay3c3c7d12019-05-08 14:54:12 -0700263
264 quote! {
265 impl Debug for Lite<syn::#ident> {
266 fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
David Tolnay5302f0e2019-05-08 23:26:18 -0700267 let _val = &self.value;
David Tolnay3c3c7d12019-05-08 14:54:12 -0700268 #body
269 }
270 }
271 }
272}
273
274pub fn generate(defs: &Definitions) -> Result<()> {
275 let mut impls = TokenStream::new();
276 for node in &defs.types {
David Tolnay5302f0e2019-05-08 23:26:18 -0700277 impls.extend(expand_impl(&defs, node));
David Tolnay3c3c7d12019-05-08 14:54:12 -0700278 }
279
280 file::write(
281 DEBUG_SRC,
282 quote! {
283 use super::{Lite, RefCast};
284 use std::fmt::{self, Debug};
285
286 #impls
287 },
288 )?;
289
290 Ok(())
291}