mmdflux 2.1.0

Render Mermaid diagrams as Unicode text, ASCII, SVG, and MMDS JSON.
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
#!/usr/bin/env python3

from __future__ import annotations

import argparse
import re
import sys
from collections import defaultdict, deque
from pathlib import Path


MOD_DECL_RE = re.compile(
    r"^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;\s*$"
)
USE_RE = re.compile(r"\b(?:pub\s+)?use\s+([^;]+);", re.MULTILINE | re.DOTALL)
PATH_TOKEN_RE = re.compile(r"\b(?:crate|self|super)(?:::[A-Za-z_][A-Za-z0-9_]*)+")
BLOCK_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
LINE_COMMENT_RE = re.compile(r"//.*?$", re.MULTILINE)


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description=(
            "Generate a pivoted Mermaid dependency view for Rust modules in the mmdflux crate."
        )
    )
    parser.add_argument(
        "--crate-root",
        default="src/lib.rs",
        help="Path to the crate root file to analyze (default: src/lib.rs).",
    )
    parser.add_argument(
        "--module",
        required=True,
        help=(
            "Module label to pivot on, such as 'runtime' at max-depth 1 or "
            "'runtime::facade' at max-depth 2."
        ),
    )
    parser.add_argument(
        "--max-depth",
        type=int,
        default=1,
        help="Collapse module paths to this depth before rendering (default: 1).",
    )
    parser.add_argument(
        "--direction",
        choices=["outbound", "inbound", "both"],
        default="outbound",
        help="Traversal direction from the pivot module (default: outbound).",
    )
    parser.add_argument(
        "--mode",
        choices=["tree", "dag"],
        default="tree",
        help="Render a spanning tree or the reachable DAG/subgraph (default: tree).",
    )
    parser.add_argument(
        "--condense-scc",
        action="store_true",
        help="Operate on the SCC-condensed graph instead of raw modules.",
    )
    parser.add_argument(
        "--direction-layout",
        choices=["LR", "RL", "TB", "BT"],
        default="LR",
        help="Mermaid flowchart direction (default: LR).",
    )
    parser.add_argument(
        "--members-per-line",
        type=int,
        default=3,
        help="How many module names to place on each SCC label line when condensed (default: 3).",
    )
    parser.add_argument(
        "--output",
        help="Write the generated Mermaid diagram to this file instead of stdout.",
    )
    return parser.parse_args()


def module_dir_for(file_path: Path) -> Path:
    if file_path.name in {"lib.rs", "main.rs", "mod.rs"}:
        return file_path.parent
    return file_path.parent / file_path.stem


def read_text(path: Path) -> str:
    return path.read_text(encoding="utf-8")


def should_skip_mod(name: str, skip_for_test: bool) -> bool:
    return skip_for_test or name == "tests" or name.endswith("_tests")


def resolve_child_module_file(parent_file: Path, module_name: str) -> Path | None:
    search_root = module_dir_for(parent_file)
    candidates = [search_root / f"{module_name}.rs", search_root / module_name / "mod.rs"]
    for candidate in candidates:
        if candidate.exists():
            return candidate
    return None


def discover_modules(crate_root: Path) -> dict[tuple[str, ...], Path]:
    modules: dict[tuple[str, ...], Path] = {}
    pending: list[tuple[tuple[str, ...], Path]] = [((), crate_root)]

    while pending:
        module_path, file_path = pending.pop()
        if module_path in modules:
            continue
        modules[module_path] = file_path

        skip_next_mod_for_test = False
        for line in read_text(file_path).splitlines():
            stripped = line.strip()
            if stripped.startswith("#[cfg(") and "test" in stripped:
                skip_next_mod_for_test = True
                continue
            if stripped.startswith("#["):
                continue

            match = MOD_DECL_RE.match(stripped)
            if not match:
                skip_next_mod_for_test = False
                continue

            module_name = match.group(1)
            if should_skip_mod(module_name, skip_next_mod_for_test):
                skip_next_mod_for_test = False
                continue

            child_file = resolve_child_module_file(file_path, module_name)
            if child_file is None:
                print(
                    f"warning: could not resolve module {module_name} declared in {file_path}",
                    file=sys.stderr,
                )
                skip_next_mod_for_test = False
                continue

            pending.append((module_path + (module_name,), child_file))
            skip_next_mod_for_test = False

    return modules


