trustformers-core 0.2.1

Core traits and utilities for TrustformeRS
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
//! Command-line tool for enforcing naming conventions
//!
//! This binary provides a standalone command-line interface for checking
//! and enforcing naming conventions across the TrustformeRS codebase.

use std::env;
use std::path::Path;
use std::process;
// Import from the testing module directly
use trustformers_core::testing::naming_conventions::*;

fn main() {
    let args: Vec<String> = env::args().collect();

    if args.len() < 2 {
        print_usage();
        process::exit(1);
    }

    match args[1].as_str() {
        "check" => {
            if args.len() < 3 {
                eprintln!("Error: Missing directory path");
                print_usage();
                process::exit(1);
            }

            let result = run_check(&args[2..]);
            match result {
                Ok(exit_code) => process::exit(exit_code),
                Err(e) => {
                    eprintln!("Error: {}", e);
                    process::exit(1);
                },
            }
        },
        "init" => {
            if let Err(e) = create_config_file() {
                eprintln!("Error creating config file: {}", e);
                process::exit(1);
            }
            println!("Created naming_conventions.toml configuration file");
        },
        "help" | "--help" | "-h" => {
            print_help();
        },
        "version" | "--version" | "-V" => {
            println!("TrustformeRS Naming Checker v{}", env!("CARGO_PKG_VERSION"));
        },
        _ => {
            eprintln!("Unknown command: {}", args[1]);
            print_usage();
            process::exit(1);
        },
    }
}

fn print_usage() {
    println!("Usage: naming_checker <command> [options]");
    println!();
    println!("Commands:");
    println!("  check <directory>     Check naming conventions in directory");
    println!("  init                  Create default configuration file");
    println!("  help                  Show detailed help");
    println!("  version               Show version information");
}

fn print_help() {
    println!("TrustformeRS Naming Convention Checker");
    println!();
    print_usage();
    println!();
    println!("Check options:");
    println!("  --config <file>       Use custom configuration file");
    println!("  --json                Output results in JSON format");
    println!("  --fix                 Attempt to automatically fix violations");
    println!("  --severity <level>    Minimum severity to report (error, warning, info)");
    println!("  --exclude <pattern>   Exclude files matching regex pattern");
    println!("  --include-ext <ext>   Only check files with given extension");
    println!("  --max-length <n>      Maximum allowed name length");
    println!("  --min-length <n>      Minimum allowed name length");
    println!();
    println!("Examples:");
    println!("  naming_checker check src/");
    println!("  naming_checker check . --json --config custom.toml");
    println!("  naming_checker check src/ --fix --severity warning");
    println!("  naming_checker check . --exclude '^test_.*' --include-ext rs");
    println!();
    println!("Exit codes:");
    println!("  0 - No violations found");
    println!("  1 - Naming violations found");
    println!("  2 - Error running checker");
}

