objdiff-core 3.7.3

A local diffing tool for decompilation projects.
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
use std::{
    fs::File,
    path::{Path, PathBuf},
};

use heck::{ToShoutySnakeCase, ToSnakeCase, ToUpperCamelCase};
use proc_macro2::TokenStream;
use quote::{format_ident, quote};

#[derive(Debug, serde::Deserialize)]
pub struct ConfigSchema {
    pub properties: Vec<ConfigProperty>,
    pub groups: Vec<ConfigGroup>,
}

#[derive(Debug, serde::Deserialize)]
#[serde(tag = "type")]
pub enum ConfigProperty {
    #[serde(rename = "boolean")]
    Boolean(ConfigPropertyBoolean),
    #[serde(rename = "choice")]
    Choice(ConfigPropertyChoice),
}

#[derive(Debug, serde::Deserialize)]
pub struct ConfigPropertyBase {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
}

#[derive(Debug, serde::Deserialize)]
pub struct ConfigPropertyBoolean {
    #[serde(flatten)]
    pub base: ConfigPropertyBase,
    pub default: bool,
}

#[derive(Debug, serde::Deserialize)]
pub struct ConfigPropertyChoice {
    #[serde(flatten)]
    pub base: ConfigPropertyBase,
    pub default: String,
    pub items: Vec<ConfigPropertyChoiceItem>,
}

#[derive(Debug, serde::Deserialize)]
pub struct ConfigPropertyChoiceItem {
    pub value: String,
    pub name: String,
    pub description: Option<String>,
}

#[derive(Debug, serde::Deserialize)]
pub struct ConfigGroup {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub properties: Vec<String>,
}

