aboutsummaryrefslogtreecommitdiffstats
path: root/crates/mk_config/src/generate.rs
blob: d06945ed36777af5673ac88dcb33c91ed2af7401 (plain) (blame)
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
// yt - A fully featured command line YouTube client
//
// Copyright (C) 2026 Soispha Peetz <soispha@b-peetz.de>
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This file is part of Yt.
//
// You should have received a copy of the License along with this program.
// If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.

use std::iter;

use proc_macro2::TokenStream as TokenStream2;
use quote::{ToTokens, TokenStreamExt, format_ident, quote};
use syn::{Attribute, Expr, Ident, Type};

use crate::parse;

#[derive(Debug)]
pub(crate) struct Config {
    name: Ident,
    sections: Vec<ConfigSection>,
    fields: Vec<ConfigField>,
    imports: Vec<syn::Path>,
}

#[derive(Debug)]
pub(crate) struct ConfigSection {
    name: Vec<Ident>,
    fields: Vec<ConfigField>,
    is_public: bool,
    documentation: Vec<Attribute>,
}

#[derive(Debug)]
pub(crate) struct ConfigField {
    name: Vec<Ident>,
    default: Option<ConfigFieldDefault>,
    ty: Type,
    documentation: Vec<Attribute>,

    /// Whether this config field was create to include the parent-child relation ships between
    /// config sections.
    is_section: bool,
    is_public: bool,
    finalizer: Option<Ident>,
}

#[derive(Debug)]
pub(crate) struct ConfigFieldDefault {
    default: Expr,
    may_error: bool,
}

impl From<parse::FieldDefault> for ConfigFieldDefault {
    fn from(value: parse::FieldDefault) -> Self {
        Self {
            default: value.default,
            may_error: value.may_error,
        }
    }
}

impl ToTokens for ConfigFieldDefault {
    fn to_tokens(&self, tokens: &mut TokenStream2) {
        let Self { default, may_error } = self;
        if *may_error {
            tokens.extend(quote! {
                #default?
            });
        } else {
            tokens.extend(quote! {
                #default
            });
        }
    }
}

impl From<parse::ParseBase> for Config {
    fn from(value: parse::ParseBase) -> Self {
        let mut sections = vec![];
        let mut new_fields = vec![];

        value.fields.into_iter().for_each(|field| match field {
            parse::ParsePart::Section { .. } => {
                sections.extend(ConfigSection::from_parse_part(vec![], field.clone()));
                new_fields.push(ConfigField::spawn_from_section(vec![], field));
            }
            parse::ParsePart::Field { .. } => {
                new_fields.push(ConfigField::from_parse_part(vec![], field));
            }
        });

        Self {
            name: value.name,
            sections,
            fields: new_fields,
            imports: value.imports,
        }
    }
}

impl ConfigSection {
    fn from_parse_part(prefix: Vec<Ident>, value: parse::ParsePart) -> Vec<Self> {
        if let parse::ParsePart::Section {
            name,
            fields,
            documentation,
        } = value
        {
            let new_name: Vec<_> = prefix.into_iter().chain(iter::once(name)).collect();

            let mut sections = vec![];
            let mut new_fields = vec![];

            for field in fields {
                match field {
                    parse::ParsePart::Section { .. } => {
                        sections.extend(Self::from_parse_part(new_name.clone(), field.clone()));
                        new_fields.push(ConfigField::spawn_from_section(new_name.clone(), field));
                    }
                    parse::ParsePart::Field { .. } => {
                        new_fields.push(ConfigField::from_parse_part(new_name.clone(), field));
                    }
                }
            }

            sections.push(Self {
                name: new_name,
                fields: new_fields,
                is_public: true,
                documentation,
            });

            sections
        } else {
            unreachable!("Only called on sections")
        }
    }
}

impl ConfigField {
    fn from_parse_part(prefix: Vec<Ident>, value: parse::ParsePart) -> Self {
        if let parse::ParsePart::Field {
            name,
            ty,
            default,
            documentation,
            finalizer,
        } = value
        {
            let new_name = prefix.into_iter().chain(iter::once(name)).collect();

            Self {
                name: new_name,
                default: default.map(Into::into),
                ty,
                is_section: false,
                is_public: true,
                documentation,
                finalizer,
            }
        } else {
            unreachable!("Only called on fields")
        }
    }

