shifty-algebra 0.1.8

Core SHACL formalism IR: path algebra, shape grammar, selectors, schema, and reference semantics
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
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
//! Human-readable rendering of the IR for debugging (`shacl inspect`).
//!
//! Shapes form a graph, so we render a **flat arena dump**: one line per arena
//! slot, `@i = <φ>`, with child shapes referenced as `@j`. This is unambiguous,
//! cycle-proof, and shows sharing — exactly what you want when inspecting how a
//! lowering produced the IR. Paths and value types (which are trees) render
//! inline in the formalism's notation.

use crate::path::Path;
use crate::schema::Schema;
use crate::selector::Selector;
use crate::shape::{Shape, ShapeArena, ShapeId};
use crate::term::{NodeKindSet, Term};
use crate::value_type::{Bound, ValueType};
use std::collections::BTreeSet;

/// Render a whole schema as a flat, cycle-safe text dump. Only shapes reachable
/// from the statements/rules are shown (intermediate arena slots are elided);
/// the header reports `reachable/total`.
pub fn schema_to_text(schema: &Schema) -> String {
    let reachable = reachable_shapes(schema);
    let mut out = String::new();
    out.push_str(&format!(
        "schema: {} statement(s), {} rule(s), {}/{} shape(s)\n",
        schema.statements.len(),
        schema.rules.len(),
        reachable.len(),
        schema.arena.len()
    ));

    out.push_str("shapes:\n");
    for id in &reachable {
        let name_suffix = schema
            .names
            .get(id)
            .map(|iri| format!("  # {}", compact(iri)))
            .unwrap_or_default();
        out.push_str(&format!(
            "  @{} = {}{}\n",
            id.0,
            shape_def(&schema.arena, *id),
            name_suffix
        ));
    }

    if !schema.statements.is_empty() {
        out.push_str("statements:\n");
        for st in &schema.statements {
            out.push_str(&format!(
                "  {}{}\n",
                selector_to_string(&st.selector),
                child(&schema.arena, st.shape)
            ));
        }
    }

    if !schema.rules.is_empty() {
        out.push_str("rules:\n");
        for r in &schema.rules {
            let conds: Vec<String> = r
                .conditions
                .iter()
                .map(|c| child(&schema.arena, *c))
                .collect();
            out.push_str(&format!(
                "  on {} [if {}] order={} {}{}\n",
                selector_to_string(&r.selector),
                if conds.is_empty() {
                    "·".into()
                } else {
                    conds.join(", ")
                },
                r.order.unwrap_or(0),
                if r.deactivated { "(deactivated)" } else { "" },
                rule_head_to_string(&r.head),
            ));
        }
    }

    out
}

fn rule_head_to_string(head: &crate::rule::RuleHead) -> String {
    use crate::rule::RuleHead;
    match head {
        RuleHead::Triple {
            subject,
            predicate,
            object,
        } => format!(
            "+({}, {}, {})",
            node_expr_to_string(subject),
            node_expr_to_string(predicate),
            node_expr_to_string(object),
        ),
        RuleHead::Sparql(_) => "construct{…}".to_string(),
    }
}

fn node_expr_to_string(e: &crate::expr::NodeExpr) -> String {
    use crate::expr::NodeExpr;
    match e {
        NodeExpr::This => "this".to_string(),
        NodeExpr::Constant(t) => term_to_string(t),
        NodeExpr::Path(p) => path_to_string(p),
        NodeExpr::Filter { input, shape } => {
            format!("filter({}, @{})", node_expr_to_string(input), shape.0)
        }
        NodeExpr::Intersection(es) => es
            .iter()
            .map(node_expr_to_string)
            .collect::<Vec<_>>()
            .join(""),
        NodeExpr::Union(es) => es
            .iter()
            .map(node_expr_to_string)
            .collect::<Vec<_>>()
            .join(""),
        NodeExpr::Function { iri, args } => format!(
            "{}({})",
            compact(iri.as_str()),
            args.iter()
                .map(node_expr_to_string)
                .collect::<Vec<_>>()
                .join(", ")
        ),
    }
}

/// A reference to a child shape: `⊤` is inlined (it carries no information),
/// everything else prints as its slot label.
fn child(arena: &ShapeArena, id: ShapeId) -> String {
    match arena.get(id) {
        Shape::Top => "".to_string(),
        _ => format!("@{}", id.0),
    }
}

