defamed 0.2.0

Default, positional and named parameters
Documentation
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Various methods for manipulating a particular block of code.

use proc_macro as pm;
use proc_macro2 as pm2;
use quote::{quote, ToTokens};

use crate::{
    macro_gen::{self, MacroType},
    permute::{
        fields::{StructField, StructFields},
        params, ParamAttr, PermutedItem,
    },
    traits::StripAttributes,
};

/// Output of a processing function
pub struct ProcOutput {
    /// Modified code to be substituted in-place
    pub modified: pm2::TokenStream,
    /// Generated code to be appended to the end of macro invocation
    pub generated: pm2::TokenStream,
}

impl From<pm::TokenStream> for ProcOutput {
    fn from(value: pm::TokenStream) -> Self {
        Self {
            modified: value.into(),
            generated: Default::default(),
        }
    }
}

impl From<pm2::TokenStream> for ProcOutput {
    fn from(value: pm2::TokenStream) -> Self {
        Self {
            modified: value,
            generated: Default::default(),
        }
    }
}

impl From<ProcOutput> for pm::TokenStream {
    fn from(value: ProcOutput) -> Self {
        let mut modified = value.modified;
        modified.extend(value.generated);

        modified.into()
    }
}

/// Process a standalone function.
/// The crate path of the funciton is passed as an optional parameter.
pub fn item_fn(input: syn::ItemFn, fn_path: Option<syn::Path>) -> ProcOutput {
    let syn::ItemFn {
        attrs,
        vis,
        sig,
        block,
    } = input;

    // check visibility vs provided path
    match (&vis, fn_path.as_ref()) {
        (syn::Visibility::Restricted(syn::VisRestricted { path, .. }), None) => {
            if !path.is_ident("self") {
                return syn::Error::new(
                    sig.ident.span(),
                    "Attribute requires a path to the function for public functions",
                )
                .to_compile_error()
                .into();
            }
        }
        (syn::Visibility::Public(_), None) => {
            return syn::Error::new(
                sig.ident.span(),
                "Attribute requires a path to the function for public functions",
            )
            .to_compile_error()
            .into();
        }
        _ => (),
    }

    let params = match params::FunctionParams::from_punctuated(sig.inputs.clone()) {
        Ok(p) => p,
        Err(e) => return e.to_compile_error().into(),
    };

    if let Some(invalid) = params.first_invalid_param() {
        return syn::Error::new(
            invalid.inner_span(),
            "Default parameters must be placed after all positional parameters",
        )
        .to_compile_error()
        .into();
    }

    let params_inner = params.params.clone();
    let (positional, default) = {
        let partition = params_inner.iter().enumerate().find_map(|(idx, f)| {
            if matches!(f.default_value, ParamAttr::Default | ParamAttr::Value(_)) {
                Some(idx)
            } else {
                None
            }
        });

        match partition {
            Some(p) => {
                let tup = params_inner.split_at(p);
                (tup.0.to_vec(), tup.1.to_vec())
            }
            None => (params_inner, vec![]),
        }
    };

    let permuted_new = crate::permute::permute(positional, default);
    let permuted_concat = permuted_new
        .into_iter()
        .map(|permutation| [permutation.0, permutation.1].concat())
        .collect::<Vec<_>>();

    // let permuted = params.permute_params();
    let new_args = params.to_punctuated();
    let mut new_sig = sig.clone();
    new_sig.inputs = new_args;

    // let doc_attrs = attrs
    //     .iter()
    //     .cloned()
    //     .filter(|a| a.path().is_ident("doc"))
    //     .collect::<Vec<_>>();

    let generated = macro_gen::generate_func_macro(
        vis.clone(),
        // doc_attrs,
        // package_name,
        fn_path,
        new_sig.ident.clone(),
        permuted_concat,
        macro_gen::MacroType::Function,
    );

    let mod_fn = syn::ItemFn {
        attrs,
        vis,
        sig: new_sig,
        block,
    }
    .to_token_stream();

    ProcOutput {
        modified: mod_fn,
        generated,
    }
}

