valve_compilers 1.1.0

A type-safe, ergonomic, and extensible library for building command-line arguments for Valve's Source Engine compiler tools.
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
use heck::{ToPascalCase, ToSnakeCase};
use quote::{format_ident, quote};
use serde::Deserialize;
use std::env;
use std::fs;
use std::path::Path;

// Structures for parsing TOML
#[derive(Debug, Deserialize)]
struct CompilerConfig {
    name: String,
    description: String,
    working_dir: String,
    parameters: Vec<ParameterConfig>,
}

#[derive(Debug, Deserialize, Clone)]
struct ParameterConfig {
    name: String,
    description: String,
    argument: String,
    value_type: ValueType,
    default_value: Option<String>,
    #[serde(default)]
    is_default: bool,
    constraints: Option<ConstraintsConfig>,
}

#[derive(Debug, Deserialize, Clone)]
struct ConstraintsConfig {
    compatible_games: Option<Vec<u32>>,
}

#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum ValueType {
    Flag,
    Float,
    Integer,
    String,
    Path,
}

fn main() {
    let out_dir = env::var_os("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("generated_compilers.rs");
    println!("cargo:rerun-if-changed=configs/");

    let mut compiler_modules = Vec::new();
    let mut compiler_metadata = Vec::new();

    // Find all TOML files in the directory
    let manifest_dir = std::path::PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap());
    let compilers_configs_dir = manifest_dir.join("compiler_configs");
    if !compilers_configs_dir.exists() || !compilers_configs_dir.is_dir() {
        panic!("'compiler_configs' directory not found at {:?} or is not a directory.", compilers_configs_dir);
    }

    for entry in fs::read_dir(&compilers_configs_dir)
        .unwrap_or_else(|_| panic!("Failed to read compilers directory at {:?}", compilers_configs_dir))
    {
        let entry = entry.expect("Failed to read entry");
        let path = entry.path();

        if !path.is_file() || path.extension().and_then(|s| s.to_str()) != Some("toml") {
            continue;
        }

        let toml_content = fs::read_to_string(&path).expect("Failed to read TOML file");
        let config: CompilerConfig = match toml::from_str::<CompilerConfig>(&toml_content) {
            Ok(c) => c,
            Err(e) => {
                panic!(
                    "\n\n\
                    ===============================================================\n\
                    [BUILD SCRIPT ERROR] Invalid TOML Configuration File\n\
                    ===============================================================\n\
                    File:    {}\n\
                    Error:   {}\n\
                    ---------------------------------------------------------------\n",
                    path.display(),
                    e
                )
            },
        };

        if config.parameters.is_empty() {
            eprintln!("File: {} does not contain any parameters. Skipping.", path.display());
            continue;
        }

        let module_name_str = config.name.to_snake_case();
        let struct_name_str = config.name.to_pascal_case();

        compiler_modules.push(generate_compiler_module(&config));
        compiler_metadata.push((struct_name_str, module_name_str));
    }

    let compiler_enum_token_stream = generate_compiler_enum(&compiler_metadata);

    // Assemble everything together
    let final_code = quote! {
        #[comment = "THIS FILE IS AUTO-GENERATED BY BUILD.RS. DO NOT EDIT."]

        #(#compiler_modules)*
        #compiler_enum_token_stream
    };

    let syntax_tree = match syn::parse2::<syn::File>(final_code) {
        Ok(tree) => tree,
        Err(e) => {
            panic!(
                "Failed to parse generated code: {}\n",
                e
            );
        }
    };

    let formatted_code = prettyplease::unparse(&syntax_tree);
    fs::write(&dest_path, formatted_code).unwrap();
    println!("cargo:rerun-if-changed=build.rs");
}

