chipgraph 0.1.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.
Files changed (252) hide show
  1. chipgraph/__init__.py +7 -0
  2. chipgraph/adapters/__init__.py +1 -0
  3. chipgraph/adapters/format/__init__.py +6 -0
  4. chipgraph/adapters/format/__main__.py +16 -0
  5. chipgraph/adapters/format/_yaml_lines.py +54 -0
  6. chipgraph/adapters/format/chip_yaml.py +323 -0
  7. chipgraph/adapters/format/qsoc_contract.py +246 -0
  8. chipgraph/adapters/llm/__init__.py +58 -0
  9. chipgraph/adapters/llm/_budget.py +173 -0
  10. chipgraph/adapters/llm/_errors.py +50 -0
  11. chipgraph/adapters/llm/_nda.py +30 -0
  12. chipgraph/adapters/llm/_retry.py +85 -0
  13. chipgraph/adapters/llm/anthropic.py +247 -0
  14. chipgraph/adapters/llm/decide_backend.py +179 -0
  15. chipgraph/adapters/llm/fake.py +87 -0
  16. chipgraph/adapters/llm/guard.py +68 -0
  17. chipgraph/adapters/parser/__init__.py +22 -0
  18. chipgraph/adapters/parser/cocotb.py +304 -0
  19. chipgraph/adapters/parser/generic_regex.py +75 -0
  20. chipgraph/adapters/parser/verible.py +55 -0
  21. chipgraph/adapters/parser/verilator.py +46 -0
  22. chipgraph/adapters/review/__init__.py +7 -0
  23. chipgraph/adapters/review/file.py +123 -0
  24. chipgraph/adapters/review/github.py +886 -0
  25. chipgraph/adapters/runner/__init__.py +7 -0
  26. chipgraph/adapters/runner/local.py +122 -0
  27. chipgraph/adapters/runtime/__init__.py +5 -0
  28. chipgraph/adapters/runtime/claude_code/__init__.py +24 -0
  29. chipgraph/adapters/runtime/claude_code/agents.py +158 -0
  30. chipgraph/adapters/runtime/claude_code/decisions.py +280 -0
  31. chipgraph/adapters/runtime/claude_code/guarded.py +310 -0
  32. chipgraph/adapters/runtime/claude_code/isolation.py +482 -0
  33. chipgraph/adapters/runtime/claude_code/loop.py +342 -0
  34. chipgraph/adapters/runtime/claude_code/previous.py +419 -0
  35. chipgraph/adapters/runtime/claude_code/review.py +492 -0
  36. chipgraph/adapters/runtime/claude_code/runtime.py +192 -0
  37. chipgraph/adapters/runtime/claude_code/service.py +2285 -0
  38. chipgraph/adapters/tool/__init__.py +7 -0
  39. chipgraph/adapters/tool/cmd.py +229 -0
  40. chipgraph/adapters/tool/edalize.py +773 -0
  41. chipgraph/adapters/tool/filelist.py +259 -0
  42. chipgraph/adapters/tool/pyslang.py +485 -0
  43. chipgraph/adapters/vcs/__init__.py +1 -0
  44. chipgraph/adapters/vcs/git.py +521 -0
  45. chipgraph/app/__init__.py +10 -0
  46. chipgraph/app/baseline.py +339 -0
  47. chipgraph/app/build.py +332 -0
  48. chipgraph/app/checks.py +202 -0
  49. chipgraph/app/context.py +191 -0
  50. chipgraph/app/errors.py +11 -0
  51. chipgraph/app/executors.py +79 -0
  52. chipgraph/app/findings.py +203 -0
  53. chipgraph/app/ingest.py +523 -0
  54. chipgraph/checks/__init__.py +52 -0
  55. chipgraph/checks/_cdc_analyze.py +272 -0
  56. chipgraph/checks/_cdc_elaborate.py +455 -0
  57. chipgraph/checks/_common.py +268 -0
  58. chipgraph/checks/_cross.py +96 -0
  59. chipgraph/checks/_model.py +64 -0
  60. chipgraph/checks/_naming_pyslang.py +235 -0
  61. chipgraph/checks/_naming_rules.py +127 -0
  62. chipgraph/checks/_xref_syntax.py +260 -0
  63. chipgraph/checks/cdc_struct.py +235 -0
  64. chipgraph/checks/connect.py +353 -0
  65. chipgraph/checks/cross_chip.py +454 -0
  66. chipgraph/checks/duplicate.py +153 -0
  67. chipgraph/checks/filelist.py +323 -0
  68. chipgraph/checks/format.py +268 -0
  69. chipgraph/checks/generated.py +151 -0
  70. chipgraph/checks/hardcode.py +233 -0
  71. chipgraph/checks/layout.py +155 -0
  72. chipgraph/checks/naming.py +311 -0
  73. chipgraph/checks/plan_check.py +901 -0
  74. chipgraph/checks/ports_diff.py +203 -0
  75. chipgraph/checks/spec_schema.py +277 -0
  76. chipgraph/checks/style.py +910 -0
  77. chipgraph/checks/tb_static.py +599 -0
  78. chipgraph/checks/trace.py +224 -0
  79. chipgraph/checks/vendor_guard.py +369 -0
  80. chipgraph/checks/wrap_check.py +486 -0
  81. chipgraph/cli/__init__.py +1688 -0
  82. chipgraph/cli/next_steps.py +137 -0
  83. chipgraph/core/__init__.py +1 -0
  84. chipgraph/core/config/__init__.py +93 -0
  85. chipgraph/core/config/defaults.py +14 -0
  86. chipgraph/core/config/errors.py +32 -0
  87. chipgraph/core/config/loader.py +766 -0
  88. chipgraph/core/config/models.py +845 -0
  89. chipgraph/core/config/templates.py +340 -0
  90. chipgraph/core/contracts/__init__.py +75 -0
  91. chipgraph/core/contracts/_paths.py +26 -0
  92. chipgraph/core/contracts/agent.py +49 -0
  93. chipgraph/core/contracts/artifact.py +68 -0
  94. chipgraph/core/contracts/check.py +76 -0
  95. chipgraph/core/contracts/event.py +70 -0
  96. chipgraph/core/contracts/export.py +128 -0
  97. chipgraph/core/contracts/finding.py +171 -0
  98. chipgraph/core/contracts/gate.py +50 -0
  99. chipgraph/core/contracts/rule.py +177 -0
  100. chipgraph/core/contracts/types.py +45 -0
  101. chipgraph/core/engine/__init__.py +70 -0
  102. chipgraph/core/engine/agent_rule.py +1362 -0
  103. chipgraph/core/engine/baseline.py +283 -0
  104. chipgraph/core/engine/decide.py +462 -0
  105. chipgraph/core/engine/fanout.py +1358 -0
  106. chipgraph/core/engine/gate.py +170 -0
  107. chipgraph/core/engine/graph.py +647 -0
  108. chipgraph/core/engine/records.py +60 -0
  109. chipgraph/core/engine/rules.py +92 -0
  110. chipgraph/core/engine/scheduler.py +637 -0
  111. chipgraph/core/engine/select.py +1239 -0
  112. chipgraph/core/engine/targets.py +342 -0
  113. chipgraph/core/model/__init__.py +98 -0
  114. chipgraph/core/model/entities.py +244 -0
  115. chipgraph/core/model/export.py +16 -0
  116. chipgraph/core/model/ingest.py +693 -0
  117. chipgraph/core/model/json_value.py +4 -0
  118. chipgraph/core/model/keys.py +95 -0
  119. chipgraph/core/model/model.py +153 -0
  120. chipgraph/core/model/provenance.py +27 -0
  121. chipgraph/core/model/query.py +583 -0
  122. chipgraph/core/model/registry.py +80 -0
  123. chipgraph/core/model/relations.py +61 -0
  124. chipgraph/core/model/store.py +279 -0
  125. chipgraph/core/plugin_api/__init__.py +81 -0
  126. chipgraph/core/plugin_api/local.py +167 -0
  127. chipgraph/core/plugin_api/pack.py +159 -0
  128. chipgraph/core/plugin_api/protocols.py +177 -0
  129. chipgraph/core/plugin_api/registry.py +111 -0
  130. chipgraph/core/plugin_api/types.py +94 -0
  131. chipgraph/core/runtime/__init__.py +41 -0
  132. chipgraph/core/runtime/executor.py +79 -0
  133. chipgraph/core/runtime/queue.py +565 -0
  134. chipgraph/core/runtime/roles/__init__.py +91 -0
  135. chipgraph/core/runtime/roles/data/author.md +41 -0
  136. chipgraph/core/runtime/roles/data/critic.md +56 -0
  137. chipgraph/core/runtime/roles/data/planner.md +38 -0
  138. chipgraph/core/runtime/roles/data/researcher.md +37 -0
  139. chipgraph/core/runtime/roles/data/rtl-author.md +64 -0
  140. chipgraph/core/runtime/roles/data/tb-author.md +48 -0
  141. chipgraph/core/runtime/roles/data/triage.md +34 -0
  142. chipgraph/core/runtime/roles/policy.py +299 -0
  143. chipgraph/core/runtime/roles/registry.py +52 -0
  144. chipgraph/core/runtime/roles/review.py +275 -0
  145. chipgraph/core/runtime/roles/schema.py +82 -0
  146. chipgraph/core/runtime/roles/skills.py +134 -0
  147. chipgraph/core/runtime/roles/spec.py +232 -0
  148. chipgraph/core/state/__init__.py +1 -0
  149. chipgraph/core/state/artifacts.py +156 -0
  150. chipgraph/core/state/backend.py +117 -0
  151. chipgraph/core/state/findings.py +151 -0
  152. chipgraph/core/state/handoff.py +411 -0
  153. chipgraph/core/state/idempotency.py +59 -0
  154. chipgraph/core/state/journal.py +238 -0
  155. chipgraph/core/state/layout.py +82 -0
  156. chipgraph/core/state/lock.py +195 -0
  157. chipgraph/core/state/trace.py +225 -0
  158. chipgraph/learn/__init__.py +96 -0
  159. chipgraph/learn/draft.py +187 -0
  160. chipgraph/learn/infer.py +580 -0
  161. chipgraph/learn/models.py +145 -0
  162. chipgraph/learn/try_run.py +228 -0
  163. chipgraph/mcp/__init__.py +12 -0
  164. chipgraph/mcp/model_tools.py +167 -0
  165. chipgraph/mcp/server.py +787 -0
  166. chipgraph/orgs/qnsc/naming-v1.yml +113 -0
  167. chipgraph/orgs/qnsc/profile.yml +5 -0
  168. chipgraph/packs/__init__.py +8 -0
  169. chipgraph/packs/assist/__init__.py +16 -0
  170. chipgraph/packs/assist/ask/__init__.py +58 -0
  171. chipgraph/packs/assist/ask/_db.py +57 -0
  172. chipgraph/packs/assist/ask/_project.py +230 -0
  173. chipgraph/packs/assist/ask/answer.py +266 -0
  174. chipgraph/packs/assist/ask/check.py +182 -0
  175. chipgraph/packs/assist/ask/contract.py +115 -0
  176. chipgraph/packs/assist/ask/documents.py +157 -0
  177. chipgraph/packs/assist/ask/fts.py +80 -0
  178. chipgraph/packs/assist/ask/retrieve.py +331 -0
  179. chipgraph/packs/assist/audit/__init__.py +383 -0
  180. chipgraph/packs/assist/pack.yml +13 -0
  181. chipgraph/packs/assist/triage/__init__.py +64 -0
  182. chipgraph/packs/assist/triage/contract.py +94 -0
  183. chipgraph/packs/assist/triage/parse.py +371 -0
  184. chipgraph/packs/assist/triage/question.py +384 -0
  185. chipgraph/packs/assist/triage/report.py +160 -0
  186. chipgraph/packs/assist/triage/rules.py +447 -0
  187. chipgraph/packs/assist/triage/run.py +224 -0
  188. chipgraph/packs/digital_rtl/__init__.py +19 -0
  189. chipgraph/packs/digital_rtl/layout.py +144 -0
  190. chipgraph/packs/digital_rtl/pack.yml +25 -0
  191. chipgraph/packs/digital_rtl/plan/__init__.py +34 -0
  192. chipgraph/packs/digital_rtl/plan/__main__.py +16 -0
  193. chipgraph/packs/digital_rtl/plan/context.py +82 -0
  194. chipgraph/packs/digital_rtl/plan/expand.py +94 -0
  195. chipgraph/packs/digital_rtl/plan/model.py +150 -0
  196. chipgraph/packs/digital_rtl/plan/resolver.py +400 -0
  197. chipgraph/packs/digital_rtl/plan/show.py +176 -0
  198. chipgraph/packs/digital_rtl/pr/__init__.py +11 -0
  199. chipgraph/packs/digital_rtl/pr/body.py +165 -0
  200. chipgraph/packs/digital_rtl/pr/gate.py +110 -0
  201. chipgraph/packs/digital_rtl/pr/open.py +397 -0
  202. chipgraph/packs/digital_rtl/rtl/__init__.py +9 -0
  203. chipgraph/packs/digital_rtl/rtl/context.py +272 -0
  204. chipgraph/packs/digital_rtl/rules/open_pr.yml +30 -0
  205. chipgraph/packs/digital_rtl/rules/plan.yml +28 -0
  206. chipgraph/packs/digital_rtl/rules/plan_expand.yml +29 -0
  207. chipgraph/packs/digital_rtl/rules/pr_gate.yml +27 -0
  208. chipgraph/packs/digital_rtl/rules/review.yml +31 -0
  209. chipgraph/packs/digital_rtl/rules/rtl_module.yml +53 -0
  210. chipgraph/packs/digital_rtl/skills/lang-sv-rtl.md +58 -0
  211. chipgraph/packs/digital_rtl/skills/org-naming.md +29 -0
  212. chipgraph/packs/digital_rtl/skills/plan-modules.md +63 -0
  213. chipgraph/packs/digital_rtl/skills/review-diff.md +41 -0
  214. chipgraph/packs/digital_rtl/targets/plan.yml +11 -0
  215. chipgraph/packs/digital_rtl/targets/rtl.yml +20 -0
  216. chipgraph/packs/digital_rtl/wrapper/__init__.py +24 -0
  217. chipgraph/packs/digital_rtl/wrapper/common.py +171 -0
  218. chipgraph/packs/digital_rtl/wrapper/context.py +222 -0
  219. chipgraph/packs/digital_rtl/wrapper/emacs.py +626 -0
  220. chipgraph/packs/digital_rtl/wrapper/expansion.py +304 -0
  221. chipgraph/packs/digital_rtl/wrapper/lisp.py +504 -0
  222. chipgraph/packs/digital_rtl/wrapper/resolver.py +60 -0
  223. chipgraph/packs/digital_rtl/wrapper/rules/wrapper.yml +41 -0
  224. chipgraph/packs/digital_rtl/wrapper/rules/wrapper_gen.yml +35 -0
  225. chipgraph/packs/digital_rtl/wrapper/skills/wrapper-auto.md +120 -0
  226. chipgraph/packs/dv/__init__.py +15 -0
  227. chipgraph/packs/dv/declaration.py +392 -0
  228. chipgraph/packs/dv/interface.py +596 -0
  229. chipgraph/packs/dv/pack.yml +14 -0
  230. chipgraph/packs/dv/rules/tb_module.yml +42 -0
  231. chipgraph/packs/dv/skills/dv/cocotb.md +72 -0
  232. chipgraph/packs/spec_core/__init__.py +9 -0
  233. chipgraph/packs/spec_core/extract/__init__.py +12 -0
  234. chipgraph/packs/spec_core/extract/_markdown.py +371 -0
  235. chipgraph/packs/spec_core/extract/_text.py +116 -0
  236. chipgraph/packs/spec_core/extract/mas.py +975 -0
  237. chipgraph/packs/spec_core/gen/__init__.py +11 -0
  238. chipgraph/packs/spec_core/gen/agents_md/__init__.py +148 -0
  239. chipgraph/packs/spec_core/gen/agents_md/_context.py +239 -0
  240. chipgraph/packs/spec_core/gen/agents_md/_markers.py +131 -0
  241. chipgraph/packs/spec_core/gen/agents_md/agents_md.md.j2 +178 -0
  242. chipgraph/packs/spec_core/gen/diagram/__init__.py +110 -0
  243. chipgraph/packs/spec_core/gen/diagram/__main__.py +44 -0
  244. chipgraph/packs/spec_core/gen/diagram/_diagrams.py +403 -0
  245. chipgraph/packs/spec_core/gen/diagram/_scene.py +163 -0
  246. chipgraph/packs/spec_core/pack.yml +6 -0
  247. chipgraph/py.typed +0 -0
  248. chipgraph-0.1.0.dist-info/METADATA +53 -0
  249. chipgraph-0.1.0.dist-info/RECORD +252 -0
  250. chipgraph-0.1.0.dist-info/WHEEL +4 -0
  251. chipgraph-0.1.0.dist-info/entry_points.txt +61 -0
  252. chipgraph-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,454 @@
