Debian Codegraph @

brian2/sphinxext/briandoc.py

raw
1 """
2 ========
3 briandoc
4 ========
5
6 Sphinx extension that handles docstrings in the Numpy standard format with some
7 brian-specific tweaks. [1]
8
9 It will:
10
11 - Convert Parameters etc. sections to field lists.
12 - Convert See Also section to a See also entry.
13 - Renumber references.
14 - Extract the signature from the docstring, if it can't be determined otherwise.
15
16 .. [1] https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
17
18 """
19
20 import inspect
21 import pydoc
22 import re
23
24 from docutils import nodes, statemachine
25 from docutils.parsers.rst import Directive, directives
26 from docutils.statemachine import ViewList
27 from sphinx.domains.c import CDomain
28 from sphinx.domains.python import PythonDomain, PyXRefRole
29 from sphinx.roles import XRefRole
30
31 from brian2.core.preferences import prefs
32
33 from .docscrape_sphinx import SphinxDocString, get_doc_object
34
35
36 class BrianPrefsDirective(Directive):
37 """
38 A sphinx 'Directive' for automatically generated documentation of Brian preferences.
39
40 The directive takes an optional argument, the basename of the preferences
41 to document. In addition, you can specify a `nolinks` option which means
42 that no target links for the references are added. Do this if you document
43 preferences in more then one place.
44
45 Examples
46 --------
47
48 Document one category of preferences and generate links::
49
50 .. document_brian_prefs:: core
51
52 Document all preferences without generating links::
53
54 .. document_brian_prefs::
55 :nolinks:
56 """
57
58 required_arguments = 0
59 optional_arguments = 1
60 final_argument_whitespace = True
61 option_spec = {"nolinks": directives.flag, "as_file": directives.flag}
62 has_content = False
63
64 def run(self):
65 # The section that should be documented
66 if len(self.arguments):
67 section = self.arguments[0]
68 else:
69 section = None
70 if "as_file" in self.options:
71 rawtext = prefs.as_file
72 return [nodes.literal_block(text=rawtext)]
73 else:
74 rawtext = prefs.get_documentation(section, "nolinks" not in self.options)
75 include_lines = statemachine.string2lines(rawtext, convert_whitespace=True)
76 self.state_machine.insert_input(include_lines, "Brian preferences")
77 return []
78
79
80 def brianobj_role(role, rawtext, text, lineno, inliner, options=None, content=None):
81 """
82 A Sphinx role, used as a wrapper for the default `py:obj` role, allowing
83 us to use the simple backtick syntax for brian classes/functions without
84 having to qualify the package for classes/functions that are available after
85 a `from brian2 import *`, e.g `NeuronGroup`.
86 Also allows to directly link to preference names using the same syntax.
87 """
88 if options is None:
89 options = {}
90 if content is None:
91 content = []
92 if text in prefs:
93 linktext = text.replace("_", "-").replace(".", "-")
94 text = f"{text} <brian-pref-{linktext}>"
95 # Use sphinx's cross-reference role
96 xref = XRefRole(warn_dangling=True)
97 return xref("std:ref", rawtext, text, lineno, inliner, options, content)
98 else:
99 if text and ("~" not in text):
100 try:
101 # A simple class or function name
102 if "." not in text:
103 module = __import__("brian2", fromlist=[str(text)])
104 imported = getattr(module, str(text), None)
105 if getattr(imported, "__module__", None):
106 text = f"~{imported.__module__}.{text}"
107 if inspect.isfunction(imported):
108 text += "()"
109 # Possibly a method/classmethod/attribute name
110 elif len(text.split(".")) == 2:
111 classname, attrname = text.split(".")
112 # Remove trailing parentheses (will be readded for display)
113 if attrname.endswith("()"):
114 attrname = attrname[:-2]
115 module = __import__("brian2", fromlist=[str(classname)])
116 imported = getattr(module, str(classname), None)
117 if hasattr(imported, "__module__"):
118 # Add trailing parentheses only for methods not for
119 # attributes
120 if inspect.ismethod(getattr(imported, str(attrname), None)):
121 parentheses = "()"
122 else:
123 parentheses = ""
124
125 text = (
126 f"{classname}.{attrname}{parentheses} "
127 f"<{imported.__module__}.{classname}.{attrname}>"
128 )
129
130 except ImportError:
131 pass
132 role = "py:obj"
133 py_role = PyXRefRole()
134 return py_role(role, rawtext, text, lineno, inliner, options, content)
135
136
137 def mangle_docstrings(app, what, name, obj, options, lines, reference_offset=None):
138 if reference_offset is None:
139 reference_offset = [0]
140 cfg = dict()
141 if what == "module":
142 # Strip top title
143 title_re = re.compile(r"^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*", re.I | re.S)
144 lines[:] = title_re.sub("", "\n".join(lines)).split("\n")
145 exported_members = getattr(obj, "__all__", None)
146 if exported_members:
147 lines.append("*Exported members:* ")
148 exported_members = sorted(exported_members)
149 # do not print more than 25 members
150 lines.append(", ".join([f"`{member}`" for member in exported_members[:25]]))
151 if len(exported_members) > 25:
152 lines.append(f"... ({int(len(exported_members) - 25)} more members)")
153
154 lines.append("")
155 else:
156 doc = get_doc_object(obj, what, "\n".join(lines), name=name, config=cfg)
157 lines[:] = str(doc).split("\n")
158
159 # replace reference numbers so that there are no duplicates
160 references = []
161 for line in lines:
162 line = line.strip()
163 m = re.match(r"^.. \[([a-z0-9_.-])\]", line, re.I)
164 if m:
165 references.append(m.group(1))
166
167 # start renaming from the longest string, to avoid overwriting parts
168 references.sort(key=lambda x: -len(x))
169 if references:
170 for i in range(len(lines)):
171 for r in references:
172 if re.match(r"^\d+$", r):
173 new_r = f"R{int(reference_offset[0] + int(r))}"
174 else:
175 new_r = f"{r}{int(reference_offset[0])}"
176 lines[i] = lines[i].replace(f"[{r}]_", f"[{new_r}]_")
177 lines[i] = lines[i].replace(f".. [{r}]", f".. [{new_r}]")
178
179 reference_offset[0] += len(references)
180
181
182 def mangle_signature(app, what, name, obj, options, sig, retann):
183 # Do not try to inspect classes that don't define `__init__`
184 if inspect.isclass(obj) and (
185 not hasattr(obj, "__init__")
186 or "initializes x; see " in pydoc.getdoc(obj.__init__)
187 ):
188 return "", ""
189
190 if not (callable(obj) or hasattr(obj, "__argspec_is_invalid_")):
191 return
192 if not hasattr(obj, "__doc__"):
193 return
194
195 doc = SphinxDocString(pydoc.getdoc(obj))
196 if doc["Signature"]:
197 sig = re.sub("^[^(]*", "", doc["Signature"])
198 return sig, ""
199
200
201 def setup(app, get_doc_object_=get_doc_object):
202 global get_doc_object
203 get_doc_object = get_doc_object_
204
205 app.connect("autodoc-process-docstring", mangle_docstrings)
206 app.connect("autodoc-process-signature", mangle_signature)
207
208 # Extra mangling domains
209 app.add_domain(NumpyPythonDomain)
210 app.add_domain(NumpyCDomain)
211
212 directives.register_directive("document_brian_prefs", BrianPrefsDirective)
213
214 # provide the brianobj role with a link to the Python domain
215 app.add_role("brianobj", brianobj_role)
216
217
218 # ------------------------------------------------------------------------------
219 # Docstring-mangling domains
220 # ------------------------------------------------------------------------------
221
222
223 class ManglingDomainBase:
224 directive_mangling_map = {}
225
226 def __init__(self, *a, **kw):
227 super().__init__(*a, **kw)
228 self.wrap_mangling_directives()
229
230 def wrap_mangling_directives(self):
231 for name, objtype in self.directive_mangling_map.items():
232 self.directives[name] = wrap_mangling_directive(
233 self.directives[name], objtype
234 )
235
236
237 class NumpyPythonDomain(ManglingDomainBase, PythonDomain):
238 name = "np"
239 directive_mangling_map = {
240 "function": "function",
241 "class": "class",
242 "exception": "class",
243 "method": "function",
244 "classmethod": "function",
245 "staticmethod": "function",
246 "attribute": "attribute",
247 }
248
249
250 class NumpyCDomain(ManglingDomainBase, CDomain):
251 name = "np-c"
252 directive_mangling_map = {
253 "function": "function",
254 "member": "attribute",
255 "macro": "function",
256 "type": "class",
257 "var": "object",
258 }
259
260
261 def wrap_mangling_directive(base_directive, objtype):
262 class directive(base_directive):
263 def run(self):
264 env = self.state.document.settings.env
265
266 name = None
267 if self.arguments:
268 m = re.match(r"^(.*\s+)?(.*?)(\(.*)?", self.arguments[0])
269 name = m.group(2).strip()
270
271 if not name:
272 name = self.arguments[0]
273
274 lines = list(self.content)
275 mangle_docstrings(env.app, objtype, name, None, None, lines)
276 self.content = ViewList(lines, self.content.parent)
277
278 return base_directive.run(self)
279
280 return directive