GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — buildex/buildex.py at main · hww/buildex

Expand file tree

/

buildex.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
2294 lines (2027 loc) · 93 KB
/

buildex.py

Copy path

File metadata and controls

2294 lines (2027 loc) · 93 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
buildex.py — генератор документации по архитектуре (стиль даташитов 90-х).
Идея: в YAML описывается только СУТЬ (регистры, биты, коды, автоматы, карты памяти,
временные диаграммы). Картинки и таблицы выводятся из сути сами.
Раскладка проекта:
src/<project>/spec/*.yaml спецификации (много документов через '---')
src/<project>/docs/**/*.md текст документации с директивами {{...}}
src/<project>/buildex.yaml (необязательно) lang: en | ru
out/<project>/docs/... результат (+ gen/ с картинками и таблицами)
Директивы в Markdown:
{{auto:NAME}} рисунок (если есть) + таблица
{{figure:NAME}} рисунок с подписью и автонумерацией
{{table:NAME}} таблица с подписью и автонумерацией
{{ref:NAME}} ссылка на сущность; {{ref:NAME.FIELD}} — на поле/код/регистр
{{const:NAME}} значение константы
{{include:path}} вставка другого .md
Команды:
buildex.py [build] [project ...] [--deploy] [--watch]
buildex.py kinds список сущностей
buildex.py explain <kind> схема и пример
buildex.py new <kind> <name> заготовка YAML (в stdout)
"""
import argparse
import copy
import difflib
import filecmp
import hashlib
import importlib.util
import html
import math
import os
import posixpath
import re
import shutil
import sys
import time
import urllib.parse
from pathlib import Path
from types import SimpleNamespace as NS
import yaml
VERSION = "1.6"
ROOT = Path(__file__).resolve().parent
SRC = ROOT / "src"
OUT = ROOT / "out"
# =============================================================================
# Утилиты
# =============================================================================
INK = "#000000"
GRAY_TXT = "#555555"
FILL_A, FILL_B = "#F2F2F2", "#E0E0E0"
FILL_FIXED = "#DCE8F6"
GROUP_FILLS = ["#F2F2F2", "#DCE8F6", "#E6F2DC", "#F6E8DC", "#EBDCF6", "#F6F3DC"]
CAPTIONS = {
"en": {"figure": "Figure", "table": "Table", "fields": "Fields"},
"ru": {"figure": "Рис.", "table": "Таблица", "fields": "Поля"},
}
def esc(v):
return html.escape(str(v), quote=True)
def n(v):
s = f"{v:.1f}"
return s[:-2] if s.endswith(".0") else s
def as_int(v):
if isinstance(v, bool):
return None
if isinstance(v, int):
return v
if isinstance(v, str):
try:
return int(v.replace("_", "").strip(), 0)
except ValueError:
return None
return None
def as_list(v):
if v is None:
return []
return list(v) if isinstance(v, (list, tuple)) else [v]
def anchor_id(name):
return re.sub(r"[^A-Za-z0-9_.\-]", "_", str(name))
def hexw(v, bits):
return f"0x{v:0{max(1, (bits + 3) // 4)}X}"
def fmt_size(sz):
for unit, k in (("GiB", 1 << 30), ("MiB", 1 << 20), ("KiB", 1 << 10)):
if sz >= k and sz % k == 0:
return f"{sz // k} {unit}"
return f"{sz} B"
def md_cell(v):
if v is None or v == "":
return "—"
return str(v).replace("|", "\\|").replace("\n", "<br>")
def md_table(headers, rows):
out = ["| " + " | ".join(headers) + " |", "| " + " | ".join("---" for _ in headers) + " |"]
for r in rows:
out.append("| " + " | ".join(md_cell(c) for c in r) + " |")
return "\n".join(out) + "\n"
def write_if_changed(path, content, produced):
path = Path(path)
produced.add(path.resolve())
path.parent.mkdir(parents=True, exist_ok=True)
if path.exists() and path.read_text(encoding="utf-8") == content:
return
path.write_text(content, encoding="utf-8")
def smart_copy(src, dst, produced):
produced.add(Path(dst).resolve())
dst.parent.mkdir(parents=True, exist_ok=True)
if dst.exists() and filecmp.cmp(src, dst, shallow=False):
return
shutil.copy2(src, dst)
def _hash(p):
h = hashlib.md5()
with open(p, "rb") as f:
for chunk in iter(lambda: f.read(1 << 16), b""):
h.update(chunk)
return h.hexdigest()
def sync_tree(src_dir, dst_dir, produced):
"""Зеркалит src_dir -> dst_dir, копируя только новые/изменённые файлы (по md5)."""
src_dir, dst_dir = Path(src_dir), Path(dst_dir)
if not src_dir.exists():
return
for f in sorted(src_dir.rglob("*")):
if not f.is_file():
continue
dst = dst_dir / f.relative_to(src_dir)
produced.add(dst.resolve())
if dst.exists() and _hash(dst) == _hash(f):
continue
dst.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(f, dst)
# ---------- метрики текста (оценка ширины без шрифтов) ----------
_NARROW = set("iljtfIr.,:;'|!()[]/\\ 1")
_WIDE = set("mwMW@%")
def tw(s, size, mono=False, bold=False):
s = str(s)
if mono:
return len(s) * size * 0.6
w = 0.0
for ch in s:
if ch in _NARROW:
w += 0.32
elif ch in _WIDE:
w += 0.88
elif ch.isupper() or ch.isdigit():
w += 0.66
else:
w += 0.56
return w * size * (1.07 if bold else 1.0)
# =============================================================================
# Диагностика
# =============================================================================
class Diag:
def __init__(self):
self.errors, self.warnings = [], []
def err(self, where, msg):
self.errors.append(f"{where}: {msg}")
def warn(self, where, msg):
self.warnings.append(f"{where}: {msg}")
def report(self):
for w in self.warnings:
print(f" ⚠️ {w}")
for e in self.errors:
print(f" ❌ {e}")
def W_(spec):
return f"{spec.get('_file', '?')}:{spec.get('_line', '?')} {spec.get('kind', '?')} '{spec.get('name', '?')}'"
BASE_KEYS = ["kind", "name", "title", "subtitle", "description", "view", "notes"]
def check_keys(d, allowed, where, P, what="key"):
allowed = list(allowed)
for k in d:
if str(k).startswith("_") or k in allowed:
continue
m = difflib.get_close_matches(str(k), allowed, n=1)
hint = f" — did you mean '{m[0]}'?" if m else f" (allowed: {', '.join(sorted(allowed))})"
P.diag.err(where, f"unknown {what} '{k}'{hint}")
class UniqueLoader(yaml.SafeLoader):
"""SafeLoader, который ловит дубли ключей (типично: забыли '---') и помнит строку документа."""
last_line = 0
def construct_document(self, node):
self.last_line = node.start_mark.line + 1
return super().construct_document(node)
def construct_mapping(self, node, deep=False):
seen = set()
for k, _ in node.value:
if isinstance(k, yaml.ScalarNode):
if k.value in seen:
raise yaml.constructor.ConstructorError(
None, None,
f"duplicate key '{k.value}' at line {k.start_mark.line + 1} "
f"(forgot '---' between documents?)", k.start_mark)
seen.add(k.value)
return super().construct_mapping(node, deep)
# =============================================================================
# SVG-примитивы
# =============================================================================
SVG_DEFS = """<defs>
<pattern id="hatch" width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(45)">
<rect width="6" height="6" fill="#FFFFFF"/><line x1="0" y1="0" x2="0" y2="6" stroke="#B0B0B0" stroke-width="2"/></pattern>
<pattern id="xpat" width="8" height="8" patternUnits="userSpaceOnUse">
<rect width="8" height="8" fill="#FFFFFF"/><path d="M0 0L8 8M8 0L0 8" stroke="#C07070" stroke-width="1"/></pattern>
<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto">
<path d="M0 0L10 5L0 10z" fill="#000000"/></marker>
</defs>"""
class Svg:
def __init__(self):
self.p = []
def add(self, s):
self.p.append(s)
def line(self, x1, y1, x2, y2, stroke=INK, sw=1, dash=None):
d = f' stroke-dasharray="{dash}"' if dash else ""
self.p.append(f'<line x1="{n(x1)}" y1="{n(y1)}" x2="{n(x2)}" y2="{n(y2)}" stroke="{stroke}" stroke-width="{sw}"{d}/>')
def rect(self, x, y, w, h, fill="none", stroke=INK, sw=1.5, rx=0, dash=None):
d = f' stroke-dasharray="{dash}"' if dash else ""
r = f' rx="{rx}"' if rx else ""
self.p.append(f'<rect x="{n(x)}" y="{n(y)}" width="{n(w)}" height="{n(h)}" fill="{fill}" stroke="{stroke}" stroke-width="{sw}"{r}{d}/>')
def poly(self, pts, fill="none", stroke=INK, sw=1.5):
s = " ".join(f"{n(x)},{n(y)}" for x, y in pts)
self.p.append(f'<polygon points="{s}" fill="{fill}" stroke="{stroke}" stroke-width="{sw}"/>')
def path(self, d, stroke=INK, sw=1.5, fill="none", marker=False, dash=None):
m = ' marker-end="url(#arr)"' if marker else ""
da = f' stroke-dasharray="{dash}"' if dash else ""
self.p.append(f'<path d="{d}" fill="{fill}" stroke="{stroke}" stroke-width="{sw}"{m}{da}/>')
def circle(self, cx, cy, r, fill="none", stroke=INK, sw=1.5):
self.p.append(f'<circle cx="{n(cx)}" cy="{n(cy)}" r="{n(r)}" fill="{fill}" stroke="{stroke}" stroke-width="{sw}"/>')
def text(self, x, y, t, size=12, anchor="middle", bold=False, mono=False, fill=INK, rot=None, halo=False, over=False):
cls = ' class="m"' if mono else ""
w = ' font-weight="700"' if bold else ""
tr = f' transform="rotate({rot} {n(x)} {n(y)})"' if rot else ""
st = []
if halo:
st.append("paint-order:stroke;stroke:#fff;stroke-width:3px;stroke-linejoin:round")
if over:
st.append("text-decoration:overline")
sty = f' style="{";".join(st)}"' if st else ""
self.p.append(f'<text x="{n(x)}" y="{n(y)}" font-size="{n(size)}" text-anchor="{anchor}" fill="{fill}"{w}{cls}{tr}{sty}>{esc(t)}</text>')
def fit_label(self, cx, cy, t, avail_w, avail_h, bold=True, max_size=14, min_size=9, fill=INK, halo=False):
"""Подпись внутри ячейки: уменьшаем шрифт, затем поворачиваем, затем обрезаем."""
t = str(t)
size = max_size
while size >= min_size and tw(t, size, bold=bold) > avail_w - 6:
size -= 1
if size >= min_size:
self.text(cx, cy + size * 0.35, t, size, bold=bold, fill=fill, halo=halo)
return
rsize = min(12, max_size)
while rsize >= min_size and tw(t, rsize, bold=bold) > avail_h - 8:
rsize -= 1
if rsize >= min_size and avail_w >= rsize + 4:
self.text(cx, cy + rsize * 0.35, t, rsize, bold=bold, fill=fill, rot=-90, halo=halo)
return
s = t
while len(s) > 1 and tw(s + "…", min_size, bold=bold) > avail_w - 4:
s = s[:-1]
self.text(cx, cy + min_size * 0.35, s + "…", min_size, bold=bold, fill=fill, halo=halo)
def inner(self):
return "\n".join(self.p)
def svg_doc(W, H, title, subtitle, inner):
W = max(W, tw(title, 22, bold=True) + 64, tw(subtitle or "", 14) + 64)
head = (f'<text x="32" y="38" font-size="22" font-weight="700" fill="{INK}">{esc(title)}</text>\n'
f'<text x="32" y="62" font-size="14" fill="{GRAY_TXT}">{esc(subtitle or "")}</text>\n')
return (f'<svg xmlns="http://www.w3.org/2000/svg" width="{n(W)}" height="{n(H)}" viewBox="0 0 {n(W)} {n(H)}">\n'
f'{SVG_DEFS}\n<style>text{{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}}'
f'.m{{font-family:ui-monospace,Menlo,Consolas,"DejaVu Sans Mono",monospace}}</style>\n'
f'<rect width="{n(W)}" height="{n(H)}" fill="#FFFFFF"/>\n{head}{inner}\n</svg>\n')
# =============================================================================
# Поля (bitfield) — общая основа для bitfield / encoding / regmap
# =============================================================================
FIELD_KEYS = ["name", "bits", "bit", "msb", "lsb", "description", "access", "reset", "enum", "reserved", "value", "group", "overlay"]
def fmt_const(v, nbits):
if nbits == 1:
return str(v)
if nbits <= 4:
return format(v, f"0{nbits}b") + "b"
return hexw(v, nbits)
def fmt_reset(v, nbits):
if isinstance(v, int) and not isinstance(v, bool):
return str(v) if nbits == 1 else hexw(v, nbits)
return None if v is None else str(v)
def norm_field(raw, W, where, P):
if not isinstance(raw, dict):
P.diag.err(where, f"field must be a mapping, got {raw!r}")
return None
nm = raw.get("name")
check_keys(raw, FIELD_KEYS, f"{where} field '{nm}'", P, "field key")
reserved = bool(raw.get("reserved", False))
if nm is None and reserved:
nm = "RSV"
if not nm:
P.diag.err(where, f"field without 'name': {raw!r}")
return None
nm = str(nm)
msb = lsb = None
if "bits" in raw:
b = raw["bits"]
if isinstance(b, (list, tuple)) and len(b) == 2:
msb, lsb = as_int(b[0]), as_int(b[1])
elif as_int(b) is not None and not isinstance(b, str):
msb = lsb = as_int(b)
elif isinstance(b, str) and ":" in b:
p = b.strip("[] ").split(":")
msb, lsb = as_int(p[0]), as_int(p[1])
elif "bit" in raw:
msb = lsb = as_int(raw["bit"])
elif "msb" in raw and "lsb" in raw:
msb, lsb = as_int(raw["msb"]), as_int(raw["lsb"])
if msb is None or lsb is None:
P.diag.err(where, f"field '{nm}': need 'bits: [msb, lsb]' or 'bit: N'")
return None
if not (0 <= lsb <= msb < W):
P.diag.err(where, f"field '{nm}': bits [{msb}:{lsb}] outside 0..{W - 1}")
return None
nb = msb - lsb + 1
fixed = None
if "value" in raw:
fixed = as_int(raw["value"])
if fixed is None or not (0 <= fixed < (1 << nb)):
P.diag.err(where, f"field '{nm}': value {raw['value']!r} does not fit {nb} bit(s)")
fixed = None
return NS(name=nm, msb=msb, lsb=lsb, nb=nb, desc=raw.get("description"), access=raw.get("access"),
reset=fmt_reset(raw.get("reset"), nb), enum=raw.get("enum"), reserved=reserved,
fixed=fixed, group=raw.get("group"), overlay=bool(raw.get("overlay")))
def apply_fixed(fields, fixed, where, P):
for k, v in (fixed or {}).items():
f = next((x for x in fields if x.name == k), None)
if f is None:
m = difflib.get_close_matches(str(k), [x.name for x in fields], n=1)
P.diag.err(where, f"'fixed/when' refers to unknown field '{k}'" + (f" — did you mean '{m[0]}'?" if m else ""))
continue
iv = as_int(v)
if iv is None or not (0 <= iv < (1 << f.nb)):
P.diag.err(where, f"field '{k}': value {v!r} does not fit {f.nb} bit(s)")
continue
f.fixed = iv
def check_layout(fields, W, where, P, warn_gaps=True, tag=""):
used, cover = {}, set()
for f in fields:
cover.update(range(f.lsb, f.msb + 1))
if f.overlay:
continue
for b in range(f.lsb, f.msb + 1):
if b in used:
P.diag.err(where, f"{tag}fields '{used[b]}' and '{f.name}' overlap at bit {b} (use 'overlay: true' for an alternate meaning of the same bits)")
break
used[b] = f.name
if warn_gaps:
gaps, start = [], None
for b in range(W + 1):
if b < W and b not in cover:
start = b if start is None else start
elif start is not None:
gaps.append((b - 1, start))
start = None
if gaps:
P.diag.warn(where, f"{tag}bits not covered: " + ", ".join(f"[{h}:{l}]" if h != l else f"[{h}]" for h, l in reversed(gaps)))
def check_field_enums(fields, where, P):
for f in fields:
if not f.enum:
continue
e = P.REG.get(f.enum)
if e is None or e.get("kind") != "enum":
m = difflib.get_close_matches(str(f.enum), [k for k, v in P.REG.items() if v.get("kind") == "enum"], n=1)
P.diag.err(where, f"field '{f.name}': enum '{f.enum}' not found" + (f" — did you mean '{m[0]}'?" if m else ""))
continue
for lo, hi, _ in e.get("_ranges", []):
if hi >= (1 << f.nb):
P.diag.warn(where, f"field '{f.name}' is {f.nb} bit(s) but enum '{f.enum}' has value {hi}")
break
def merge_fields(base, extra):
out = list(base)
for f in extra:
for i, g in enumerate(out):
if g.name == f.name:
out[i] = f
break
else:
out.append(f)
return out
def resolve_bitfield(spec, P, stack=()):
if "_res" in spec:
return spec["_res"]
where = W_(spec)
if spec["name"] in stack:
P.diag.err(where, "cyclic 'extends'")
spec["_res"] = None
return None
W, base = None, []
if spec.get("extends"):
b = P.REG.get(spec["extends"])
if b is None or b.get("kind") != "bitfield":
P.diag.err(where, f"'extends: {spec['extends']}' — bitfield not found")
else:
r = resolve_bitfield(b, P, tuple(stack) + (spec["name"],))
if r:
W, base = r[0], [copy.copy(f) for f in r[1]]
if spec.get("width") is not None:
w = as_int(spec["width"])
if w is None or not 1 <= w <= 256:
P.diag.err(where, f"bad 'width': {spec['width']!r}")
else:
W = w
if W is None:
P.diag.err(where, "missing 'width' (or 'extends')")
spec["_res"] = None
return None
extra = [f for f in (norm_field(r, W, where, P) for r in as_list(spec.get("fields"))) if f]
fields = merge_fields(base, extra)
apply_fixed(fields, spec.get("fixed"), where, P)
fields.sort(key=lambda f: -f.msb)
check_layout(fields, W, where, P, warn_gaps=not spec.get("partial"))
spec["_res"] = (W, fields)
return spec["_res"]
def fields_table_md(fields, W):
ha = any(f.access for f in fields)
hr = any(f.reset is not None for f in fields)
hf = any(f.fixed is not None for f in fields)
hd = ["Field", "Bits", "Width"] + (["Access"] if ha else []) + (["Reset"] if hr else []) + (["Fixed"] if hf else []) + ["Description"]
rows = []
for f in sorted(fields, key=lambda x: -x.msb):
bits = f"[{f.msb}:{f.lsb}]" if f.msb != f.lsb else f"[{f.msb}]"
d = f.desc or ("Reserved" if f.reserved else "")
if f.enum:
d = (d + " " if d else "") + "{{" + "ref:" + str(f.enum) + "}}"
row = [f'<a id="{anchor_id(f.name)}"></a>**{f.name}**', bits, f.nb]
if ha:
row.append(f.access)
if hr:
row.append(f.reset)
if hf:
row.append(None if f.fixed is None else fmt_const(f.fixed, f.nb))
row.append(d)
rows.append(row)
return md_table(hd, rows)
def notes_md(spec):
notes = as_list(spec.get("notes"))
if not notes:
return ""
return "\n**Notes:**\n\n" + "".join(f"- {x}\n" for x in notes)
# ---------- рисование одной «полосы» битов ----------
def draw_lane(svg, fields, hi, lo, x0, y, col_w, row_h, idx_base=0):
nb = hi - lo + 1
svg.rect(x0, y, nb * col_w, row_h, fill="#FFFFFF", stroke=INK, sw=1.5)
for i, f in enumerate(fields):
sh, sl = min(f.msb, hi), max(f.lsb, lo)
if sh < sl or f.overlay:
continue
x = x0 + (hi - sh) * col_w
w = (sh - sl + 1) * col_w
if f.reserved:
fill = "url(#hatch)"
elif f.fixed is not None:
fill = FILL_FIXED
else:
fill = FILL_A if (i + idx_base) % 2 == 0 else FILL_B
svg.rect(x, y, w, row_h, fill=fill, stroke=INK, sw=1.5)
cx, cy = x + w / 2, y + row_h / 2
halo = f.reserved
if f.fixed is not None and w >= 18 and f.name:
top = f.name
val = fmt_const(f.fixed, f.nb)
if tw(top, 12, bold=True) <= w - 6 and tw(val, 11, mono=True) <= w - 4:
svg.text(cx, cy - 3, top, 12, bold=True)
svg.text(cx, cy + 12, val, 11, mono=True, fill="#1A3A6A")
else:
svg.fit_label(cx, cy, f"{top}={val}", w, row_h, bold=True, max_size=12, halo=halo)
elif f.name:
svg.fit_label(cx, cy, f.name, w, row_h, bold=True, max_size=14, halo=halo)
# засечки по границам битов внутри поля (сверху)
for b in range(sh, sl, -1):
xx = x0 + (hi - b + 1) * col_w
svg.line(xx, y, xx, y + row_h * 0.14, INK, 1)
def draw_overlays(svg, fields, hi, lo, x0, y, col_w):
"""Поля с overlay: true — альтернативная трактовка тех же битов, тонкая полоса под строкой."""
used = 0
for f in fields:
sh, sl = min(f.msb, hi), max(f.lsb, lo)
if not f.overlay or sh < sl:
continue
x = x0 + (hi - sh) * col_w
w = (sh - sl + 1) * col_w
yy = y + 4 + used * 24
svg.rect(x, yy, w, 20, fill="#FFF8E1", stroke="#8A6D00", sw=1.2, dash="4,2")
svg.fit_label(x + w / 2, yy + 10, f.name, w, 20, bold=True, max_size=11, min_size=8)
used += 1
return used * 24
def draw_bit_numbers(svg, bits, hi, x0, col_w, y):
for b in sorted(set(bits), reverse=True):
if 0 <= b <= hi:
svg.text(x0 + (hi - b + 0.5) * col_w, y, str(b), 11, mono=True, fill="#444444")
def draw_info_line(svg, fields, hi, lo, x0, col_w, y):
drawn = False
for f in fields:
sh, sl = min(f.msb, hi), max(f.lsb, lo)
if sh < sl or not (f.access or f.reset is not None):
continue
t = " · ".join(str(x) for x in (f.access, f.reset) if x not in (None, ""))
w = (sh - sl + 1) * col_w
if tw(t, 10, mono=True) <= w - 2:
svg.text(x0 + (hi - sh) * col_w + w / 2, y, t, 10, mono=True, fill=GRAY_TXT)
drawn = True
return drawn
def edge_bits(fields):
s = set()
for f in fields:
s.add(f.msb)
s.add(f.lsb)
return s
# =============================================================================
# KIND: bitfield
# =============================================================================
def v_bitfield(spec, P):
where = W_(spec)
check_keys(spec, BASE_KEYS + ["width", "fields", "extends", "fixed", "split", "partial"], where, P)
r = resolve_bitfield(spec, P)
if r:
check_field_enums(r[1], where, P)
sp = spec.get("split")
if sp is not None and (as_int(sp) is None or as_int(sp) < 1):
P.diag.err(where, f"bad 'split': {sp!r}")
def d_bitfield(spec, P):
r = spec.get("_res")
if not r:
return None
W, fields = r
lane = as_int(spec.get("split")) or min(W, 32)
lanes = [(min(W - 1, h + lane - 1), h) for h in range(0, W, lane)]
lanes = [(hi, lo) for hi, lo in sorted(lanes, reverse=True)]
multi = len(lanes) > 1
gutter = 78 if multi else 0
x0 = 32 + gutter
col_w = min(36.0, 1080.0 / lane)
row_h = 50
info = any(f.access or f.reset is not None for f in fields)
svg = Svg()
y = 104
for hi, lo in lanes:
draw_bit_numbers(svg, [b for f in fields for b in (f.msb, f.lsb) if lo <= b <= hi] + [hi, lo], hi, x0, col_w, y - 8)
if multi:
svg.text(32, y + row_h / 2 + 4, f"[{hi}:{lo}]", 13, "start", mono=True, fill=GRAY_TXT)
draw_lane(svg, fields, hi, lo, x0, y, col_w, row_h)
y += draw_overlays(svg, fields, hi, lo, x0, y + row_h, col_w)
if info:
draw_info_line(svg, fields, hi, lo, x0, col_w, y + row_h + 14)
y += 20
y += row_h + 34
Wpx = x0 + lane * col_w + 32
return svg_doc(Wpx, y - 4, spec.get("title", spec["name"]), spec.get("subtitle", f"{W}-bit register"), svg.inner())
def t_bitfield(spec, P):
r = spec.get("_res")
return (fields_table_md(r[1], r[0]) + notes_md(spec)) if r else None
def a_bitfield(spec):
r = spec.get("_res")
return {f.name for f in r[1]} if r else set()
# =============================================================================
# KIND: enum (таблица кодов)
# =============================================================================
_RANGE_RE = re.compile(r"^\s*(\S+?)\s*\.\.\s*(\S+?)\s*$")
def parse_value(v):
iv = as_int(v)
if iv is not None:
return iv, iv
if isinstance(v, str):
m = _RANGE_RE.match(v)
if m and as_int(m.group(1)) is not None and as_int(m.group(2)) is not None:
return as_int(m.group(1)), as_int(m.group(2))
return None
def fmt_value(v, spec):
radix = spec.get("radix", "dec")
bits = as_int(spec.get("width")) or 1
def one(x):
if radix == "hex":
return hexw(x, bits)
if radix == "bin":
return f"0b{x:0{bits}b}"
return str(x)
pv = parse_value(v)
if pv is None:
return str(v)
if pv[0] == pv[1] and not isinstance(v, str):
return one(pv[0])
return f"{one(pv[0])}..{one(pv[1])}"
def v_enum(spec, P):
where = W_(spec)
check_keys(spec, BASE_KEYS + ["entries", "columns", "width", "radix"], where, P)
entries = spec.get("entries")
if not isinstance(entries, list) or not entries:
P.diag.err(where, "'entries' must be a non-empty list")
return
if spec.get("radix", "dec") not in ("dec", "hex", "bin"):
P.diag.err(where, "'radix' must be dec | hex | bin")
ranges, order = [], []
for i, e in enumerate(entries):
if not isinstance(e, dict) or "value" not in e or "name" not in e:
P.diag.err(where, f"entry #{i + 1} needs 'value' and 'name': {e!r}")
continue
for k in e:
if k not in order:
order.append(k)
pv = parse_value(e["value"])
if pv:
for lo, hi, nm in ranges:
if pv[0] <= hi and lo <= pv[1]:
P.diag.err(where, f"value {e['value']} ('{e['name']}') overlaps '{nm}'")
break
ranges.append((pv[0], pv[1], e["name"]))
spec["_ranges"] = ranges
w = as_int(spec.get("width"))
if w:
for lo, hi, nm in ranges:
if hi >= (1 << w):
P.diag.warn(where, f"value {hi} ('{nm}') does not fit width {w}")
cols = []
if spec.get("columns"):
for c in spec["columns"]:
if isinstance(c, dict):
cols.append((c["key"], c.get("title", str(c["key"]).replace("_", " ").capitalize())))
else:
cols.append((c, str(c).replace("_", " ").capitalize()))
else:
keys = ["value", "name"] + [k for k in order if k not in ("value", "name")]
cols = [(k, k.replace("_", " ").capitalize()) for k in keys]
spec["_cols"] = cols
def t_enum(spec, P):
if "_cols" not in spec:
return None
rows = []
for e in spec["entries"]:
row = []
for k, _ in spec["_cols"]:
v = e.get(k)
if k == "value":
v = fmt_value(v, spec)
elif k == "name":
v = f'<a id="{anchor_id(e.get("name"))}"></a>**{e.get("name")}**'
row.append(v)
rows.append(row)
return md_table([t for _, t in spec["_cols"]], rows) + notes_md(spec)
def a_enum(spec):
return {str(e.get("name")) for e in spec.get("entries", []) if isinstance(e, dict)}
# =============================================================================
# KIND: encoding (семейство форматов слова)
# =============================================================================
def v_encoding(spec, P):
where = W_(spec)
check_keys(spec, BASE_KEYS + ["width", "common", "variants"], where, P)
W = as_int(spec.get("width"))
if W is None or not 1 <= W <= 128:
P.diag.err(where, "missing or bad 'width'")
return
common = [f for f in (norm_field(r, W, where, P) for r in as_list(spec.get("common"))) if f]
variants = spec.get("variants")
if not isinstance(variants, list) or not variants:
P.diag.err(where, "'variants' must be a non-empty list")
return
res, seen_when = [], {}
for i, v in enumerate(variants):
vw = f"{where} variant #{i + 1}"
if not isinstance(v, dict) or "name" not in v:
P.diag.err(vw, "variant needs 'name'")
continue
vw = f"{where} variant '{v['name']}'"
check_keys(v, ["name", "title", "when", "fields", "ref", "description"], vw, P, "variant key")
if v.get("ref"):
b = P.REG.get(v["ref"])
if b is None or b.get("kind") != "bitfield":
P.diag.err(vw, f"ref '{v['ref']}' is not a bitfield")
continue
r = resolve_bitfield(b, P)
if not r:
continue
if r[0] != W:
P.diag.err(vw, f"ref '{v['ref']}' is {r[0]} bits, expected {W}")
fields = [copy.copy(f) for f in r[1]]
else:
extra = [f for f in (norm_field(r_, W, vw, P) for r_ in as_list(v.get("fields"))) if f]
fields = merge_fields([copy.copy(f) for f in common], extra)
when = v.get("when") or {}
apply_fixed(fields, when, vw, P)
fields.sort(key=lambda f: -f.msb)
check_layout(fields, W, vw, P, tag="")
check_field_enums(fields, vw, P)
key = tuple(sorted((str(k), as_int(x)) for k, x in when.items()))
if key in seen_when:
P.diag.err(vw, f"same 'when' as variant '{seen_when[key]}' — ambiguous decoding")
seen_when[key] = v["name"]
res.append(NS(name=str(v["name"]), title=v.get("title"), when=when, desc=v.get("description"), fields=fields))
spec["_W"], spec["_vars"] = W, res
def when_str(when):
return " ".join(f"{k}={v}" for k, v in when.items())
def stack_diagram(title, subtitle, rows, W, header_bits):
"""rows: [(label, sublabel, fields)] — общая сетка битов, подписи слева."""
svg = Svg()
lab_w = max([tw(r[0], 13, bold=True) for r in rows] + [tw(r[1], 11, mono=True) for r in rows if r[1]] + [30]) + 20
x0 = 32 + lab_w
col_w = min(36.0, 1000.0 / W)
row_h, gap, y = 46, 14, 112
draw_bit_numbers(svg, header_bits | {W - 1, 0}, W - 1, x0, col_w, y - 10)
for i, (lab, sub, fields) in enumerate(rows):
svg.text(32, y + row_h / 2 - (3 if sub else -4), lab, 13, "start", bold=True)
if sub:
svg.text(32, y + row_h / 2 + 13, sub, 11, "start", mono=True, fill=GRAY_TXT)
draw_lane(svg, fields, W - 1, 0, x0, y, col_w, row_h)
y += draw_overlays(svg, fields, W - 1, 0, x0, y + row_h, col_w)
y += row_h + gap
return svg_doc(x0 + W * col_w + 32, y + 8, title, subtitle, svg.inner())
def d_encoding(spec, P):
if "_vars" not in spec:
return None
W = spec["_W"]
rows = [(v.title or v.name, when_str(v.when), v.fields) for v in spec["_vars"]]
bits = set()
for v in spec["_vars"]:
bits |= edge_bits(v.fields)
return stack_diagram(spec.get("title", spec["name"]), spec.get("subtitle", f"{W}-bit word · {len(rows)} formats"), rows, W, bits)
def t_encoding(spec, P):
if "_vars" not in spec:
return None
md = md_table(["Format", "Selector", "Description"],
[[f'<a id="{anchor_id(v.name)}"></a>**{v.title or v.name}**', f"`{when_str(v.when)}`" if v.when else "—", v.desc] for v in spec["_vars"]])
for v in spec["_vars"]:
md += f"\n**{v.title or v.name}**" + (f" (`{when_str(v.when)}`)" if v.when else "") + "\n\n"
md += fields_table_md(v.fields, spec["_W"])
return md + notes_md(spec)
def a_encoding(spec):
s = set()
for v in spec.get("_vars", []):
s.add(v.name)
s |= {f.name for f in v.fields}
return s
# =============================================================================
# KIND: regmap (регистры по смещениям)
# =============================================================================
def v_regmap(spec, P):
where = W_(spec)
check_keys(spec, BASE_KEYS + ["width", "registers", "base"], where, P)
W = as_int(spec.get("width", 32))
if W is None or not 1 <= W <= 128:
P.diag.err(where, "bad 'width'")
return
regs, seen = [], {}
for i, r in enumerate(as_list(spec.get("registers"))):
rw = f"{where} register #{i + 1}"
if not isinstance(r, dict) or "name" not in r or "offset" not in r:
P.diag.err(rw, "register needs 'offset' and 'name'")
continue
rw = f"{where} register '{r['name']}'"
check_keys(r, ["offset", "name", "ref", "fields", "access", "reset", "description", "width"], rw, P, "register key")
off = as_int(r["offset"])
if off is None:
P.diag.err(rw, f"bad offset {r['offset']!r}")
continue
if off in seen:
P.diag.err(rw, f"offset {hexw(off, 8)} already used by '{seen[off]}'")
seen[off] = r["name"]
rwid, fields = as_int(r.get("width")) or W, []
if r.get("ref"):
b = P.REG.get(r["ref"])
if b is None or b.get("kind") != "bitfield":
P.diag.err(rw, f"ref '{r['ref']}' is not a bitfield")
else:
rr = resolve_bitfield(b, P)
if rr:
rwid, fields = rr[0], rr[1]
elif r.get("fields"):
fields = [f for f in (norm_field(x, rwid, rw, P) for x in r["fields"]) if f]
fields.sort(key=lambda f: -f.msb)
check_layout(fields, rwid, rw, P)
check_field_enums(fields, rw, P)
regs.append(NS(offset=off, name=str(r["name"]), fields=fields, width=rwid, access=r.get("access"),
reset=fmt_reset(r.get("reset"), rwid), desc=r.get("description")))
regs.sort(key=lambda r: r.offset)
spec["_W"], spec["_regs"] = W, regs
def _offw(regs):
return max([2] + [(r.offset.bit_length() + 3) // 4 for r in regs])
def t_regmap(spec, P):
if "_regs" not in spec:
return None
regs = spec["_regs"]
ow = _offw(regs)
ha = any(r.access for r in regs)
hr = any(r.reset is not None for r in regs)
hd = ["Offset", "Name"] + (["Access"] if ha else []) + (["Reset"] if hr else []) + ["Description"]
rows = []
for r in regs:
row = [f"`0x{r.offset:0{ow}X}`", f'<a id="{anchor_id(r.name)}"></a>**{r.name}**']
if ha:
row.append(r.access)
if hr:
row.append(r.reset)
row.append(r.desc)
rows.append(row)
md = md_table(hd, rows)
for r in regs:
if r.fields:
md += f"\n**{r.name}** (`0x{r.offset:0{ow}X}`)\n\n" + fields_table_md(r.fields, r.width)
return md + notes_md(spec)
def d_regmap(spec, P):
if "_regs" not in spec:
return None
W, regs = spec["_W"], spec["_regs"]
ow = _offw(regs)
rows, bits = [], set()
for r in regs:
fl = r.fields or [NS(name=r.name, msb=r.width - 1, lsb=0, nb=r.width, fixed=None, reserved=False, access=None, reset=None, desc=None, enum=None, overlay=False, group=None)]
bits |= edge_bits(fl)
rows.append((r.name, f"0x{r.offset:0{ow}X}", fl))
return stack_diagram(spec.get("title", spec["name"]), spec.get("subtitle", f"{W}-bit registers"), rows, W, bits)
def a_regmap(spec):
s = set()
for r in spec.get("_regs", []):
s.add(r.name)
s |= {f.name for f in r.fields}
return s
# =============================================================================
# KIND: memmap
# =============================================================================
def v_memmap(spec, P):
where = W_(spec)
check_keys(spec, BASE_KEYS + ["width", "regions", "order"], where, P)
aw = as_int(spec.get("width", 32)) or 32
regs = []
for i, r in enumerate(as_list(spec.get("regions"))):
rw = f"{where} region #{i + 1}"
if not isinstance(r, dict) or "name" not in r:
P.diag.err(rw, "region needs 'name'")
continue
rw = f"{where} region '{r['name']}'"
check_keys(r, ["name", "start", "end", "size", "access", "purpose", "description", "group", "width"], rw, P, "region key")
st = as_int(r.get("start"))
en = as_int(r.get("end"))
sz = as_int(r.get("size"))
if st is None or (en is None and sz is None):
P.diag.err(rw, "need 'start' and ('end' or 'size')")
continue
if en is None:
en = st + sz - 1
if en < st:
P.diag.err(rw, "end < start")
continue
if en >= (1 << aw):
P.diag.err(rw, f"end {hex(en)} outside {aw}-bit address space")
regs.append(NS(name=str(r["name"]), start=st, end=en, access=r.get("access"),
purpose=r.get("purpose") or r.get("description"), group=r.get("group"), width=r.get("width")))
regs.sort(key=lambda r: r.start)
for a, b in zip(regs, regs[1:]):
if b.start <= a.end:
P.diag.err(where, f"regions '{a.name}' and '{b.name}' overlap")
spec["_aw"], spec["_regions"] = aw, regs
def d_memmap(spec, P):
if "_regions" not in spec:
return None
aw, regs = spec["_aw"], spec["_regions"]
dig = (aw + 3) // 4
items = []
for i, r in enumerate(regs):
if i and r.start > regs[i - 1].end + 1:
items.append(NS(gap=True, start=regs[i - 1].end + 1, end=r.start - 1))
View remainder of file in raw view
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.