etdl-cli 0.2.1

ETDL CLI: compile and validate .etdl documents with IEC 61025 fault tree and IEC 62502 event tree analysis, generating Rust for microservices
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
use clap::{Parser, Subcommand};
use serde::Serialize;
use std::path::{Path, PathBuf};

#[derive(Parser)]
#[command(
    name = "etdl",
    version,
    about = "ETDL parser, validator, and compiler",
    after_help = "Exit codes: 0 = success, 1 = validation/compile failure, 2 = usage error"
)]
struct Cli {
    /// Emit machine-readable JSON output.
    #[arg(long, global = true)]
    json: bool,

    /// Suppress all non-error output.
    #[arg(long, global = true)]
    quiet: bool,

    /// Emit extra detail.
    #[arg(long, global = true)]
    verbose: bool,

    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Compile an .etdl document to a target language.
    Compile {
        #[arg(help = "Path to .etdl document")]
        file: PathBuf,

        #[arg(
            long,
            default_value = "rust",
            help = "Target language for code generation"
        )]
        target: String,

        #[arg(
            long,
            default_value = ".",
            help = "Output directory for generated code"
        )]
        out_dir: PathBuf,
    },
    /// Validate one or more .etdl documents (files or directories).
    Validate {
        #[arg(help = "Path(s) to .etdl document(s) or directories")]
        files: Vec<PathBuf>,
    },
    /// Analyze a document and print reliability summary (fault trees, branches).
    Analyze {
        #[arg(help = "Path to .etdl document")]
        file: PathBuf,
    },
    /// Discover candidate failure modes in source code (reliability ontology).
    Discover {
        #[arg(help = "Path to a source file or directory to analyze")]
        path: PathBuf,
    },
    Version,
}

fn main() {
    let Cli {
        json,
        quiet,
        verbose,
        command,
    } = Cli::parse();

    let flags = CliFlags {
        json,
        quiet,
        verbose,
    };

    let code = match command {
        Command::Compile {
            file,
            target,
            out_dir,
        } => cmd_compile(&flags, &file, &target, &out_dir),
        Command::Validate { files } => cmd_validate(&flags, &files),
        Command::Analyze { file } => cmd_analyze(&flags, &file),
        Command::Discover { path } => cmd_discover(&flags, &path),
        Command::Version => {
            if flags.json {
                println!(
                    "{}",
                    serde_json::json!({ "name": "etdl", "version": env!("CARGO_PKG_VERSION") })
                );
            } else {
                println!("etdl {}", env!("CARGO_PKG_VERSION"));
            }
            0
        }
    };

    std::process::exit(code);
}

#[derive(Clone, Copy)]
struct CliFlags {
    json: bool,
    quiet: bool,
    verbose: bool,
}

/// Collect all `.etdl` files from the given paths (files or directories).
fn collect_etdl_files(paths: &[PathBuf]) -> Result<Vec<PathBuf>, String> {
    let mut out = Vec::new();
    for p in paths {
        let meta =
            std::fs::metadata(p).map_err(|e| format!("cannot access '{}': {}", p.display(), e))?;
        if meta.is_dir() {
            let mut entries: Vec<PathBuf> = std::fs::read_dir(p)
                .map_err(|e| format!("cannot read directory '{}': {}", p.display(), e))?
                .filter_map(|e| e.ok().map(|e| e.path()))
                .filter(|p| p.extension().is_some_and(|x| x == "etdl"))
                .collect();
            entries.sort();
            out.extend(entries);
        } else {
            out.push(p.clone());
        }
    }
    Ok(out)
}

fn resolve_diagnostic_positions(
    diagnostics: &mut [etdl_compiler::validate::Diagnostic],
    content: &str,
) {
    let index = etdl_parser::spanned::build_span_index(content).ok();
    for d in diagnostics.iter_mut() {
        if d.line.is_none() {
            if let (Some(key), Some(index)) = (&d.key, &index) {
                if let Some(el) = index.resolve(key) {
                    let span = el.key_span.unwrap_or(el.span);
                    d.line = Some(span.line);
                    d.column = Some(span.column);
                    d.end_line = Some(span.end_line);
                    d.end_column = Some(span.end_column);
                }
            }
        }
    }
}