/// Shapes reachable from the schema's statements and rules, following shape
/// references through selectors and shape children.
fn reachable_shapes(schema: &Schema) -> BTreeSet<ShapeId> {
    let mut stack: Vec<ShapeId> = Vec::new();
    for st in &schema.statements {
        stack.push(st.shape);
        stack.extend(selector_shapes(&st.selector));
    }
    for r in &schema.rules {
        stack.extend(r.conditions.iter().copied());
        stack.extend(selector_shapes(&r.selector));
    }
    let mut seen = BTreeSet::new();
    while let Some(id) = stack.pop() {
        if seen.insert(id) {
            stack.extend(shape_children(schema.arena.get(id)));
        }
    }
    seen
}

fn shape_children(shape: &Shape) -> Vec<ShapeId> {
    match shape {
        Shape::Annotated { shape, .. } => vec![*shape],
        Shape::Not(c) => vec![*c],
        Shape::And(cs) | Shape::Or(cs) => cs.clone(),
        Shape::Count { qualifier, .. } => vec![*qualifier],
        _ => Vec::new(),
    }
}

fn selector_shapes(sel: &Selector) -> Vec<ShapeId> {
    match sel {
        Selector::HasPath(_, id) => vec![*id],
        _ => Vec::new(),
    }
}

fn shape_def(arena: &ShapeArena, id: ShapeId) -> String {
    match arena.get(id) {
        Shape::Annotated { severity, shape } => {
            format!("severity({}, {})", severity, child(arena, *shape))
        }
        Shape::Top => "".to_string(),
        Shape::Pending => "⟨pending⟩".to_string(),
        Shape::TestConst(t) => format!("test({})", term_to_string(t)),
        Shape::TestType(vt) => format!("test({})", value_type_to_string(vt)),
        Shape::TestKind(k) => format!("nodeKind({})", node_kinds_to_string(k)),
        Shape::Closed(q) => {
            let preds: Vec<String> = q.iter().map(|n| compact(n.as_str())).collect();
            format!("closed{{{}}}", preds.join(", "))
        }
        Shape::Eq(p, pred) => format!("eq({}, {})", path_to_string(p), compact(pred.as_str())),
        Shape::Disj(p, pred) => format!("disj({}, {})", path_to_string(p), compact(pred.as_str())),
        Shape::Lt(p, pred) => format!("lt({}, {})", path_to_string(p), compact(pred.as_str())),
        Shape::Le(p, pred) => format!("le({}, {})", path_to_string(p), compact(pred.as_str())),
        Shape::UniqueLang(p) => format!("uniqueLang({})", path_to_string(p)),
        Shape::Not(c) => format!("¬{}", child(arena, *c)),
        Shape::And(cs) => join_children(arena, cs, ""),
        Shape::Or(cs) => join_children(arena, cs, ""),
        Shape::Count {
            path,
            min,
            max,
            qualifier,
        } => {
            let lo = min.map(|n| n.to_string()).unwrap_or_default();
            let hi = max.map(|n| n.to_string()).unwrap_or_default();
            format!(
                "∃[{lo}..{hi}] {} . {}",
                path_to_string(path),
                child(arena, *qualifier)
            )
        }
        Shape::Sparql(c) => format!("sparql({:?}){{}}", c.kind),
    }
}

fn join_children(arena: &ShapeArena, cs: &[ShapeId], sep: &str) -> String {
    if cs.is_empty() {
        return "()".to_string();
    }
    cs.iter()
        .map(|c| child(arena, *c))
        .collect::<Vec<_>>()
        .join(sep)
}

/// Render a single shape (its top-level form; children as `@id`). Useful for
/// constraint messages in validation reports.
pub fn shape_to_string(arena: &ShapeArena, id: ShapeId) -> String {
    shape_def(arena, id)
}

/// A fully-expanded, human-readable description of a shape for repair-hole
/// display: every child shape is inlined recursively (no bare `@id` slot
/// references), the `sh:class` encoding is named `instance of C`, and leaves
/// render in the formalism's notation. Recursive shapes are cut at a fixed depth,
/// falling back to the slot label `@id`. Prefer this over [`shape_to_string`] when
/// the reader wants the *whole* constraint, not a one-level form with pointers.
pub fn describe_shape(arena: &ShapeArena, id: ShapeId) -> String {
    describe_shape_within(arena, id, 8)
}