1
+ """`CrossChipCheck`: chip-wide consistency across IPs and the chip contract (layer 1).
2
+
3
+ Deterministic cross-artifact checks over the model `chipgraph ingest` built
4
+ (DESIGN.md 4.4 "Chéo IP và chip", 4.8 layer 1):
5
+
6
+ - `address.overlap`: two memory regions whose `[base, base+size)` windows overlap (int
7
+ base and size only; a region with a string size is skipped with an `info`).
8
+ - `interrupt.line_shared`: two interrupts assigned to the same line.
9
+ - `interrupt.count`: an IP's spec declares interrupt output ports (name matches `regex`,
10
+ default `^o_int_`; widths summed) but the contract gives its instances a different
11
+ number of lines. Compared per IP through `instance_of` (D38), only when both sides are
12
+ known.
13
+ - `interrupt.no_block`: an interrupt with no owning block; the IP whose name matches the
14
+ interrupt's exactly is suggested, and nothing is guessed otherwise.
15
+ - `clock.unknown` / `reset.unknown`: a block, port or module names a clock/reset key (or
16
+ bare name) that is not a `clock:`/`reset:` entity in the model.
17
+ - D38 (`instance.dangling`, `block.unknown`, `instance.unmapped`): an instance whose IP
18
+ is missing, a `block:` reference absent from the model, and a contract instance (a
19
+ block with a memory region) that is neither an IP nor an instance of one.
20
+
21
+ With a `--block`, only issues involving that IP or one of its instances are reported.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import re
27
+ import time
28
+
29
+ from chipgraph.checks._common import ArgError, error_result, optional_str
30
+ from chipgraph.checks._cross import (
31
+ block_key,
32
+ block_param,
33
+ load_model_or_skip,
34
+ result_from_issues,
35
+ scope_block_keys,
36
+ )
37
+ from chipgraph.core.contracts import CheckResult, CheckSpec, Issue
38
+ from chipgraph.core.model.entities import (
39
+ EntityBase,
40
+ InterruptEntity,
41
+ MemoryRegionEntity,
42
+ ModuleEntity,
43
+ PortEntity,
44
+ )
45
+ from chipgraph.core.model.model import DesignModel
46
+ from chipgraph.core.plugin_api.types import ToolContext
47
+
48
+ _DEFAULT_INTERRUPT_PORT_REGEX = r"^o_int_"
49
+
50
+
51
+ class CrossChipCheck:
52
+ """Checks chip-wide address, interrupt and clock/reset consistency."""
53
+
54
+ id = "cross_chip"
55
+ name = "Cross chip"
56
+ per_block = False # chip-wide: `chipgraph check` runs it once, not per block
57
+
58
+ async def run(self, spec: CheckSpec, ctx: ToolContext) -> CheckResult:
59
+ start = time.monotonic()
60
+ try:
61
+ int_port_regex = re.compile(
62
+ optional_str(spec.args, "interrupt_port_regex", _DEFAULT_INTERRUPT_PORT_REGEX)
63
+ )
64
+ except (ArgError, re.error) as exc:
65
+ return error_result(spec, f"bad interrupt_port_regex: {exc}", start)
66
+
67
+ loaded = load_model_or_skip(spec, ctx, start)
68
+ if isinstance(loaded, CheckResult):
69
+ return loaded
70
+ model = loaded.model
71
+ block = block_param(ctx)
72
+ scope = scope_block_keys(model, block) if block else None
73
+
74
+ issues: list[Issue] = []
75
+ issues.extend(_address_overlap(model, scope))
76
+ issues.extend(_interrupt_line_shared(model, scope))
77
+ issues.extend(_interrupt_count(model, scope, int_port_regex))
78
+ issues.extend(_interrupt_no_block(model, scope))
79
+ issues.extend(_clock_reset_unknown(model, scope))
80
+ issues.extend(_d38(model, scope))
81
+ return result_from_issues(spec, issues, loaded, start)
82
+
83
+
84
+ # --------------------------------------------------------------------------------------
85
+ # helpers
86
+ # --------------------------------------------------------------------------------------
87
+
88
+
89
+ def _prov(entity: EntityBase) -> tuple[str | None, int | None]:
90
+ return entity.source.file, entity.source.line
91
+
92
+
93
+ def _entity_block(entity: EntityBase) -> str | None:
94
+ block = getattr(entity, "block", None)
95
+ if isinstance(block, str) and block:
96
+ return block
97
+ attr_block = entity.attrs.get("block")
98
+ if isinstance(attr_block, str) and attr_block:
99
+ return attr_block
100
+ return None
101
+
102
+
103
+ def _in_scope(scope: set[str] | None, *block_keys: str | None) -> bool:
104
+ """True when no scope is set, or any of `block_keys` is in the scope."""
105
+ if scope is None:
106
+ return True
107
+ return any(bk in scope for bk in block_keys if bk is not None)
108
+
109
+
110
+ # --- address ---------------------------------------------------------------------------
111
+
112
+
113
+ def _address_overlap(model: DesignModel, scope: set[str] | None) -> list[Issue]:
114
+ issues: list[Issue] = []
115
+ regions: list[MemoryRegionEntity] = []
116
+ for region in model.by_kind("memory_region"):
117
+ assert isinstance(region, MemoryRegionEntity)
118
+ if not isinstance(region.base, int) or not isinstance(region.size, int):
119
+ file, line = _prov(region)
120
+ issues.append(
121
+ Issue(
122
+ file=file,
123
+ line=line,
124
+ rule="address.skipped",
125
+ severity="info",
126
+ msg=(
127
+ f"memory region {region.key!r} has a non-integer base/size "
128
+ f"({region.base!r}/{region.size!r}); overlap not checked"
129
+ ),
130
+ )
131
+ )
132
+ continue
133
+ regions.append(region)
134
+
135
+ regions.sort(key=lambda r: (r.base, r.key))
136
+ for i, a in enumerate(regions):
137
+ for b in regions[i + 1 :]:
138
+ assert isinstance(a.base, int) and isinstance(a.size, int)
139
+ assert isinstance(b.base, int) and isinstance(b.size, int)
140
+ if b.base >= a.base + a.size:
141
+ break # sorted by base: no later region can overlap `a`
142
+ if not _in_scope(scope, _entity_block(a), _entity_block(b)):
143
+ continue
144
+ file, line = _prov(b)
145
+ issues.append(
146
+ Issue(
147
+ file=file,
148
+ line=line,
149
+ rule="address.overlap",
150
+ severity="error",
151
+ msg=(
152
+ f"memory region {b.key!r} [{b.base:#x}, {b.base + b.size:#x}) overlaps "
153
+ f"{a.key!r} [{a.base:#x}, {a.base + a.size:#x})"
154
+ ),
155
+ )
156
+ )
157
+ return issues
158
+
159
+
160
+ # --- interrupts ------------------------------------------------------------------------
161
+
162
+
163
+ def _interrupt_line_shared(model: DesignModel, scope: set[str] | None) -> list[Issue]:
164
+ issues: list[Issue] = []
165
+ by_line: dict[int, list[InterruptEntity]] = {}
166
+ for irq in model.by_kind("interrupt"):
167
+ assert isinstance(irq, InterruptEntity)
168
+ if irq.line is None:
169
+ continue
170
+ by_line.setdefault(irq.line, []).append(irq)
171
+
172
+ for line_no, irqs in sorted(by_line.items()):
173
+ if len(irqs) < 2:
174
+ continue
175
+ irqs.sort(key=lambda e: e.key)
176
+ first = irqs[0]
177
+ for other in irqs[1:]:
178
+ if not _in_scope(scope, _entity_block(first), _entity_block(other)):
179
+ continue
180
+ file, line = _prov(other)
181
+ issues.append(
182
+ Issue(
183
+ file=file,
184
+ line=line,
185
+ rule="interrupt.line_shared",
186
+ severity="error",
187
+ msg=(f"interrupt {other.key!r} shares line {line_no} with {first.key!r}"),
188
+ )
189
+ )
190
+ return issues
191
+
192
+
193
+ def _interrupt_count(
194
+ model: DesignModel, scope: set[str] | None, port_regex: re.Pattern[str]
195
+ ) -> list[Issue]:
196
+ """Check each contract interrupt against the outputs of the IP it belongs to.
197
+
198
+ The IP's interrupt outputs are its spec output ports matching `port_regex` (width
199
+ summed). Using fewer of them than the IP has is valid (an instance may leave an
200
+ output unconnected, e.g. a timer in 64-bit mode). Two things are errors:
201
+
202
+ - `interrupt.count`: the contract gives the instance more interrupt sources than the
203
+ IP has outputs;
204
+ - `interrupt.port_unknown`: the contract names a port (`attrs.ports`) that the IP does
205
+ not have. The IP's port names are the RTL ports of the modules it owns (its wrapper
206
+ and the vendored IP). Without RTL in the model the name is not checked: a spec
207
+ describes the wrapper, not every port of the IP inside it.
208
+ """
209
+ issues: list[Issue] = []
210
+ outputs: dict[str, int] = {}
211
+ output_prov: dict[str, tuple[str | None, int | None]] = {}
212
+ for port in model.by_kind("port"):
213
+ assert isinstance(port, PortEntity)
214
+ ip = _spec_port_block(port)
215
+ if ip is None:
216
+ continue
217
+ if port.direction != "output" or not port_regex.search(port.name):
218
+ continue
219
+ if isinstance(port.width, int):
220
+ outputs[ip] = outputs.get(ip, 0) + port.width
221
+ output_prov.setdefault(ip, _prov(port))
222
+
223
+ rtl_names = _rtl_port_names_by_block(model)
224
+ ip_of = {r.src: r.dst for r in model.get_relations(kind="instance_of")}
225
+
226
+ for irq in sorted(model.by_kind("interrupt"), key=lambda e: e.key):
227
+ assert isinstance(irq, InterruptEntity)
228
+ inst_key = _entity_block(irq)
229
+ if inst_key is None or irq.line is None:
230
+ continue
231
+ ip_key = ip_of.get(inst_key, inst_key)
232
+ ip = _block_name_of(ip_key)
233
+ if not _in_scope(scope, ip_key, inst_key):
234
+ continue
235
+ file, line = _prov(irq)
236
+
237
+ sources = irq.attrs.get("sources")
238
+ count = sources if isinstance(sources, int) and sources > 0 else 1
239
+ have = outputs.get(ip)
240
+ if have is not None and count > have:
241
+ spec_file, spec_line = output_prov[ip]
242
+ issues.append(
243
+ Issue(
244
+ file=file,
245
+ line=line,
246
+ rule="interrupt.count",
247
+ severity="error",
248
+ msg=(
249
+ f"{irq.key!r} gives {inst_key!r} {count} interrupt source(s), but its IP "
250
+ f"{ip_key!r} has {have} interrupt output(s) "
251
+ f"({spec_file or '?'}:{spec_line or '-'})"
252
+ ),
253
+ )
254
+ )
255
+
256
+ known = rtl_names.get(ip_key, set())
257
+ if not known:
258
+ continue # no RTL for this IP in the model: its port names are unknown
259
+ ports = irq.attrs.get("ports")
260
+ for raw in ports if isinstance(ports, list) else []:
261
+ if not isinstance(raw, str):
262
+ continue
263
+ name = raw.split("[", 1)[0].strip()
264
+ if name and name not in known:
265
+ issues.append(
266
+ Issue(
267
+ file=file,
268
+ line=line,
269
+ rule="interrupt.port_unknown",
270
+ severity="error",
271
+ msg=(
272
+ f"{irq.key!r} names port {name!r}, which IP {ip_key!r} does not "
273
+ "have (not a port of any RTL module it owns)"
274
+ ),
275
+ )
276
+ )
277
+ return issues
278
+
279
+
280
+ def _block_name_of(block: str) -> str:
281
+ return block.partition(":")[2]
282
+
283
+
284
+ def _rtl_port_names_by_block(model: DesignModel) -> dict[str, set[str]]:
285
+ """RTL port names of every module, grouped by the block that owns the module."""
286
+ owner = {
287
+ m.key: m.block
288
+ for m in model.by_kind("module")
289
+ if isinstance(m, ModuleEntity) and isinstance(m.block, str)
290
+ }
291
+ names: dict[str, set[str]] = {}
292
+ for port in model.by_kind("port"):
293
+ assert isinstance(port, PortEntity)
294
+ block = owner.get(port.module or "")
295
+ if block is not None:
296
+ names.setdefault(block, set()).add(port.name)
297
+ return names
298
+
299
+
300
+ def _interrupt_no_block(model: DesignModel, scope: set[str] | None) -> list[Issue]:
301
+ issues: list[Issue] = []
302
+ for irq in model.by_kind("interrupt"):
303
+ assert isinstance(irq, InterruptEntity)
304
+ if _entity_block(irq) is not None:
305
+ continue
306
+ # Suggest the IP whose block name matches the interrupt's name exactly; never guess.
307
+ _, _, rest = irq.key.partition(":")
308
+ suggestion = block_key(rest)
309
+ has_match = model.get(suggestion) is not None
310
+ if scope is not None and (not has_match or suggestion not in scope):
311
+ continue
312
+ file, line = _prov(irq)
313
+ hint = f"; it may belong to {suggestion!r}" if has_match else ""
314
+ issues.append(
315
+ Issue(
316
+ file=file,
317
+ line=line,
318
+ rule="interrupt.no_block",
319
+ severity="error",
320
+ msg=f"interrupt {irq.key!r} has no owning block{hint}",
321
+ )
322
+ )
323
+ return issues
324
+
325
+
326
+ def _spec_port_block(port: PortEntity) -> str | None:
327
+ _, _, rest = port.key.partition(":")
328
+ parts = rest.split(".")
329
+ if len(parts) >= 3 and parts[0] == "spec":
330
+ return parts[1]
331
+ return None
332
+
333
+
334
+ # --- clock / reset ---------------------------------------------------------------------
335
+
336
+
337
+ def _clock_reset_unknown(model: DesignModel, scope: set[str] | None) -> list[Issue]:
338
+ issues: list[Issue] = []
339
+ clocks = {e.key for e in model.by_kind("clock")}
340
+ resets = {e.key for e in model.by_kind("reset")}
341
+
342
+ def known(kind: str, ref: str, present: set[str]) -> bool:
343
+ # A reference is either a full key (`clock:peri`) or a bare name (`peri`).
344
+ return ref in present or f"{kind}:{ref}" in present
345
+
346
+ for entity in model.entities.values():
347
+ if entity.kind not in ("block", "port", "module"):
348
+ continue
349
+ block_of = entity.key if entity.kind == "block" else _entity_block(entity)
350
+ for kind, present, rule in (
351
+ ("clock", clocks, "clock.unknown"),
352
+ ("reset", resets, "reset.unknown"),
353
+ ):
354
+ ref = _clock_reset_ref(entity, kind)
355
+ if ref is None or known(kind, ref, present):
356
+ continue
357
+ if not _in_scope(scope, block_of):
358
+ continue
359
+ file, line = _prov(entity)
360
+ issues.append(
361
+ Issue(
362
+ file=file,
363
+ line=line,
364
+ rule=rule,
365
+ severity="error",
366
+ msg=f"{entity.kind} {entity.key!r} refers to unknown {kind} {ref!r}",
367
+ )
368
+ )
369
+ return issues
370
+
371
+
372
+ def _clock_reset_ref(entity: EntityBase, kind: str) -> str | None:
373
+ typed = getattr(entity, kind, None)
374
+ if isinstance(typed, str) and typed:
375
+ return typed
376
+ attr = entity.attrs.get(kind)
377
+ if isinstance(attr, str) and attr:
378
+ return attr
379
+ return None
380
+
381
+
382
+ # --- D38 -------------------------------------------------------------------------------
383
+
384
+
385
+ def _d38(model: DesignModel, scope: set[str] | None) -> list[Issue]:
386
+ issues: list[Issue] = []
387
+ instance_of = model.get_relations(kind="instance_of")
388
+ region_blocks = {
389
+ _entity_block(r) for r in model.by_kind("memory_region") if _entity_block(r) is not None
390
+ }
391
+
392
+ # 1. An IP instance not in the contract: a block declared an `instance_of` some IP
393
+ # but with no memory region (the contract memory map does not list it). A dangling
394
+ # IP target is reported by rule 2 (block.unknown) instead.
395
+ for rel in instance_of:
396
+ if rel.src in region_blocks or model.get(rel.src) is None:
397
+ continue
398
+ if not _in_scope(scope, rel.src, rel.dst):
399
+ continue
400
+ src = model.get(rel.src)
401
+ file, line = _prov(src) if src is not None else (None, None)
402
+ issues.append(
403
+ Issue(
404
+ file=file,
405
+ line=line,
406
+ rule="instance.no_region",
407
+ severity="error",
408
+ msg=(
409
+ f"instance {rel.src!r} is an instance_of {rel.dst!r} but has no memory "
410
+ "region in the contract"
411
+ ),
412
+ )
413
+ )
414
+
415
+ # 2. A `block:` reference (typed `block`, `attrs.block`, or a relation endpoint,
416
+ # including an instance_of target) that points at a block not present in the model.
417
+ for block_ref, referrer, entity in _block_references(model):
418
+ if model.get(block_ref) is not None:
419
+ continue
420
+ if not _in_scope(scope, block_ref, _entity_block(entity) if entity else None):
421
+ continue
422
+ file, line = _prov(entity) if entity is not None else (None, None)
423
+ issues.append(
424
+ Issue(
425
+ file=file,
426
+ line=line,
427
+ rule="block.unknown",
428
+ severity="error",
429
+ msg=f"{referrer} refers to block {block_ref!r}, which is not in the model",
430
+ )
431
+ )
432
+ return issues
433
+
434
+
435
+ def _block_references(model: DesignModel) -> list[tuple[str, str, EntityBase | None]]:
436
+ """Every `block:` reference in the model: (block_key, referrer_label, referring entity)."""
437
+ seen: set[tuple[str, str]] = set()
438
+ out: list[tuple[str, str, EntityBase | None]] = []
439
+ for key in sorted(model.entities):
440
+ entity = model.entities[key]
441
+ for ref in (getattr(entity, "block", None), entity.attrs.get("block")):
442
+ if isinstance(ref, str) and ref.startswith("block:") and (ref, key) not in seen:
443
+ seen.add((ref, key))
444
+ out.append((ref, f"{entity.kind} {key!r}", entity))
445
+ for i, rel in enumerate(model.relations):
446
+ for endpoint in (rel.src, rel.dst):
447
+ label = f"relation[{i}] {rel.kind!r}"
448
+ if endpoint.startswith("block:") and (endpoint, label) not in seen:
449
+ seen.add((endpoint, label))
450
+ out.append((endpoint, label, None))
451
+ return out
452
+
453
+
454
+ __all__ = ["CrossChipCheck"]
@@ -0,0 +1,153 @@
1
+ """`DuplicateCheck`: no two module declarations share a name, no two IP files are copies.
2
+
3
+ A repo-wide, file-reading check (DESIGN.md 7.3 `duplicate`, 4.8 layer 1):
4
+
5
+ - `duplicate.module`: two `module` declarations with the same name in different files,
6
+ found with the pyslang syntax tree (reusing `_naming_pyslang`);
7
+ - `duplicate.file`: two byte-identical RTL files at different paths ("two copies of the
8
+ same IP").
9
+
10
+ It reads files, not the Design Model; the idempotency key is over the files it read.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import time
16
+ from collections import defaultdict
17
+ from pathlib import Path
18
+
19
+ from chipgraph.checks._common import (
20
+ ArgError,
21
+ compute_idempotency_key,
22
+ error_result,
23
+ glob_to_regex,
24
+ iter_repo_files,
25
+ optional_list_of_str,
26
+ sha256_bytes,
27
+ )
28
+ from chipgraph.checks._naming_pyslang import declared_identifiers, parse_file
29
+ from chipgraph.core.contracts import CheckResult, CheckSpec, Issue
30
+ from chipgraph.core.contracts.types import CheckStatus
31
+ from chipgraph.core.plugin_api.types import ToolContext
32
+
33
+ _DEFAULT_SCOPE = ("**/*.sv", "**/*.v")
34
+ # A wrapper's AUTO source (`<name>.src.sv`, M2-12) declares the module its generated file
35
+ # declares again; vendored IP is not the project's.
36
+ _DEFAULT_IGNORE = ("**/vendor/**", "vendor/**", "**/*.src.sv")
37
+
38
+
39
+ class DuplicateCheck:
40
+ """Checks for duplicate module names and byte-identical RTL files."""
41
+
42
+ id = "duplicate"
43
+ name = "Duplicate"
44
+ per_block = False # chip-wide: `chipgraph check` runs it once, not per block
45
+
46
+ async def run(self, spec: CheckSpec, ctx: ToolContext) -> CheckResult:
47
+ start = time.monotonic()
48
+ try:
49
+ scope = optional_list_of_str(spec.args, "scope") or list(_DEFAULT_SCOPE)
50
+ ignore = optional_list_of_str(spec.args, "ignore") or list(_DEFAULT_IGNORE)
51
+ except ArgError as exc:
52
+ return error_result(spec, str(exc), start)
53
+
54
+ scope_regexes = [glob_to_regex(p) for p in scope]
55
+ ignore_regexes = [glob_to_regex(p) for p in ignore]
56
+ in_scope = [
57
+ f
58
+ for f in iter_repo_files(ctx.repo_root)
59
+ if any(r.fullmatch(f) for r in scope_regexes)
60
+ and not any(r.fullmatch(f) for r in ignore_regexes)
61
+ ]
62
+
63
+ issues: list[Issue] = []
64
+ file_hashes: list[tuple[str, str]] = []
65
+ modules: dict[str, list[tuple[str, int]]] = defaultdict(list)
66
+ by_content: dict[str, list[str]] = defaultdict(list)
67
+
68
+ for rel in in_scope:
69
+ path = ctx.repo_root / rel
70
+ try:
71
+ data = path.read_bytes()
72
+ except OSError:
73
+ continue
74
+ file_hashes.append((rel, sha256_bytes(data)))
75
+ by_content[sha256_bytes(data)].append(rel)
76
+ for name, line in _module_decls(path):
77
+ modules[name].append((rel, line))
78
+
79
+ issues.extend(_duplicate_modules(modules))
80
+ issues.extend(_duplicate_files(by_content))
81
+
82
+ ordered = sorted(issues, key=lambda i: (i.file or "", i.line or 0, i.rule, i.msg))
83
+ key = compute_idempotency_key(spec.id, spec.args, file_hashes)
84
+ status: CheckStatus = "fail" if ordered else "pass"
85
+ return CheckResult(
86
+ check_id=spec.id,
87
+ status=status,
88
+ issues=tuple(ordered),
89
+ duration_s=time.monotonic() - start,
90
+ idempotency_key=key,
91
+ )
92
+
93
+
94
+ def _module_decls(path: Path) -> list[tuple[str, int]]:
95
+ """The (name, line) of every `module` declared in `path` (empty on a parse error)."""
96
+ try:
97
+ tree = parse_file(path)
98
+ except OSError:
99
+ return []
100
+ return [(d.name, d.line) for d in declared_identifiers(tree) if d.kind == "module"]
101
+
102
+
103
+ def _duplicate_modules(modules: dict[str, list[tuple[str, int]]]) -> list[Issue]:
104
+ issues: list[Issue] = []
105
+ for name, sites in sorted(modules.items()):
106
+ # Only a name declared in more than one distinct file is a duplicate; the same
107
+ # file declaring a name twice is a different (syntax) problem.
108
+ distinct_files = sorted({rel for rel, _ in sites})
109
+ if len(distinct_files) < 2:
110
+ continue
111
+ first = min(sites) # (file, line) of the first declaration
112
+ for rel, line in sorted(sites):
113
+ if (rel, line) == first:
114
+ continue
115
+ issues.append(
116
+ Issue(
117
+ file=rel,
118
+ line=line,
119
+ rule="duplicate.module",
120
+ severity="error",
121
+ msg=(
122
+ f"module {name!r} is also declared at {first[0]}:{first[1]}; "
123
+ "a module name must be unique across the repo"
124
+ ),
125
+ )
126
+ )
127
+ return issues
128
+
129
+
130
+ def _duplicate_files(by_content: dict[str, list[str]]) -> list[Issue]:
131
+ issues: list[Issue] = []
132
+ for _digest, paths in by_content.items():
133
+ if len(paths) < 2:
134
+ continue
135
+ ordered = sorted(paths)
136
+ first = ordered[0]
137
+ for rel in ordered[1:]:
138
+ issues.append(
139
+ Issue(
140
+ file=rel,
141
+ line=None,
142
+ rule="duplicate.file",
143
+ severity="error",
144
+ msg=(
145
+ f"{rel} is byte-identical to {first}; "
146
+ "two copies of the same RTL at different paths"
147
+ ),
148
+ )
149
+ )
150
+ return issues
151
+
152
+
153
+ __all__ = ["DuplicateCheck"]