fn append_duplicate_warnings(
    diagnostics: &mut Vec<etdl_compiler::validate::Diagnostic>,
    content: &str,
) {
    if let Ok(duplicates) = etdl_parser::spanned::detect_duplicate_ids(content) {
        for dup in duplicates {
            let mut d = etdl_compiler::validate::Diagnostic::warning(
                "V-001",
                format!(
                    "duplicate {} id '{}' in tree '{}'",
                    dup.kind, dup.id, dup.tree
                ),
            )
            .with_position(dup.span.line, dup.span.column);
            d.end_line = Some(dup.span.end_line);
            d.end_column = Some(dup.span.end_column);
            diagnostics.push(d);
        }
    }
}

#[derive(Serialize)]
struct DiagnosticJson<'a> {
    code: &'a str,
    severity: &'a str,
    message: &'a str,
    line: Option<u32>,
    column: Option<u32>,
}

fn diagnostic_line(d: &etdl_compiler::validate::Diagnostic) -> String {
    let level = if d.is_error() { "ERROR" } else { "WARNING" };
    let position = match (d.line, d.column) {
        (Some(l), Some(c)) => format!(" ({}:{})", l + 1, c + 1),
        _ => String::new(),
    };
    format!("[{}] {}{}: {}", level, d.code, position, d.message)
}

fn print_diagnostics(flags: &CliFlags, diagnostics: &[etdl_compiler::validate::Diagnostic]) {
    if flags.json {
        let items: Vec<DiagnosticJson> = diagnostics
            .iter()
            .map(|d| DiagnosticJson {
                code: &d.code,
                severity: if d.is_error() { "error" } else { "warning" },
                message: &d.message,
                line: d.line,
                column: d.column,
            })
            .collect();
        println!("{}", serde_json::to_string(&items).unwrap_or_default());
    } else {
        for d in diagnostics {
            // Diagnostics go to stdout when not quiet; errors always visible.
            if flags.quiet && !d.is_error() {
                continue;
            }
            println!("{}", diagnostic_line(d));
        }
    }
}

fn cmd_compile(flags: &CliFlags, file: &Path, target: &str, out_dir: &Path) -> i32 {
    if target != "rust" {
        eprintln!(
            "error: unsupported target language '{}'; supported: rust",
            target
        );
        return 1;
    }

    let content = match std::fs::read_to_string(file) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("error: cannot read file '{}': {}", file.display(), e);
            return 1;
        }
    };

    let doc = match etdl_parser::parse_document(&content) {
        Ok(doc) => doc,
        Err(e) => {
            eprintln!("error: {}", e);
            return 1;
        }
    };

    let base_dir = file.parent().unwrap_or(Path::new("."));

    let registry = match etdl_parser::load_asyncapi_imports(&doc, base_dir) {
        Ok(registry) => registry,
        Err(e) => {
            eprintln!("error: {}", e);
            return 1;
        }
    };

    let compiler = etdl_compiler::Compiler::new();
    let base_dir = file.parent().unwrap_or(Path::new("."));
    let mut result = compiler.compile_with_base(&doc, &registry, base_dir);

    append_duplicate_warnings(&mut result.diagnostics, &content);
    resolve_diagnostic_positions(&mut result.diagnostics, &content);

    let error_count = result.diagnostics.iter().filter(|d| d.is_error()).count();
    let warning_count = result.diagnostics.iter().filter(|d| !d.is_error()).count();

    print_diagnostics(flags, &result.diagnostics);

    match result.rust_output {
        Some(output) => {
            let stem = file.file_stem().unwrap_or_default().to_string_lossy();
            let out_path = out_dir.join(format!("{}.rs", stem));

            if !out_dir.exists() {
                if let Err(e) = std::fs::create_dir_all(out_dir) {
                    eprintln!("error: cannot create output directory: {}", e);
                    return 1;
                }
            }

            if let Err(e) = std::fs::write(&out_path, output) {
                eprintln!(
                    "error: cannot write generated code to {}: {}",
                    out_path.display(),
                    e
                );
                return 1;
            }

            // If a reliability build manifest was produced, write it next to
            // the generated code for reproducibility (provenance).
            if let Some(manifest) = &result.build_manifest {
                let manifest_path = out_dir.join("etdl-build-manifest.json");
                if let Ok(json) = serde_json::to_string_pretty(manifest) {
                    if let Err(e) = std::fs::write(&manifest_path, json) {
                        eprintln!(
                            "warning: cannot write build manifest to {}: {}",
                            manifest_path.display(),
                            e
                        );
                    } else if flags.verbose {
                        eprintln!(
                            "reliability build manifest written to {}",
                            manifest_path.display()
                        );
                    }
                }
            }

            if !flags.quiet {
                println!(
                    "compiled '{}' to '{}' ({} errors, {} warnings)",
                    file.display(),
                    out_path.display(),
                    error_count,
                    warning_count
                );
            }
            0
        }
        None => {
            if !flags.quiet {
                eprintln!(
                    "compilation failed with {} errors and {} warnings",
                    error_count, warning_count
                );
            }
            1
        }
    }
}

