panproto-cli 0.39.0

Schematic version control CLI for panproto
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
//! Theory DSL CLI commands.

use std::path::Path;

use miette::Result;

/// Validate a theory document (load + typecheck).
pub fn cmd_theory_validate(file: &Path, verbose: bool) -> Result<()> {
    let resolver = panproto_theory_dsl::builtin_resolver();
    let doc = panproto_theory_dsl::load(file).map_err(|e| miette::miette!("{e}"))?;

    if verbose {
        eprintln!("loaded document: {}", doc.id);
    }

    let compiled =
        panproto_theory_dsl::compile(&doc, &resolver).map_err(|e| miette::miette!("{e}"))?;

    eprintln!(
        "valid: {} theories, {} morphisms, {} protocols",
        compiled.theories.len(),
        compiled.morphisms.len(),
        compiled.protocols.len(),
    );
    Ok(())
}

/// Compile a theory document and print resulting theory names as JSON.
pub fn cmd_theory_compile(file: &Path, json: bool, verbose: bool) -> Result<()> {
    let resolver = panproto_theory_dsl::builtin_resolver();
    let doc = panproto_theory_dsl::load(file).map_err(|e| miette::miette!("{e}"))?;
    let compiled =
        panproto_theory_dsl::compile(&doc, &resolver).map_err(|e| miette::miette!("{e}"))?;

    // Theory, morphism, protocol, and composition maps are `HashMap`s
    // keyed on name; iterate in a sorted order so CLI output (both
    // human-readable and JSON) is byte-stable across runs.
    let mut theory_names: Vec<&String> = compiled.theories.keys().collect();
    theory_names.sort();
    let mut morphism_names: Vec<&String> = compiled.morphisms.keys().collect();
    morphism_names.sort();
    let mut protocol_names: Vec<&String> = compiled.protocols.keys().collect();
    protocol_names.sort();
    let mut composition_names: Vec<&String> = compiled.composition_specs.keys().collect();
    composition_names.sort();

    if json {
        let summary = serde_json::json!({
            "id": compiled.id,
            "theories": theory_names,
            "morphisms": morphism_names,
            "protocols": protocol_names,
            "compositions": composition_names,
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&summary).map_err(|e| miette::miette!("{e}"))?
        );
    } else {
        println!("Document: {}", compiled.id);
        for name in &theory_names {
            let theory = &compiled.theories[*name];
            println!(
                "  theory {name}: {} sorts, {} ops, {} eqs",
                theory.sorts.len(),
                theory.ops.len(),
                theory.eqs.len(),
            );
            if verbose {
                for sort in &theory.sorts {
                    println!("    sort {}", sort.name);
                }
                for op in &theory.ops {
                    println!("    op {} : arity {}", op.name, op.arity());
                }
            }
        }
        for name in &morphism_names {
            println!("  morphism {name}");
        }
        for name in &protocol_names {
            println!("  protocol {name}");
        }
    }
    Ok(())
}

/// Compile all theory documents in a directory.
pub fn cmd_theory_compile_dir(dir: &Path, verbose: bool) -> Result<()> {
    let result = panproto_theory_dsl::load_dir(dir).map_err(|e| miette::miette!("{e}"))?;
    let resolver = panproto_theory_dsl::builtin_resolver();

    let mut total_theories = 0usize;
    let mut total_morphisms = 0usize;
    let mut total_protocols = 0usize;

    for doc in &result.documents {
        match panproto_theory_dsl::compile(doc, &resolver) {
            Ok(compiled) => {
                total_theories += compiled.theories.len();
                total_morphisms += compiled.morphisms.len();
                total_protocols += compiled.protocols.len();
                if verbose {
                    eprintln!("compiled {}: {:?}", doc.id, compiled);
                }
            }
            Err(e) => {
                eprintln!("error compiling {}: {e}", doc.id);
            }
        }
    }

    for (path, err) in &result.errors {
        eprintln!("error loading {}: {err}", path.display());
    }

    println!(
        "compiled {} documents: {total_theories} theories, {total_morphisms} morphisms, {total_protocols} protocols",
        result.documents.len(),
    );
    Ok(())
}

