cote-derive 0.12.2

Quickly build your command line utils
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{
    parse_quote, spanned::Spanned, Attribute, Field, GenericArgument, Generics, Ident,
    ImplGenerics, Lifetime, LifetimeParam, Lit, PathArguments, Type, TypeGenerics, TypeParam,
    WhereClause,
};

use crate::{
    config::{self, Config, Configs},
    error,
    value::Value,
};

pub const CONFIG_SUB: &str = "sub";
pub const CONFIG_ARG: &str = "arg";
pub const CONFIG_CMD: &str = "cmd";
pub const CONFIG_POS: &str = "pos";
pub const CONFIG_DOC: &str = "doc";
pub const POLICY_SEQ: &str = "seq";
pub const POLICY_FWD: &str = "fwd";
pub const POLICY_DELAY: &str = "delay";
pub const HELP_OPTION: &str = "--help;-h=b: Display help message";

#[derive(Debug, Clone, Copy)]
pub enum AttrKind {
    Sub,

    Arg,

    Cmd,

    Pos,

    Main,
}

impl AttrKind {
    pub fn is_sub(&self) -> bool {
        matches!(self, AttrKind::Sub)
    }

    // pub fn is_arg(&self) -> bool {
    //     matches!(self, AttrKind::Arg)
    // }

    pub fn is_cmd(&self) -> bool {
        matches!(self, AttrKind::Cmd)
    }

    pub fn is_pos(&self) -> bool {
        matches!(self, AttrKind::Pos)
    }

    pub fn is_main(&self) -> bool {
        matches!(self, AttrKind::Main)
    }

    pub fn name(&self) -> &'static str {
        match self {
            AttrKind::Sub => CONFIG_SUB,
            AttrKind::Arg => CONFIG_ARG,
            AttrKind::Cmd => CONFIG_CMD,
            AttrKind::Pos => CONFIG_POS,
            AttrKind::Main => unreachable!("Main don't need this"),
        }
    }

    pub fn gen_infer(&self, cfg_ident: &Ident, field_ty: &Type) -> syn::Result<TokenStream> {
        match self {
            AttrKind::Cmd => Ok(quote! {
                cote::prelude::ConfigValue::set_type::<#field_ty>(&mut #cfg_ident);
                <cote::prelude::Cmd as cote::prelude::InferOverride>::infer_fill_info(&mut #cfg_ident)?;
                <cote::prelude::Cmd as cote::prelude::Infer>::infer_fill_info(&mut #cfg_ident)?;
            }),
            AttrKind::Pos => {
                Ok(quote! {
                    // using information of Pos<T>
                    <cote::prelude::Pos<#field_ty> as cote::prelude::InferOverride>::infer_fill_info(&mut #cfg_ident)?;
                    <cote::prelude::Pos<#field_ty> as cote::prelude::Infer>::infer_fill_info(&mut #cfg_ident)?;
                })
            }
            AttrKind::Arg => Ok(quote! {
                <#field_ty as cote::prelude::InferOverride>::infer_fill_info(&mut #cfg_ident)?;
                <#field_ty as cote::prelude::Infer>::infer_fill_info(&mut #cfg_ident)?;
            }),
            _ => {
                unreachable!("In AttrKind, can not get here ...")
            }
        }
    }
}

#[derive(Debug)]
pub struct FieldCfg<'a, T> {
    id: u64,

    ty: &'a Type,

    kind: AttrKind,

    ident: &'a Ident,

    docs: Vec<Lit>,

    configs: Configs<T>,
}

impl<'a, T: config::Kind + PartialEq> FieldCfg<'a, T> {
    pub fn new(id: u64, field: &'a Field, kind: AttrKind) -> syn::Result<Self> {
        let ty = &field.ty;
        let ident = field.ident.as_ref();
        let ident = ident.ok_or_else(|| error(field.span(), "Not support unnamed field"))?;
        let configs = Configs::<T>::parse_attrs(kind.name(), &field.attrs);
        let docs = Self::filter_comment_doc(&field.attrs);

        Ok(Self {
            id,
            ty,
            kind,
            ident,
            configs,
            docs,
        })
    }