fn cmd_validate(flags: &CliFlags, paths: &[PathBuf]) -> i32 {
    let files = match collect_etdl_files(paths) {
        Ok(f) => f,
        Err(e) => {
            eprintln!("error: {}", e);
            return 1;
        }
    };

    if files.is_empty() {
        eprintln!("error: no .etdl files found");
        return 1;
    }

    if flags.verbose {
        eprintln!("etdl: validating {} file(s)", files.len());
    }

    let mut worst_exit = 0;

    if flags.json {
        let mut results = Vec::new();
        for file in &files {
            let (diagnostics, ok) = validate_one(flags, file);
            if !ok {
                worst_exit = 1;
            }
            let items: Vec<DiagnosticJson> = diagnostics
                .iter()
                .map(|d| DiagnosticJson {
                    code: &d.code,
                    severity: if d.is_error() { "error" } else { "warning" },
                    message: &d.message,
                    line: d.line,
                    column: d.column,
                })
                .collect();
            results.push(serde_json::json!({
                "file": file.display().to_string(),
                "valid": ok,
                "diagnostics": items,
            }));
        }
        println!("{}", serde_json::json!({ "results": results }));
        return worst_exit;
    }

    for file in &files {
        let (diagnostics, ok) = validate_one(flags, file);
        let error_count = diagnostics.iter().filter(|d| d.is_error()).count();
        let warning_count = diagnostics.iter().filter(|d| !d.is_error()).count();

        if ok {
            if !flags.quiet {
                println!(
                    "document '{}' is valid ({} errors, {} warnings)",
                    file.display(),
                    error_count,
                    warning_count
                );
            }
        } else {
            worst_exit = 1;
            if !flags.quiet {
                eprintln!(
                    "document '{}' has {} validation errors",
                    file.display(),
                    error_count
                );
            }
        }
    }

    worst_exit
}

fn validate_one(flags: &CliFlags, file: &Path) -> (Vec<etdl_compiler::validate::Diagnostic>, bool) {
    let content = match std::fs::read_to_string(file) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("[ERROR] {}: {}", file.display(), e);
            return (Vec::new(), false);
        }
    };

    let doc = match etdl_parser::parse_document(&content) {
        Ok(doc) => doc,
        Err(e) => {
            eprintln!("[ERROR] {}: {}", file.display(), e);
            return (Vec::new(), false);
        }
    };

    let base_dir = file.parent().unwrap_or(Path::new("."));
    let registry = match etdl_parser::load_asyncapi_imports(&doc, base_dir) {
        Ok(registry) => registry,
        Err(e) => {
            eprintln!("[ERROR] {}: {}", file.display(), e);
            return (Vec::new(), false);
        }
    };

    let compiler = etdl_compiler::Compiler::new();
    let base_dir = file.parent().unwrap_or(Path::new("."));
    let mut diagnostics = compiler.validate_with_base(&doc, &registry, base_dir);

    append_duplicate_warnings(&mut diagnostics, &content);
    resolve_diagnostic_positions(&mut diagnostics, &content);

    // In JSON mode the caller serializes the diagnostics; avoid duplicate output.
    if !flags.json {
        print_diagnostics(flags, &diagnostics);
    }

    let ok = !diagnostics.iter().any(|d| d.is_error());
    (diagnostics, ok)
}

