allium-cli 3.4.1

CLI for checking Allium specification files
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
mod domain_model;
mod test_plan;

use allium_parser::diagnostic::Severity;
use allium_parser::lexer::SourceMap;
use allium_parser::AmbiguousImports;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

const HELP: &str = "\
allium - validate, parse and analyse Allium specification files

Usage: allium <command> [arguments]
       allium [-h | --help] [-V | --version]

Commands:
  check    Validate spec files and report structural diagnostics (JSON)
  analyse  Analyse process completeness: data flow, reachability, conflicts (JSON)
  parse    Parse a spec file and print the AST as JSON
  plan     Derive test obligations from a spec
  model    Extract the domain model as structured data
  help     Print help for the CLI or for a specific command

Options:
  -h, --help     Show this help message and exit
  -V, --version  Print version information and exit

Run `allium help <command>` or `allium <command> --help` for per-command help.
";

const CHECK_HELP: &str = "\
allium check - validate spec files and report structural diagnostics

Usage: allium check <path>...

Each <path> is a .allium file or a directory. Directories are searched
recursively for .allium files. Outputs JSON with a diagnostics array
containing line-level structural warnings and errors.

Exit codes:
  0  No errors or warnings
  1  One or more errors or warnings were reported
  2  No inputs provided, or no .allium files could be resolved
";

const ANALYSE_HELP: &str = "\
allium analyse - analyse process completeness

Usage: allium analyse <path>...

Runs structural checks (same as `check`) plus process-level analysis:
data flow tracing, edge reachability, deadlock detection, conflict
detection, and invariant verification. Outputs JSON with both a
diagnostics array and a findings array.

Exit codes:
  0  No findings
  1  One or more findings were produced
  2  No inputs provided, or no .allium files could be resolved
";

const PARSE_HELP: &str = "\
allium parse - parse a spec file and print the AST as JSON

Usage: allium parse <file.allium>

Prints a JSON document describing the parsed module and any diagnostics
produced during parsing.
";

const PLAN_HELP: &str = "\
allium plan - derive test obligations from a spec

Usage: allium plan <file.allium>

Prints a JSON document describing the test plan implied by the spec,
including invariants, rule pre- and post-conditions, and transitions.
";

const MODEL_HELP: &str = "\
allium model - extract the domain model as structured data

Usage: allium model <file.allium>

Prints a JSON document describing entities, value types and generators
derived from the spec.
";

fn main() -> ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();

    if args.is_empty() {
        eprintln!("allium: missing command");
        eprintln!("Run `allium --help` for usage.");
        return ExitCode::from(2);
    }

    match args[0].as_str() {
        "--help" | "-h" => {
            print!("{HELP}");
            return ExitCode::SUCCESS;
        }
        "--version" | "-V" => {
            println!(
                "allium {} (language versions: 1, 2, 3)",
                env!("CARGO_PKG_VERSION")
            );
            return ExitCode::SUCCESS;
        }
        "help" => return cmd_help(&args[1..]),
        _ => {}
    }

    let subcommand = args[0].as_str();
    let rest = &args[1..];

    match subcommand {
        "check" | "analyse" | "parse" | "plan" | "model" => {
            if rest.iter().any(|a| a == "--help" || a == "-h") {
                print!("{}", subcommand_help(subcommand));
                return ExitCode::SUCCESS;
            }
            match subcommand {
                "check" => cmd_check(rest),
                "analyse" => cmd_analyse(rest),
                "parse" => cmd_parse(rest),
                "plan" => cmd_plan(rest),
                "model" => cmd_model(rest),
                _ => unreachable!(),
            }
        }
        other => {
            eprintln!("allium: unknown command `{other}`");
            eprintln!("Run `allium --help` for available commands.");
            ExitCode::from(2)
        }
    }
}

fn cmd_help(args: &[String]) -> ExitCode {
    match args.first().map(String::as_str) {
        None => {
            print!("{HELP}");
            ExitCode::SUCCESS
        }
        Some("check") | Some("analyse") | Some("parse") | Some("plan") | Some("model") => {
            print!("{}", subcommand_help(args[0].as_str()));
            ExitCode::SUCCESS
        }
        Some(other) => {
            eprintln!("allium: unknown command `{other}`");
            eprintln!("Run `allium --help` for available commands.");
            ExitCode::from(2)
        }
    }
}

