aboutsummaryrefslogtreecommitdiff
path: root/syn/codegen/src/debug.rs
blob: 91938812ccc33ff420b827b919ded28198b37abc (plain)
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
use crate::file;
use anyhow::Result;
use proc_macro2::{Ident, Span, TokenStream};
use quote::quote;
use syn::Index;
use syn_codegen::{Data, Definitions, Node, Type};

const DEBUG_SRC: &str = "../tests/debug/gen.rs";

fn rust_type(ty: &Type) -> TokenStream {
    match ty {
        Type::Syn(ty) => {
            let ident = Ident::new(ty, Span::call_site());
            quote!(syn::#ident)
        }
        Type::Std(ty) => {
            let ident = Ident::new(ty, Span::call_site());
            quote!(#ident)
        }
        Type::Ext(ty) => {
            let ident = Ident::new(ty, Span::call_site());
            quote!(proc_macro2::#ident)
        }
        Type::Token(ty) | Type::Group(ty) => {
            let ident = Ident::new(ty, Span::call_site());
            quote!(syn::token::#ident)
        }
        Type::Punctuated(ty) => {
            let element = rust_type(&ty.element);
            let punct = Ident::new(&ty.punct, Span::call_site());
            quote!(syn::punctuated::Punctuated<#element, #punct>)
        }
        Type::Option(ty) => {
            let inner = rust_type(ty);
            quote!(Option<#inner>)
        }
        Type::Box(ty) => {
            let inner = rust_type(ty);
            quote!(Box<#inner>)
        }
        Type::Vec(ty) => {
            let inner = rust_type(ty);
            quote!(Vec<#inner>)
        }
        Type::Tuple(ty) => {
            let inner = ty.iter().map(rust_type);
            quote!((#(#inner,)*))
        }
    }
}

fn is_printable(ty: &Type) -> bool {
    match ty {
        Type::Ext(name) => name != "Span",
        Type::Box(ty) => is_printable(ty),
        Type::Tuple(ty) => ty.iter().any(is_printable),
        Type::Token(_) | Type::Group(_) => false,
        Type::Syn(name) => name != "Reserved",
        Type::Std(_) | Type::Punctuated(_) | Type::Option(_) | Type::Vec(_) => true,
    }
}

fn format_field(val: &TokenStream, ty: &Type) -> Option<TokenStream> {
    if !is_printable(ty) {
        return None;
    }
    let format = match ty {
        Type::Option(ty) => {
            let inner = quote!(_val);
            let format = format_field(&inner, ty).map(|format| {
                quote! {
                    formatter.write_str("(")?;
                    Debug::fmt(#format, formatter)?;
                    formatter.write_str(")")?;
                }
            });
            let ty = rust_type(ty);
            quote!({
                #[derive(RefCast)]
                #[repr(transparent)]
                struct Print(Option<#ty>);
                impl Debug for Print {
                    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                        match &self.0 {
                            Some(#inner) => {
                                formatter.write_str("Some")?;
                                #format
                                Ok(())
                            }
                            None => formatter.write_str("None"),
                        }
                    }
                }
                Print::ref_cast(#val)
            })
        }
        Type::Tuple(ty) => {
            let printable: Vec<TokenStream> = ty
                .iter()
                .enumerate()
                .filter_map(|(i, ty)| {
                    let index = Index::from(i);
                    let val = quote!(&#val.#index);
                    format_field(&val, ty)
                })
                .collect();
            if printable.len() == 1 {
                printable.into_iter().next().unwrap()
            } else {
                quote! {
                    &(#(#printable),*)
                }
            }
        }
        _ => quote! { Lite(#val) },
    };
    Some(format)
}

fn syntax_tree_enum<'a>(outer: &str, inner: &str, fields: &'a [Type]) -> Option<&'a str> {
    if fields.len() != 1 {
        return None;
    }
    const WHITELIST: &[&str] = &["PathArguments", "Visibility"];
    match &fields[0] {
        Type::Syn(ty) if WHITELIST.contains(&outer) || outer.to_owned() + inner == *ty => Some(ty),
        _ => None,
    }
}

fn lookup<'a>(defs: &'a Definitions, name: &str) -> &'a Node {
    for node in &defs.types {
        if node.ident == name {
            return node;
        }
    }
    panic!("not found: {}", name)
}

fn expand_impl_body(defs: &Definitions, node: &Node, name: &str) -> TokenStream {
    let ident = Ident::new(&node.ident, Span::call_site());

    match &node.data {
        Data::Enum(variants) => {
            let arms = variants.iter().map(|(v, fields)| {
                let variant = Ident::new(v, Span::call_site());
                if fields.is_empty() {
                    quote! {
                        syn::#ident::#variant => formatter.write_str(#v),
                    }
                } else if let Some(inner) = syntax_tree_enum(name, v, fields) {
                    let path = format!("{}::{}", name, v);
                    let format = expand_impl_body(defs, lookup(defs, inner), &path);
                    quote! {
                        syn::#ident::#variant(_val) => {
                            #format
                        }
                    }
                } else if fields.len() == 1 {
                    let ty = &fields[0];
                    let val = quote!(_val);
                    let format = format_field(&val, ty).map(|format| {
                        quote! {
                            formatter.write_str("(")?;
                            Debug::fmt(#format, formatter)?;
                            formatter.write_str(")")?;
                        }
                    });
                    quote! {
                        syn::#ident::#variant(_val) => {
                            formatter.write_str(#v)?;
                            #format
                            Ok(())
                        }
                    }
                } else {
                    let pats = (0..fields.len())
                        .map(|i| Ident::new(&format!("_v{}", i), Span::call_site()));
                    let fields = fields.iter().enumerate().filter_map(|(i, ty)| {
                        let index = Ident::new(&format!("_v{}", i), Span::call_site());
                        let val = quote!(#index);
                        let format = format_field(&val, ty)?;
                        Some(quote! {
                            formatter.field(#format);
                        })
                    });
                    quote! {
                        syn::#ident::#variant(#(#pats),*) => {
                            let mut formatter = formatter.debug_tuple(#v);
                            #(#fields)*
                            formatter.finish()
                        }
                    }
                }
            });
            let nonexhaustive = if node.exhaustive {
                None
            } else {
                Some(quote!(_ => unreachable!()))
            };
            quote! {
                match _val {
                    #(#arms)*
                    #nonexhaustive
                }
            }
        }
        Data::Struct(fields) => {
            let fields = fields.iter().filter_map(|(f, ty)| {
                let ident = Ident::new(f, Span::call_site());
                if let Type::Option(ty) = ty {
                    let inner = quote!(_val);
                    let format = format_field(&inner, ty).map(|format| {
                        quote! {
                            let #inner = &self.0;
                            formatter.write_str("(")?;
                            Debug::fmt(#format, formatter)?;
                            formatter.write_str(")")?;
                        }
                    });
                    let ty = rust_type(ty);
                    Some(quote! {
                        if let Some(val) = &_val.#ident {
                            #[derive(RefCast)]
                            #[repr(transparent)]
                            struct Print(#ty);
                            impl Debug for Print {
                                fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                                    formatter.write_str("Some")?;
                                    #format
                                    Ok(())
                                }
                            }
                            formatter.field(#f, Print::ref_cast(val));
                        }
                    })
                } else {
                    let val = quote!(&_val.#ident);
                    let format = format_field(&val, ty)?;
                    let mut call = quote! {
                        formatter.field(#f, #format);
                    };
                    if let Type::Vec(_) | Type::Punctuated(_) = ty {
                        call = quote! {
                            if !_val.#ident.is_empty() {
                                #call
                            }
                        };
                    }
                    Some(call)
                }
            });
            quote! {
                let mut formatter = formatter.debug_struct(#name);
                #(#fields)*
                formatter.finish()
            }
        }
        Data::Private => {
            if node.ident == "LitInt" || node.ident == "LitFloat" {
                quote! {
                    write!(formatter, "{}", _val)
                }
            } else {
                quote! {
                    write!(formatter, "{:?}", _val.value())
                }
            }
        }
    }
}

fn expand_impl(defs: &Definitions, node: &Node) -> TokenStream {
    if node.ident == "Reserved" {
        return TokenStream::new();
    }

    let ident = Ident::new(&node.ident, Span::call_site());
    let body = expand_impl_body(defs, node, &node.ident);

    quote! {
        impl Debug for Lite<syn::#ident> {
            fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                let _val = &self.value;
                #body
            }
        }
    }
}

pub fn generate(defs: &Definitions) -> Result<()> {
    let mut impls = TokenStream::new();
    for node in &defs.types {
        impls.extend(expand_impl(&defs, node));
    }

    file::write(
        DEBUG_SRC,
        quote! {
            use super::{Lite, RefCast};
            use std::fmt::{self, Debug};

            #impls
        },
    )?;

    Ok(())
}