/// Join the descriptions of several shapes a value must *all* satisfy with “and”
/// — the rendering of a conjunction held as separate shapes (e.g. a `ConformsToAll`
/// hole). Each member is itself fully expanded via [`describe_shape`].
pub fn describe_shapes(arena: &ShapeArena, ids: &[ShapeId]) -> String {
    if ids.is_empty() {
        return "any node".to_string();
    }
    ids.iter()
        .map(|id| describe_shape(arena, *id))
        .collect::<Vec<_>>()
        .join(" and ")
}

fn describe_shape_within(arena: &ShapeArena, id: ShapeId, depth: u8) -> String {
    // ∃≥1 (rdf:type/rdfs:subClassOf*).test(C) — the encoding of sh:class C.
    if let Some(class) = class_target_shape(id, arena) {
        return format!("instance of {}", term_to_string(&class));
    }
    match arena.get(id) {
        Shape::Top | Shape::Pending => "any node".to_string(),
        // Past the depth budget, name the slot rather than risk a recursive shape.
        _ if depth == 0 => format!("@{}", id.0),
        // sh:severity is transparent — describe the wrapped shape.
        Shape::Annotated { shape, .. } => describe_shape_within(arena, *shape, depth - 1),
        Shape::Not(c) => format!("not ({})", describe_shape_within(arena, *c, depth - 1)),
        Shape::And(cs) => join_describe(arena, cs, " and ", depth),
        Shape::Or(cs) => join_describe(arena, cs, " or ", depth),
        Shape::Count {
            path,
            min,
            max,
            qualifier,
        } => {
            let lo = min.map(|n| n.to_string()).unwrap_or_default();
            let hi = max.map(|n| n.to_string()).unwrap_or_default();
            let q = describe_shape_within(arena, *qualifier, depth - 1);
            format!("∃[{lo}..{hi}] {} . {q}", path_to_string(path))
        }
        // Every remaining variant is a leaf with no child shapes: its one-level
        // formal rendering is already fully expanded.
        _ => shape_def(arena, id),
    }
}

/// Render each child for an `And`/`Or`, parenthesizing nested boolean
/// combinations so the joined string reads unambiguously.
fn join_describe(arena: &ShapeArena, cs: &[ShapeId], sep: &str, depth: u8) -> String {
    if cs.is_empty() {
        return "()".to_string();
    }
    cs.iter()
        .map(|c| {
            let d = describe_shape_within(arena, *c, depth - 1);
            match arena.get(*c) {
                Shape::And(_) | Shape::Or(_) => format!("({d})"),
                _ => d,
            }
        })
        .collect::<Vec<_>>()
        .join(sep)
}

pub fn selector_to_string(sel: &Selector) -> String {
    match sel {
        Selector::HasOut(q) => format!("{} .⊤", compact(q.as_str())),
        Selector::HasIn(q) => format!("{}⁻ .⊤", compact(q.as_str())),
        Selector::IsConst(t) => format!("node({})", term_to_string(t)),
        Selector::HasPath(p, _) => format!("∃≥1 {} . φ", path_to_string(p)),
        Selector::Sparql(_) => "sparql{…}".to_string(),
    }
}

/// Like [`selector_to_string`], but resolves a path selector's qualifier against
/// `arena`: class targets render as `class(C)`, and any other path target shows
/// its actual qualifier shape instead of a bare `φ`. Prefer this whenever the
/// arena is in hand — the resolved form is far more useful for debugging.
pub fn selector_to_string_in(sel: &Selector, arena: &ShapeArena) -> String {
    if let Some(class) = class_target(sel, arena) {
        return format!("class({})", term_to_string(class));
    }
    match sel {
        Selector::HasPath(p, q) => {
            format!("∃≥1 {} . {}", path_to_string(p), shape_def(arena, *q))
        }
        other => selector_to_string(other),
    }
}

/// If `sel` targets a class — the `∃≥1 rdf:type/rdfs:subClassOf* . test(C)` form
/// that `sh:targetClass` and implicit class targets lower to — the class term
/// `C`. `None` for every other selector.
pub fn class_target<'a>(sel: &'a Selector, arena: &'a ShapeArena) -> Option<&'a Term> {
    let Selector::HasPath(path, qualifier) = sel else {
        return None;
    };
    if !is_class_path(path) {
        return None;
    }
    match arena.get(*qualifier) {
        Shape::TestConst(class) => Some(class),
        _ => None,
    }
}