fn subcommand_help(name: &str) -> &'static str {
    match name {
        "check" => CHECK_HELP,
        "analyse" => ANALYSE_HELP,
        "parse" => PARSE_HELP,
        "plan" => PLAN_HELP,
        "model" => MODEL_HELP,
        _ => HELP,
    }
}

// ---------------------------------------------------------------------------
// Multi-file commands: check, analyse
// ---------------------------------------------------------------------------

/// Per-file analysis result fed back from the closure to the multi-file loop.
struct FileResult {
    diagnostics: Vec<serde_json::Value>,
    findings: Vec<serde_json::Value>,
    has_issues: bool,
}

/// A parsed file ready for analysis.
struct ParsedFile {
    path: PathBuf,
    source: String,
    result: allium_parser::ParseResult,
}

/// Cross-module context computed once and passed to each file's analysis.
struct CrossModuleContext {
    /// Per-file: declaration names referenced by other modules.
    external_refs: HashMap<PathBuf, HashSet<String>>,
    /// Per-file: use path strings that resolved to files in the check set.
    resolved_use_paths: HashMap<PathBuf, HashSet<String>>,
    /// Per-file: `use` alias → trigger names the aliased module provides or
    /// emits. Aliases whose targets are outside the check set are absent.
    imported_triggers: HashMap<PathBuf, HashMap<String, HashSet<String>>>,
    /// Per-file: `use` alias → (imported entity/value type → declared field
    /// names). Lets a qualified `default alias/Type` literal be validated
    /// against the imported schema. Aliases whose targets are outside the check
    /// set are absent.
    imported_entity_fields: HashMap<PathBuf, HashMap<String, HashMap<String, HashSet<String>>>>,
    /// Per-file: names and triggers that more than one imported module could
    /// resolve, so unqualified references to them are ambiguous (issue #15).
    ambiguous_imports: HashMap<PathBuf, AmbiguousImports>,
}

/// Shared loop for commands that process multiple .allium files.
///
/// Parses all files first, builds the cross-module reference map, then
/// analyses each file with knowledge of which declarations are referenced
/// externally and which use paths resolved.
fn run_multi_file(
    command: &str,
    args: &[String],
    analyse_file: impl Fn(&Path, &str, &allium_parser::ParseResult, &SourceMap, &HashSet<String>, &HashSet<String>, &HashMap<String, HashSet<String>>, &HashMap<String, HashMap<String, HashSet<String>>>, &AmbiguousImports) -> FileResult,
) -> ExitCode {
    let files = resolve_files(args);
    if files.is_empty() {
        eprintln!("No .allium files found.");
        return ExitCode::from(2);
    }

    // Pass 1: parse all files.
    let mut parsed: Vec<ParsedFile> = Vec::new();
    let mut any_issues = false;

    for path in &files {
        let source = match std::fs::read_to_string(path) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{}: {e}", path.display());
                any_issues = true;
                continue;
            }
        };
        let result = allium_parser::parse(&source);
        parsed.push(ParsedFile {
            path: path.clone(),
            source,
            result,
        });
    }

    // Pass 2: build cross-module context.
    let ctx = build_cross_module_context(&parsed);

    // Pass 3: analyse each file with cross-module context.
    let no_ambiguity = AmbiguousImports::default();
    for pf in &parsed {
        let source_map = SourceMap::new(&pf.source);
        let key = canonical_key(&pf.path);
        let refs = ctx.external_refs.get(&key).cloned().unwrap_or_default();
        let use_paths = ctx.resolved_use_paths.get(&key).cloned().unwrap_or_default();
        let imports = ctx.imported_triggers.get(&key).cloned().unwrap_or_default();
        let imported_fields = ctx.imported_entity_fields.get(&key).cloned().unwrap_or_default();
        let ambiguous = ctx.ambiguous_imports.get(&key).unwrap_or(&no_ambiguity);
        let file_result = analyse_file(&pf.path, &pf.source, &pf.result, &source_map, &refs, &use_paths, &imports, &imported_fields, ambiguous);

        if file_result.has_issues {
            any_issues = true;
        }

        let output = serde_json::json!({
            "command": command,
            "spec_file": pf.path.display().to_string(),
            "diagnostics": file_result.diagnostics,
            "findings": file_result.findings,
        });

        println!("{}", serde_json::to_string_pretty(&output).unwrap());
    }

    if any_issues { ExitCode::from(1) } else { ExitCode::SUCCESS }
}