def strip_comments(source: str) -> str:
    without_block_comments = BLOCK_COMMENT_RE.sub("", source)
    return LINE_COMMENT_RE.sub("", without_block_comments)


def split_top_level_commas(value: str) -> list[str]:
    parts: list[str] = []
    current: list[str] = []
    depth = 0

    for ch in value:
        if ch == "{":
            depth += 1
        elif ch == "}":
            depth -= 1
        elif ch == "," and depth == 0:
            piece = "".join(current).strip()
            if piece:
                parts.append(piece)
            current = []
            continue
        current.append(ch)

    tail = "".join(current).strip()
    if tail:
        parts.append(tail)
    return parts


def expand_use_tree(expr: str, prefix: str = "") -> list[str]:
    expr = " ".join(expr.split())
    expr = expr.strip()
    if not expr:
        return []

    if expr.startswith("{") and expr.endswith("}"):
        inner = expr[1:-1]
        expanded: list[str] = []
        for part in split_top_level_commas(inner):
            expanded.extend(expand_use_tree(part, prefix))
        return expanded

    expr = expr.split(" as ", 1)[0].strip()
    brace_index = expr.find("{")
    if brace_index >= 0:
        base = expr[:brace_index].rstrip(":").strip()
        inner = expr[brace_index + 1 : expr.rfind("}")]
        next_prefix = f"{prefix}::{base}" if prefix else base
        expanded: list[str] = []
        for part in split_top_level_commas(inner):
            expanded.extend(expand_use_tree(part, next_prefix))
        return expanded

    return [f"{prefix}::{expr}" if prefix else expr]


def resolve_reference(
    current_module: tuple[str, ...], raw_ref: str, known_modules: set[tuple[str, ...]]
) -> tuple[str, ...] | None:
    cleaned = raw_ref.strip().rstrip(":")
    if not cleaned:
        return None

    parts = [part for part in cleaned.split("::") if part]
    if not parts:
        return None

    if parts[0] == "crate":
        absolute = parts[1:]
    elif parts[0] == "self":
        absolute = list(current_module) + parts[1:]
    elif parts[0] == "super":
        base = list(current_module)
        index = 0
        while index < len(parts) and parts[index] == "super":
            if base:
                base.pop()
            index += 1
        absolute = base + parts[index:]
    else:
        return None

    if not absolute:
        return None

    for prefix_len in range(len(absolute), 0, -1):
        candidate = tuple(absolute[:prefix_len])
        if candidate in known_modules:
            return candidate
    return None


def collect_dependencies(
    modules: dict[tuple[str, ...], Path],
) -> dict[tuple[str, ...], set[tuple[str, ...]]]:
    known_modules = set(modules)
    dependencies: dict[tuple[str, ...], set[tuple[str, ...]]] = defaultdict(set)

    for module_path, file_path in modules.items():
        if not module_path:
            continue

        source = strip_comments(read_text(file_path))

        for use_body in USE_RE.findall(source):
            for raw_ref in expand_use_tree(use_body):
                target = resolve_reference(module_path, raw_ref, known_modules)
                if target is not None:
                    dependencies[module_path].add(target)

        for raw_ref in PATH_TOKEN_RE.findall(source):
            target = resolve_reference(module_path, raw_ref, known_modules)
            if target is not None:
                dependencies[module_path].add(target)

    return dependencies


def collapse_module_path(module_path: tuple[str, ...], max_depth: int) -> tuple[str, ...]:
    if len(module_path) <= max_depth:
        return module_path
    return module_path[:max_depth]