/// If `id` is a `∃≥1 (rdf:type/rdfs:subClassOf*).test(C)` shape (the encoding
/// of `sh:class C`), return `C`. `None` for all other shapes.
pub fn class_target_shape(id: ShapeId, arena: &ShapeArena) -> Option<Term> {
    let Shape::Count {
        ref path,
        min: Some(1),
        max: None,
        qualifier,
    } = arena.get(id).clone()
    else {
        return None;
    };
    if !is_class_path(path) {
        return None;
    }
    if let Shape::TestConst(c) = arena.get(qualifier).clone() {
        Some(c)
    } else {
        None
    }
}

/// Is `p` the `rdf:type/rdfs:subClassOf*` path used to encode class targeting?
fn is_class_path(p: &Path) -> bool {
    const RDF_TYPE: &str = "http://www.w3.org/1999/02/22-rdf-syntax-ns#type";
    const RDFS_SUBCLASS_OF: &str = "http://www.w3.org/2000/01/rdf-schema#subClassOf";
    let Path::Seq(parts) = p else { return false };
    matches!(
        parts.as_slice(),
        [Path::Pred(ty), Path::Star(sub)]
            if ty.as_str() == RDF_TYPE
                && matches!(sub.as_ref(), Path::Pred(s) if s.as_str() == RDFS_SUBCLASS_OF)
    )
}

// ---- paths (precedence: atom > * > ^ > / > |) ----

pub fn path_to_string(p: &Path) -> String {
    render_alt(p)
}

fn render_alt(p: &Path) -> String {
    match p {
        Path::Alt(parts) => parts.iter().map(render_seq).collect::<Vec<_>>().join(" | "),
        _ => render_seq(p),
    }
}

fn render_seq(p: &Path) -> String {
    match p {
        Path::Seq(parts) => parts.iter().map(render_unary).collect::<Vec<_>>().join("/"),
        _ => render_unary(p),
    }
}

fn render_unary(p: &Path) -> String {
    match p {
        Path::Inverse(inner) => format!("^{}", render_postfix(inner)),
        _ => render_postfix(p),
    }
}

fn render_postfix(p: &Path) -> String {
    match p {
        Path::Star(inner) => format!("{}*", render_atom(inner)),
        _ => render_atom(p),
    }
}

fn render_atom(p: &Path) -> String {
    match p {
        Path::Id => "id".to_string(),
        Path::Pred(nn) => compact(nn.as_str()),
        // compound paths in atom position need grouping
        _ => format!("({})", render_alt(p)),
    }
}

// ---- value types ----

pub fn value_type_to_string(vt: &ValueType) -> String {
    match vt {
        ValueType::Any => "any".to_string(),
        ValueType::Datatype(nn) => format!("datatype({})", compact(nn.as_str())),
        ValueType::NumericRange { lo, hi } => {
            let mut parts = Vec::new();
            if let Some(Bound { value, inclusive }) = lo {
                parts.push(format!("{}{}", if *inclusive { "" } else { ">" }, value));
            }
            if let Some(Bound { value, inclusive }) = hi {
                parts.push(format!("{}{}", if *inclusive { "" } else { "<" }, value));
            }
            format!("range({})", parts.join(", "))
        }
        ValueType::Length { min, max } => {
            let lo = min.map(|n| n.to_string()).unwrap_or_default();
            let hi = max.map(|n| n.to_string()).unwrap_or_default();
            format!("length[{lo}..{hi}]")
        }
        ValueType::Pattern { regex, flags } => format!("pattern(/{regex}/{flags})"),
        ValueType::LangIn(langs) => format!("langIn({})", langs.join(", ")),
        ValueType::And(parts) => parts
            .iter()
            .map(value_type_to_string)
            .collect::<Vec<_>>()
            .join(" & "),
    }
}

fn node_kinds_to_string(k: &NodeKindSet) -> String {
    let mut parts = Vec::new();
    if k.iri {
        parts.push("IRI");
    }
    if k.blank {
        parts.push("BlankNode");
    }
    if k.literal {
        parts.push("Literal");
    }
    parts.join("|")
}

fn term_to_string(t: &Term) -> String {
    match t {
        Term::NamedNode(nn) => compact(nn.as_str()),
        other => other.to_string(),
    }
}

// ---- IRI compaction against well-known namespaces ----