/// Build both cross-module maps by examining all parsed files.
fn build_cross_module_context(parsed: &[ParsedFile]) -> CrossModuleContext {
    // Set of canonical paths in the check set, for resolving use targets.
    let check_set: HashSet<PathBuf> = parsed
        .iter()
        .map(|pf| canonical_key(&pf.path))
        .collect();

    // Pre-compute each file's declared names so we can match unqualified
    // references against imported module declarations.
    let declared: HashMap<PathBuf, HashSet<String>> = parsed
        .iter()
        .map(|pf| {
            (
                canonical_key(&pf.path),
                allium_parser::collect_declared_names(&pf.result.module),
            )
        })
        .collect();

    // Pre-compute each file's provided/emitted trigger names so importing
    // files can resolve `alias/Trigger` subscriptions across the check set.
    let trigger_outputs: HashMap<PathBuf, HashSet<String>> = parsed
        .iter()
        .map(|pf| {
            (
                canonical_key(&pf.path),
                allium_parser::collect_trigger_outputs(&pf.result.module),
            )
        })
        .collect();

    // Pre-compute each file's entity/value type → field-name schema so importing
    // files can validate `default alias/Type = { ... }` literals against the
    // imported type's declared fields.
    let entity_field_outputs: HashMap<PathBuf, HashMap<String, HashSet<String>>> = parsed
        .iter()
        .map(|pf| {
            (
                canonical_key(&pf.path),
                allium_parser::collect_entity_field_schemas(&pf.result.module),
            )
        })
        .collect();

    let mut external_refs: HashMap<PathBuf, HashSet<String>> = HashMap::new();
    let mut resolved_use_paths: HashMap<PathBuf, HashSet<String>> = HashMap::new();
    let mut imported_triggers: HashMap<PathBuf, HashMap<String, HashSet<String>>> = HashMap::new();
    let mut imported_entity_fields: HashMap<
        PathBuf,
        HashMap<String, HashMap<String, HashSet<String>>>,
    > = HashMap::new();
    let mut ambiguous_imports: HashMap<PathBuf, AmbiguousImports> = HashMap::new();

    for pf in parsed {
        // For bare filenames (no directory component), parent() returns "".
        // Joining "" with a relative use path still works because canonicalize
        // resolves it against the process working directory.
        let base = pf.path.parent().unwrap_or(Path::new("."));
        let file_key = canonical_key(&pf.path);

        // Collect use declarations: alias → use-path string, and resolve each
        // against the check set. Also build alias → canonical target key.
        let mut aliases: HashMap<&str, String> = HashMap::new();
        let mut alias_targets: HashMap<&str, PathBuf> = HashMap::new();
        let mut resolved_for_file: HashSet<String> = HashSet::new();

        for d in &pf.result.module.declarations {
            if let allium_parser::ast::Decl::Use(u) = d {
                let path_text = u.path.text();
                let target = base.join(&path_text);
                let target_key = canonical_key(&target);

                if check_set.contains(&target_key) {
                    resolved_for_file.insert(path_text.clone());
                }

                if let Some(alias) = &u.alias {
                    alias_targets.insert(alias.name.as_str(), target_key);
                    aliases.insert(alias.name.as_str(), path_text);
                }
            }
        }

        // 1. Qualified references (core/InputEvent) and alias-member
        //    references (core.EntityMap) — both produce (qualifier, name)
        //    pairs from collect_qualified_references.
        let qrefs = allium_parser::collect_qualified_references(&pf.result.module);
        for (qualifier, name) in &qrefs {
            if let Some(target_key) = alias_targets.get(qualifier.as_str()) {
                external_refs.entry(target_key.clone()).or_default().insert(name.clone());
            }
        }

        // 2. Unqualified references — any uppercase ident used in this file
        //    that matches a declaration in an imported module. This covers
        //    bare entity names in rule bodies and type names in contract
        //    signatures. Subtract locally-declared names first so that a
        //    local declaration doesn't spuriously suppress a same-named
        //    declaration in an imported module.
        let all_idents = allium_parser::collect_all_referenced_idents(&pf.result.module);
        let local_names = allium_parser::collect_declared_names(&pf.result.module);
        let imported_idents: HashSet<&String> = all_idents.difference(&local_names).collect();
        for target_key in alias_targets.values() {
            if let Some(target_decls) = declared.get(target_key) {
                for name in &imported_idents {
                    if target_decls.contains(name.as_str()) {
                        external_refs.entry(target_key.clone()).or_default().insert((*name).clone());
                    }
                }
            }
        }

        // 3. Imported triggers — for each alias whose target is in the check
        //    set, the trigger names the target module provides or emits.
        let mut imported_for_file: HashMap<String, HashSet<String>> = HashMap::new();
        for (alias, target_key) in &alias_targets {
            if let Some(triggers) = trigger_outputs.get(target_key) {
                imported_for_file.insert((*alias).to_string(), triggers.clone());
            }
        }
        imported_triggers.insert(file_key.clone(), imported_for_file);

        // 3b. Imported entity field schemas — for each alias whose target is in
        //     the check set, that module's entity/value type → field names.
        let mut imported_fields_for_file: HashMap<String, HashMap<String, HashSet<String>>> =
            HashMap::new();
        for (alias, target_key) in &alias_targets {
            if let Some(fields) = entity_field_outputs.get(target_key) {
                imported_fields_for_file.insert((*alias).to_string(), fields.clone());
            }
        }
        imported_entity_fields.insert(file_key.clone(), imported_fields_for_file);

        // 4. Ambiguous imports — names declared, and triggers provided or
        //    emitted, by more than one distinct imported file. Keyed by
        //    distinct target so that two aliases for the same file are not
        //    counted as ambiguous (issue #15).
        let mut name_sources: HashMap<&String, BTreeMap<&PathBuf, &str>> = HashMap::new();
        let mut trigger_sources: HashMap<&String, BTreeMap<&PathBuf, &str>> = HashMap::new();
        for (alias, target_key) in &alias_targets {
            if let Some(decls) = declared.get(target_key) {
                for name in decls {
                    let by_target = name_sources.entry(name).or_default();
                    let entry = by_target.entry(target_key).or_insert(alias);
                    if *alias < *entry {
                        *entry = alias;
                    }
                }
            }
            if let Some(triggers) = trigger_outputs.get(target_key) {
                for name in triggers {
                    let by_target = trigger_sources.entry(name).or_default();
                    let entry = by_target.entry(target_key).or_insert(alias);
                    if *alias < *entry {
                        *entry = alias;
                    }
                }
            }
        }
        let collapse = |sources: HashMap<&String, BTreeMap<&PathBuf, &str>>| -> HashMap<String, Vec<String>> {
            sources
                .into_iter()
                .filter(|(_, by_target)| by_target.len() >= 2)
                .map(|(name, by_target)| {
                    let mut aliases: Vec<String> =
                        by_target.values().map(|a| a.to_string()).collect();
                    aliases.sort();
                    (name.clone(), aliases)
                })
                .collect()
        };
        ambiguous_imports.insert(
            file_key.clone(),
            AmbiguousImports {
                names: collapse(name_sources),
                triggers: collapse(trigger_sources),
            },
        );

        resolved_use_paths.insert(file_key, resolved_for_file);
    }

    CrossModuleContext {
        external_refs,
        resolved_use_paths,
        imported_triggers,
        imported_entity_fields,
        ambiguous_imports,
    }
}