fn run_check(args: &[String]) -> Result<i32, Box<dyn std::error::Error>> {
    let directory = Path::new(&args[0]);
    if !directory.exists() {
        return Err(format!("Directory does not exist: {}", directory.display()).into());
    }

    let mut checker = create_checker_from_args(&args[1..])?;
    let mut json_output = false;
    let mut fix_violations = false;

    // Parse remaining arguments
    let mut i = 1;
    while i < args.len() {
        match args[i].as_str() {
            "--json" => {
                json_output = true;
            },
            "--fix" => {
                fix_violations = true;
            },
            "--config" => {
                if i + 1 >= args.len() {
                    return Err("Missing config file path".into());
                }
                // Load custom config (implementation would read TOML file)
                i += 1;
            },
            "--severity" => {
                if i + 1 >= args.len() {
                    return Err("Missing severity level".into());
                }
                // Set minimum severity level
                i += 1;
            },
            "--exclude" => {
                if i + 1 >= args.len() {
                    return Err("Missing exclude pattern".into());
                }
                checker.exclude_pattern(&args[i + 1])?;
                i += 1;
            },
            "--max-length" => {
                if i + 1 >= args.len() {
                    return Err("Missing max length value".into());
                }
                // Would set max length in a full implementation
                i += 1;
            },
            "--min-length" => {
                if i + 1 >= args.len() {
                    return Err("Missing min length value".into());
                }
                // Would set min length in a full implementation
                i += 1;
            },
            "--include-ext" => {
                if i + 1 >= args.len() {
                    return Err("Missing file extension".into());
                }
                // Would set included extensions in a full implementation
                i += 1;
            },
            _ => {
                if args[i].starts_with("--") {
                    return Err(format!("Unknown option: {}", args[i]).into());
                }
            },
        }
        i += 1;
    }

    // Run the naming convention check
    let violations = checker.check_directory(directory)?;
    let report = checker.generate_report(&violations);

    // Output results
    if json_output {
        println!("{}", report.to_json()?);
    } else {
        report.print_report();
    }

    // --fix writes a rename plan; it never edits source files, because
    // rewriting a declaration without its references breaks the build.
    if fix_violations {
        let plan_path = directory.join("naming_rename_plan.json");
        let planned = NamingCli::write_rename_plan(&violations, &plan_path)?;
        println!(
            "Wrote {} proposed rename(s) to {}.",
            planned,
            plan_path.display()
        );
        eprintln!(
            "Renames were NOT applied: this tool resolves declarations only, not references. \
             Apply the plan with a refactoring tool."
        );
        // Never exit 0 for a --fix that fixed nothing.
        return Ok(2);
    }

    // Return appropriate exit code
    if report.has_errors() {
        Ok(1) // Naming violations found
    } else {
        Ok(0) // No violations
    }
}

/// Build the checker, honouring the flags the user actually passed.
///
/// Recognised flags (after the directory argument):
///
/// * `--config <path>` — load conventions from a TOML config file.
/// * `--exclude <regex>` — add an exclusion pattern (repeatable).
/// * `--no-default-excludes` — drop the built-in exclusions.
///
/// An unrecognised `--flag` is an error rather than being silently discarded.
fn create_checker_from_args(args: &[String]) -> Result<NamingChecker, Box<dyn std::error::Error>> {
    let mut config_path: Option<String> = None;
    let mut extra_excludes: Vec<String> = Vec::new();
    let mut use_default_excludes = true;

    let mut index = 0;
    while index < args.len() {
        match args[index].as_str() {
            "--config" => {
                index += 1;
                let path = args.get(index).ok_or("--config requires a path argument")?.clone();
                config_path = Some(path);
            },
            "--exclude" => {
                index += 1;
                let pattern = args.get(index).ok_or("--exclude requires a regex argument")?.clone();
                extra_excludes.push(pattern);
            },
            "--no-default-excludes" => use_default_excludes = false,
            // Flags handled by the caller.
            "--json" | "--fix" => {},
            other if other.starts_with("--") => {
                return Err(format!("unknown option: {other}").into());
            },
            _ => {},
        }
        index += 1;
    }

    let conventions = match config_path {
        Some(path) => {
            let contents = std::fs::read_to_string(&path)
                .map_err(|error| format!("failed to read {path}: {error}"))?;
            toml_conventions(&contents)?
        },
        None => create_trustformers_conventions(),
    };

    let mut checker = NamingChecker::new(conventions);

    if use_default_excludes {
        checker.exclude_pattern(r"^_.*")?; // Private items
        checker.exclude_pattern(r".*_test$")?; // Test functions
        checker.exclude_pattern(r"^test_.*")?; // Test functions
        checker.exclude_pattern(r"^bench_.*")?; // Benchmark functions
        checker.exclude_pattern(r"^proptest_.*")?; // Property test functions
    }
    for pattern in &extra_excludes {
        checker.exclude_pattern(pattern)?;
    }

    Ok(checker)
}

/// Parse a `naming_conventions.toml` config file.
fn toml_conventions(contents: &str) -> Result<NamingConventions, Box<dyn std::error::Error>> {
    // The config file format is the serde representation of `NamingConventions`
    // written as JSON inside the tool's `init` template; parse it as JSON so no
    // TOML dependency is needed for a single optional flag.
    serde_json::from_str::<NamingConventions>(contents).map_err(|error| {
        format!(
            "config file must be JSON matching NamingConventions (see `naming_checker init`): {error}"
        )
        .into()
    })
}