def collapse_graph(
    modules: dict[tuple[str, ...], Path],
    dependencies: dict[tuple[str, ...], set[tuple[str, ...]]],
    max_depth: int,
) -> tuple[set[tuple[str, ...]], dict[tuple[str, ...], set[tuple[str, ...]]]]:
    grouped_nodes = {
        collapse_module_path(module_path, max_depth)
        for module_path in modules
        if module_path
    }

    grouped_edges: dict[tuple[str, ...], set[tuple[str, ...]]] = defaultdict(set)
    for source, targets in dependencies.items():
        collapsed_source = collapse_module_path(source, max_depth)
        for target in targets:
            collapsed_target = collapse_module_path(target, max_depth)
            if collapsed_source == collapsed_target:
                continue
            grouped_edges[collapsed_source].add(collapsed_target)

    for node in grouped_nodes:
        grouped_edges.setdefault(node, set())

    return grouped_nodes, grouped_edges


def tarjan_scc(
    nodes: set[tuple[str, ...]],
    edges: dict[tuple[str, ...], set[tuple[str, ...]]],
) -> list[list[tuple[str, ...]]]:
    index = 0
    stack: list[tuple[str, ...]] = []
    on_stack: set[tuple[str, ...]] = set()
    indices: dict[tuple[str, ...], int] = {}
    lowlinks: dict[tuple[str, ...], int] = {}
    components: list[list[tuple[str, ...]]] = []

    def strongconnect(node: tuple[str, ...]) -> None:
        nonlocal index
        indices[node] = index
        lowlinks[node] = index
        index += 1
        stack.append(node)
        on_stack.add(node)

        for neighbor in sorted(edges.get(node, ())):
            if neighbor not in indices:
                strongconnect(neighbor)
                lowlinks[node] = min(lowlinks[node], lowlinks[neighbor])
            elif neighbor in on_stack:
                lowlinks[node] = min(lowlinks[node], indices[neighbor])

        if lowlinks[node] == indices[node]:
            component: list[tuple[str, ...]] = []
            while True:
                member = stack.pop()
                on_stack.remove(member)
                component.append(member)
                if member == node:
                    break
            components.append(sorted(component))

    for node in sorted(nodes):
        if node not in indices:
            strongconnect(node)

    return components


def build_condensation_graph(
    components: list[list[tuple[str, ...]]],
    edges: dict[tuple[str, ...], set[tuple[str, ...]]],
) -> tuple[dict[int, list[tuple[str, ...]]], dict[int, set[int]], dict[tuple[str, ...], int]]:
    component_nodes = {index: component for index, component in enumerate(components)}
    node_to_component: dict[tuple[str, ...], int] = {}
    for index, component in component_nodes.items():
        for node in component:
            node_to_component[node] = index

    condensation_edges: dict[int, set[int]] = defaultdict(set)
    for source, targets in edges.items():
        source_component = node_to_component[source]
        for target in targets:
            target_component = node_to_component[target]
            if source_component != target_component:
                condensation_edges[source_component].add(target_component)

    for component_id in component_nodes:
        condensation_edges.setdefault(component_id, set())

    return component_nodes, condensation_edges, node_to_component


def module_label(module_path: tuple[str, ...]) -> str:
    return "::".join(module_path)


def node_id(label: str) -> str:
    safe = re.sub(r"[^A-Za-z0-9_]+", "_", label).strip("_")
    return f"node_{safe or 'root'}"


def reverse_edges(edges: dict[str, set[str]]) -> dict[str, set[str]]:
    reversed_edges: dict[str, set[str]] = {node: set() for node in edges}
    for source, targets in edges.items():
        for target in targets:
            reversed_edges.setdefault(target, set()).add(source)
        reversed_edges.setdefault(source, set())
    return reversed_edges


def chunked(items: list[str], width: int) -> list[list[str]]:
    return [items[idx : idx + width] for idx in range(0, len(items), width)]


def scc_label(component: list[tuple[str, ...]], members_per_line: int) -> str:
    names = [module_label(member) for member in component]
    if len(component) == 1:
        return names[0]

    lines = [f"cycle ({len(component)} modules)"]
    lines.extend(", ".join(group) for group in chunked(names, members_per_line))
    return "<br/>".join(lines)