/// Validate a morphism document.
pub fn cmd_theory_check_morphism(file: &Path, verbose: bool) -> Result<()> {
    let resolver = panproto_theory_dsl::builtin_resolver();
    let doc = panproto_theory_dsl::load(file).map_err(|e| miette::miette!("{e}"))?;

    if verbose {
        eprintln!("loaded document: {}", doc.id);
    }

    let compiled =
        panproto_theory_dsl::compile(&doc, &resolver).map_err(|e| miette::miette!("{e}"))?;

    if compiled.morphisms.is_empty() {
        eprintln!("warning: no morphisms in document");
    } else {
        // `compiled.morphisms` is a `HashMap`; sort by name so the
        // verbose report is byte-stable across runs.
        let mut names: Vec<&String> = compiled.morphisms.keys().collect();
        names.sort();
        for name in names {
            eprintln!("morphism '{name}' is valid");
        }
    }
    Ok(())
}

/// Replay a composition and print the result.
pub fn cmd_theory_recompose(file: &Path, verbose: bool) -> Result<()> {
    let resolver = panproto_theory_dsl::builtin_resolver();
    let doc = panproto_theory_dsl::load(file).map_err(|e| miette::miette!("{e}"))?;
    let compiled =
        panproto_theory_dsl::compile(&doc, &resolver).map_err(|e| miette::miette!("{e}"))?;

    // Iterate in sorted name order so output is stable across runs.
    let mut theory_names: Vec<&String> = compiled.theories.keys().collect();
    theory_names.sort();
    for name in &theory_names {
        let theory = &compiled.theories[*name];
        println!(
            "theory {name}: {} sorts, {} ops, {} eqs",
            theory.sorts.len(),
            theory.ops.len(),
            theory.eqs.len(),
        );
        if verbose {
            for sort in &theory.sorts {
                println!("  sort {}", sort.name);
            }
            for op in &theory.ops {
                println!("  op {} : arity {}", op.name, op.arity());
            }
        }
    }

    let mut composition_names: Vec<&String> = compiled.composition_specs.keys().collect();
    composition_names.sort();
    if let Some(name) = composition_names.first() {
        let spec = &compiled.composition_specs[*name];
        println!("composition '{name}': {} steps", spec.steps.len());
    }
    Ok(())
}