    pub fn filter_comment_doc(attrs: &[Attribute]) -> Vec<Lit> {
        let attrs = attrs.iter().filter(|v| v.path().is_ident(CONFIG_DOC));
        let mut ret = vec![];

        for attr in attrs {
            if let syn::Meta::NameValue(meta) = &attr.meta {
                if let syn::Expr::Lit(syn::ExprLit { lit, .. }) = &meta.value {
                    ret.push(lit.clone());
                }
            }
        }
        ret
    }

    // With api, automate generated by api-gen ...
    // pub fn with_id(mut self, value: u64) -> Self {
    //     self.id = value;
    //     self
    // }

    // pub fn with_kind(mut self, value: AttrKind) -> Self {
    //     self.kind = value;
    //     self
    // }

    // pub fn with_docs(mut self, value: Vec<Lit>) -> Self {
    //     self.docs = value;
    //     self
    // }

    // pub fn with_configs(mut self, value: Configs<T>) -> Self {
    //     self.configs = value;
    //     self
    // }

    // Get api, automate generated by api-gen ...
    pub fn id(&self) -> u64 {
        self.id
    }

    pub fn kind(&self) -> AttrKind {
        self.kind
    }

    pub fn docs(&self) -> &[Lit] {
        &self.docs
    }

    pub fn configs(&self) -> &Configs<T> {
        &self.configs
    }

    pub fn ty(&self) -> &'a Type {
        self.ty
    }

    pub fn ident(&self) -> &'a Ident {
        self.ident
    }

    pub fn has_cfg(&self, kind: T) -> bool {
        self.configs.has_cfg(kind)
    }

    pub fn find_cfg(&self, kind: T) -> Option<&Config<T>> {
        self.configs.find_cfg(kind)
    }

    pub fn find_value(&self, kind: T) -> Option<&Value> {
        self.configs.find_cfg(kind).map(|v| v.value())
    }

    pub fn collect_help_msgs(&self) -> Option<TokenStream> {
        if self.docs().is_empty() {
            None
        } else {
            let docs = self.docs.iter();

            Some(quote! {
                [ #(#docs),* ].into_iter().map(|v|v.trim()).collect::<Vec<_>>().join(" ")
            })
        }
    }
}

#[derive(Debug)]
pub struct Utils;

impl Utils {
    pub fn ident2opt_name(ident: &str) -> String {
        if ident.chars().count() > 1 {
            format!("--{}", ident.replace('_', "-"))
        } else {
            format!("-{}", ident)
        }
    }

    pub fn id2opt_ident(id: u64, span: Span) -> Ident {
        Ident::new(&format!("option_{}", id), span)
    }

    pub fn id2opt_uid_ident(id: u64, span: Span) -> Ident {
        Ident::new(&format!("option_{}_uid", id), span)
    }

    pub fn id2uid_literal(id: u64) -> syn::Lit {
        syn::Lit::Verbatim(proc_macro2::Literal::u64_suffixed(id))
    }

