systemap 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
systemap/check.py ADDED
@@ -0,0 +1,873 @@
1
+ """Check the map geometry and the meaning tables mechanically.
2
+
3
+ The map's positions are fixed in the model (written by `systemap place`
4
+ or by hand) and its relations are hand-authored, so two kinds of quiet
5
+ lie are possible: a card drawn where the model does not claim it, or a
6
+ sentence that names a flow the model no longer has. Both fail here
7
+ instead of shipping.
8
+
9
+ What is checked, in order:
10
+
11
+ placement ..... every card inside its band, no two cards overlapping,
12
+ every flow naming known components (the model)
13
+ routes ........ every edge an orthogonal path that passes through no
14
+ card it does not connect and crosses no region box it
15
+ neither starts nor ends in (both counted, each offender
16
+ listed with the router's reason)
17
+ labels ........ every edge label seated without touching a card, a
18
+ header or another label (the schematic's collision pass,
19
+ re-verified from the boxes it reports), and every
20
+ container and region header inside its box and off
21
+ every card: a sub wraps to a second line and is
22
+ refused past that
23
+ type size ..... nothing in the figure set below 11px
24
+ meaning ....... every flow has a layer and a sentence, every component a
25
+ plain word, every journey step a real edge and real ids,
26
+ every verb override a real edge
27
+ wheel ......... for every component, the relationship wheel's name labels
28
+ stay off each other and off the centre (the wheel sizes
29
+ itself to its labels, so nothing can leave the drawing)
30
+ coverage ...... every module in the facts is claimed by exactly one
31
+ component, unless the configuration ignores it with a
32
+ reason or it is an empty package marker; an incomplete
33
+ map fails. The top map alone: a card that opens a map
34
+ claims its modules once, for the whole tree
35
+ nesting ....... the map inside a card claims exactly the modules the
36
+ card claims, no more and no fewer, each once; its
37
+ actors are cards of the map it is inside
38
+ entry ......... every module a component names is in the facts, and the
39
+ entry it names is a public module-level name one of
40
+ them defines (a function, a class, an object); the map draws
41
+ what exists today, so a name the code does not have
42
+ would draw a part that is not there
43
+ interface ..... every `interface` line starts with a name the
44
+ component's modules define (`Class.method` needs both),
45
+ refused with the closest defined name
46
+ stale ......... the facts file describes the tree, the page is what the
47
+ renderer draws from the facts and the model, and every
48
+ configured figure is what the generator draws; the
49
+ same comparisons `extract --check` and `render --check`
50
+ make, run in one place
51
+
52
+ The CLI prints one line per problem, the fix under each group, and exits
53
+ 1 when any is found. Every rule but coverage runs on every map of the
54
+ tree (`run_tree`); a sub-map's lines carry its id in front.
55
+ """
56
+
57
+ from __future__ import annotations
58
+
59
+ import difflib
60
+ import json
61
+ import math
62
+ import re
63
+ from collections.abc import Iterable, Mapping
64
+ from dataclasses import dataclass, field, replace
65
+ from pathlib import Path
66
+ from typing import Any
67
+
68
+ from systemap import extract, figure, nest, page
69
+ from systemap.config import Config, Ignore
70
+ from systemap.model import (
71
+ Component,
72
+ Layer,
73
+ Meaning,
74
+ Model,
75
+ all_layers,
76
+ claimed,
77
+ defines_entry,
78
+ is_symbol,
79
+ module_matches,
80
+ public_names,
81
+ symbol_claims,
82
+ )
83
+ from systemap.model import problems as model_problems
84
+ from systemap.schematic import TEXT_PX
85
+ from systemap.schematic import render as render_schematic
86
+
87
+ Box = tuple[float, float, float, float]
88
+
89
+
90
+ def _overlap(a: Box, b: Box) -> bool:
91
+ ax, ay, aw, ah = a
92
+ bx, by, bw, bh = b
93
+ return ax < bx + bw and bx < ax + aw and ay < by + bh and by < ay + ah
94
+
95
+
96
+ def _box(values: list[float]) -> Box:
97
+ return float(values[0]), float(values[1]), float(values[2]), float(values[3])
98
+
99
+
100
+ def check_labels(meta: dict[str, Any]) -> list[str]:
101
+ """The labels rule: edge labels and header text, from the boxes the drawing reports."""
102
+ out = list(meta.get("collisions", []))
103
+ labels: list[dict[str, Any]] = meta.get("labels", [])
104
+ cards: dict[str, list[float]] = meta.get("cards", {})
105
+ for header in meta.get("headers", []):
106
+ hb = _box(header["box"])
107
+ for cid, cb in cards.items():
108
+ if _overlap(hb, _box(cb)):
109
+ out.append(f"header of {header['kind']} {header['id']} touches card {cid}")
110
+ for k, lab in enumerate(labels):
111
+ lb = _box(lab["box"])
112
+ for cid, cb in cards.items():
113
+ if _overlap(lb, _box(cb)):
114
+ out.append(f"label '{lab['artifact']}' touches card {cid}")
115
+ for other in labels[k + 1 :]:
116
+ if _overlap(lb, _box(other["box"])):
117
+ out.append(f"label '{lab['artifact']}' touches label '{other['artifact']}'")
118
+ return out
119
+
120
+
121
+ def _seg_hits(a: list[float], b: list[float], box: Box) -> bool:
122
+ """Does the axis-aligned segment a-b cross the interior of box?"""
123
+ bx, by, bw, bh = box
124
+ (x0, y0), (x1, y1) = a, b
125
+ if abs(y0 - y1) < 1e-6:
126
+ if not (by < y0 < by + bh):
127
+ return False
128
+ return min(x0, x1) < bx + bw and max(x0, x1) > bx
129
+ if not (bx < x0 < bx + bw):
130
+ return False
131
+ return min(y0, y1) < by + bh and max(y0, y1) > by
132
+
133
+
134
+ def check_routes(meta: dict[str, Any], model: Model) -> tuple[list[str], int, int]:
135
+ """(problems, edges through a foreign card, edges across a foreign region).
136
+
137
+ A segment is judged against the exact card box (the router keeps a
138
+ margin, so a touch here is a real pass-through) and against every
139
+ region box other than the two the edge belongs to. An edge is counted
140
+ once per offence, and listed with the router's own reason when it had
141
+ to fall back.
142
+ """
143
+ out: list[str] = []
144
+ paths: dict[Any, list[list[float]]] = meta.get("paths", {})
145
+ cards: dict[str, list[float]] = meta.get("cards", {})
146
+ notes: list[str] = meta.get("notes", [])
147
+ region_of = {c.id: c.region or "" for c in model.components}
148
+ regions = {r.id: _box(list(r.box)) for r in model.regions}
149
+ through = 0
150
+ across = 0
151
+ for i, f in enumerate(model.flows):
152
+ src, dst, art = f.src, f.dst, f.artifact
153
+ pts = paths.get(str(i)) or paths.get(i)
154
+ if not pts:
155
+ out.append(f"route: {src} -> {dst} ('{art}') has no path")
156
+ continue
157
+ segs = list(zip(pts, pts[1:], strict=False))
158
+ hit_cards = sorted(
159
+ cid
160
+ for cid, box in cards.items()
161
+ if cid not in (src, dst) and any(_seg_hits(a, b, _box(box)) for a, b in segs)
162
+ )
163
+ hit_regions = sorted(
164
+ rid
165
+ for rid, box in regions.items()
166
+ if rid not in (region_of[src], region_of[dst])
167
+ and any(_seg_hits(a, b, box) for a, b in segs)
168
+ )
169
+ why = next((n for n in notes if n.startswith(f"{src} -> {dst}:")), "")
170
+ reason = f" ({why.split(': ', 1)[1]})" if why else ""
171
+ if hit_cards:
172
+ through += 1
173
+ out.append(f"route: {src} -> {dst} passes through {', '.join(hit_cards)}{reason}")
174
+ if hit_regions:
175
+ across += 1
176
+ out.append(f"route: {src} -> {dst} crosses region {', '.join(hit_regions)}{reason}")
177
+ return out, through, across
178
+
179
+
180
+ def check_type_size(svg: str) -> list[str]:
181
+ small = sorted(
182
+ {float(m) for m in re.findall(r"font-size:\s*([0-9.]+)px", svg) if float(m) < TEXT_PX}
183
+ )
184
+ return [f"text set at {s}px, below {TEXT_PX}px" for s in small]
185
+
186
+
187
+ # ---- the wheel, mirrored from schematic._INTERACTIVE_JS ----------------------
188
+ # The page lays the wheel out in the browser; this is the same arithmetic in
189
+ # Python so the label geometry can be checked without one. Keep the two in
190
+ # step: a change to one is a change to both.
191
+
192
+ CX, CY, R = 200.0, 200.0, 118.0
193
+ MONO_CHAR_W = 6.6
194
+ NAME_LINE_H = 13.0
195
+
196
+
197
+ def wrap_name(cid: str) -> list[str]:
198
+ parts = re.findall(r"[A-Z]+[a-z0-9]*|[a-z0-9]+", cid) or [cid]
199
+ lines: list[str] = []
200
+ cur = ""
201
+ for p in parts:
202
+ if cur and len(cur + p) > 10:
203
+ lines.append(cur)
204
+ cur = p
205
+ else:
206
+ cur += p
207
+ if cur:
208
+ lines.append(cur)
209
+ return lines[:3]
210
+
211
+
212
+ def wheel_boxes(
213
+ cid: str, edges: list[dict[str, str]], layers: tuple[Layer, ...]
214
+ ) -> tuple[Box, list[tuple[str, Box]]]:
215
+ order = {layer.id: i for i, layer in enumerate(layers)}
216
+ idx = sorted(
217
+ (i for i, e in enumerate(edges) if cid in (e["from"], e["to"])),
218
+ key=lambda i: (order[edges[i]["layer"]], i),
219
+ )
220
+ groups = 0
221
+ prev: str | None = None
222
+ for i in idx:
223
+ if edges[i]["layer"] != prev:
224
+ groups += 1
225
+ prev = edges[i]["layer"]
226
+ gap = 0.5 if groups > 1 else 0.0
227
+ step = 360.0 / (len(idx) + gap * groups) if idx else 360.0
228
+ hw, hh = max(34.0, len(cid) * 3.7 + 12), 15.0
229
+ centre: Box = (CX - hw, CY - hh, 2 * hw, 2 * hh)
230
+ boxes: list[tuple[str, Box]] = []
231
+ a = -90.0
232
+ prev = None
233
+ for i in idx:
234
+ e = edges[i]
235
+ if prev is not None and e["layer"] != prev:
236
+ a += gap * step
237
+ prev = e["layer"]
238
+ th = math.radians(a)
239
+ a += step
240
+ ux, uy = math.cos(th), math.sin(th)
241
+ other = e["to"] if e["from"] == cid else e["from"]
242
+ lines = wrap_name(other)
243
+ n = len(lines)
244
+ lw = max(len(line) for line in lines) * MONO_CHAR_W
245
+ ex, ey = CX + (R + 9) * ux, CY + (R + 9) * uy
246
+ if abs(ux) < 0.35:
247
+ first = ey - 4 - (n - 1) * NAME_LINE_H if uy < 0 else ey + 12
248
+ left = ex - lw / 2
249
+ else:
250
+ first = ey + 4 - (n - 1) * 6.5
251
+ left = ex + 2 if ux > 0 else ex - 2 - lw
252
+ top = first - 10
253
+ boxes.append((other, (left, top, lw, (n - 1) * NAME_LINE_H + NAME_LINE_H)))
254
+ return centre, boxes
255
+
256
+
257
+ def check_wheels(edges: list[dict[str, str]], model: Model, meaning: Meaning) -> list[str]:
258
+ """Name labels on the wheel off the centre and off each other.
259
+
260
+ The page fits the wheel's viewBox to its labels (`wheelExtent`), so a
261
+ label cannot leave the drawing and no rule says so.
262
+ """
263
+ out: list[str] = []
264
+ layers = all_layers(model, meaning)
265
+ for c in model.components:
266
+ cid = c.id
267
+ centre, boxes = wheel_boxes(cid, edges, layers)
268
+ for k, (name, box) in enumerate(boxes):
269
+ if _overlap(box, centre):
270
+ out.append(f"wheel of {cid}: label {name} touches the centre")
271
+ for other, ob in boxes[k + 1 :]:
272
+ if _overlap(box, ob):
273
+ out.append(f"wheel of {cid}: labels {name} and {other} touch")
274
+ return out
275
+
276
+
277
+ # ---- coverage: every module claimed once --------------------------------------
278
+
279
+
280
+ @dataclass(frozen=True)
281
+ class Coverage:
282
+ """What the coverage rule found.
283
+
284
+ `checked` is false when there were no facts to check against, which is
285
+ itself a failure: a map cannot be called complete against nothing.
286
+ `total` counts every module in the facts and `mapped` how many are
287
+ accounted for: claimed by exactly one component, taken out of the rule
288
+ by an ignore with a reason (`ignored`, counted among the mapped), or an
289
+ empty package marker left out on its own (`markers`, likewise). Mapped
290
+ is total when the map is complete, and the total is the extract's.
291
+ `counted` is false for the map inside a card: the card claims its
292
+ modules once, on the map above, and the nesting rule holds the
293
+ sub-map to exactly those, so nothing is counted twice.
294
+ """
295
+
296
+ checked: bool
297
+ mapped: int
298
+ total: int
299
+ ignored: int
300
+ problems: tuple[str, ...]
301
+ markers: int = 0
302
+ counted: bool = True
303
+
304
+ @property
305
+ def ok(self) -> bool:
306
+ return self.checked and not self.problems
307
+
308
+
309
+ def check_coverage(model: Model, facts: dict[str, Any], ignores: Iterable[Ignore]) -> Coverage:
310
+ """Every module in the facts is claimed by exactly one component.
311
+
312
+ A module no component claims is a hole in the map: the reader cannot
313
+ find that code on the page. A module two components claim is a lie in
314
+ the other direction: the page says one thing does it and another thing
315
+ also does it. An ignore in the configuration takes a module out of the
316
+ first rule, with its reason on record, by exact name or as `pkg.sub.*`
317
+ for a subtree; it never excuses the second. An empty package marker
318
+ (an `__init__` with no public names and no imports) is left out of
319
+ the first rule on its own. An ignore that matches nothing in the facts
320
+ is reported, so a stale entry cannot quietly outlive the module it
321
+ named, and so is one that names only markers, which is not needed.
322
+ """
323
+ if not facts:
324
+ return Coverage(False, 0, 0, 0, ("no facts to check coverage against",))
325
+ components = facts.get("components", {})
326
+ modules = sorted(components)
327
+ markers = {m for m in modules if extract.is_empty_marker(components[m])}
328
+ ignore_list = list(ignores)
329
+ problems: list[str] = []
330
+ for ignore in ignore_list:
331
+ matched = [m for m in modules if module_matches(ignore.module, m)]
332
+ if not matched:
333
+ problems.append(f"ignore names a module the facts do not have: {ignore.module}")
334
+ elif all(m in markers for m in matched):
335
+ problems.append(
336
+ f"ignore is not needed: {ignore.module} is an empty package marker, left out "
337
+ "of the coverage rule on its own; remove the entry"
338
+ )
339
+ ignored = {m for m in modules if any(module_matches(i.module, m) for i in ignore_list)}
340
+ mapped = n_ignored = n_markers = 0
341
+ for m in modules:
342
+ owners = [
343
+ c.id for c in model.components if any(module_matches(p, m) for p in c.implemented_by)
344
+ ]
345
+ if len(owners) > 1:
346
+ times = "twice" if len(owners) == 2 else f"{len(owners)} times"
347
+ problems.append(f"claimed {times}: {m} ({', '.join(owners)})")
348
+ elif owners:
349
+ mapped += 1
350
+ elif m in markers:
351
+ mapped += 1
352
+ n_markers += 1
353
+ elif m in ignored:
354
+ mapped += 1
355
+ n_ignored += 1
356
+ else:
357
+ problems.append(f"unmapped: {m} (no component claims it)")
358
+ return Coverage(True, mapped, len(modules), n_ignored, tuple(problems), n_markers)
359
+
360
+
361
+ # The coverage of a map inside a card: nothing, on record.
362
+ NOT_COUNTED = Coverage(True, 0, 0, 0, (), counted=False)
363
+
364
+
365
+ # ---- nesting: the map inside a card is that card and nothing else --------------
366
+
367
+
368
+ def check_nesting(
369
+ parent: Model, card: Component, sub: Model, facts: dict[str, Any], sub_label: str
370
+ ) -> list[str]:
371
+ """The map inside `card` claims exactly what the card claims; its actors are cards above.
372
+
373
+ The card claims its modules once, on the parent map, and coverage
374
+ counts them there. The sub-map must claim every one of them and
375
+ nothing else, each by exactly one card: a module it leaves out has
376
+ no place inside, and a module it adds is drawn twice, once on each
377
+ map. Symbol claims count for no module, as everywhere; an empty
378
+ package marker is left out, as the coverage rule leaves it out. The
379
+ sub-map's actors stand for the cards around `card` on the parent
380
+ map, so its edges to the outside have somewhere to land: every actor
381
+ id must be a card of the parent map, and not `card` itself. The
382
+ claims are compared through the facts, so with none only the actors
383
+ are checked; the entry rule names a module the facts do not have.
384
+ """
385
+ where = f"the map inside {card.id} ({sub_label})"
386
+ out: list[str] = []
387
+ for c in sub.components:
388
+ if c.kind != "actor":
389
+ continue
390
+ if c.id == card.id:
391
+ out.append(f"{where} has actor {c.id}, the card it is inside")
392
+ elif c.id not in parent.ids:
393
+ out.append(
394
+ f"{where} has actor {c.id}, which is not a card of the map it is inside; "
395
+ "a sub-map's actors are the cards around its card"
396
+ )
397
+ components = facts.get("components", {})
398
+ if not components:
399
+ return out
400
+ markers = {m for m in components if extract.is_empty_marker(components[m])}
401
+ wanted = [m for m in claimed(card, components) if m not in markers]
402
+ have: dict[str, list[str]] = {}
403
+ for c in sub.components:
404
+ if c.kind == "actor":
405
+ continue
406
+ for m in claimed(c, components):
407
+ if m not in markers:
408
+ have.setdefault(m, []).append(c.id)
409
+ for m, owners in have.items():
410
+ if len(owners) > 1:
411
+ out.append(f"{where} claims {m} twice ({', '.join(owners)})")
412
+ for m in sorted(set(have) - set(wanted)):
413
+ out.append(f"{where} claims {m}, which {card.id} does not claim ({', '.join(have[m])})")
414
+ for m in wanted:
415
+ if m not in have:
416
+ out.append(f"{where} leaves {m} unclaimed, which {card.id} claims")
417
+ return out
418
+
419
+
420
+ # ---- entry: a card is code that exists today ----------------------------------
421
+
422
+ # The kinds whose card may be a namespace with no way in: state is what
423
+ # they are, and their modules alone say they exist.
424
+ ENTRY_OPTIONAL = ("store", "context")
425
+
426
+
427
+ def check_entry(model: Model, facts: dict[str, Any]) -> list[str]:
428
+ """Every component names modules the facts have and an entry they define.
429
+
430
+ The map draws what exists. A module the facts do not have, an empty
431
+ entry, or an entry none of the claimed modules define would each draw
432
+ a part that is not in the tree, so all three are refused. A store or
433
+ a context card may have no entry (a constants table, a namespace):
434
+ its modules alone say it exists, and an entry it does give is checked
435
+ like any other. A symbol
436
+ claim (`pkg.mod:name`) must name a module the facts have, a public
437
+ name that module defines, and a module some component claims: the
438
+ symbol's card is a part inside that component's module, and a symbol
439
+ of a module nobody owns would be a card with no place. Actors claim
440
+ no code and are never checked.
441
+ """
442
+ components = facts.get("components", {})
443
+ if not components:
444
+ return []
445
+ owned = {m for c in model.components for m in claimed(c, components)}
446
+ out: list[str] = []
447
+ for c in model.components:
448
+ if c.kind == "actor":
449
+ continue
450
+ for pattern in c.implemented_by:
451
+ if is_symbol(pattern):
452
+ continue
453
+ if not any(module_matches(pattern, m) for m in components):
454
+ out.append(f"{c.id} names module {pattern} which is not in the facts")
455
+ symbols: list[str] = []
456
+ for module, name in symbol_claims(c):
457
+ symbol = f"{module}:{name}"
458
+ if module not in components:
459
+ out.append(f"{c.id} claims symbol {symbol} of a module not in the facts")
460
+ continue
461
+ if name not in public_names(components[module]):
462
+ out.append(f"{c.id} claims symbol {symbol} which {module} does not define")
463
+ continue
464
+ if module not in owned:
465
+ out.append(
466
+ f"{c.id} claims symbol {symbol} of a module nobody claims; a symbol "
467
+ "claim needs the module's owner on the map"
468
+ )
469
+ continue
470
+ symbols.append(symbol)
471
+ modules = claimed(c, components)
472
+ if not modules and not symbols:
473
+ if not c.implemented_by:
474
+ out.append(f"{c.id} names no module; a component is code in the tree")
475
+ continue
476
+ held = ", ".join(modules + symbols)
477
+ if not c.entry:
478
+ if c.kind not in ENTRY_OPTIONAL:
479
+ out.append(f"{c.id} names no entry; its modules are {held}")
480
+ continue
481
+ if not defines_entry(c, facts):
482
+ out.append(f"{c.id} names entry {c.entry} which none of its modules defines ({held})")
483
+ return out
484
+
485
+
486
+ # ---- interface: the signature names something the modules define ------------------
487
+
488
+ # The leading identifier of an interface line, and the method after a dot
489
+ # when the line reads `Class.method`. The token ends at `(`, `.`, `->`,
490
+ # whitespace or anything else that is not part of a name.
491
+ INTERFACE_HEAD = re.compile(r"\s*([A-Za-z_][A-Za-z0-9_]*)(?:\.([A-Za-z_][A-Za-z0-9_]*))?")
492
+
493
+
494
+ def interface_head(text: str) -> tuple[str, str] | None:
495
+ """(the leading identifier, the method after a dot or empty), or None
496
+ when the line starts with no identifier at all."""
497
+ found = INTERFACE_HEAD.match(text)
498
+ if found is None:
499
+ return None
500
+ return found.group(1), found.group(2) or ""
501
+
502
+
503
+ def method_names(record: Mapping[str, Any], class_name: str) -> set[str]:
504
+ """The public methods one facts record gives a class, from their signatures."""
505
+ out: set[str] = set()
506
+ for group in ("classes", "errors"):
507
+ for cls in record.get(group, []):
508
+ if cls.get("name") != class_name:
509
+ continue
510
+ for sig in cls.get("methods", []):
511
+ found = re.match(r"(?:async )?def (\w+)\(", sig)
512
+ if found:
513
+ out.add(found.group(1))
514
+ return out
515
+
516
+
517
+ def _reexport_sources(record: Mapping[str, Any], name: str) -> list[str]:
518
+ """The modules a record's `names` say define `name`, when it is re-exported."""
519
+ return [
520
+ str(n["reexport_of"])
521
+ for n in record.get("names", [])
522
+ if n.get("name") == name and n.get("reexport_of")
523
+ ]
524
+
525
+
526
+ def _closest(name: str, candidates: Iterable[str]) -> str:
527
+ matches = difflib.get_close_matches(name, sorted(set(candidates)), n=1, cutoff=0.0)
528
+ return matches[0] if matches else ""
529
+
530
+
531
+ def check_interface(model: Model, facts: dict[str, Any]) -> list[str]:
532
+ """Every `interface` starts with a name the component's modules define.
533
+
534
+ The interface line is what the reader is told other parts reach the
535
+ component by, so its leading identifier (the token before `(`, `.`,
536
+ `->` or whitespace) must be a public name one of the claimed modules
537
+ defines, a re-export included, or a name the component claims by
538
+ symbol. `Class.method` needs both: the class, and a public method of
539
+ it in the facts. The line is refused with the closest defined name,
540
+ since a session found most of its interface lines wrong after a check
541
+ that never read them. `interface` stays optional; an empty one is not
542
+ checked, and an actor claims no code.
543
+ """
544
+ components = facts.get("components", {})
545
+ if not components:
546
+ return []
547
+ out: list[str] = []
548
+ for c in model.components:
549
+ problem = interface_problem(c, components)
550
+ if problem:
551
+ out.append(problem)
552
+ return out
553
+
554
+
555
+ def interface_problem(c: Component, components: Mapping[str, Any]) -> str:
556
+ """The interface rule for one card: the problem line, or empty when it passes.
557
+
558
+ The one definition of the rule: `check_interface` reports it and
559
+ `systemap delta` compares it at two commits, so a name that vanished
560
+ is judged by the same words that refuse it.
561
+ """
562
+ if c.kind == "actor" or not c.interface.strip():
563
+ return ""
564
+ modules = claimed(c, components)
565
+ symbols = symbol_claims(c)
566
+ names: set[str] = set()
567
+ for m in modules:
568
+ names |= public_names(components[m])
569
+ names |= {name for _module, name in symbols}
570
+ held = ", ".join(modules + [f"{m}:{n}" for m, n in symbols])
571
+ head = interface_head(c.interface)
572
+ if head is None:
573
+ return (
574
+ f"{c.id} interface '{c.interface}' does not start with a name; start it "
575
+ f"with a public name one of its modules defines ({held})"
576
+ )
577
+ name, method = head
578
+ if name not in names:
579
+ closest = _closest(name, names)
580
+ hint = f"; closest: {closest}" if closest else ""
581
+ return (
582
+ f"{c.id} interface starts with {name}, which none of its modules defines ({held}){hint}"
583
+ )
584
+ if not method:
585
+ return ""
586
+ methods: set[str] = set()
587
+ for m in modules:
588
+ methods |= method_names(components[m], name)
589
+ # A class re-exported by a package __init__ keeps its methods in
590
+ # the module that defines it.
591
+ for source in _reexport_sources(components[m], name):
592
+ if source in components:
593
+ methods |= method_names(components[source], name)
594
+ for m, n in symbols:
595
+ if n == name and m in components:
596
+ methods |= method_names(components[m], name)
597
+ if method not in methods and method not in names:
598
+ # The class's own methods first: a wrong method is usually a
599
+ # misspelt one, not a module-level name.
600
+ closest = _closest(method, methods) or _closest(method, names)
601
+ hint = f"; closest: {closest}" if closest else ""
602
+ return (
603
+ f"{c.id} interface names {name}.{method}, but {name} has no public method "
604
+ f"{method} ({held}){hint}"
605
+ )
606
+ return ""
607
+
608
+
609
+ # ---- stale: the outputs are what the tree and the model say ----------------------
610
+
611
+
612
+ def stale_facts(
613
+ fresh: dict[str, Any], stored: dict[str, Any], model: Model, prefixes: set[str]
614
+ ) -> list[str]:
615
+ """Ways the stored facts no longer describe the tree, plus claims of
616
+ modules the tree does not have. The rule `extract --check` runs."""
617
+ problems = extract.drift(fresh, stored) + extract.mapping_drift(fresh, model, prefixes)
618
+ if not stored:
619
+ problems.insert(0, "no facts have been built yet")
620
+ return problems
621
+
622
+
623
+ def stale(
624
+ cfg: Config,
625
+ tree: nest.Tree,
626
+ fresh: dict[str, Any] | None = None,
627
+ ) -> list[str]:
628
+ """Every output that is older than the tree or the model.
629
+
630
+ The facts are compared against a fresh extraction, every map's page
631
+ against a fresh render from the stored facts (the committed page must
632
+ match the committed facts, whatever the tree has since done), and
633
+ each configured figure against the generator. A model that
634
+ contradicts itself cannot be rendered honestly, so its page is not
635
+ compared then; the placement and meaning rules report the rest.
636
+ """
637
+ fresh = fresh if fresh is not None else extract.build(cfg)
638
+ stored = extract.read_facts(cfg.facts_path)
639
+ if not stored:
640
+ return ["no facts have been built yet"]
641
+ # Only the drift is stale here: a claim of a module the tree does not
642
+ # have is the entry rule's finding, and a placement problem is the
643
+ # placement rule's, so neither is reported twice.
644
+ out = [f"facts: {line}" for line in extract.drift(fresh, stored)]
645
+ for m in tree.maps:
646
+ if model_problems(m.model, m.meaning):
647
+ continue
648
+ html = page.build(
649
+ cfg,
650
+ m.model,
651
+ m.meaning,
652
+ m.theme,
653
+ stored,
654
+ {"has_change": False},
655
+ nesting=page.nesting_of(cfg, tree, m, stored),
656
+ )
657
+ out += _stale_file(cfg, m.page_path(cfg), html)
658
+ for fig in cfg.figures:
659
+ if not tree.has(fig.map):
660
+ raise nest.unknown_map(tree, fig.map)
661
+ m = tree.get(fig.map)
662
+ if model_problems(m.model, m.meaning):
663
+ continue
664
+ html, _collisions = figure.configured(cfg, tree, m, stored, fig)
665
+ out += _stale_file(cfg, cfg.out_path / fig.out, html)
666
+ return out
667
+
668
+
669
+ def _stale_file(cfg: Config, path: Path, expected: str) -> list[str]:
670
+ rel = cfg.rel(path)
671
+ if not path.is_file():
672
+ return [f"{rel} has not been rendered"]
673
+ if path.read_text(encoding="utf-8") != expected:
674
+ return [f"{rel} differs from what systemap renders"]
675
+ return []
676
+
677
+
678
+ # ---- one run -------------------------------------------------------------------
679
+
680
+
681
+ @dataclass(frozen=True)
682
+ class Result:
683
+ """Everything one check run found.
684
+
685
+ `problems` are the placement, meaning, route, label, type-size and
686
+ wheel findings; `coverage` is the module rule; `entry` is the rule that
687
+ every card is code in the tree; `interface` the rule that a signature
688
+ names what the modules define; `nesting` the rule that the map inside
689
+ a card is that card and nothing else (on the sub-map's own result);
690
+ `stale` is filled in by the CLI, which has the configuration the
691
+ comparison needs; `through` and `across` count edges through a
692
+ foreign card and across a foreign region.
693
+ """
694
+
695
+ problems: list[str]
696
+ through: int
697
+ across: int
698
+ coverage: Coverage
699
+ entry: list[str] = field(default_factory=list)
700
+ interface: list[str] = field(default_factory=list)
701
+ nesting: list[str] = field(default_factory=list)
702
+ stale: list[str] = field(default_factory=list)
703
+
704
+ @property
705
+ def ok(self) -> bool:
706
+ return (
707
+ not self.problems
708
+ and self.coverage.ok
709
+ and not self.entry
710
+ and not self.interface
711
+ and not self.nesting
712
+ and not self.stale
713
+ )
714
+
715
+
716
+ def run(
717
+ model: Model,
718
+ meaning: Meaning,
719
+ t: dict[str, Any],
720
+ facts: dict[str, Any],
721
+ ignores: Iterable[Ignore] = (),
722
+ observed_by: Iterable[str] = (),
723
+ *,
724
+ coverage: bool = True,
725
+ ) -> Result:
726
+ """Check one map against the facts.
727
+
728
+ Placement and meaning are checked first; the drawing is only attempted
729
+ once those are clean, since a model that contradicts itself cannot be
730
+ drawn honestly. Coverage is checked regardless, because it reads the
731
+ facts and the claims only, never the drawing; `coverage=False` is the
732
+ map inside a card, whose modules the card counted once above.
733
+ `observed_by` is the repository's list of non-import mechanisms; it
734
+ changes what the drawing says of an edge, never what the check refuses.
735
+ """
736
+ problems = model_problems(model, meaning)
737
+ through = across = 0
738
+ if not problems:
739
+ svg, detail = render_schematic(model, meaning, t, facts, observed_by=observed_by)
740
+ meta = json.loads(detail)["_meta"]
741
+ route_problems, through, across = check_routes(meta, model)
742
+ problems += route_problems
743
+ problems += check_labels(meta)
744
+ problems += check_type_size(svg)
745
+ problems += check_wheels(meta["edges"], model, meaning)
746
+ counted = check_coverage(model, facts, ignores) if coverage else NOT_COUNTED
747
+ return Result(
748
+ problems,
749
+ through,
750
+ across,
751
+ counted,
752
+ entry=check_entry(model, facts),
753
+ interface=check_interface(model, facts),
754
+ )
755
+
756
+
757
+ def run_tree(
758
+ tree: nest.Tree,
759
+ facts: dict[str, Any],
760
+ ignores: Iterable[Ignore] = (),
761
+ observed_by: Iterable[str] = (),
762
+ ) -> dict[str, Result]:
763
+ """Every map checked, by map id: coverage on the top, nesting on each sub-map."""
764
+ out: dict[str, Result] = {}
765
+ for m in tree.maps:
766
+ result = run(m.model, m.meaning, m.theme, facts, ignores, observed_by, coverage=m.top)
767
+ card = tree.opening_card(m)
768
+ if card is not None:
769
+ parent = tree.get(m.parent or "")
770
+ nesting = check_nesting(parent.model, card, m.model, facts, m.rel)
771
+ result = replace(result, nesting=nesting)
772
+ out[m.id] = result
773
+ return out
774
+
775
+
776
+ def tree_ok(results: Mapping[str, Result]) -> bool:
777
+ return all(result.ok for result in results.values())
778
+
779
+
780
+ def with_stale(result: Result, lines: list[str]) -> Result:
781
+ return replace(result, stale=lines)
782
+
783
+
784
+ def _plural(n: int, noun: str) -> str:
785
+ return f"{n} {noun}{'s' if n != 1 else ''}"
786
+
787
+
788
+ def coverage_line(cov: Coverage) -> str:
789
+ """`coverage: 144 of 144 modules mapped, 5 of them ignored with a reason,
790
+ 9 of them empty package markers`: the mapped count includes both."""
791
+ line = f"coverage: {cov.mapped} of {cov.total} modules mapped"
792
+ if cov.ignored:
793
+ line += f", {cov.ignored} of them ignored with a reason"
794
+ if cov.markers:
795
+ noun = "an empty package marker" if cov.markers == 1 else "empty package markers"
796
+ line += f", {cov.markers} of them {noun}"
797
+ return line
798
+
799
+
800
+ def report(
801
+ model: Model, result: Result, model_file: str = "the model", prefix: str = ""
802
+ ) -> list[str]:
803
+ """The lines the CLI prints for one check run: each failing rule with
804
+ its findings and the fix under them. `prefix` is what a sub-map's
805
+ lines carry in front, its id and a colon."""
806
+ return [prefix + line for line in _report(model, result, model_file)]
807
+
808
+
809
+ def report_stale(lines: list[str]) -> list[str]:
810
+ """The stale group, printed once for the whole tree after every map's rules."""
811
+ if not lines:
812
+ return []
813
+ return [
814
+ f"stale: {_plural(len(lines), 'problem')}",
815
+ *(f" {line}" for line in lines),
816
+ " fix: run: systemap refresh, then commit the output directory",
817
+ ]
818
+
819
+
820
+ def _report(model: Model, result: Result, model_file: str) -> list[str]:
821
+ through, across = result.through, result.across
822
+ out = [
823
+ f"map routes: {through} edge{'s' if through != 1 else ''} through a card "
824
+ f"they do not connect, {across} across a region they neither start nor end in"
825
+ ]
826
+ cov = result.coverage
827
+ if not cov.counted:
828
+ pass
829
+ elif cov.checked:
830
+ out.append(coverage_line(cov))
831
+ out += [f" {line}" for line in cov.problems]
832
+ if cov.problems:
833
+ out.append(
834
+ f" fix: map every module in {model_file}, or ignore it with a reason "
835
+ "under [coverage] in the configuration"
836
+ )
837
+ else:
838
+ out.append("coverage: not checked, there are no facts; run: systemap extract")
839
+ if result.nesting:
840
+ out.append(f"nesting: {_plural(len(result.nesting), 'problem')}")
841
+ out += [f" {line}" for line in result.nesting]
842
+ out.append(
843
+ f" fix: in {model_file}, claim exactly the modules the card that opens it "
844
+ "claims, each once, and name only cards of the map above as actors"
845
+ )
846
+ if result.entry:
847
+ out.append(f"entry: {_plural(len(result.entry), 'problem')}")
848
+ out += [f" {line}" for line in result.entry]
849
+ out.append(
850
+ f" fix: in {model_file}, name only modules the facts have and set entry to "
851
+ "a public name one of them defines (a function, a class, an object such as "
852
+ "app); the map draws what exists today"
853
+ )
854
+ if result.interface:
855
+ out.append(f"interface: {_plural(len(result.interface), 'problem')}")
856
+ out += [f" {line}" for line in result.interface]
857
+ out.append(
858
+ f" fix: in {model_file}, start interface with a public name one of the "
859
+ "component's modules defines (Class.method for a method), or leave it empty"
860
+ )
861
+ problems = result.problems
862
+ if problems:
863
+ out.append(f"map layout: {_plural(len(problems), 'problem')}")
864
+ out += [f" {line}" for line in problems]
865
+ out.append(f" fix: edit {model_file}, then run: systemap check")
866
+ else:
867
+ n = len(model.components)
868
+ out.append(
869
+ f"map layout: clean ({n} cards, {len(model.flows)} orthogonal labelled "
870
+ f"edges, {n} wheels, nothing below {TEXT_PX:g}px)"
871
+ )
872
+ out += report_stale(result.stale)
873
+ return out