/// Run sample-based coercion law checks over every directed
/// equation in every theory compiled from `file`.
///
/// Non-zero exit status on any violation; clean (exit 0) otherwise.
pub fn cmd_theory_check_coercion_laws(
    file: &Path,
    json: bool,
    verbose: bool,
    var_name: &str,
) -> Result<()> {
    use panproto_core::lens::coercion_laws::{
        CoercionSampleRegistry, TheoryCoercionReport, check_theory_with_var,
    };

    let resolver = panproto_theory_dsl::builtin_resolver();
    let doc = panproto_theory_dsl::load(file).map_err(|e| miette::miette!("{e}"))?;
    let compiled =
        panproto_theory_dsl::compile(&doc, &resolver).map_err(|e| miette::miette!("{e}"))?;

    let registry = CoercionSampleRegistry::with_defaults();
    // Compile's `theories` is a `HashMap`; iterate in sorted name order
    // so reports (and the emitted JSON / text output) are byte-stable
    // across runs.
    let mut theory_names: Vec<&String> = compiled.theories.keys().collect();
    theory_names.sort();
    let mut reports: Vec<(String, TheoryCoercionReport)> = Vec::new();
    for name in &theory_names {
        let theory = &compiled.theories[*name];
        let report = check_theory_with_var(theory, &registry, var_name);
        reports.push(((*name).clone(), report));
    }

    let total_violations: usize = reports.iter().map(|(_, r)| r.violation_count()).sum();
    let clean = total_violations == 0;

    if json {
        let payload = serde_json::json!({
            "document": compiled.id,
            "clean": clean,
            "total_violations": total_violations,
            "theories": reports.iter().map(|(name, report)| {
                serde_json::json!({
                    "name": name,
                    "clean": report.is_clean(),
                    "violation_count": report.violation_count(),
                    "equations": report.per_equation.iter().map(|(eq_name, violations)| {
                        // Serialize structured `CoercionLawViolation`
                        // values directly rather than stringifying via
                        // `Debug`. Keeps the `kind` tag and payload
                        // fields machine-readable for downstream
                        // consumers.
                        let vs: Vec<serde_json::Value> = violations.iter()
                            .map(|v| serde_json::to_value(v)
                                .unwrap_or_else(|e| serde_json::json!({
                                    "kind": "SerializationError",
                                    "error": e.to_string(),
                                    "debug": format!("{v:?}"),
                                })))
                            .collect();
                        serde_json::json!({
                            "name": eq_name.as_ref(),
                            "violations": vs,
                        })
                    }).collect::<Vec<_>>(),
                })
            }).collect::<Vec<_>>(),
        });
        println!(
            "{}",
            serde_json::to_string_pretty(&payload).map_err(|e| miette::miette!("{e}"))?
        );
    } else {
        println!("Document: {}", compiled.id);
        for (name, report) in &reports {
            if report.is_clean() {
                println!(
                    "  theory {name}: clean ({} equations checked)",
                    report.per_equation.len()
                );
                if verbose {
                    for (eq, _) in &report.per_equation {
                        println!("    equation {eq}: ok");
                    }
                }
            } else {
                println!(
                    "  theory {name}: {} violation(s) across {} equation(s)",
                    report.violation_count(),
                    report.per_equation.len(),
                );
                for (eq, violations) in &report.per_equation {
                    if !violations.is_empty() {
                        println!("    equation {eq}: {} violation(s)", violations.len());
                        for v in violations {
                            println!("      {v:?}");
                        }
                    }
                }
            }
        }
        if clean {
            let n = reports.len();
            let msg = match n {
                0 => "No theories to check.".to_owned(),
                1 => "All 1 theory clean.".to_owned(),
                _ => format!("All {n} theories clean."),
            };
            println!("{msg}");
        } else {
            println!("Total violations: {total_violations}");
            if let Some(suggested) = suggest_var_name_from_reports(&reports, var_name) {
                println!(
                    "hint: every equation errored on unbound variable '{suggested}'; \
                     pass --var-name {suggested} to override the default '{var_name}'"
                );
            }
        }
    }

    if clean {
        Ok(())
    } else {
        // The report printed above already summarises the failure
        // ("Total violations: N"). Return an un-rendered error so the
        // user sees one diagnostic (the printed report), not two
        // (report plus a redundant miette bail message). The non-zero
        // exit status still propagates via the `Err` return.
        Err(miette::miette!("coercion law violation(s) detected"))
    }
}

/// Inspect the per-theory reports for the "unbound variable X"
/// anti-pattern. Returns the suggested name when at least 75% of
/// violations are eval errors that name the same unbound variable
/// (and that variable is not the current `var_name`); otherwise
/// returns `None`.
///
/// The ratio is deliberately loose so a single unrelated violation
/// (e.g. one genuine `Backward` law failure) does not suppress the
/// hint when the dominant signal is still "every equation is using
/// the wrong free variable".
fn suggest_var_name_from_reports(
    reports: &[(
        String,
        panproto_core::lens::coercion_laws::TheoryCoercionReport,
    )],
    current_var: &str,
) -> Option<String> {
    use panproto_core::lens::coercion_laws::CoercionLawViolation;

    let mut total: usize = 0;
    let mut matching: usize = 0;
    let mut suggested: Option<String> = None;
    for (_, report) in reports {
        for (_, violations) in &report.per_equation {
            for v in violations {
                total += 1;
                let (CoercionLawViolation::ForwardEvalError { error, .. }
                | CoercionLawViolation::InverseEvalError { error, .. }) = v
                else {
                    continue;
                };
                let Some(name) = extract_unbound_variable_name(error) else {
                    continue;
                };
                match &suggested {
                    None => {
                        suggested = Some(name);
                        matching += 1;
                    }
                    Some(existing) if existing == &name => {
                        matching += 1;
                    }
                    // A different unbound-variable name was seen. The
                    // extracted name is no longer unanimous among
                    // matching violations; bail out rather than emit
                    // an ambiguous hint.
                    Some(_) => return None,
                }
            }
        }
    }
    if total == 0 {
        return None;
    }
    // Require at least 75% of all violations to be matching
    // unbound-variable eval errors sharing the same name. Integer
    // comparison: `4 * matching >= 3 * total` avoids floating point.
    if matching.saturating_mul(4) < total.saturating_mul(3) {
        return None;
    }
    let name = suggested?;
    if name == current_var {
        return None;
    }
    Some(name)
}