    fn spawn_from_section(prefix: Vec<Ident>, field: parse::ParsePart) -> ConfigField {
        if let parse::ParsePart::Section {
            name,
            documentation,
            ..
        } = field
        {
            let config_name = name_ident(&name);
            let new_name = prefix.into_iter().chain(iter::once(name)).collect();

            Self {
                name: new_name,
                default: None,
                ty: syn::parse_quote!(#config_name),
                is_section: true,
                is_public: true,
                documentation,
                finalizer: None,
            }
        } else {
            unreachable!("Should only be called, on Sections")
        }
    }
}

struct ConfDeser {
    sections: Vec<ConfigSection>,
    fields: Vec<ConfigField>,
}

impl From<&Config> for ConfDeser {
    fn from(value: &Config) -> Self {
        fn field_to_deser(field: &ConfigField) -> ConfigField {
            let field_ty = field.ty.clone();

            ConfigField {
                name: field.name.clone(),
                default: None,
                documentation: field.documentation.clone(),
                ty: if field.default.is_some() || field.is_section {
                    syn::parse_quote!(Option<#field_ty>)
                } else {
                    // TODO: We could also accept this value here, and then throw an error later.
                    // But right now, we just use serde to complain to the user <2026-08-20>
                    field_ty
                },
                is_section: field.is_section,
                is_public: false,
                finalizer: None,
            }
        }

        Self {
            sections: value
                .sections
                .iter()
                .map(|section| ConfigSection {
                    name: section.name.clone(),
                    fields: section.fields.iter().map(field_to_deser).collect(),
                    is_public: false,
                    documentation: section.documentation.clone(),
                })
                .collect(),
            fields: value.fields.iter().map(field_to_deser).collect(),
        }
    }
}

impl ToTokens for ConfDeser {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self { sections, fields } = self;

        let serde = serde(false);
        tokens.extend(quote! {
            #serde
            #[derive(Clone, Debug)]
            pub(super) struct ConfDeser {
                #(
                    #fields
                )*
            }
            #(
                #sections
            )*
        });
    }
}

impl ToTokens for Config {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self {
            name,
            sections,
            fields,
            imports,
        } = self;

        let serde = serde(true);
        tokens.extend(quote! {
            #(
                use #imports;
            )*

            #[derive(Debug)]
            #serde
            pub(crate) struct #name {
                #(
                    #fields
                )*
            }
        });
        tokens.append_all(sections.iter());

        let default_config = generate_default_config(fields, sections);
        let option_assign = generate_option_assign(fields, sections);
        let option_finalizer = generate_option_finalizer(fields, sections);
        let field_deser_assign: Vec<_> = fields
            .iter()
            .map(|field| field.field_assign_deser(&[]))
            .collect();
        let conf_deser = ConfDeser::from(self);
        tokens.extend(quote! {
            mod __inner {
                #(
                    use #imports;
                )*

                #conf_deser
            }

            impl #name {
                /// Parse the configuration from a config file at `config_file_path`.
                ///
                /// This will then also take the config overrides via `options` into consideration,
                /// and finally run the finalizers, defined via the macro.
                pub(crate) fn from_config_file(
                    config_file_path: &std::path::Path,
                    options: Vec<(Vec<String>, toml::Value)>
                ) -> anyhow::Result<Self> {
                    use anyhow::Context;

                    let config: __inner::ConfDeser = toml::from_str(
                        &std::fs::read_to_string(config_file_path).unwrap_or(String::new()),
                    ).context("Failed to parse the config file as toml")?;

                    let mut base = Self {
                        #(
                            #field_deser_assign
                        )*
                    };

                    for (name, value) in options {
                        let name = name.join(".");

                        match name.as_str() {
                            #option_assign
                            other => anyhow::bail!("Option name '{other}' is not known")
                        }
                    }

                    // Run the finalizers
                    {
                        #option_finalizer
                    }

                    Ok(base)
                }

                /// Return the default configuration in semi TOML format, with it's doc comments appended
                /// to the document.
                ///
                /// The default values, will be the pretty-printed rust defaults, so it's not
                /// actually possible to parse it as TOML.
                pub(crate) const fn config_doc() -> &'static str {
                    #default_config
                }
            }
        });
    }
}

impl ToTokens for ConfigSection {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        fn field_to_default(field: &ConfigField) -> TokenStream2 {
            let ConfigField {
                name,
                default,
                is_section,
                ty,
                ..
            } = field;

            let last_name = name.last().expect("Exists");
            if let Some(default) = default {
                quote! {
                    #last_name: #default,
                }
            } else if *is_section {
                quote! {
                    #last_name: #ty::default()?,
                }
            } else {
                let msg = format!(
                    "No default value for field '{last_name}'. Auto defaults are not yet implemented."
                );
                quote! {
                    #last_name: {compile_error!(#msg)},
                }
            }
        }