/// Process a struct definition
pub fn item_struct(input: syn::ItemStruct, s_path: Option<syn::Path>) -> ProcOutput {
    match input.fields {
        syn::Fields::Named(named_fields) => item_struct_struct(
            s_path,
            input.attrs,
            input.vis,
            input.ident,
            input.generics,
            named_fields,
        ),
        syn::Fields::Unnamed(unnamed_fields) => item_struct_tuple(
            s_path,
            input.attrs,
            input.vis,
            input.ident,
            input.generics,
            unnamed_fields,
        ),
        syn::Fields::Unit => {
            let warning = proc_macro_warning::FormattedWarning::new_deprecated(
                    "IrrelevantMacro",
                    "Remove this attribute macro. Unit structs do not contain any fields and cannot have default parameters.",
                    input.ident.span(),
                );

            quote! {
                #warning
            }
            .into()
        }
    }
}

/// Process a normal struct
fn item_struct_struct(
    s_path: Option<syn::Path>,
    attrs: Vec<syn::Attribute>,
    vis: syn::Visibility,
    ident: syn::Ident,
    generics: syn::Generics,
    fields: syn::FieldsNamed,
) -> ProcOutput {
    match (&vis, s_path.as_ref()) {
        (syn::Visibility::Restricted(syn::VisRestricted { path, .. }), p) => {
            if !fields.named.iter().all(|f| {
                matches!(
                    f.vis,
                    syn::Visibility::Public(_) | syn::Visibility::Restricted(_)
                )
            }) {
                return syn::Error::new(
                    ident.span(),
                    "Non-private structs must have non-private fields",
                )
                .to_compile_error()
                .into();
            }

            if p.is_none() && !path.is_ident("self") {
                return syn::Error::new(
                    ident.span(),
                    "Attribute requires a path to the struct for public structs",
                )
                .to_compile_error()
                .into();
            }
        }
        (syn::Visibility::Public(_), p) => {
            if !fields
                .named
                .iter()
                .all(|f| matches!(f.vis, syn::Visibility::Public(_)))
            {
                return syn::Error::new(ident.span(), "Public structs must have public fields")
                    .to_compile_error()
                    .into();
            }

            if p.is_none() {
                return syn::Error::new(
                    ident.span(),
                    "Attribute requires a path to the struct for public structs",
                )
                .to_compile_error()
                .into();
            }
        }
        (syn::Visibility::Inherited, _) => (),
    }

    let n_fields = match StructFields::from_named(ident.clone(), fields.named.clone()) {
        Ok(f) => f,
        Err(e) => return e.to_compile_error().into(),
    };

    if let Some(invalid) = n_fields.first_invalid() {
        return syn::Error::new(
            invalid.ident.span(),
            "Default parameters must be placed after all positional parameters",
        )
        .to_compile_error()
        .into();
    }

    let stripped_fields = n_fields.strip_attributes();
    let fields_inner = n_fields.fields;

    let (positional, defaults) = {
        let partition = fields_inner.iter().enumerate().find_map(|(idx, f)| {
            if matches!(f.default_value, ParamAttr::Default | ParamAttr::Value(_)) {
                Some(idx)
            } else {
                None
            }
        });

        match partition {
            Some(p) => {
                let tup = fields_inner.split_at(p);
                (tup.0.to_vec(), tup.1.to_vec())
            }
            None => (fields_inner, vec![]),
        }

        // (0,0)
    };

    let permuted = crate::permute::permute(positional, defaults);

    let joined = permuted
        .into_iter()
        .map(|permutation| {
            let has_missing = permutation
                .1
                .iter()
                .any(|item| matches!(item, PermutedItem::Default(_)));

            match has_missing {
                true => [
                    permutation.0,
                    permutation.1,
                    vec![PermutedItem::Default(StructField::dot_dot())],
                ]
                .concat(),
                false => [permutation.0, permutation.1].concat(),
            }
        })
        .collect::<Vec<_>>();

    let generated = macro_gen::generate_func_macro(
        vis.clone(),
        s_path.clone(),
        ident.clone(),
        joined,
        MacroType::Struct,
    );

    ProcOutput {
        modified: syn::ItemStruct {
            attrs,
            vis,
            struct_token: Default::default(),
            ident,
            generics,
            fields: stripped_fields,
            semi_token: None,
        }
        .to_token_stream(),
        generated,
    }
}