const WELL_KNOWN: &[(&str, &str)] = &[
    ("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#"),
    ("rdfs", "http://www.w3.org/2000/01/rdf-schema#"),
    ("sh", "http://www.w3.org/ns/shacl#"),
    ("xsd", "http://www.w3.org/2001/XMLSchema#"),
    ("owl", "http://www.w3.org/2002/07/owl#"),
];

/// Compact an IRI using well-known prefixes, else `<iri>`.
fn compact(iri: &str) -> String {
    for (prefix, ns) in WELL_KNOWN {
        if let Some(local) = iri.strip_prefix(ns) {
            return format!("{prefix}:{local}");
        }
    }
    format!("<{iri}>")
}

/// Render the algebra AST as a Graphviz DOT digraph.
///
/// Each reachable arena slot becomes a node labeled `@id\n<φ-form>`. Structural
/// edges (Not→child, And/Or→children, Count→qualifier) are drawn as solid arcs.
/// Statements appear as diamond entry nodes; rules as hexagon entry nodes with
/// dashed condition edges.
pub fn schema_to_dot(schema: &Schema) -> String {
    let reachable = reachable_shapes(schema);
    let mut out = String::from("digraph shifty_algebra_ast {\n");
    out.push_str("  rankdir=TB;\n");
    out.push_str("  node [shape=box, style=rounded, fontname=monospace];\n\n");

    // Shape nodes
    for id in &reachable {
        let def = shape_def_dot(&schema.arena, *id);
        let name_line = schema
            .names
            .get(id)
            .map(|iri| format!("\n{}", compact(iri)))
            .unwrap_or_default();
        let label = dot_escape(&format!("@{}{}\n{}", id.0, name_line, def));
        let node_attrs = match schema.arena.get(*id) {
            Shape::Top => format!(
                "shape=ellipse, style=\"rounded,filled\", fillcolor=lightgray, label=\"{label}\""
            ),
            Shape::Not(_) => format!(
                "shape=ellipse, style=\"rounded,filled\", fillcolor=lightsalmon, label=\"{label}\""
            ),
            Shape::And(_) => format!(
                "shape=box, style=\"rounded,filled\", fillcolor=lightblue, label=\"{label}\""
            ),
            Shape::Or(_) => format!(
                "shape=box, style=\"rounded,filled\", fillcolor=lightyellow, label=\"{label}\""
            ),
            Shape::Count { .. } => format!(
                "shape=box, style=\"rounded,filled\", fillcolor=lightgreen, label=\"{label}\""
            ),
            _ => format!("label=\"{label}\""),
        };
        out.push_str(&format!("  shape_{} [{}];\n", id.0, node_attrs));
    }
    out.push('\n');

    // Structural edges between shapes
    for id in &reachable {
        match schema.arena.get(*id) {
            Shape::Not(c) => {
                out.push_str(&format!(
                    "  shape_{} -> shape_{} [label=\"¬\"];\n",
                    id.0, c.0
                ));
            }
            Shape::And(cs) => {
                for (i, c) in cs.iter().enumerate() {
                    out.push_str(&format!(
                        "  shape_{} -> shape_{} [label=\"{}\"];\n",
                        id.0, c.0, i
                    ));
                }
            }
            Shape::Or(cs) => {
                for (i, c) in cs.iter().enumerate() {
                    out.push_str(&format!(
                        "  shape_{} -> shape_{} [label=\"{}\"];\n",
                        id.0, c.0, i
                    ));
                }
            }
            Shape::Count { qualifier, .. } => {
                out.push_str(&format!(
                    "  shape_{} -> shape_{} [label=\"qualifier\", style=dashed, color=darkgreen];\n",
                    id.0, qualifier.0
                ));
            }
            _ => {}
        }
    }
    out.push('\n');

    // Statement entry nodes
    for (i, st) in schema.statements.iter().enumerate() {
        let sel_label = dot_escape(&selector_to_string(&st.selector));
        out.push_str(&format!(
            "  stmt_{i} [shape=diamond, style=filled, fillcolor=lightyellow, label=\"stmt:{i}\\n{sel_label}\"];\n"
        ));
        out.push_str(&format!("  stmt_{i} -> shape_{};\n", st.shape.0));
        if let Selector::HasPath(_, shape_id) = &st.selector {
            out.push_str(&format!(
                "  stmt_{i} -> shape_{} [style=dashed, color=gray50, label=\"path-shape\"];\n",
                shape_id.0
            ));
        }
    }
    out.push('\n');

    // Rule entry nodes
    for (i, r) in schema.rules.iter().enumerate() {
        let sel_label = dot_escape(&selector_to_string(&r.selector));
        let order_label = r.order.map(|o| format!(" ord={o}")).unwrap_or_default();
        let deact = if r.deactivated { " (off)" } else { "" };
        out.push_str(&format!(
            "  rule_{i} [shape=hexagon, style=filled, fillcolor=plum, label=\"rule:{i}\\n{sel_label}{}{}\"];\n",
            dot_escape(&order_label),
            dot_escape(deact)
        ));
        for (j, c) in r.conditions.iter().enumerate() {
            out.push_str(&format!(
                "  rule_{i} -> shape_{} [style=dashed, color=purple4, label=\"cond:{j}\"];\n",
                c.0
            ));
        }
    }

    out.push_str("}\n");
    out
}