    pub fn gen_opt_create(
        ident: &Ident,
        cfg_modifer: Option<TokenStream>,
    ) -> syn::Result<TokenStream> {
        Ok(quote! {
            let #ident = {
                let cfg = {
                    let mut cfg = cote::prelude::SetCfg::<Set>::default();

                    #cfg_modifer
                    cfg
                };
                cote::prelude::Ctor::new_with(cote::prelude::SetExt::ctor_mut(set, &ctor_name)?, cfg).map_err(Into::into)?
            };
        })
    }

    pub fn gen_opt_insert(
        ident: &Ident,
        uid_ident: &Ident,
        uid_literal: &syn::Lit,
    ) -> syn::Result<TokenStream> {
        Ok(quote! {
            let #uid_ident = set.insert(#ident);

            assert_eq!(#uid_ident, #uid_literal, "Oops! Uid must be equal here");
        })
    }

    pub fn gen_opt_handler<T>(
        uid_ident: &Ident,
        on: Option<&Config<T>>,
        fallback: Option<&Config<T>>,
        then: Option<&Config<T>>,
    ) -> syn::Result<Option<TokenStream>> {
        if on.is_some() && fallback.is_some() {
            Err(error(
                uid_ident.span(),
                "Can not set both `on` and `fallback` attribute at same time",
            ))
        } else {
            Ok(on
                .map(|handler| {
                    if let Some(then) = then {
                        quote! {
                            parser.entry(#uid_ident)?.on(#handler).then(#then);
                        }
                    } else {
                        quote! {
                            parser.entry(#uid_ident)?.on(#handler);
                        }
                    }
                })
                .or_else(|| {
                    fallback.map(|handler| {
                        if let Some(then) = then {
                            quote! {
                                parser.entry(#uid_ident)?.fallback(#handler).then(#then);
                            }
                        } else {
                            quote! {
                                parser.entry(#uid_ident)?.fallback(#handler);
                            }
                        }
                    })
                }))
        }
    }

    pub fn check_in_ty(ty: &Type, ty_name: &str) -> syn::Result<bool> {
        if let Type::Path(path) = ty {
            if let Some(segment) = path.path.segments.last() {
                let ident = segment.ident.to_string();

                if ident == ty_name {
                    return Ok(true);
                } else if let PathArguments::AngleBracketed(ab) = &segment.arguments {
                    for arg in ab.args.iter() {
                        if let GenericArgument::Type(next_ty) = arg {
                            return Self::check_in_ty(next_ty, ty_name);
                        }
                    }
                }
            }
            Ok(false)
        } else {
            Err(error(ty, "Cote not support reference type"))
        }
    }

    pub fn gen_policy_ty(policy_name: &str) -> Option<TokenStream> {
        match policy_name {
            POLICY_FWD => Some(quote! {
                cote::prelude::FwdPolicy<'inv, Set>
            }),
            POLICY_DELAY => Some(quote! {
                cote::prelude::DelayPolicy<'inv, Set>
            }),
            POLICY_SEQ => Some(quote! {
                cote::prelude::SeqPolicy<'inv, Set>
            }),
            _ => None,
        }
    }

    pub fn gen_policy_default_ty(policy_name: &str) -> Option<TokenStream> {
        match policy_name {
            POLICY_FWD => Some(quote! {
                cote::prelude::FwdPolicy<'inv, cote::prelude::CoteSet>
            }),
            POLICY_DELAY => Some(quote! {
                cote::prelude::DelayPolicy<'inv, cote::prelude::CoteSet>
            }),
            POLICY_SEQ => Some(quote! {
                cote::prelude::SeqPolicy<'inv, cote::prelude::CoteSet>
            }),
            _ => None,
        }
    }

    // variable name: `ret`, `rctx`, and `parser`
    pub fn gen_sync_ret(
        has_sub: bool,
        enable_abort: bool,
        enable_normal: bool,
        help_uid: Option<u64>,
    ) -> syn::Result<TokenStream> {
        let abort_help = enable_abort.then(|| {
            Some(quote! {
                if error_or_failure {
                    rctx.set_display_help(true);
                    rctx.set_exit(false);
                }
            })
        });
        let normal_help = enable_normal.then(|| {
            let uid_literal = Utils::id2uid_literal(help_uid.unwrap());
            Some(quote! {
                if cote::prelude::OptValueExt::val::<bool>(cote::prelude::SetExt::opt(set, #uid_literal)?).ok() == Some(&true) {
                    rctx.set_display_help(true);
                    rctx.set_exit(!error_or_failure);
                    // if we have sub parsers and we not in sub parser
                    // running ctx not have sub parser flag
                    // then we should not exit to show the error of sub command
                    if #has_sub && !sub_parser && !rctx.sub_parser() {
                        //rctx.set_exit(false);
                    }
                }
            })
        });

        Ok(quote! {
            let error_or_failure = ret.is_err() ||
            // or the return value has failure
            !ret.as_ref().map(cote::prelude::Status::status).unwrap_or(true);

            #abort_help
            #normal_help
        })
    }
}

pub struct GenericsModifier(Generics);

impl GenericsModifier {
    pub fn new(generics: Generics) -> Self {
        Self(generics)
    }

    pub fn insert_lifetime(&mut self, lifetime: &str) -> &mut Self {
        self.0.params.insert(
            0,
            syn::GenericParam::from(LifetimeParam::new(Lifetime::new(lifetime, self.0.span()))),
        );
        self
    }

    pub fn append_type(&mut self, ty: &str) -> &mut Self {
        self.0
            .params
            .push(syn::GenericParam::from(TypeParam::from(Ident::new(
                ty,
                self.0.span(),
            ))));
        self
    }

    pub fn mod_for_ipd(&mut self, used: &[&Ident]) -> &mut Self {
        let orig_where = self.0.where_clause.as_ref().map(|v| &v.predicates);
        let infer_override = Self::gen_inferoverride_for_ty(used);
        let fetch = Self::gen_fetch_for_ty(used, quote!(Set));
        let new_where: WhereClause = parse_quote! {
            where
            Set: cote::prelude::Set + cote::prelude::OptParser<Output: cote::prelude::Information> +
            cote::prelude::OptValidator + cote::prelude::SetValueFindExt + Default + 'inv,
            cote::prelude::SetCfg<Set>: cote::prelude::ConfigValue + Default,
            #(#used: cote::prelude::Infer + cote::prelude::ErasedTy,)*
            #(<#used as cote::prelude::Infer>::Val: cote::prelude::RawValParser,)*
            #infer_override
            #fetch
            #orig_where
        };

        self.0.where_clause = Some(new_where);
        self.insert_lifetime("'inv");
        self.append_type("Set");
        self
    }

    pub fn split_for_impl_ipd(
        &mut self,
        used: &[&Ident],
    ) -> (ImplGenerics<'_>, TypeGenerics<'_>, Option<&WhereClause>) {
        self.mod_for_ipd(used);
        self.0.split_for_impl()
    }

    pub fn mod_for_esd(&mut self, used: &[&Ident]) -> &mut Self {
        let orig_where = self.0.where_clause.as_ref().map(|v| &v.predicates);
        let fetch = Self::gen_fetch_for_ty(used, quote!(Set));
        let new_where: WhereClause = parse_quote! {
            where
            Set: cote::prelude::SetValueFindExt,
            cote::prelude::SetCfg<Set>: cote::prelude::ConfigValue + Default,
            #fetch
            #orig_where
        };

        self.0.where_clause = Some(new_where);
        self.insert_lifetime("'set");
        self.append_type("Set");
        self
    }

    pub fn split_for_impl_esd(
        &mut self,
        used: &[&Ident],
    ) -> (ImplGenerics<'_>, TypeGenerics<'_>, Option<&WhereClause>) {
        self.mod_for_esd(used);
        self.0.split_for_impl()
    }

    pub fn mod_for_pi(&mut self, used: &[&Ident]) -> &mut Self {
        let orig_where = self.0.where_clause.as_ref().map(|v| &v.predicates);
        let new_where: WhereClause = parse_quote! {
            where
                #(#used: cote::prelude::Infer + cote::prelude::ErasedTy,)*
                #(<#used as cote::prelude::Infer>::Val: cote::prelude::RawValParser,)*
                #orig_where
        };

        self.0.where_clause = Some(new_where);
        self
    }

    pub fn split_for_impl_pi(
        &mut self,
        used: &[&Ident],
    ) -> (ImplGenerics<'_>, TypeGenerics<'_>, Option<&WhereClause>) {
        self.mod_for_pi(used);
        self.0.split_for_impl()
    }

    pub fn mod_for_fetch(&mut self, used: &[&Ident]) -> &mut Self {
        let orig_where = self.0.where_clause.as_ref().map(|v| &v.predicates);
        let fetch = Self::gen_fetch_for_ty(used, quote!(Set));
        let new_where: WhereClause = parse_quote! {
            where
                Set: cote::prelude::SetValueFindExt,
                cote::prelude::SetCfg<Set>: cote::prelude::ConfigValue + Default,
                Self: cote::prelude::ErasedTy + Sized,
                #fetch
                #orig_where
        };

        self.0.where_clause = Some(new_where);
        self.append_type("Set");
        self
    }

    pub fn split_for_impl_fetch(
        &mut self,
        used: &[&Ident],
    ) -> (ImplGenerics<'_>, TypeGenerics<'_>, Option<&WhereClause>) {
        self.mod_for_fetch(used);
        self.0.split_for_impl()
    }

    pub fn gen_fetch_for_ty(used: &[&Ident], set: TokenStream) -> TokenStream {
        quote! {
            #(#used: cote::prelude::Fetch<#set>,)*
        }
    }

    pub fn gen_inferoverride_for_ty(used: &[&Ident]) -> TokenStream {
        quote! {
            #(#used: cote::prelude::InferOverride)*
        }
    }
}

impl ToTokens for GenericsModifier {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        ToTokens::to_tokens(&self.0, tokens)
    }
}

#[derive(Debug, Default)]
pub struct OptUpdate {
    pub c: Option<TokenStream>,

    pub i: Option<TokenStream>,

    pub h: Option<TokenStream>,
}

impl OptUpdate {
    pub fn with_create(mut self, value: TokenStream) -> Self {
        self.c = Some(value);
        self
    }

    pub fn with_insert(mut self, value: TokenStream) -> Self {
        self.i = Some(value);
        self
    }

    pub fn with_handler(mut self, value: TokenStream) -> Self {
        self.h = Some(value);
        self
    }
}

// #[derive(Debug, Clone, Copy)]
// pub enum WrapperTy<'a> {
//     Opt(&'a Type),

//     Res(&'a Type),

//     Vec(&'a Type),

//     OptVec(&'a Type),

//     ResVec(&'a Type),

//     Null(&'a Type),
// }

// impl<'a> WrapperTy<'a> {
//     pub fn new(ty: &'a Type) -> Self {
//         let (ret, inner_ty) = Self::check_wrapper_ty(ty, "Option");

//         if ret {
//             match Self::check_wrapper_ty(inner_ty, "Vec") {
//                 (true, inner_ty) => Self::OptVec(inner_ty),
//                 (false, inner_ty) => Self::Opt(inner_ty),
//             }
//         } else {
//             let (ret, inner_ty) = Self::check_wrapper_ty(ty, "Result");

//             if ret {
//                 match Self::check_wrapper_ty(inner_ty, "Vec") {
//                     (true, inner_ty) => Self::ResVec(inner_ty),
//                     (false, inner_ty) => Self::Res(inner_ty),
//                 }
//             } else {
//                 match Self::check_wrapper_ty(inner_ty, "Vec") {
//                     (true, inner_ty) => Self::Vec(inner_ty),
//                     (false, _) => Self::Null(ty),
//                 }
//             }
//         }
//     }

//     pub fn inner_type(&self) -> &Type {
//         match self {
//             Self::Res(ty) => ty,
//             Self::Opt(ty) => ty,
//             Self::Vec(ty) => ty,
//             Self::OptVec(ty) => ty,
//             Self::ResVec(ty) => ty,
//             Self::Null(ty) => ty,
//         }
//     }

//     pub fn check_wrapper_ty(ty: &'a Type, name: &str) -> (bool, &'a Type) {
//         if let Type::Path(path) = ty {
//             if let Some(segment) = path.path.segments.last() {
//                 let ident_str = segment.ident.to_string();

//                 if ident_str == name {
//                     if let PathArguments::AngleBracketed(ab) = &segment.arguments {
//                         if let Some(GenericArgument::Type(next_ty)) = ab.args.first().as_ref() {
//                             return (true, next_ty);
//                         }
//                     }
//                 }
//             }
//         }
//         (false, ty)
//     }
// }