/// Process a tuple struct
fn item_struct_tuple(
    s_path: Option<syn::Path>,
    attrs: Vec<syn::Attribute>,
    vis: syn::Visibility,
    ident: syn::Ident,
    generics: syn::Generics,
    fields: syn::FieldsUnnamed,
) -> ProcOutput {
    match (&vis, s_path.as_ref()) {
        (syn::Visibility::Restricted(syn::VisRestricted { path, .. }), p) => {
            if !fields.unnamed.iter().all(|f| {
                matches!(
                    f.vis,
                    syn::Visibility::Public(_) | syn::Visibility::Restricted(_)
                )
            }) {
                return syn::Error::new(
                    ident.span(),
                    "Non-private struct tuples must have non-private items",
                )
                .to_compile_error()
                .into();
            }

            if p.is_none() && !path.is_ident("self") {
                return syn::Error::new(
                    ident.span(),
                    "Attribute requires a path to the struct tuple for public structs",
                )
                .to_compile_error()
                .into();
            }
        }
        (syn::Visibility::Public(_), p) => {
            if !fields
                .unnamed
                .iter()
                .all(|f| matches!(f.vis, syn::Visibility::Public(_)))
            {
                return syn::Error::new(
                    ident.span(),
                    "Public struct tuples must have public items",
                )
                .to_compile_error()
                .into();
            }

            if p.is_none() {
                return syn::Error::new(
                    ident.span(),
                    "Attribute requires a path to the struct for public struct tuples",
                )
                .to_compile_error()
                .into();
            }
        }
        (syn::Visibility::Inherited, _) => (),
    }

    let un_fields = match StructFields::from_unnamed(ident.clone(), fields.unnamed.clone()) {
        Ok(un) => un,
        Err(e) => return e.to_compile_error().into(),
    };

    if let Some(invalid) = un_fields.first_invalid() {
        return syn::Error::new(
            invalid.ident.span(),
            "Default parameters must be placed after all positional parameters",
        )
        .to_compile_error()
        .into();
    }

    let stripped_fields = un_fields.strip_attributes();
    let fields_inner = un_fields.fields;

    let (positional, defaults) = {
        let partition = fields_inner.iter().enumerate().find_map(|(idx, f)| {
            if matches!(f.default_value, ParamAttr::Default | ParamAttr::Value(_)) {
                Some(idx)
            } else {
                None
            }
        });

        match partition {
            Some(p) => {
                let tup = fields_inner.split_at(p);
                (tup.0.to_vec(), tup.1.to_vec())
            }
            None => (fields_inner, vec![]),
        }
    };

    let permuted = crate::permute::permute_tuple_struct(positional, defaults);

    let generated = macro_gen::generate_func_macro(
        vis.clone(),
        s_path.clone(),
        ident.clone(),
        permuted,
        MacroType::StructTuple,
    );

    ProcOutput {
        modified: syn::ItemStruct {
            attrs,
            vis,
            struct_token: Default::default(),
            ident,
            generics,
            fields: stripped_fields,
            semi_token: None,
        }
        .to_token_stream(),
        generated,
    }
}

#[allow(unused)]
fn impl_item_fn(input: syn::ImplItemFn) {
    // this is the only thing that is different from item_fn
    let def_ness = input.defaultness;

    let item_as_fn = syn::ItemFn {
        attrs: input.attrs,
        vis: input.vis,
        sig: input.sig,
        block: Box::new(input.block),
    };
}

/// Processes all functions inside an `impl` block
#[allow(unused)]
pub fn item_impl(input: syn::ItemImpl) -> ProcOutput {
    let inter = input.items.into_iter().map(|item| match item {
        syn::ImplItem::Const(_) => todo!(),
        syn::ImplItem::Fn(f) => {}
        syn::ImplItem::Type(_) => todo!(),
        syn::ImplItem::Macro(_) => todo!(),
        syn::ImplItem::Verbatim(_) => todo!(),
        _ => todo!(),
    });

    todo!()
}

#[allow(dead_code)]
pub fn item_mod(_input: syn::ItemMod) -> ProcOutput {
    todo!()
}

#[cfg(test)]
mod tests {
    use quote::quote;

    #[test]
    fn test_match_impl_block() {
        let tokens = quote! {
            impl SomeStruct {
                pub fn new() -> Self {
                    SomeStruct {}
                }
            }
        };

        let _: syn::ItemImpl = syn::parse2(tokens).unwrap();
    }

    #[test]
    fn test_match_mod_block() {
        let tokens = quote! {
            mod some_module {
                struct X{}
            }
        };

        let _: syn::ItemMod = syn::parse2(tokens).unwrap();
    }
}