fn build_doc(name: &str, description: Option<&str>) -> TokenStream {
    let mut doc = format!(" {name}");
    let mut out = quote! { #[doc = #doc] };
    if let Some(description) = description {
        doc = format!(" {description}");
        out.extend(quote! { #[doc = ""] });
        out.extend(quote! { #[doc = #doc] });
    }
    out
}

pub fn generate_diff_config() {
    let schema_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("config-schema.json");
    println!("cargo:rerun-if-changed={}", schema_path.display());
    let schema_file = File::open(schema_path).expect("Failed to open config schema file");
    let schema: ConfigSchema =
        serde_json::from_reader(schema_file).expect("Failed to parse config schema");

    let mut enums = TokenStream::new();
    for property in &schema.properties {
        let ConfigProperty::Choice(choice) = property else {
            continue;
        };
        let enum_ident = format_ident!("{}", choice.base.id.to_upper_camel_case());
        let mut variants = TokenStream::new();
        let mut full_variants = TokenStream::new();
        let mut variant_info = TokenStream::new();
        let mut variant_to_str = TokenStream::new();
        let mut variant_to_name = TokenStream::new();
        let mut variant_to_description = TokenStream::new();
        let mut variant_from_str = TokenStream::new();
        for item in &choice.items {
            let variant_name = item.value.to_upper_camel_case();
            let variant_ident = format_ident!("{}", variant_name);
            let is_default = item.value == choice.default;
            variants.extend(build_doc(&item.name, item.description.as_deref()));
            if is_default {
                variants.extend(quote! { #[default] });
            }
            let value = &item.value;
            variants.extend(quote! {
                #[cfg_attr(feature = "serde", serde(rename = #value, alias = #variant_name))]
                #variant_ident,
            });
            full_variants.extend(quote! { #enum_ident::#variant_ident, });
            variant_to_str.extend(quote! { #enum_ident::#variant_ident => #value, });
            let name = &item.name;
            variant_to_name.extend(quote! { #enum_ident::#variant_ident => #name, });
            if let Some(description) = &item.description {
                variant_to_description.extend(quote! {
                    #enum_ident::#variant_ident => Some(#description),
                });
            } else {
                variant_to_description.extend(quote! {
                    #enum_ident::#variant_ident => None,
                });
            }
            let description = if let Some(description) = &item.description {
                quote! { Some(#description) }
            } else {
                quote! { None }
            };
            variant_info.extend(quote! {
                ConfigEnumVariantInfo {
                    value: #value,
                    name: #name,
                    description: #description,
                    is_default: #is_default,
                },
            });
            variant_from_str.extend(quote! {
                if s.eq_ignore_ascii_case(#value) { return Ok(#enum_ident::#variant_ident); }
            });
        }
        enums.extend(quote! {
            #[derive(Copy, Clone, Debug, Default, Eq, PartialEq, Hash)]
            #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
            pub enum #enum_ident {
                #variants
            }
            impl ConfigEnum for #enum_ident {
                #[inline]
                fn variants() -> &'static [Self] {
                    static VARIANTS: &[#enum_ident] = &[#full_variants];
                    VARIANTS
                }
                #[inline]
                fn variant_info() -> &'static [ConfigEnumVariantInfo] {
                    static VARIANT_INFO: &[ConfigEnumVariantInfo] = &[
                        #variant_info
                    ];
                    VARIANT_INFO
                }
                fn as_str(&self) -> &'static str {
                    match self {
                        #variant_to_str
                    }
                }
                fn name(&self) -> &'static str {
                    match self {
                        #variant_to_name
                    }
                }
                fn description(&self) -> Option<&'static str> {
                    match self {
                        #variant_to_description
                    }
                }
            }
            impl core::str::FromStr for #enum_ident {
                type Err = ();
                fn from_str(s: &str) -> Result<Self, Self::Err> {
                    #variant_from_str
                    Err(())
                }
            }
        });
    }

    let mut groups = TokenStream::new();
    let mut group_idents = Vec::new();
    for group in &schema.groups {
        let ident = format_ident!("CONFIG_GROUP_{}", group.id.to_shouty_snake_case());
        let id = &group.id;
        let name = &group.name;
        let description = if let Some(description) = &group.description {
            quote! { Some(#description) }
        } else {
            quote! { None }
        };
        let properties =
            group.properties.iter().map(|p| format_ident!("{}", p.to_upper_camel_case()));
        groups.extend(quote! {
            ConfigPropertyGroup {
                id: #id,
                name: #name,
                description: #description,
                properties: &[#(ConfigPropertyId::#properties,)*],
            },
        });
        group_idents.push(ident);
    }

    let mut property_idents = Vec::new();
    let mut property_variants = TokenStream::new();
    let mut variant_info = TokenStream::new();
    let mut config_property_id_to_str = TokenStream::new();
    let mut config_property_id_to_name = TokenStream::new();
    let mut config_property_id_to_description = TokenStream::new();
    let mut config_property_id_to_kind = TokenStream::new();
    let mut property_fields = TokenStream::new();
    let mut default_fields = TokenStream::new();
    let mut get_property_value_variants = TokenStream::new();
    let mut set_property_value_variants = TokenStream::new();
    let mut set_property_value_str_variants = TokenStream::new();
    let mut config_property_id_from_str = TokenStream::new();
    for property in &schema.properties {
        let base = match property {
            ConfigProperty::Boolean(b) => &b.base,
            ConfigProperty::Choice(c) => &c.base,
        };
        let id = &base.id;
        let enum_ident = format_ident!("{}", id.to_upper_camel_case());
        property_idents.push(enum_ident.clone());
        config_property_id_to_str.extend(quote! { Self::#enum_ident => #id, });
        let name = &base.name;
        config_property_id_to_name.extend(quote! { Self::#enum_ident => #name, });
        if let Some(description) = &base.description {
            config_property_id_to_description.extend(quote! {
                Self::#enum_ident => Some(#description),
            });
        } else {
            config_property_id_to_description.extend(quote! {
                Self::#enum_ident => None,
            });
        }
        let doc = build_doc(name, base.description.as_deref());
        property_variants.extend(quote! { #doc #enum_ident, });
        property_fields.extend(doc);
        let field_ident = format_ident!("{}", id.to_snake_case());
        match property {
            ConfigProperty::Boolean(b) => {
                let default = b.default;
                if default {
                    property_fields.extend(quote! {
                        #[cfg_attr(feature = "serde", serde(default = "default_true"))]
                    });
                }
                property_fields.extend(quote! {
                    pub #field_ident: bool,
                });
                default_fields.extend(quote! {
                    #field_ident: #default,
                });
            }
            ConfigProperty::Choice(_) => {
                property_fields.extend(quote! {
                    pub #field_ident: #enum_ident,
                });
                default_fields.extend(quote! {
                    #field_ident: #enum_ident::default(),
                });
            }
        }
        let property_value = match property {
            ConfigProperty::Boolean(_) => {
                quote! { ConfigPropertyValue::Boolean(self.#field_ident) }
            }
            ConfigProperty::Choice(_) => {
                quote! { ConfigPropertyValue::Choice(self.#field_ident.as_str()) }
            }
        };
        get_property_value_variants.extend(quote! {
            ConfigPropertyId::#enum_ident => #property_value,
        });
        match property {
            ConfigProperty::Boolean(_) => {
                set_property_value_variants.extend(quote! {
                    ConfigPropertyId::#enum_ident => {
                        if let ConfigPropertyValue::Boolean(value) = value {
                            self.#field_ident = value;
                            Ok(())
                        } else {
                            Err(())
                        }
                    },
                });
                set_property_value_str_variants.extend(quote! {
                    ConfigPropertyId::#enum_ident => {
                        if let Ok(value) = value.parse() {
                            self.#field_ident = value;
                            Ok(())
                        } else {
                            Err(())
                        }
                    },
                });
            }
            ConfigProperty::Choice(_) => {
                set_property_value_variants.extend(quote! {
                    ConfigPropertyId::#enum_ident => {
                        if let ConfigPropertyValue::Choice(value) = value {
                            if let Ok(value) = value.parse() {
                                self.#field_ident = value;
                                Ok(())
                            } else {
                                Err(())
                            }
                        } else {
                            Err(())
                        }
                    },
                });
                set_property_value_str_variants.extend(quote! {
                    ConfigPropertyId::#enum_ident => {
                        if let Ok(value) = value.parse() {
                            self.#field_ident = value;
                            Ok(())
                        } else {
                            Err(())
                        }
                    },
                });
            }
        }
        let description = if let Some(description) = &base.description {
            quote! { Some(#description) }
        } else {
            quote! { None }
        };
        variant_info.extend(quote! {
            ConfigEnumVariantInfo {
                value: #id,
                name: #name,
                description: #description,
                is_default: false,
            },
        });
        match property {
            ConfigProperty::Boolean(_) => {
                config_property_id_to_kind.extend(quote! {
                    Self::#enum_ident => ConfigPropertyKind::Boolean,
                });
            }
            ConfigProperty::Choice(_) => {
                config_property_id_to_kind.extend(quote! {
                    Self::#enum_ident => ConfigPropertyKind::Choice(#enum_ident::variant_info()),
                });
            }
        }
        let snake_id = id.to_snake_case();
        config_property_id_from_str.extend(quote! {
            if s.eq_ignore_ascii_case(#id) || s.eq_ignore_ascii_case(#snake_id) {
                return Ok(Self::#enum_ident);
            }
        });
    }

    let tokens = quote! {
        pub trait ConfigEnum: Sized {
            fn variants() -> &'static [Self];
            fn variant_info() -> &'static [ConfigEnumVariantInfo];
            fn as_str(&self) -> &'static str;
            fn name(&self) -> &'static str;
            fn description(&self) -> Option<&'static str>;
        }
        #[derive(Clone, Debug)]
        pub struct ConfigEnumVariantInfo {
            pub value: &'static str,
            pub name: &'static str,
            pub description: Option<&'static str>,
            pub is_default: bool,
        }
        #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
        pub enum ConfigPropertyId {
            #property_variants
        }
        impl ConfigEnum for ConfigPropertyId {
            #[inline]
            fn variants() -> &'static [Self] {
                static VARIANTS: &[ConfigPropertyId] = &[#(ConfigPropertyId::#property_idents,)*];
                VARIANTS
            }
            #[inline]
            fn variant_info() -> &'static [ConfigEnumVariantInfo] {
                static VARIANT_INFO: &[ConfigEnumVariantInfo] = &[
                    #variant_info
                ];
                VARIANT_INFO
            }
            fn as_str(&self) -> &'static str {
                match self {
                    #config_property_id_to_str
                }
            }
            fn name(&self) -> &'static str {
                match self {
                    #config_property_id_to_name
                }
            }
            fn description(&self) -> Option<&'static str> {
                match self {
                    #config_property_id_to_description
                }
            }
        }
        impl ConfigPropertyId {
            pub fn kind(&self) -> ConfigPropertyKind {
                match self {
                    #config_property_id_to_kind
                }
            }
        }
        impl core::str::FromStr for ConfigPropertyId {
            type Err = ();
            fn from_str(s: &str) -> Result<Self, Self::Err> {
                #config_property_id_from_str
                Err(())
            }
        }
        #[derive(Clone, Debug)]
        pub struct ConfigPropertyGroup {
            pub id: &'static str,
            pub name: &'static str,
            pub description: Option<&'static str>,
            pub properties: &'static [ConfigPropertyId],
        }
        pub static CONFIG_GROUPS: &[ConfigPropertyGroup] = &[#groups];
        #[derive(Clone, Debug, Eq, PartialEq, Hash)]
        pub enum ConfigPropertyValue {
            Boolean(bool),
            Choice(&'static str),
        }
        impl ConfigPropertyValue {
            #[cfg(feature = "serde")]
            pub fn to_json(&self) -> serde_json::Value {
                match self {
                    ConfigPropertyValue::Boolean(value) => serde_json::Value::Bool(*value),
                    ConfigPropertyValue::Choice(value) => serde_json::Value::String(value.to_string()),
                }
            }
        }
        impl core::fmt::Display for ConfigPropertyValue {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                match *self {
                    ConfigPropertyValue::Boolean(value) => write!(f, "{value}"),
                    ConfigPropertyValue::Choice(value) => f.write_str(value),
                }
            }
        }
        #[derive(Clone, Debug)]
        pub enum ConfigPropertyKind {
            Boolean,
            Choice(&'static [ConfigEnumVariantInfo]),
        }
        #enums
        #[cfg(feature = "serde")]
        #[inline(always)]
        fn default_true() -> bool { true }
        #[derive(Clone, Debug)]
        #[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize), serde(default))]
        pub struct DiffObjConfig {
            #property_fields
        }
        impl Default for DiffObjConfig {
            fn default() -> Self {
                Self {
                    #default_fields
                }
            }
        }
        impl DiffObjConfig {
            pub fn get_property_value(&self, id: ConfigPropertyId) -> ConfigPropertyValue {
                match id {
                    #get_property_value_variants
                }
            }
            #[allow(clippy::result_unit_err)]
            pub fn set_property_value(&mut self, id: ConfigPropertyId, value: ConfigPropertyValue) -> Result<(), ()> {
                match id {
                    #set_property_value_variants
                }
            }
            #[allow(clippy::result_unit_err)]
            pub fn set_property_value_str(&mut self, id: ConfigPropertyId, value: &str) -> Result<(), ()> {
                match id {
                    #set_property_value_str_variants
                }
            }
        }
    };
    let file = syn::parse2(tokens).unwrap();
    let formatted = prettyplease::unparse(&file);
    std::fs::write(
        PathBuf::from(std::env::var_os("OUT_DIR").unwrap()).join("config.gen.rs"),
        formatted,
    )
    .unwrap();
}