/// Normalise a path for use as a map key. Uses canonicalize when possible,
/// falls back to the raw path. This assumes that all files in a single check
/// invocation will either all canonicalise successfully or all fail — if some
/// canonicalise and others don't (e.g. broken symlinks), the same underlying
/// file could produce different keys and cross-module lookups would miss.
fn canonical_key(path: &Path) -> PathBuf {
    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
}

fn cmd_check(args: &[String]) -> ExitCode {
    run_multi_file("check", args, |path, source, result, source_map, external_refs, resolved_use_paths, imported_triggers, imported_entity_fields, ambiguous_imports| {
        let analysis = allium_parser::analyze_with_cross_module(&result.module, source, external_refs, resolved_use_paths, imported_triggers, imported_entity_fields, ambiguous_imports);
        let diagnostics: Vec<serde_json::Value> = result
            .diagnostics
            .iter()
            .chain(analysis.iter())
            .map(|d| diagnostic_to_json(d, path, source_map))
            .collect();
        let has_issues = diagnostics.iter().any(|d| {
            d["severity"] == "error" || d["severity"] == "warning"
        });
        FileResult { diagnostics, findings: vec![], has_issues }
    })
}

fn cmd_analyse(args: &[String]) -> ExitCode {
    run_multi_file("analyse", args, |path, source, result, source_map, external_refs, resolved_use_paths, imported_triggers, imported_entity_fields, ambiguous_imports| {
        let analyse_result = allium_parser::analyse_with_cross_module(&result.module, source, external_refs, resolved_use_paths, imported_triggers, imported_entity_fields, ambiguous_imports);
        let diagnostics: Vec<serde_json::Value> = result
            .diagnostics
            .iter()
            .chain(analyse_result.diagnostics.iter())
            .map(|d| diagnostic_to_json(d, path, source_map))
            .collect();
        let has_issues = !analyse_result.findings.is_empty();
        FileResult { diagnostics, findings: analyse_result.findings, has_issues }
    })
}