def build_render_graph(
    nodes: set[tuple[str, ...]],
    edges: dict[tuple[str, ...], set[tuple[str, ...]]],
    condense_scc: bool,
    members_per_line: int,
) -> tuple[
    dict[str, str],
    dict[str, str],
    dict[str, set[str]],
    dict[str, str],
    dict[str, str],
]:
    if not condense_scc:
        raw_to_render = {module_label(node): module_label(node) for node in nodes}
        display_labels = dict(raw_to_render)
        render_edges = {
            module_label(source): {module_label(target) for target in targets}
            for source, targets in edges.items()
        }
        render_edges = {label: render_edges.get(label, set()) for label in display_labels}
        node_styles = {label: "normal" for label in display_labels}
        node_ids = {label: node_id(label) for label in display_labels}
        return raw_to_render, display_labels, render_edges, node_styles, node_ids

    components = tarjan_scc(nodes, edges)
    component_nodes, condensation_edges, node_to_component = build_condensation_graph(
        components, edges
    )

    display_labels = {
        f"scc::{component_id}": scc_label(component_nodes[component_id], members_per_line)
        for component_id in component_nodes
    }
    render_edges = {
        f"scc::{component_id}": {f"scc::{target}" for target in targets}
        for component_id, targets in condensation_edges.items()
    }
    node_styles = {
        f"scc::{component_id}": len(component_nodes[component_id]) > 1
        for component_id in component_nodes
    }
    node_ids = {label: node_id(label) for label in display_labels}
    raw_to_render = {
        module_label(node): f"scc::{node_to_component[node]}"
        for node in nodes
    }
    style_labels = {
        label: ("cycle" if is_cycle else "normal")
        for label, is_cycle in node_styles.items()
    }
    return raw_to_render, display_labels, render_edges, style_labels, node_ids


def resolve_pivot_label(
    requested_module: str,
    raw_nodes: set[tuple[str, ...]],
    raw_label_to_render_label: dict[str, str],
) -> str:
    normalized = requested_module.strip()
    available = sorted(module_label(node) for node in raw_nodes)
    if normalized not in raw_label_to_render_label:
        choices = ", ".join(available)
        raise ValueError(
            f"unknown module '{requested_module}' for this max-depth. Available modules: {choices}"
        )
    return raw_label_to_render_label[normalized]


def tree_edges_from_pivot(
    pivot: str,
    edges: dict[str, set[str]],
    direction: str,
) -> tuple[set[str], set[tuple[str, str]]]:
    if direction == "both":
        raise ValueError("tree mode requires --direction inbound or outbound")

    traversal_edges = edges if direction == "outbound" else reverse_edges(edges)
    visited = {pivot}
    tree_edges: set[tuple[str, str]] = set()
    queue: deque[str] = deque([pivot])

    while queue:
        current = queue.popleft()
        for neighbor in sorted(traversal_edges.get(current, ())):
            if neighbor in visited:
                continue
            visited.add(neighbor)
            queue.append(neighbor)
            if direction == "outbound":
                tree_edges.add((current, neighbor))
            else:
                tree_edges.add((neighbor, current))

    return visited, tree_edges


def reachable_nodes(
    pivot: str,
    edges: dict[str, set[str]],
    direction: str,
) -> set[str]:
    forward = edges
    backward = reverse_edges(edges)

    def walk(start: str, graph: dict[str, set[str]]) -> set[str]:
        seen = {start}
        queue: deque[str] = deque([start])
        while queue:
            current = queue.popleft()
            for neighbor in sorted(graph.get(current, ())):
                if neighbor in seen:
                    continue
                seen.add(neighbor)
                queue.append(neighbor)
        return seen

    if direction == "outbound":
        return walk(pivot, forward)
    if direction == "inbound":
        return walk(pivot, backward)
    return walk(pivot, forward) | walk(pivot, backward)


def dag_subgraph_edges(
    included_nodes: set[str],
    edges: dict[str, set[str]],
) -> set[tuple[str, str]]:
    return {
        (source, target)
        for source, targets in edges.items()
        if source in included_nodes
        for target in targets
        if target in included_nodes
    }