        let Self {
            name,
            fields,
            is_public,
            documentation,
        } = self;
        let last_name = name_ident(name.last().expect("Exists"));

        let default_fields: Vec<_> = fields.iter().map(field_to_default).collect();
        let from_deser_fields: Vec<_> = fields
            .iter()
            .map(|field| field.field_assign_deser(name))
            .collect();

        let vis = vis(*is_public);
        let serde = serde(*is_public);
        tokens.extend(quote! {
            #serde
            #[derive(Clone, Debug)]
            #(#documentation)*
            #vis struct #last_name {
                #(
                    #fields
                )*
            }
        });
        if *is_public {
            tokens.extend(quote! {
                impl #last_name {
                    fn default() -> anyhow::Result<Self> {
                        Ok(Self {
                            #(
                                #default_fields
                            )*
                        })
                    }
                    fn from_inner(from: Option<__inner::#last_name>, config: __inner::ConfDeser) -> anyhow::Result<Self> {
                        if let Some(from) = from {
                            Ok(Self {
                                #(
                                    #from_deser_fields
                                )*
                            })
                        } else {
                            Self::default()
                        }
                    }
                }
            });
        }
    }
}

impl ConfigField {
    fn field_assign_deser(&self, prefix: &[Ident]) -> TokenStream2 {
        let ConfigField {
            name,
            is_section,
            default,
            ty,
            ..
        } = self;

        let base = if prefix.is_empty() {
            quote! {
                config.#(#name).*
            }
        } else {
            let mut new = name.clone();
            for p in prefix {
                let next = new.remove(0);
                assert_eq!(p, &next);
            }
            quote! {
                from.#(#new).*
            }
        };

        let last_name = name.last().expect("Exists");

        if *is_section {
            quote! {
                #last_name: #ty::from_inner(#base.clone(), config.clone())?,
            }
        } else {
            match default {
                Some(default) => {
                    quote! {
                        #last_name: {
                            match #base {
                                Some(val) => val,
                                None => #default,
                            }
                        },
                    }
                }
                None => {
                    // NOTE: When there is no default value, we also don't accept one in the __inner
                    // part. <2026-08-20>
                    quote! {
                        #last_name: #base,
                    }
                }
            }
        }
    }
}
impl ToTokens for ConfigField {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let Self {
            name,
            ty,
            is_public,
            documentation,
            ..
        } = self;
        let last_name = name.last().expect("Exists");

        let vis = vis(*is_public);
        tokens.extend(quote! {
            #(#documentation)*
            #vis #last_name: #ty,
        });
    }
}

fn name_ident(name: &Ident) -> Ident {
    let mut name: Vec<_> = name.to_string().chars().collect();
    name[0] = name[0].to_ascii_uppercase();

    format_ident!("{}Config", name.into_iter().collect::<String>())
}
fn vis(is_public: bool) -> TokenStream2 {
    if is_public {
        quote! {pub(crate)}
    } else {
        quote! {pub(super)}
    }
}
fn serde(is_public: bool) -> TokenStream2 {
    if is_public {
        quote! {
            #[derive(serde::Serialize, serde::Deserialize)]
        }
    } else {
        quote! {
            #[derive(serde::Deserialize)]
        }
    }
    // quote! {}
}