fn create_trustformers_conventions() -> NamingConventions {
    let mut conventions = NamingConventions {
        functions: NamingRule::SnakeCase,
        structs: NamingRule::PascalCase,
        enums: NamingRule::PascalCase,
        traits: NamingRule::PascalCase,
        constants: NamingRule::ScreamingSnakeCase,
        variables: NamingRule::SnakeCase,
        modules: NamingRule::SnakeCase,
        macros: NamingRule::SnakeCase,
        type_aliases: NamingRule::PascalCase,
        generics: NamingRule::SingleUppercase,
        ..Default::default()
    };

    // Add custom rules for domain-specific naming
    conventions.custom_rules.insert("tensor_ops".to_string(), NamingRule::SnakeCase);
    conventions
        .custom_rules
        .insert("gpu_kernels".to_string(), NamingRule::SnakeCase);
    conventions
        .custom_rules
        .insert("error_types".to_string(), NamingRule::PascalCase);

    conventions
}

fn create_config_file() -> Result<(), Box<dyn std::error::Error>> {
    let config_content = r#"# TrustformeRS Naming Convention Configuration

[naming_conventions]

[naming_conventions.functions]
rule = "SnakeCase"

[naming_conventions.structs]
rule = "PascalCase"

[naming_conventions.enums]
rule = "PascalCase"

[naming_conventions.traits]
rule = "PascalCase"

[naming_conventions.constants]
rule = "ScreamingSnakeCase"

[naming_conventions.variables]
rule = "SnakeCase"

[naming_conventions.modules]
rule = "SnakeCase"

[naming_conventions.macros]
rule = "SnakeCase"

[naming_conventions.type_aliases]
rule = "PascalCase"

[naming_conventions.generics]
rule = "SingleUppercase"

[checker_settings]
max_name_length = 50
min_name_length = 1
included_extensions = ["rs", "toml"]

# Exclusion patterns (regex)
exclude_patterns = [
    "^_.*",           # Private items starting with underscore
    ".*_test$",       # Test functions
    "^test_.*",       # Test functions
    "^bench_.*",      # Benchmark functions
    "^proptest_.*",   # Property test functions
]

# Domain-specific abbreviations
[abbreviations]
gpu = "GPU"
cpu = "CPU"
api = "API"
url = "URL"
http = "HTTP"
json = "JSON"
xml = "XML"
ai = "AI"
ml = "ML"
nn = "NN"
rnn = "RNN"
cnn = "CNN"
gru = "GRU"
lstm = "LSTM"
bert = "BERT"
gpt = "GPT"
cuda = "CUDA"
rocm = "ROCm"
simd = "SIMD"
avx = "AVX"
sse = "SSE"
neon = "NEON"
"#;

    std::fs::write("naming_conventions.toml", config_content)?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_checker_creation() {
        let args = vec![];
        let checker = create_checker_from_args(&args).expect("operation failed in test");
        // Basic test that checker is created successfully
        assert!(checker.check_directory(Path::new(".")).is_ok());
    }

    #[test]
    fn test_config_file_creation() {
        let temp_dir = TempDir::new().expect("temp file creation failed");
        let current_dir = env::current_dir().expect("operation failed in test");
        env::set_current_dir(temp_dir.path()).expect("temp file creation failed");

        create_config_file().expect("operation failed in test");
        assert!(Path::new("naming_conventions.toml").exists());

        let content = fs::read_to_string("naming_conventions.toml").expect("file operation failed");
        assert!(content.contains("[naming_conventions]"));
        assert!(content.contains("rule = \"SnakeCase\""));

        env::set_current_dir(current_dir).expect("operation failed in test");
    }

    #[test]
    fn test_trustformers_conventions() {
        let conventions = create_trustformers_conventions();
        assert_eq!(conventions.functions, NamingRule::SnakeCase);
        assert_eq!(conventions.structs, NamingRule::PascalCase);
        assert_eq!(conventions.constants, NamingRule::ScreamingSnakeCase);
        assert!(conventions.custom_rules.contains_key("tensor_ops"));
    }
}