// ---------------------------------------------------------------------------
// Single-file commands: parse, plan, model
// ---------------------------------------------------------------------------

/// Shared handler for commands that take a single .allium file, parse it, and
/// print a JSON-serialisable result.
fn run_single_file(
    usage: &str,
    args: &[String],
    transform: impl FnOnce(&allium_parser::Module, &str) -> serde_json::Value,
) -> ExitCode {
    if args.len() != 1 {
        eprintln!("Usage: {usage}");
        return ExitCode::from(2);
    }

    let path = Path::new(&args[0]);
    let source = match std::fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{}: {e}", path.display());
            return ExitCode::from(1);
        }
    };

    let result = allium_parser::parse(&source);
    let output = transform(&result.module, &source);
    println!("{}", serde_json::to_string_pretty(&output).unwrap());
    ExitCode::SUCCESS
}

fn cmd_parse(args: &[String]) -> ExitCode {
    // Parse is slightly different: it serialises the full ParseResult, not a
    // transform of the module. Keep it inline rather than forcing it through
    // run_single_file.
    if args.len() != 1 {
        eprintln!("Usage: allium parse <file.allium>");
        return ExitCode::from(2);
    }

    let path = Path::new(&args[0]);
    let source = match std::fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) => {
            eprintln!("{}: {e}", path.display());
            return ExitCode::from(1);
        }
    };

    let result = allium_parser::parse(&source);
    println!("{}", serde_json::to_string_pretty(&result).unwrap());
    ExitCode::SUCCESS
}

fn cmd_plan(args: &[String]) -> ExitCode {
    run_single_file("allium plan <file.allium>", args, |module, source| {
        let plan = test_plan::generate_test_plan(module, source);
        serde_json::to_value(plan).unwrap()
    })
}

fn cmd_model(args: &[String]) -> ExitCode {
    run_single_file("allium model <file.allium>", args, |module, source| {
        let model = domain_model::extract_domain_model(module, source);
        serde_json::to_value(model).unwrap()
    })
}

// ---------------------------------------------------------------------------
// Shared helpers
// ---------------------------------------------------------------------------

fn diagnostic_to_json(
    d: &allium_parser::Diagnostic,
    path: &Path,
    source_map: &SourceMap,
) -> serde_json::Value {
    let (line, col) = source_map.line_col(d.span.start);
    let severity = match d.severity {
        Severity::Error => "error",
        Severity::Warning => "warning",
        Severity::Info => "info",
    };
    serde_json::json!({
        "code": d.code,
        "severity": severity,
        "message": d.message,
        "location": {
            "file": path.display().to_string(),
            "line": line + 1,
            "col": col + 1,
        }
    })
}

fn resolve_files(args: &[String]) -> Vec<PathBuf> {
    let mut files = Vec::new();
    for arg in args {
        let path = Path::new(arg);
        if path.is_dir() {
            collect_allium_files(path, &mut files);
        } else if path.extension().is_some_and(|e| e == "allium") {
            files.push(path.to_path_buf());
        } else {
            // Try as-is (might be a glob pattern the shell expanded)
            files.push(path.to_path_buf());
        }
    }
    files
}

fn collect_allium_files(dir: &Path, out: &mut Vec<PathBuf>) {
    let entries = match std::fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return,
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            collect_allium_files(&path, out);
        } else if path.extension().is_some_and(|e| e == "allium") {
            out.push(path);
        }
    }
}