fn generate_option_assign(fields: &[ConfigField], sections: &[ConfigSection]) -> TokenStream2 {
    fn name_str(name: &[Ident]) -> String {
        name.iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(".")
    }
    fn value(ty: &Type) -> TokenStream2 {
        let ty_str = ty.to_token_stream().to_string();

        quote! {
            {
                use serde::Deserialize;

                let value_str = value.to_string();
                let deserializer = toml::de::ValueDeserializer::parse(&value_str)
                    .with_context(|| format!("Failed to parse value for option override '{name}' as '{}'", #ty_str))?;
                <#ty>::deserialize(deserializer).context("Failed to deserialize default value for '{name}'")?
            }
        }
    }

    fn mk_field(field: &ConfigField) -> TokenStream2 {
        let ConfigField { name, ty, .. } = field;

        let name_str = name_str(name);
        let value = value(ty);

        quote! {
            #name_str => base.#(#name).* = #value,
        }
    }
    fn mk_section(section: &ConfigSection) -> TokenStream2 {
        let ConfigSection { name, fields, .. } = section;

        let name_str = name_str(name);
        let fields: Vec<_> = fields.iter().map(mk_field).collect();
        let value = {
            let last_name = name.last().expect("to exist");
            let ty = name_ident(last_name);
            let ty: Type = syn::parse_quote! {#ty};

            value(&ty)
        };

        quote! {
            #name_str => base.#(#name).* = #value,
            #(
                #fields
            )*
        }
    }

    let fields: Vec<_> = fields.iter().map(mk_field).collect();
    let sections: Vec<_> = sections.iter().map(mk_section).collect();

    quote! {
        #(
            #fields
        )*
        #(
            #sections
        )*
    }
}
fn generate_option_finalizer(fields: &[ConfigField], sections: &[ConfigSection]) -> TokenStream2 {
    fn mk_field(field: &ConfigField) -> TokenStream2 {
        let ConfigField {
            name, finalizer, ..
        } = field;

        match finalizer {
            Some(finalizer) => {
                let context_msg = format!(
                    "While running the finalizer for config value '{}'",
                    name.iter()
                        .map(ToString::to_string)
                        .collect::<Vec<_>>()
                        .join(".")
                );

                quote! {
                    #finalizer(&base.#(#name).*).context(#context_msg)?;
                }
            }
            None => quote! {},
        }
    }
    fn mk_section(section: &ConfigSection) -> TokenStream2 {
        let ConfigSection { fields, .. } = section;

        let fields: Vec<_> = fields.iter().map(mk_field).collect();
        quote! {
            #(
                #fields
            )*
        }
    }
    let fields: Vec<_> = fields.iter().map(mk_field).collect();
    let sections: Vec<_> = sections.iter().map(mk_section).collect();

    quote! {
        #(
            #fields
        )*
        #(
            #sections
        )*
    }
}

fn generate_default_config(fields: &[ConfigField], sections: &[ConfigSection]) -> String {
    fn mk_doc_comment(attr: &Attribute) -> String {
        let comment = match &attr.meta {
            syn::Meta::Path(_) => todo!(),
            syn::Meta::List(_) => todo!(),
            syn::Meta::NameValue(meta_name_value) => &meta_name_value.value,
        };

        let comment = comment.to_token_stream().to_string();
        let comment = comment.trim_matches('\"').trim();
        format!("# {comment}")
    }

    fn mk_field(field: &ConfigField) -> Option<String> {
        let ConfigField {
            name,
            default,
            documentation,
            is_section,
            ..
        } = field;

        let documentation = documentation.iter().map(mk_doc_comment).collect::<Vec<_>>();

        let last_name = name.last().expect("to exist");
        if let Some(default) = default {
            let default = {
                let file = syn::parse2::<syn::File>(quote::quote! {
                  fn deleteme(){
                      #default
                  }
                })
                .expect("The default value is valid rust code, and should be parsable");

                {
                    let mut str = prettyplease::unparse(&file);

                    // remove the outer function
                    str = str.replace("fn deleteme() {\n", "");

                    if let Some(pos) = str.rfind("\n}\n") {
                        str.replace_range(pos..pos + 3, "");
                    }

                    // remove the function indent
                    str = str
                        .lines()
                        .map(|line| if line.len() >= 4 { &line[4..] } else { line })
                        .collect::<Vec<_>>()
                        .join("\n");

                    str
                }
            };

            Some(format!(
                "{}{}{} = {}\n",
                documentation.join("\n"),
                if documentation.is_empty() { "" } else { "\n" },
                last_name,
                default
            ))
        } else if *is_section {
            None
        } else {
            todo!("no default fields, to yet supported")
        }
    }
    fn mk_section(section: &ConfigSection) -> String {
        let ConfigSection {
            fields,
            name,
            documentation,
            ..
        } = section;

        let documentation = documentation.iter().map(mk_doc_comment).collect::<Vec<_>>();
        let fields: Vec<_> = fields.iter().filter_map(mk_field).collect();
        let name = name.iter().map(ToString::to_string).collect::<Vec<_>>();

        format!(
            "{}{}[{}]\n{}\n",
            documentation.join("\n"),
            if documentation.is_empty() { "" } else { "\n" },
            name.join("."),
            fields.join("\n")
        )
    }
    let fields: Vec<_> = fields.iter().filter_map(mk_field).collect();
    let sections: Vec<_> = sections.iter().map(mk_section).collect();

    format!(
        "{}\n",
        format!("{}{}", fields.join("\n"), sections.join("\n")).trim()
    )
}