/// Generates a module for a single compiler (e.g., `vbsp`).
fn generate_compiler_module(config: &CompilerConfig) -> proc_macro2::TokenStream {
    //=========================================================================================
    // STEP 1: IDENTIFIERS & METADATA
    // - Create the necessary identifiers (names for the module, structs, enums).
    // - Extract static metadata strings from the configuration.
    //=========================================================================================
    let module_name = format_ident!("{}", config.name.to_snake_case());
    let struct_name = format_ident!("{}", config.name.to_pascal_case());
    let arg_enum_name = format_ident!("{}Arg", config.name.to_pascal_case());
    let name_str = &config.name;
    let description_str = &config.description;
    let working_dir_template = &config.working_dir;
    let arg_doc_comment = format!("Enum of arguments for {}", struct_name);


    //=========================================================================================
    // STEP 2: `ARG` ENUM GENERATION
    // - Create the variants for the compiler's argument enum.
    // - E.g., `pub enum VbspArg { Verbose, NoWater, MicroVolumeTest(f32), ... }`
    //=========================================================================================
    let arg_variants = config.parameters.iter().map(|param| {
        let variant_name = format_ident!("{}", param.name.to_pascal_case());
        let doc_comment = &param.description;
        match param.value_type {
            ValueType::Flag => quote! { #[doc = #doc_comment] #variant_name, },
            ValueType::Float => quote! { #[doc = #doc_comment] #variant_name(f32), },
            ValueType::Integer => quote! { #[doc = #doc_comment] #variant_name(i64), },
            ValueType::String => quote! { #[doc = #doc_comment] #variant_name(String), },
            ValueType::Path => quote! { #[doc = #doc_comment] #variant_name(std::path::PathBuf), },
        }
    });


    //=========================================================================================
    // STEP 3: `COMPILER` STRUCT `DEFAULT` IMPLEMENTATION
    // - Generate the initializers for arguments marked as `is_default = true` in the TOML.
    //   This is used to populate `selected_args` in the `Default::default()` implementation.
    //=========================================================================================
    let default_arg_initializers = config.parameters.iter()
        .filter(|p| p.is_default)
        .map(|p| {
            let variant_ident = format_ident!("{}", p.name.to_pascal_case());
            match p.value_type {
                ValueType::Flag => quote! { #arg_enum_name::#variant_ident },
                _ => {
                    let default_val_str = p.default_value.as_ref()
                        .expect(&format!("Parameter '{}' needs a default_value", p.name));
                    let value = match p.value_type {
                        ValueType::Float => {
                            let val: f32 = default_val_str.parse().expect("Invalid float");
                            quote! { #val }
                        },
                        ValueType::Integer => {
                            let val: i64 = default_val_str.parse().expect("Invalid integer");
                            quote! { #val }
                        },
                        ValueType::Path => quote! { std::path::PathBuf::from(#default_val_str) },
                        ValueType::String => quote! { #default_val_str.to_string() },
                        ValueType::Flag => unreachable!(),
                    };
                    quote! { #arg_enum_name::#variant_ident(#value) }
                }
            }
        });


    //=========================================================================================
    // STEP 4: `COMPILERARG` TRAIT IMPLEMENTATION
    // - Generate the `match` arms for each method required by the `CompilerArg` trait.
    //=========================================================================================

    // --- `name()` method arms ---
    let name_arms = config.parameters.iter().map(|p| {
        let variant = format_ident!("{}", p.name.to_pascal_case());
        let name_str = &p.name;
        quote! { Self::#variant { .. } => #name_str, }
    });

    // --- `description()` method arms ---
    let desc_arms = config.parameters.iter().map(|p| {
        let variant = format_ident!("{}", p.name.to_pascal_case());
        let desc_str = &p.description;
        quote! { Self::#variant { .. } => #desc_str, }
    });

    // --- `value_type()` method arms ---
    let value_type_arms = config.parameters.iter()
        .filter(|p| p.value_type != ValueType::Flag)
        .map(|p| {
            let variant = format_ident!("{}", p.name.to_pascal_case());
            let vt_ident = match p.value_type {
                ValueType::Float => format_ident!("Float"),
                ValueType::Integer => format_ident!("Integer"),
                ValueType::String => format_ident!("String"),
                ValueType::Path => format_ident!("Path"),
                ValueType::Flag => unreachable!(), // This case is impossible due to the filter()
            };
            quote! { Self::#variant { .. } => ValueType::#vt_ident, }
        });

    // --- `get_default_value()` method arms ---
    let default_value_arms = config.parameters.iter().filter_map(|p| {
        let default_value = p.default_value.as_ref()?;
        let variant = format_ident!("{}", p.name.to_pascal_case());
        let value = match p.value_type {
            ValueType::Float => {
                let val: f32 = default_value.parse().expect("Invalid float default value");
                quote! { #val }
            }
            ValueType::Integer => {
                let val: i64 = default_value.parse().expect("Invalid integer default value");
                quote! { #val }
            }
            ValueType::String => quote! { #default_value.to_string() },
            ValueType::Flag => return None, // Flags cannot have default values
            ValueType::Path => quote! { std::path::PathBuf::from(#default_value) },
        };
        Some(quote! { Self::#variant { .. } => Some(#arg_enum_name::#variant(#value)), })
    });

    // --- `as_arg()` method arms ---
    let as_arg_arms = config.parameters.iter().map(|p| {
        let variant = format_ident!("{}", p.name.to_pascal_case());
        let argument = &p.argument;

        if p.value_type == ValueType::Flag {
            return quote! { Self::#variant => (#argument, None), }
        }

        let value_expr = if p.value_type == ValueType::Path {
            quote! { val.to_string_lossy() }
        } else {
            quote! { val }
        };

        quote! { Self::#variant(val) => (#argument, Some(#value_expr.to_string())), }
    });

    // --- `is_default()` method arms ---
    let is_default_arms = config.parameters.iter()
        .filter(|p| p.is_default)
        .map(|p| {
            let variant = format_ident!("{}", p.name.to_pascal_case());
            quote! { Self::#variant { .. } => true, }
        });

    // --- `compatible_games()` method arms ---
    let compatible_games_arms = config.parameters.iter()
        .filter_map(|p| {
            let variant = format_ident!("{}", p.name.to_pascal_case());
            p.constraints.as_ref().and_then(|c| c.compatible_games.as_ref()).map(|games| {
                quote! { Self::#variant { .. } => Some(&[#(#games),*]), }
            })
        });


    //=========================================================================================
    // STEP 5: `TRYFROM<&STR>` TRAIT IMPLEMENTATION
    // - Generate the `match` arms for parsing string inputs into `Arg` enum variants.
    //=========================================================================================
    let try_from_arms = config.parameters.iter().map(|p| {
        let arg_str = &p.argument;
        let variant_ident = format_ident!("{}", p.name.to_pascal_case());

        match p.value_type {
            ValueType::Flag => quote! {
                #arg_str => {
                    if value_opt.is_some() {
                        return Err(ParseArgError::UnexpectedValue(#arg_str));
                    }
                    Ok(Self::#variant_ident)
                }
            },
            _ => {
                let parse_logic = match p.value_type {
                    ValueType::Float => quote! { value_str.parse::<f32>() },
                    ValueType::Integer => quote! { value_str.parse::<i64>() },
                    ValueType::String => quote! { Ok::<_, ()>(value_str.to_string()) },
                    ValueType::Path => quote! { Ok::<_, ()>(std::path::PathBuf::from(value_str)) },
                    ValueType::Flag => unreachable!(),
                };

                quote! {
                    #arg_str => {
                        let value_str = value_opt.ok_or(ParseArgError::MissingValue(#arg_str))?;
                        let parsed_val = #parse_logic.map_err(|_| ParseArgError::InvalidValue {
                            argument: #arg_str,
                            value: value_str.to_string(),
                        })?;
                        Ok(Self::#variant_ident(parsed_val))
                    }
                }
            }
        }
    });


    //=========================================================================================
    // STEP 6: FINAL ASSEMBLY
    // - Combine all the generated token streams into the final module structure.
    //=========================================================================================
    quote! {
        #[doc = "This module is auto-generated by build.rs."]
        pub mod #module_name {
            use crate::{Compiler, CompilerArg, ValueType, ParseArgError};
            use std::fmt;

            #[doc = #description_str]
            #[derive(Debug, Clone)]
            #[cfg_attr(feature = "serialization", derive(serde::Serialize, serde::Deserialize))]
            pub struct #struct_name {
                pub selected_args: Vec<#arg_enum_name>,
            }

            // Implementation of the main `Compiler` trait for the struct.
            impl Compiler for #struct_name {
                type Arg = #arg_enum_name;

                fn name(&self) -> &'static str { #name_str }
                fn description(&self) -> &'static str { #description_str }
                fn working_dir_template(&self) -> &'static str { #working_dir_template }

                fn get_args(&self) -> &[Self::Arg] { &self.selected_args }
                fn add_arg(&mut self, arg: Self::Arg) { self.selected_args.push(arg); }
                fn clear_args(&mut self) { self.selected_args.clear(); }
            }

            // `Default` implementation populates the struct with default arguments.
            impl Default for #struct_name {
                fn default() -> Self {
                    Self {
                        selected_args: vec![ #(#default_arg_initializers),* ],
                    }
                }
            }

            // `new()` constructor for an empty, non-default instance.
            impl #struct_name {
                pub fn new() -> Self {
                    Self {
                        selected_args: Vec::new()
                    }
                }
            }

            #[doc = #arg_doc_comment]
            #[derive(Debug, Clone, PartialEq)]
            #[cfg_attr(feature = "enum_iter", derive(strum_macros::EnumIter))]
            #[cfg_attr(feature = "serialization", derive(serde::Serialize, serde::Deserialize))]
            pub enum #arg_enum_name {
                #(#arg_variants)*
            }

            // Implementation of the `CompilerArg` trait for the `Arg` enum.
            impl CompilerArg for #arg_enum_name {
                fn name(&self) -> &'static str {
                    match self { #(#name_arms)* }
                }
                fn description(&self) -> &'static str {
                    match self { #(#desc_arms)* }
                }
                fn value_type(&self) -> ValueType {
                    match self {
                        #(#value_type_arms)*
                        _ => ValueType::Flag,
                    }
                }
                fn get_default_value(&self) -> Option<Self> {
                    match self {
                        #(#default_value_arms)*
                        _ => None,
                    }
                }
                fn as_arg(&self) -> (&'static str, Option<String>) {
                    match self { #(#as_arg_arms)* }
                }
                fn is_default(&self) -> bool {
                    match self {
                        #(#is_default_arms)*
                        _ => false,
                    }
                }
                fn compatible_games(&self) -> Option<&'static [u32]> {
                    match self {
                        #(#compatible_games_arms)*
                        _ => None,
                    }
                }
            }

            // `Display` implementation for convenient printing.
            impl fmt::Display for #arg_enum_name {
                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    write!(f, "{}", self.name())
                }
            }

            // `TryFrom` implementations for parsing from string slices and Strings.
            impl<'a> TryFrom<&'a str> for #arg_enum_name {
                type Error = ParseArgError;

                fn try_from(value: &'a str) -> Result<Self, Self::Error> {
                    let (key, value_opt) =
                        if let Some((k, v)) = value.split_once(' ') {
                            (k, Some(v))
                        } else {
                            (value, None)
                        };

                    match key {
                        #(#try_from_arms,)*
                        _ => Err(ParseArgError::UnknownArgument(key.to_string())),
                    }
                }
            }

            impl TryFrom<String> for #arg_enum_name {
                type Error = ParseArgError;
                fn try_from(value: String) -> Result<Self, Self::Error> {
                    Self::try_from(value.as_str())
                }
            }
        }
    }
}

/// Generates the main enum that combines all compilers.
fn generate_compiler_enum(metadata: &[(String, String)]) -> proc_macro2::TokenStream {
    let variants = metadata.iter().map(|(struct_name, module_name)| {
        let struct_ident = format_ident!("{}", struct_name);
        let module_ident = format_ident!("{}", module_name);
        quote! { #struct_ident(#module_ident::#struct_ident), }
    });

    let name_arms = metadata.iter().map(|(struct_name, _)| {
        let struct_ident = format_ident!("{}", struct_name);
        quote! { Self::#struct_ident(inner) => inner.name(), }
    });

    let description_arms = metadata.iter().map(|(struct_name, _)| {
        let struct_ident = format_ident!("{}", struct_name);
        quote! { Self::#struct_ident(inner) => inner.description(), }
    });

    let build_args_arms = metadata.iter().map(|(struct_name, _)| {
        let struct_ident = format_ident!("{}", struct_name);
        quote! { Self::#struct_ident(inner) => inner.build_args(), }
    });

    let build_command_arms = metadata.iter().map(|(struct_name, _)| {
        let struct_ident = format_ident!("{}", struct_name);
        quote! { Self::#struct_ident(inner) => inner.build_command(context, executable), }
    });

    let use_statements = metadata.iter().map(|(_, module_name)| {
        let mod_name = format_ident!("{}", module_name);
        quote! { pub use #mod_name::*; }
    });

    quote! {
        #(#use_statements)*

        #[derive(Debug, Clone)]
        #[cfg_attr(feature = "enum_iter", derive(strum_macros::EnumIter))]
        #[cfg_attr(feature = "serialization", derive(serde::Serialize, serde::Deserialize))]
        #[cfg_attr(feature = "serialization", serde(tag = "compiler_type"))]
        pub enum CompilerEnum {
            #(#variants)*
        }

        impl CompilerEnum {
            pub fn name(&self) -> &'static str {
                match self { #(#name_arms)* }
            }
            pub fn description(&self) -> &'static str {
                match self { #(#description_arms)* }
            }
            pub fn build_args(&self) -> Vec<String> {
                match self { #(#build_args_arms)* }
            }
            pub fn build_command(&self, context: &CompilerContext, executable: Option<PathBuf>) -> CommandInfo {
                match self { #(#build_command_arms)* }
            }
        }
    }
}