toml_const_macros 1.3.0

proc-macros for toml_const
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
//! Struct instantiation crate.
//!
//! A toml table is converted to a custom struct.
//! The identifier of the struct is used as the struct's type.

use proc_macro2::{self as pm2, Span};
use quote::quote;
use syn::{punctuated::Punctuated, Ident};

use crate::TomlValue;

/// Chars to replace when converting to an identifier.
const REPLACE_CHARS: &[char] = &[
    ' ', '-', '_', ':', '.', '/', '\\', '"', '\'', '(', ')', '=', ',',
];

/// Generate the instantiation of an item. This can be a custom struct or a simple value.
/// If a key is provided, the instantiation will be in a field-value pair.
///
/// Keys are not provided if:
/// - the table is the root table
/// - the value is defined as an element in an array
///
/// This is basically a wrapper around [quote::ToTokens].
pub trait Instantiate {
    fn instantiate(
        &self,
        key: &str,
        toml_value: &TomlValue,
        parents: Vec<&Ident>,
    ) -> pm2::TokenStream;
}

/// Create identifiers for variables and types from a string.
pub trait ConstIdentDef {
    /// Create a valid variable identifier, formatted as SCREAMING_SNAKE_CASE.
    fn to_variable_ident(&self) -> syn::Ident;

    /// Create a valid module identifier, formatted as snake_case.
    fn to_module_ident(&self) -> syn::Ident {
        syn::Ident::new_raw(
            &self.to_variable_ident().to_string().to_lowercase(),
            Span::call_site(),
        )
    }

    /// Create a valid type identifier, formatted as PascalCase.
    fn to_type_ident(&self) -> syn::Ident;

    // /// Create an array type identifier formatted as PascalCase.
    // fn to_array_type_ident(&self) -> String {
    //     format!("{}Item", self.to_type_ident())
    // }
}

impl<T> ConstIdentDef for T
where
    T: AsRef<str>,
{
    fn to_variable_ident(&self) -> syn::Ident {
        let self_ref = self.as_ref();

        let inter = self_ref.replace(REPLACE_CHARS, "_");

        let inter = inter
            .split('_')
            .map(|item| item.to_uppercase())
            .collect::<Vec<_>>()
            .join("_");

        let inter = match inter.starts_with(char::is_numeric) {
            true => format!("_{}", inter),
            false => inter,
        };

        syn::Ident::new(&inter, Span::call_site())
    }

    fn to_type_ident(&self) -> syn::Ident {
        let inter = self.as_ref().replace(REPLACE_CHARS, "_");

        let inter = match inter.contains("_") {
            true => inter
                .split('_')
                .map(|item| {
                    let mut chars = item.chars();

                    match chars.next() {
                        Some(c) => {
                            let first_char = c.to_ascii_uppercase();
                            let rest = chars.collect::<String>().to_ascii_lowercase();
                            format!("{}{}", first_char, rest)
                        }
                        None => String::new(),
                    }
                })
                .collect::<String>(),
            false => {
                // split at a capital letter, but preserve the letter
                let inter = inter.chars().fold(String::new(), |mut acc, c| {
                    if c.is_uppercase() && !acc.is_empty() {
                        acc.push('_');
                    }
                    acc.push(c);
                    acc
                });

                inter
                    .split("_")
                    .map(|item| {
                        let mut chars = item.chars();

                        match chars.next() {
                            Some(c) => {
                                let first_char = c.to_ascii_uppercase();
                                let rest = chars.collect::<String>().to_ascii_lowercase();
                                format!("{}{}", first_char, rest)
                            }
                            None => String::new(),
                        }
                    })
                    .collect::<String>()

                // todo!()
            }
        };

        let inter = match inter.starts_with(char::is_numeric) {
            true => format!("_{}", inter),
            false => inter,
        };

        syn::Ident::new(&inter, Span::call_site())
    }
}