/// Shape label for the DOT rendering: leaf shapes show their full definition,
/// composite shapes show only their combinator (children are shown via edges).
fn shape_def_dot(arena: &ShapeArena, id: ShapeId) -> String {
    match arena.get(id) {
        Shape::Annotated { severity, .. } => format!("severity({severity})"),
        Shape::Top => "".to_string(),
        Shape::Pending => "⟨pending⟩".to_string(),
        Shape::TestConst(t) => format!("test({})", term_to_string(t)),
        Shape::TestType(vt) => format!("test({})", value_type_to_string(vt)),
        Shape::TestKind(k) => format!("nodeKind({})", node_kinds_to_string(k)),
        Shape::Closed(q) => {
            let preds: Vec<String> = q.iter().map(|n| compact(n.as_str())).collect();
            format!("closed{{{}}}", preds.join(", "))
        }
        Shape::Eq(p, pred) => format!("eq({}, {})", path_to_string(p), compact(pred.as_str())),
        Shape::Disj(p, pred) => format!("disj({}, {})", path_to_string(p), compact(pred.as_str())),
        Shape::Lt(p, pred) => format!("lt({}, {})", path_to_string(p), compact(pred.as_str())),
        Shape::Le(p, pred) => format!("le({}, {})", path_to_string(p), compact(pred.as_str())),
        Shape::UniqueLang(p) => format!("uniqueLang({})", path_to_string(p)),
        Shape::Not(_) => "¬".to_string(),
        Shape::And(cs) => format!("∧ ({})", cs.len()),
        Shape::Or(cs) => format!("∨ ({})", cs.len()),
        Shape::Count { path, min, max, .. } => {
            let lo = min.map(|n| n.to_string()).unwrap_or_default();
            let hi = max.map(|n| n.to_string()).unwrap_or_default();
            format!("∃[{lo}..{hi}] {}", path_to_string(path))
        }
        Shape::Sparql(c) => format!("sparql({:?})", c.kind),
    }
}