def render_mermaid(
    labels: dict[str, str],
    node_ids: dict[str, str],
    node_styles: dict[str, str],
    included_nodes: set[str],
    edge_pairs: set[tuple[str, str]],
    requested_module: str,
    pivot_label: str,
    crate_root_label: str,
    max_depth: int,
    direction_layout: str,
    mode: str,
    direction: str,
    condensed: bool,
) -> str:
    ordered_nodes = sorted(included_nodes)
    lines = [
        "%% Generated by scripts/generate-rust-module-deps-pivot.py",
        f"%% crate-root: {crate_root_label}",
        f"%% max-depth: {max_depth}",
        f"%% pivot-request: {requested_module}",
        f"%% pivot-node: {pivot_label}",
        f"%% mode: {mode}",
        f"%% direction: {direction}",
        f"%% condensed-scc: {'yes' if condensed else 'no'}",
        f"flowchart {direction_layout}",
    ]

    for node in ordered_nodes:
        lines.append(f'    {node_ids[node]}["{labels[node]}"]')

    for source, target in sorted(edge_pairs):
        lines.append(f"    {node_ids[source]} --> {node_ids[target]}")

    lines.extend(
        [
            "    classDef pivot fill:#fde68a,stroke:#b45309,stroke-width:2px,color:#1f2937;",
            "    classDef cycle fill:#fbe4e6,stroke:#b42318,stroke-width:2px,color:#1f2937;",
            "    classDef normal fill:#e8f0ff,stroke:#4f46e5,stroke-width:1.5px,color:#1f2937;",
        ]
    )

    lines.append(f"    class {node_ids[pivot_label]} pivot;")

    cycle_nodes = [
        node
        for node, style in node_styles.items()
        if style == "cycle" and node in included_nodes and node != pivot_label
    ]
    normal_nodes = [
        node
        for node, style in node_styles.items()
        if style == "normal" and node in included_nodes and node != pivot_label
    ]

    if cycle_nodes:
        lines.append(
            "    class " + ",".join(node_ids[node] for node in sorted(cycle_nodes)) + " cycle;"
        )
    if normal_nodes:
        lines.append(
            "    class " + ",".join(node_ids[node] for node in sorted(normal_nodes)) + " normal;"
        )

    return "\n".join(lines) + "\n"


def main() -> int:
    args = parse_args()
    if args.max_depth < 1:
        print("--max-depth must be >= 1", file=sys.stderr)
        return 2
    if args.members_per_line < 1:
        print("--members-per-line must be >= 1", file=sys.stderr)
        return 2
    if args.mode == "tree" and args.direction == "both":
        print("--mode tree requires --direction inbound or outbound", file=sys.stderr)
        return 2

    crate_root_input = Path(args.crate_root)
    crate_root = crate_root_input.resolve()
    modules = discover_modules(crate_root)
    dependencies = collect_dependencies(modules)
    raw_nodes, raw_edges = collapse_graph(modules, dependencies, args.max_depth)
    raw_label_to_render_label, display_labels, render_edges, node_styles, node_ids = build_render_graph(
        raw_nodes,
        raw_edges,
        condense_scc=args.condense_scc,
        members_per_line=args.members_per_line,
    )

    try:
        pivot_label = resolve_pivot_label(args.module, raw_nodes, raw_label_to_render_label)
    except ValueError as error:
        print(str(error), file=sys.stderr)
        return 2

    if args.mode == "tree":
        included_nodes, edge_pairs = tree_edges_from_pivot(
            pivot_label,
            render_edges,
            direction=args.direction,
        )
    else:
        included_nodes = reachable_nodes(pivot_label, render_edges, direction=args.direction)
        edge_pairs = dag_subgraph_edges(included_nodes, render_edges)

    diagram = render_mermaid(
        labels=display_labels,
        node_ids=node_ids,
        node_styles=node_styles,
        included_nodes=included_nodes,
        edge_pairs=edge_pairs,
        requested_module=args.module,
        pivot_label=pivot_label,
        crate_root_label=crate_root_input.as_posix(),
        max_depth=args.max_depth,
        direction_layout=args.direction_layout,
        mode=args.mode,
        direction=args.direction,
        condensed=args.condense_scc,
    )

    if args.output:
        output_path = Path(args.output)
        output_path.parent.mkdir(parents=True, exist_ok=True)
        output_path.write_text(diagram, encoding="utf-8")
    else:
        sys.stdout.write(diagram)

    return 0


if __name__ == "__main__":
    raise SystemExit(main())