sphinx-systemverilog 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.
@@ -0,0 +1,86 @@
1
+ """sphinx-systemverilog: a Sphinx autodoc extension for SystemVerilog.
2
+
3
+ Powered by the pyslang parser. See ``docs/design/`` for architecture.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import Any
9
+
10
+ from .__version__ import __version__
11
+
12
+
13
+ def _build_index(app: Any) -> None:
14
+ """Build the project-wide source index once per Sphinx build.
15
+
16
+ Connected to ``builder-inited`` so the index is available before any
17
+ directive runs, and stored on the build environment.
18
+ """
19
+ from sphinx.util import logging
20
+ from .model.index import build_index
21
+
22
+ logger = logging.getLogger(__name__)
23
+ config = app.config
24
+ index = build_index(
25
+ source_dirs=config.sv_source_dirs,
26
+ build_units=config.sv_build_units,
27
+ doc_style=config.sv_doc_style,
28
+ include_dirs=config.sv_include_dirs,
29
+ defines=config.sv_defines,
30
+ base_path=app.confdir,
31
+ nodocs_policy=config.sv_naturaldocs_nodocs,
32
+ document_macros=config.sv_document_macros,
33
+ )
34
+ app.env.sv_index = index
35
+ logger.info(
36
+ "sphinx-systemverilog: indexed %d SystemVerilog object(s)", len(index)
37
+ )
38
+ for diag in index.diagnostics:
39
+ if diag and diag.strip():
40
+ logger.warning(
41
+ "sphinx-systemverilog (parser): %s",
42
+ diag.strip(), type="systemverilog",
43
+ )
44
+ if index.suppressed_count:
45
+ logger.info(
46
+ "sphinx-systemverilog: suppressed %d non-error parser diagnostic(s)",
47
+ index.suppressed_count,
48
+ )
49
+
50
+
51
+ def setup(app: Any) -> dict[str, Any]:
52
+ from .autodoc import AUTODOC_DIRECTIVES
53
+ from .autodoc.diagrams import SvInheritanceDiagram, SvInstanceDiagram
54
+ from .config import register_config, validate_config
55
+ from .domain import SystemVerilogDomain
56
+
57
+ # Inheritance diagrams render through the graphviz extension.
58
+ app.setup_extension("sphinx.ext.graphviz")
59
+
60
+ register_config(app)
61
+ app.add_domain(SystemVerilogDomain)
62
+ app.add_directive_to_domain("sv", "inheritance-diagram", SvInheritanceDiagram)
63
+ app.add_directive_to_domain("sv", "instance-diagram", SvInstanceDiagram)
64
+
65
+ for name, directive in AUTODOC_DIRECTIVES.items():
66
+ app.add_directive(name, directive)
67
+
68
+ # Events mirroring sphinx.ext.autodoc's extension points.
69
+ app.add_event("sv-autodoc-process-doc")
70
+ app.add_event("sv-autodoc-skip-member")
71
+
72
+ app.connect("config-inited", validate_config)
73
+ app.connect("builder-inited", _build_index)
74
+
75
+ # viewcode: resolve [source] links and generate highlighted listings.
76
+ from . import viewcode
77
+
78
+ app.connect("doctree-resolved", viewcode.resolve_links)
79
+ app.connect("html-collect-pages", viewcode.collect_pages)
80
+ app.connect("env-purge-doc", viewcode.purge)
81
+
82
+ return {
83
+ "version": __version__,
84
+ "parallel_read_safe": True,
85
+ "parallel_write_safe": True,
86
+ }
@@ -0,0 +1,15 @@
1
+ """Single source of truth for the package version.
2
+
3
+ BASE is the released version and is what a ``v<BASE>`` tag must match.
4
+ SUFFIX is empty in the tree and is stamped by CI on non-tag builds so an
5
+ ordinary push can never produce a wheel whose version collides with a
6
+ release on PyPI.
7
+ """
8
+
9
+ BASE = "0.1.0"
10
+ SUFFIX = ""
11
+
12
+ # Read by pyproject.toml's dynamic version.
13
+ _pkg_version = BASE + SUFFIX
14
+
15
+ __version__ = _pkg_version
@@ -0,0 +1,8 @@
1
+ """Autodoc layer: auto* directives and the SvObject -> RST documenter."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .directives import AUTODOC_DIRECTIVES
6
+ from .documenters import SvDocumenter
7
+
8
+ __all__ = ["AUTODOC_DIRECTIVES", "SvDocumenter"]
@@ -0,0 +1,164 @@
1
+ """Class inheritance diagrams, rendered via ``sphinx.ext.graphviz``.
2
+
3
+ Edges come from the resolved ``extends`` relationships captured in the
4
+ :class:`~sphinx_systemverilog.model.index.SvIndex`. If Graphviz's ``dot`` is not
5
+ installed the graphviz extension degrades gracefully (it emits a warning and
6
+ skips the image); the directive itself always produces a valid node.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ from docutils import nodes
14
+ from docutils.parsers.rst import Directive
15
+ from sphinx.ext.graphviz import graphviz
16
+ from sphinx.util import logging
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+
21
+ class SvInheritanceDiagram(Directive):
22
+ """``.. sv:inheritance-diagram:: pkg::class`` -> a class hierarchy graph."""
23
+
24
+ required_arguments = 1
25
+ optional_arguments = 0
26
+ final_argument_whitespace = False
27
+ has_content = False
28
+
29
+ def run(self) -> list[nodes.Node]:
30
+ env = self.state.document.settings.env
31
+ target = self.arguments[0].strip()
32
+ index = getattr(env, "sv_index", None)
33
+ if index is None:
34
+ return []
35
+ obj = index.get(target)
36
+ if obj is None or obj.kind != "class":
37
+ logger.warning(
38
+ "sphinx-systemverilog: inheritance-diagram target %r is not a "
39
+ "documented class", target, type="systemverilog",
40
+ location=(env.docname, self.lineno),
41
+ )
42
+ return []
43
+
44
+ dot = build_inheritance_dot(index, obj)
45
+ node = graphviz()
46
+ node["code"] = dot
47
+ node["options"] = {"docname": env.docname}
48
+ node["alt"] = f"Inheritance diagram of {obj.name}"
49
+ return [node]
50
+
51
+
52
+ def build_inheritance_dot(index: Any, target: Any) -> str:
53
+ """Return Graphviz ``dot`` source for *target*'s local class hierarchy."""
54
+ classes = _class_by_name(index)
55
+ nodes_in: set[str] = set()
56
+ edges: set[tuple[str, str]] = set()
57
+
58
+ # Ancestors: walk the extends chain upward.
59
+ cur = target
60
+ seen = set()
61
+ while cur is not None and cur.name not in seen:
62
+ seen.add(cur.name)
63
+ nodes_in.add(cur.name)
64
+ base = cur.extends
65
+ if base:
66
+ nodes_in.add(base)
67
+ edges.add((cur.name, base))
68
+ cur = classes.get(base) if base else None
69
+
70
+ # Descendants: any class whose extends chain reaches the target.
71
+ for cls in classes.values():
72
+ chain = []
73
+ walk = cls
74
+ guard = set()
75
+ while walk is not None and walk.name not in guard:
76
+ guard.add(walk.name)
77
+ chain.append(walk.name)
78
+ if walk.extends == target.name:
79
+ for child_name in chain:
80
+ nodes_in.add(child_name)
81
+ edges.add((cls.name, cls.extends))
82
+ # add intermediate edges along the chain
83
+ break
84
+ walk = classes.get(walk.extends) if walk.extends else None
85
+
86
+ lines = ["digraph inheritance {", " rankdir=BT;",
87
+ ' node [shape=box, fontsize=10, height=0.25];',
88
+ ' edge [arrowsize=0.7];']
89
+ for name in sorted(nodes_in):
90
+ attrs = ' style=filled fillcolor="#e8e8e8"' if name == target.name else ""
91
+ lines.append(f' "{name}" [label="{name}"{attrs}];')
92
+ for derived, base in sorted(edges):
93
+ lines.append(f' "{derived}" -> "{base}";')
94
+ lines.append("}")
95
+ return "\n".join(lines)
96
+
97
+
98
+ def _class_by_name(index: Any) -> dict[str, Any]:
99
+ out: dict[str, Any] = {}
100
+ for root in index.roots:
101
+ for obj in root.walk():
102
+ if obj.kind == "class":
103
+ out.setdefault(obj.name, obj)
104
+ return out
105
+
106
+
107
+ class SvInstanceDiagram(Directive):
108
+ """``.. sv:instance-diagram:: top`` -> a module instantiation hierarchy."""
109
+
110
+ required_arguments = 1
111
+ optional_arguments = 0
112
+ final_argument_whitespace = False
113
+ has_content = False
114
+
115
+ def run(self) -> list[nodes.Node]:
116
+ env = self.state.document.settings.env
117
+ top = self.arguments[0].strip().split("::")[-1]
118
+ index = getattr(env, "sv_index", None)
119
+ if index is None:
120
+ return []
121
+ edges = getattr(index, "instance_edges", {})
122
+ if top not in edges:
123
+ logger.warning(
124
+ "sphinx-systemverilog: no instantiation hierarchy for module %r "
125
+ "(is it a top-level design module?)", top, type="systemverilog",
126
+ location=(env.docname, self.lineno),
127
+ )
128
+ return []
129
+ node = graphviz()
130
+ node["code"] = build_instance_dot(edges, top)
131
+ node["options"] = {"docname": env.docname}
132
+ node["alt"] = f"Instance diagram of {top}"
133
+ return [node]
134
+
135
+
136
+ def build_instance_dot(edges: dict, top: str) -> str:
137
+ """Graphviz ``dot`` for the structural composition reachable from *top*."""
138
+ lines = ["digraph instances {", " rankdir=TB;",
139
+ ' node [shape=box, fontsize=10, height=0.25];',
140
+ ' edge [arrowsize=0.7, fontsize=8];']
141
+ nodes_in: set[str] = set()
142
+ drawn: set[tuple[str, str, str]] = set()
143
+ queue = [top]
144
+ visited: set[str] = set()
145
+ while queue:
146
+ mod = queue.pop()
147
+ if mod in visited:
148
+ continue
149
+ visited.add(mod)
150
+ nodes_in.add(mod)
151
+ for inst_name, child_type in edges.get(mod, []):
152
+ nodes_in.add(child_type)
153
+ key = (mod, child_type, inst_name)
154
+ if key not in drawn:
155
+ drawn.add(key)
156
+ lines.append(
157
+ f' "{mod}" -> "{child_type}" [label="{inst_name}"];'
158
+ )
159
+ queue.append(child_type)
160
+ for name in sorted(nodes_in):
161
+ attrs = ' style=filled fillcolor="#e8e8e8"' if name == top else ""
162
+ lines.append(f' "{name}" [label="{name}"{attrs}];')
163
+ lines.append("}")
164
+ return "\n".join(lines)
@@ -0,0 +1,227 @@
1
+ """The ``auto*`` directives (autosvclass, autosvpackage, ...).
2
+
3
+ Each directive resolves a qualified name against the project-wide
4
+ :class:`~sphinx_systemverilog.model.index.SvIndex`, renders it (and optionally
5
+ its members) to RST via :class:`SvDocumenter`, and nested-parses the result so
6
+ it flows through the ``sv`` domain.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from typing import Any
12
+
13
+ from docutils import nodes
14
+ from docutils.parsers.rst import Directive, directives
15
+ from docutils.statemachine import StringList
16
+ from sphinx.util import logging
17
+ from sphinx.util.nodes import nested_parse_with_titles
18
+
19
+ from .documenters import SvDocumenter
20
+
21
+ logger = logging.getLogger(__name__)
22
+
23
+
24
+ def _members_option(arg: str | None):
25
+ """``:members:`` with no value -> True (all); with a list -> those names."""
26
+ if arg is None or not arg.strip():
27
+ return True
28
+ return [a.strip() for a in arg.replace(",", " ").split() if a.strip()]
29
+
30
+
31
+ def _names_option(arg: str | None) -> list[str]:
32
+ if not arg:
33
+ return []
34
+ return [a.strip() for a in arg.replace(",", " ").split() if a.strip()]
35
+
36
+
37
+ class AutoSvDirective(Directive):
38
+ """Base for ``auto*`` directives. Subclasses set :attr:`object_kind`."""
39
+
40
+ required_arguments = 1
41
+ optional_arguments = 0
42
+ final_argument_whitespace = False
43
+ has_content = True
44
+ option_spec = {
45
+ "members": _members_option,
46
+ "undoc-members": directives.flag,
47
+ "inherited-members": directives.flag,
48
+ "exclude-members": _names_option,
49
+ "member-order": lambda a: directives.choice(a, ("source", "alpha", "groups")),
50
+ "doc-style": directives.unchanged,
51
+ "recursive": directives.flag,
52
+ "show-inheritance": directives.flag,
53
+ # Skip silently (no warning) when the target is not in the index - used
54
+ # to make a page render the same whether optional sources are present.
55
+ "optional": directives.flag,
56
+ }
57
+
58
+ #: Restrict the resolved object to this kind (None = any).
59
+ object_kind: str | None = None
60
+
61
+ def run(self) -> list[nodes.Node]:
62
+ env = self.state.document.settings.env
63
+ app = env.app
64
+ target = self.arguments[0].strip()
65
+
66
+ index = getattr(env, "sv_index", None)
67
+ if index is None:
68
+ logger.warning(
69
+ "sphinx-systemverilog: source index not built; "
70
+ "is the extension configured with sv_source_dirs?",
71
+ location=(env.docname, self.lineno),
72
+ )
73
+ return []
74
+
75
+ obj = index.get(target)
76
+ if obj is None:
77
+ if "optional" not in self.options:
78
+ logger.warning(
79
+ "sphinx-systemverilog: cannot find SystemVerilog object %r",
80
+ target, type="systemverilog",
81
+ location=(env.docname, self.lineno),
82
+ )
83
+ return []
84
+ if self.object_kind and obj.kind != self.object_kind:
85
+ logger.warning(
86
+ "sphinx-systemverilog: %r is a %s, not a %s",
87
+ target, obj.kind, self.object_kind, type="systemverilog",
88
+ location=(env.docname, self.lineno),
89
+ )
90
+
91
+ options = self._resolve_options(env)
92
+ default_style = self.options.get("doc-style") or env.config.sv_doc_style
93
+ documenter = SvDocumenter(app, options, default_style, index=index)
94
+ rst_lines = documenter.render(obj)
95
+
96
+ container = nodes.section()
97
+ container.document = self.state.document
98
+ content = StringList(rst_lines, source="<autosv>")
99
+ nested_parse_with_titles(self.state, content, container)
100
+ return container.children
101
+
102
+ def _resolve_options(self, env) -> dict[str, Any]:
103
+ merged: dict[str, Any] = dict(env.config.sv_default_options or {})
104
+ merged.update(self.options)
105
+ # ``directives.flag`` stores None when present; normalize to True so
106
+ # callers can test truthiness.
107
+ for key in (
108
+ "undoc-members", "inherited-members", "recursive", "show-inheritance",
109
+ ):
110
+ if key in merged and merged[key] is None:
111
+ merged[key] = True
112
+ return merged
113
+
114
+
115
+ class AutoSvPackageDirective(AutoSvDirective):
116
+ object_kind = "package"
117
+
118
+
119
+ class AutoSvClassDirective(AutoSvDirective):
120
+ object_kind = "class"
121
+
122
+
123
+ class AutoSvModuleDirective(AutoSvDirective):
124
+ object_kind = "module"
125
+
126
+
127
+ class AutoSvFunctionDirective(AutoSvDirective):
128
+ object_kind = "function"
129
+
130
+
131
+ class AutoSvTaskDirective(AutoSvDirective):
132
+ object_kind = "task"
133
+
134
+
135
+ class AutoSvSummaryDirective(Directive):
136
+ """``.. autosvsummary::`` -> document a whole subtree of the index.
137
+
138
+ With no argument it documents every top-level object; ``:packages:`` /
139
+ ``:kinds:`` / a name-glob argument narrow the scope ("parse wide, reference
140
+ scope"). This is the project's Exhale-analog whole-tree front-end.
141
+ """
142
+
143
+ required_arguments = 0
144
+ optional_arguments = 1 # an optional name glob
145
+ final_argument_whitespace = False
146
+ has_content = False
147
+ option_spec = {
148
+ "members": _members_option,
149
+ "undoc-members": directives.flag,
150
+ "member-order": lambda a: directives.choice(a, ("source", "alpha", "groups")),
151
+ "packages": _names_option,
152
+ "kinds": _names_option,
153
+ "exclude": _names_option,
154
+ "doc-style": directives.unchanged,
155
+ }
156
+
157
+ def run(self) -> list[nodes.Node]:
158
+ import fnmatch
159
+
160
+ env = self.state.document.settings.env
161
+ app = env.app
162
+ index = getattr(env, "sv_index", None)
163
+ if index is None:
164
+ logger.warning(
165
+ "sphinx-systemverilog: source index not built", type="systemverilog",
166
+ location=(env.docname, self.lineno),
167
+ )
168
+ return []
169
+
170
+ glob = self.arguments[0].strip() if self.arguments else None
171
+ packages = set(self.options.get("packages") or [])
172
+ kinds = set(self.options.get("kinds") or [])
173
+ exclude = set(self.options.get("exclude") or [])
174
+
175
+ # Without a kind filter, document top-level roots (packages/modules);
176
+ # with one, gather matching objects at any depth.
177
+ if kinds:
178
+ candidates = [o for root in index.roots for o in root.walk()
179
+ if o.kind in kinds]
180
+ else:
181
+ candidates = list(index.roots)
182
+
183
+ roots = []
184
+ for obj in candidates:
185
+ qn = obj.qualified_name or obj.name
186
+ if packages and not any(
187
+ qn == p or qn.startswith(p + "::") for p in packages
188
+ ):
189
+ continue
190
+ if obj.name in exclude:
191
+ continue
192
+ if glob and not fnmatch.fnmatch(obj.name, glob):
193
+ continue
194
+ roots.append(obj)
195
+
196
+ options = dict(env.config.sv_default_options or {})
197
+ if "members" not in self.options:
198
+ options["members"] = True # whole-tree implies members
199
+ options.update(self.options)
200
+ for key in ("undoc-members",):
201
+ if key in options and options[key] is None:
202
+ options[key] = True
203
+ default_style = self.options.get("doc-style") or env.config.sv_doc_style
204
+
205
+ documenter = SvDocumenter(app, options, default_style, index=index)
206
+ rst_lines: list[str] = []
207
+ for root in roots:
208
+ rst_lines.extend(documenter.render(root))
209
+
210
+ if not rst_lines:
211
+ return []
212
+ container = nodes.section()
213
+ container.document = self.state.document
214
+ nested_parse_with_titles(
215
+ self.state, StringList(rst_lines, source="<autosvsummary>"), container
216
+ )
217
+ return container.children
218
+
219
+
220
+ AUTODOC_DIRECTIVES = {
221
+ "autosvpackage": AutoSvPackageDirective,
222
+ "autosvclass": AutoSvClassDirective,
223
+ "autosvmodule": AutoSvModuleDirective,
224
+ "autosvfunction": AutoSvFunctionDirective,
225
+ "autosvtask": AutoSvTaskDirective,
226
+ "autosvsummary": AutoSvSummaryDirective,
227
+ }