fn dot_escape(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace('"', "\\\"")
        .replace('\n', "\\n")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::schema::Statement;
    use crate::term::NamedNode;

    fn nn(s: &str) -> NamedNode {
        NamedNode::new(s).unwrap()
    }

    #[test]
    fn path_precedence_and_compaction() {
        // (ex:a/^ex:b)|ex:c*
        let p = Path::alt(vec![
            Path::seq(vec![
                Path::Pred(nn("http://ex/a")),
                Path::Inverse(Box::new(Path::Pred(nn("http://ex/b")))),
            ]),
            Path::star(Path::Pred(nn("http://www.w3.org/ns/shacl#c"))),
        ]);
        assert_eq!(path_to_string(&p), "<http://ex/a>/^<http://ex/b> | sh:c*");
    }

    #[test]
    fn schema_dump_renders_cycle() {
        // S := nodeKind(IRI) ∧ ∃[1..] ex:knows . S
        let mut schema = Schema::new();
        let knows = nn("http://ex/knows");
        let s = schema.arena.reserve();
        let kind = schema.arena.insert(Shape::TestKind(NodeKindSet::IRI));
        let reaches = schema.arena.insert(Shape::Count {
            path: Path::Pred(knows.clone()),
            min: Some(1),
            max: None,
            qualifier: s,
        });
        schema.arena.set(s, Shape::And(vec![kind, reaches]));
        schema.statements.push(Statement {
            selector: Selector::HasOut(knows),
            shape: s,
        });

        let text = schema_to_text(&schema);
        assert!(text.contains("@0 = @1 ∧ @2"));
        assert!(text.contains("@1 = nodeKind(IRI)"));
        assert!(text.contains("@2 = ∃[1..] <http://ex/knows> . @0"));
        assert!(text.contains("∃ <http://ex/knows> .⊤  ⇒  @0"));
    }

    fn class_path() -> Path {
        Path::seq(vec![
            Path::Pred(nn("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")),
            Path::star(Path::Pred(nn(
                "http://www.w3.org/2000/01/rdf-schema#subClassOf",
            ))),
        ])
    }

    #[test]
    fn class_target_is_detected_and_rendered_with_the_class() {
        let mut arena = ShapeArena::new();
        let qualifier = arena.insert(Shape::TestConst(Term::NamedNode(nn("http://ex/Person"))));
        let sel = Selector::HasPath(class_path(), qualifier);

        // the structured accessor recovers the class term…
        assert_eq!(
            class_target(&sel, &arena),
            Some(&Term::NamedNode(nn("http://ex/Person")))
        );
        // …and the arena-aware renderer names it instead of printing a bare φ.
        assert_eq!(
            selector_to_string_in(&sel, &arena),
            "class(<http://ex/Person>)"
        );
        // the arena-free renderer still falls back to the φ form.
        assert_eq!(
            selector_to_string(&sel),
            "∃≥1 rdf:type/rdfs:subClassOf* . φ"
        );
    }

    #[test]
    fn non_class_path_target_resolves_its_qualifier_inline() {
        let mut arena = ShapeArena::new();
        let qualifier = arena.insert(Shape::TestKind(NodeKindSet::IRI));
        let sel = Selector::HasPath(Path::Pred(nn("http://ex/p")), qualifier);

        assert_eq!(class_target(&sel, &arena), None);
        // the qualifier is shown rather than dropped to φ.
        assert_eq!(
            selector_to_string_in(&sel, &arena),
            "∃≥1 <http://ex/p> . nodeKind(IRI)"
        );
    }

    /// A `∃≥1 (rdf:type/rdfs:subClassOf*).test(C)` shape — the lowering of `sh:class C`.
    fn class_shape(arena: &mut ShapeArena, iri: &str) -> ShapeId {
        let test = arena.insert(Shape::TestConst(Term::NamedNode(nn(iri))));
        arena.insert(Shape::Count {
            path: class_path(),
            min: Some(1),
            max: None,
            qualifier: test,
        })
    }

    #[test]
    fn describe_shape_inlines_every_child() {
        let mut arena = ShapeArena::new();
        let a = class_shape(&mut arena, "http://ex/A");
        let b = class_shape(&mut arena, "http://ex/B");
        let or = arena.insert(Shape::Or(vec![a, b]));

        // A disjunction of class shapes expands fully — no bare `@id` slot refs,
        // unlike the one-level `shape_to_string`.
        assert_eq!(
            describe_shape(&arena, or),
            "instance of <http://ex/A> or instance of <http://ex/B>"
        );
        assert_eq!(shape_to_string(&arena, or), format!("@{} ∨ @{}", a.0, b.0));

        // `describe_shapes` (a ConformsToAll-style conjunction of separate shapes)
        // joins each member's full description with “and”.
        let kind = arena.insert(Shape::TestKind(NodeKindSet::IRI));
        assert_eq!(
            describe_shapes(&arena, &[a, kind]),
            "instance of <http://ex/A> and nodeKind(IRI)"
        );
    }

    #[test]
    fn describe_shape_guards_recursive_shapes() {
        // S := ⊤ ∧ ∃≥1 ex:knows . S  — a cyclic shape must terminate at the budget.
        let mut arena = ShapeArena::new();
        let s = arena.reserve();
        let top = arena.insert(Shape::Top);
        let reaches = arena.insert(Shape::Count {
            path: Path::Pred(nn("http://ex/knows")),
            min: Some(1),
            max: None,
            qualifier: s,
        });
        arena.set(s, Shape::And(vec![top, reaches]));
        // It renders without diverging and bottoms out at an `@id` slot label.
        let rendered = describe_shape(&arena, s);
        assert!(rendered.contains(&format!("@{}", s.0)), "{rendered}");
    }
}