fn cmd_analyze(flags: &CliFlags, file: &Path) -> i32 {
    let content = match std::fs::read_to_string(file) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("error: cannot read file '{}': {}", file.display(), e);
            return 1;
        }
    };

    let doc = match etdl_parser::parse_document(&content) {
        Ok(doc) => doc,
        Err(e) => {
            eprintln!("error: {}", e);
            return 1;
        }
    };

    let base_dir = file.parent().unwrap_or(Path::new("."));
    let registry = match etdl_parser::load_asyncapi_imports(&doc, base_dir) {
        Ok(registry) => registry,
        Err(e) => {
            eprintln!("error: {}", e);
            return 1;
        }
    };

    let compiler = etdl_compiler::Compiler::new();
    let mut diagnostics = compiler.validate_with_base(&doc, &registry, base_dir);
    append_duplicate_warnings(&mut diagnostics, &content);
    resolve_diagnostic_positions(&mut diagnostics, &content);

    let errors: Vec<_> = diagnostics.iter().filter(|d| d.is_error()).collect();
    if !errors.is_empty() {
        print_diagnostics(flags, &diagnostics);
        return 1;
    }

    // Resolve external reliability sources so probabilities reflect artifacts.
    let (resolved_events, _manifest) =
        etdl_compiler::reliability::resolve_reliability(&doc, base_dir, &mut Vec::new());
    let overrides: std::collections::BTreeMap<String, f64> = resolved_events
        .iter()
        .map(|r| (r.basic_event.clone(), r.resolved.value))
        .collect();
    let probs = etdl_compiler::fault_tree::resolve_fault_trees_with_overrides(
        &doc,
        &overrides,
        &mut Vec::new(),
    );

    if flags.json {
        let ft_json: Vec<_> = probs
            .iter()
            .map(|(id, p)| serde_json::json!({ "faultTree": id, "topEventProbability": p }))
            .collect();
        println!(
            "{}",
            serde_json::json!({
                "document": file.display().to_string(),
                "eventTrees": doc.event_trees.len(),
                "faultTrees": doc.fault_trees.as_ref().map(|f| f.len()).unwrap_or(0),
                "faultTreeProbabilities": ft_json,
            })
        );
    } else {
        println!("document: {}", file.display());
        println!("event trees: {}", doc.event_trees.len());
        println!(
            "fault trees: {}",
            doc.fault_trees.as_ref().map(|f| f.len()).unwrap_or(0)
        );
        for (id, p) in &probs {
            println!("  {}: topEvent probability = {:.6}", id, p);
        }
    }

    0
}

/// `etdl discover`: run the failure discovery analyzer on a source file or
/// directory, printing candidate failure modes. Discovery only establishes
/// possibility, never probability.
fn cmd_discover(flags: &CliFlags, path: &Path) -> i32 {
    use etdl_failure_discovery::analyzer::StaticAnalyzer;
    use etdl_failure_discovery::discovery::{FailureDiscoverer, SourceProject};

    let analyzer = StaticAnalyzer::new();
    let mut candidates = Vec::new();

    let project = SourceProject {
        name: path
            .file_name()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_default(),
        path: path.to_path_buf(),
    };

    if path.is_dir() {
        let mut files: Vec<PathBuf> = std::fs::read_dir(path)
            .map_err(|e| {
                eprintln!("error: cannot read directory '{}': {}", path.display(), e);
                1
            })
            .unwrap()
            .filter_map(|e| e.ok().map(|e| e.path()))
            .filter(|p| {
                p.extension().map_or(false, |x| {
                    x == "rs" || x == "go" || x == "ts" || x == "js" || x == "py"
                })
            })
            .collect();
        files.sort();
        for f in files {
            let sub = SourceProject {
                name: f.display().to_string(),
                path: f,
            };
            match analyzer.discover(&sub) {
                Ok(r) => candidates.extend(r.candidates),
                Err(e) => eprintln!("warning: {}", e),
            }
        }
    } else {
        match analyzer.discover(&project) {
            Ok(r) => candidates.extend(r.candidates),
            Err(e) => {
                eprintln!("error: {}", e);
                return 1;
            }
        }
    }

    if flags.json {
        println!(
            "{}",
            serde_json::json!({
                "candidates": candidates,
            })
        );
    } else {
        for c in &candidates {
            println!(
                "[{}:{}] {} ({}): {} -> {:?} confidence={:.2}",
                c.location.file,
                c.location.line,
                c.category,
                c.location.symbol.clone().unwrap_or_default(),
                c.ontology_match.clone().unwrap_or_default(),
                c.status,
                c.confidence
            );
        }
        println!("discovered {} candidate failure mode(s)", candidates.len());
    }

    0
}