/// Parse an error message of the form `"unbound variable <name>"` and
/// return `<name>` when the pattern matches. Trims surrounding quotes
/// and whitespace from the extracted name.
fn extract_unbound_variable_name(error: &str) -> Option<String> {
    let marker = "unbound variable";
    let idx = error.find(marker)?;
    let rest = &error[idx + marker.len()..];
    let rest = rest.trim_start_matches([' ', ':', '`', '\'', '"']);
    let end = rest
        .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
        .unwrap_or(rest.len());
    let name = &rest[..end];
    if name.is_empty() {
        None
    } else {
        Some(name.to_owned())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use panproto_core::lens::coercion_laws::{CoercionLawViolation, TheoryCoercionReport};
    use panproto_expr::Literal;
    use std::sync::Arc;

    fn eval_err(name: &str) -> CoercionLawViolation {
        CoercionLawViolation::ForwardEvalError {
            input: Literal::Str("probe".to_owned()),
            error: format!("unbound variable: {name}"),
        }
    }

    fn backward_err() -> CoercionLawViolation {
        CoercionLawViolation::Backward {
            input: Literal::Str("a".to_owned()),
            forward_result: Literal::Str("A".to_owned()),
            round_tripped: Literal::Str("A".to_owned()),
        }
    }

    fn single_report(violations: Vec<CoercionLawViolation>) -> Vec<(String, TheoryCoercionReport)> {
        let report = TheoryCoercionReport {
            per_equation: vec![(Arc::from("eq"), violations)],
        };
        vec![("T".to_owned(), report)]
    }

    #[test]
    fn hint_fires_when_one_backward_and_five_unbound() {
        let mut vs = vec![backward_err()];
        for _ in 0..5 {
            vs.push(eval_err("v"));
        }
        let reports = single_report(vs);
        // 5/6 ≈ 83% are matching; above the 75% threshold.
        assert_eq!(
            suggest_var_name_from_reports(&reports, "x"),
            Some("v".to_owned()),
        );
    }

    #[test]
    fn hint_suppressed_when_one_unbound_and_six_backward() {
        let mut vs = vec![eval_err("v")];
        for _ in 0..6 {
            vs.push(backward_err());
        }
        let reports = single_report(vs);
        // 1/7 ≈ 14%; well below the 75% threshold.
        assert_eq!(suggest_var_name_from_reports(&reports, "x"), None);
    }

    #[test]
    fn hint_suppressed_when_names_disagree() {
        let vs = vec![eval_err("v"), eval_err("w"), eval_err("v"), eval_err("v")];
        let reports = single_report(vs);
        assert_eq!(suggest_var_name_from_reports(&reports, "x"), None);
    }

    #[test]
    fn hint_suppressed_when_suggested_equals_current() {
        let vs = vec![eval_err("x"), eval_err("x"), eval_err("x"), eval_err("x")];
        let reports = single_report(vs);
        assert_eq!(suggest_var_name_from_reports(&reports, "x"), None);
    }

    #[test]
    fn hint_suppressed_when_no_violations() {
        let reports: Vec<(String, TheoryCoercionReport)> = Vec::new();
        assert_eq!(suggest_var_name_from_reports(&reports, "x"), None);
    }
}