impl Instantiate for toml::Value {
    fn instantiate(
        &self,
        key: &str,
        toml_value: &TomlValue,
        parents: Vec<&Ident>,
    ) -> proc_macro2::TokenStream {
        use toml::Value::*;

        match self {
            // cases when items are instantiated as fields in an array
            String(val) => quote! { #val },
            Integer(val) => quote! { #val },
            Float(val) => quote! { #val },
            Boolean(val) => quote! { #val },

            // items with inner impls
            Datetime(datetime) => datetime.instantiate(key, toml_value, vec![]),
            Array(values) => values.instantiate(key, toml_value, parents),
            Table(map) => map.instantiate(key, toml_value, parents),
        }
    }
}

impl Instantiate for toml::Table {
    fn instantiate(
        &self,
        key: &str,
        toml_value: &TomlValue,
        parents: Vec<&Ident>,
    ) -> proc_macro2::TokenStream {
        let table_type = key.to_type_ident();
        let table_mod = key.to_module_ident();

        let table_ty = match parents.len() {
            0 => {
                quote! { #table_type }
            }
            _ => {
                let p = parents.iter().collect::<Punctuated<_, syn::Token![::]>>();
                quote! { #p :: #table_type }
            }
        };

        let mut parents = parents.clone();
        parents.push(&table_mod);

        let new_params = match toml_value {
            TomlValue::Table(tab) => tab
                .iter()
                .map(|(key, val)| {
                    let inner_val = self.get(key).expect("key should exist in table");

                    inner_val.instantiate(key, val, parents.clone())
                })
                .collect::<Punctuated<pm2::TokenStream, syn::Token![,]>>(),
            TomlValue::TableMap {
                keys,
                first,
                value_type,
            } => {
                let map_vals = keys
                    .iter()
                    .map(|k| {
                        let key_lit = syn::LitStr::new(k, Span::call_site());

                        let value = self.get(k).expect("key should exist in table");
                        let value = value.instantiate(first, value_type, parents.clone());

                        quote! {#key_lit => #value}
                    })
                    .collect::<Punctuated<pm2::TokenStream, syn::Token![,]>>();

                let map_value = quote! {{
                    use toml_const::phf;
                    &toml_const::phf_map_macro! {
                        #map_vals
                    }
                }};

                self.iter()
                    .map(|(_, f_val)| f_val.instantiate(first, value_type, parents.clone()))
                    .chain([map_value])
                    .collect::<Punctuated<pm2::TokenStream, syn::Token![,]>>()
            }
            _ => unimplemented!("expected a table or table map"),
        };

        quote! {
            #table_ty::new(
                #new_params
            )
        }
    }
}

impl Instantiate for toml::value::Array {
    fn instantiate(
        &self,
        key: &str,
        toml_value: &TomlValue,
        parents: Vec<&Ident>,
    ) -> proc_macro2::TokenStream {
        let arr = if let TomlValue::Array(arr) = toml_value {
            arr
        } else {
            unimplemented!("expected a toml array value");
        };

        let val = match arr.first() {
            Some(v) => v,
            None => return quote! { &[] },
        };

        let elements = self
            .iter()
            .map(|elem| elem.instantiate(key, val, parents.clone()))
            .collect::<Punctuated<pm2::TokenStream, syn::Token![,]>>();

        quote! {
            &[ #elements ]
        }
    }
}

// datetime structs do not require a key, as they are already defined.
impl Instantiate for toml::value::Datetime {
    fn instantiate(&self, k: &str, _: &TomlValue, _: Vec<&Ident>) -> proc_macro2::TokenStream {
        match (self.date, self.time, self.offset) {
            (Some(d), Some(t), Some(o)) => {
                let d = d.instantiate(k, &TomlValue::Boolean, vec![]);
                let t = t.instantiate(k, &TomlValue::Boolean, vec![]);
                let o = o.instantiate(k, &TomlValue::Boolean, vec![]);

                quote! {
                    toml_const::OffsetDateTime {
                        date: #d,
                        time: #t,
                        offset: #o
                    }
                }
            }
            (Some(d), Some(t), None) => {
                let d = d.instantiate(k, &TomlValue::Boolean, vec![]);
                let t = t.instantiate(k, &TomlValue::Boolean, vec![]);

                quote! {
                    toml_const::LocalDateTime {
                        date: #d,
                        time: #t
                    }
                }
            }
            (Some(d), None, None) => {
                let d = d.instantiate(k, &TomlValue::Boolean, vec![]);

                quote! {
                    toml_const::LocalDate {
                        date: #d
                    }
                }
            }
            (None, Some(t), None) => {
                let t = t.instantiate(k, &TomlValue::Boolean, vec![]);

                quote! {
                    toml_const::LocalTime {
                        time: #t
                    }
                }
            }

            _ => unimplemented!("unsupported datetime combination"),
        }
    }
}

// sub structs do not require key, they implement `Key::Element`.
impl Instantiate for toml::value::Date {
    fn instantiate(&self, _: &str, _: &TomlValue, _: Vec<&Ident>) -> proc_macro2::TokenStream {
        let year = self.year;
        let month = self.month;
        let day = self.day;

        quote! {
            toml_const::Date {
                year: #year,
                month: #month,
                day: #day
            }
        }
    }
}

impl Instantiate for toml::value::Time {
    fn instantiate(&self, _: &str, _: &TomlValue, _: Vec<&Ident>) -> proc_macro2::TokenStream {
        let hour = self.hour;
        let minute = self.minute;
        let second = self.second;
        let nanosecond = self.nanosecond;

        quote! {
            toml_const::Time {
                hour: #hour,
                minute: #minute,
                second: #second,
                nanosecond: #nanosecond
            }
        }
    }
}

impl Instantiate for toml::value::Offset {
    fn instantiate(&self, _: &str, _: &TomlValue, _: Vec<&Ident>) -> proc_macro2::TokenStream {
        match self {
            toml::value::Offset::Z => quote! { toml_const::Offset::Z },
            toml::value::Offset::Custom { minutes } => quote! {
                toml_const::Offset::Custom {
                    minutes: #minutes
                }
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::*;

    #[test]
    fn test_instantiation() {
        let cargo_manifest = include_str!("../Cargo.toml");
        let toml: toml::Table = toml::Table::from_str(cargo_manifest).unwrap();
        let value: TomlValue = toml.clone().into();

        let root_ident = Ident::new("ROOT_TABLE", Span::call_site());
        let instantiation = toml.instantiate(&root_ident.to_string(), &value, vec![]);

        println!("Table instantiation: {}", instantiation);
    }

    #[test]
    fn test_split_pascal_case() {
        let inter = "PascalCase";

        let inter = inter.chars().fold(String::new(), |mut acc, c| {
            if c.is_uppercase() && !acc.is_empty() {
                acc.push('_');
            }
            acc.push(c);
            acc
        });

        println!("inter: {inter}");

        let inter = "Pascal";

        let inter = inter.chars().fold(String::new(), |mut acc, c| {
            if c.is_uppercase() && !acc.is_empty() {
                acc.push('_');
            }
            acc.push(c);
            acc
        });

        println!("inter: {inter}");
    }

    #[test]
    fn test_cfg_identifiers() {
        let key = "cfg(any(target_os = \"android\", target_os = \"ios\"))";
        let var = key.to_variable_ident();
        let ty = key.to_type_ident();
        assert_eq!(
            var.to_string(),
            "CFG_ANY_TARGET_OS____ANDROID___TARGET_OS____IOS___"
        );
        assert_eq!(ty.to_string(), "CfgAnyTargetOsAndroidTargetOsIos");

        let simple_key = "cfg(unix)";
        let var_simple = simple_key.to_variable_ident();
        let ty_simple = simple_key.to_type_ident();
        assert_eq!(var_simple.to_string(), "CFG_UNIX_");
        assert_eq!(ty_simple.to_string(), "CfgUnix");
    }
}