Debian Codegraph @

brian2/sphinxext/docscrape_sphinx.py

raw
1 import inspect
2 import pydoc
3 import re
4 import textwrap
5
6 from sphinx.pycode import ModuleAnalyzer
7
8 from .docscrape import ClassDoc, FunctionDoc, NumpyDocString
9
10
11 class SphinxDocString(NumpyDocString):
12 def __init__(self, docstring, config=None):
13 if config is None:
14 config = {}
15 NumpyDocString.__init__(self, docstring, config=config)
16
17 # string conversion routines
18 @staticmethod
19 def _str_header(name, symbol="`"):
20 return [f".. rubric:: {name}", ""]
21
22 @staticmethod
23 def _str_field_list(name):
24 return [f":{name}:"]
25
26 @staticmethod
27 def _str_indent(doc, indent=4):
28 out = []
29 for line in doc:
30 out += [" " * indent + line]
31 return out
32
33 def _str_summary(self):
34 return self["Summary"] + [""]
35
36 def _str_extended_summary(self):
37 return self["Extended Summary"] + [""]
38
39 def _str_param_list(self, name):
40 out = []
41 if self[name]:
42 out += self._str_field_list(name)
43 out += [""]
44 for param, param_type, desc in self[name]:
45 out += self._str_indent([f"**{param.strip()}** : {param_type}"])
46 out += [""]
47 out += self._str_indent(desc, 8)
48 out += [""]
49
50 return out
51
52 @property
53 def _obj(self):
54 if hasattr(self, "_cls"):
55 return self._cls
56 elif hasattr(self, "_f"):
57 return self._f
58 return None
59
60 def _str_member_list(self):
61 """
62 Generate a member listing, autosummary:: table .
63
64 """
65 out = []
66
67 for name in ["Attributes", "Methods"]:
68 if not self[name]:
69 continue
70
71 out += [f".. rubric:: {name}", ""]
72 prefix = getattr(self, "_name", "")
73
74 if prefix:
75 prefix = f"{prefix}."
76
77 autosum = []
78 for param, _, desc in self[name]:
79 param = param.strip()
80 if self._obj:
81 # Fake the attribute as a class property, but do not touch
82 # methods
83 if hasattr(self._obj, "__module__") and not (
84 hasattr(self._obj, param)
85 and callable(getattr(self._obj, param))
86 ):
87 # Do not override directly provided docstrings
88 if not len("".join(desc).strip()):
89 analyzer = ModuleAnalyzer.for_module(self._obj.__module__)
90 desc = analyzer.find_attr_docs().get(
91 (self._obj.__name__, param), ""
92 )
93
94 # Only fake a property if we got a docstring
95 if len("".join(desc).strip()):
96 setattr(
97 self._obj,
98 param,
99 property(lambda self: None, doc="\n".join(desc)),
100 )
101
102 if len(prefix):
103 autosum += [f" ~{prefix}{param}"]
104 else:
105 autosum += [f" {param}"]
106
107 if autosum:
108 out += [".. autosummary::", ""]
109 out += autosum
110
111 out += [""]
112 return out
113
114 def _str_member_docs(self, name):
115 """
116 Generate the full member autodocs
117
118 """
119 out = []
120
121 if self[name]:
122 prefix = getattr(self, "_name", "")
123
124 if prefix:
125 prefix += "."
126
127 for param, _, _ in self[name]:
128 if name == "Methods":
129 out += [f".. automethod:: {prefix}{param}"]
130 elif name == "Attributes":
131 out += [f".. autoattribute:: {prefix}{param}"]
132
133 out += [""]
134 return out
135
136 def _str_section(self, name):
137 out = []
138 if self[name]:
139 out += self._str_header(name)
140 out += [""]
141 content = textwrap.dedent("\n".join(self[name])).split("\n")
142 out += content
143 out += [""]
144 return out
145
146 def _str_see_also(self, func_role):
147 out = []
148 if self["See Also"]:
149 see_also = super()._str_see_also(func_role)
150 out = [".. seealso::", ""]
151 out += self._str_indent(see_also[2:])
152 return out
153
154 def _str_raises(self, name, func_role):
155 if not self[name]:
156 return []
157 out = []
158 out += self._str_header(name)
159 for func, _, desc in self[name]:
160 out += [f":exc:`{func}`"]
161 if desc:
162 out += self._str_indent([" ".join(desc)])
163 out += [""]
164 return out
165
166 def _str_warnings(self):
167 out = []
168 if self["Warnings"]:
169 out = [".. warning::", ""]
170 out += self._str_indent(self["Warnings"])
171 return out
172
173 def _str_index(self):
174 idx = self["index"]
175 out = []
176 if len(idx) == 0:
177 return out
178
179 out += [f".. index:: {idx.get('default', '')}"]
180 for section, references in idx.items():
181 if section == "default":
182 continue
183 elif section == "refguide":
184 out += [f" single: {', '.join(references)}"]
185 else:
186 out += [f" {section}: {','.join(references)}"]
187 return out
188
189 def _str_references(self):
190 out = []
191 if self["References"]:
192 out += self._str_header("References")
193 if isinstance(self["References"], str):
194 self["References"] = [self["References"]]
195 out.extend(self["References"])
196 out += [""]
197 # Latex collects all references to a separate bibliography,
198 # so we need to insert links to it
199 out += [".. only:: latex", ""]
200 items = []
201 for line in self["References"]:
202 m = re.match(r".. \[([a-z0-9._-]+)\]", line, re.I)
203 if m:
204 items.append(m.group(1))
205 out += [f" {', '.join([f'[{item}]_' for item in items])}", ""]
206 return out
207
208 def _str_examples(self):
209 return self._str_section("Examples")
210
211 def __str__(self, indent=0, func_role="brianobj"):
212 out = []
213 out += self._str_index() + [""]
214 out += self._str_summary()
215 out += self._str_extended_summary()
216 for param_list in ("Parameters", "Returns", "Other Parameters"):
217 out += self._str_param_list(param_list)
218 for param_list in ("Raises", "Warns"):
219 out += self._str_raises(param_list, func_role)
220 out += self._str_warnings()
221 out += self._str_see_also(func_role)
222 out += self._str_section("Notes")
223 out += self._str_references()
224 out += self._str_examples()
225 out += self._str_member_list()
226 if self["Attributes"] + self["Methods"]:
227 out += [".. rubric:: Details", ""]
228 for param_list in ("Attributes", "Methods"):
229 out += self._str_member_docs(param_list)
230 out = self._str_indent(out, indent)
231 return "\n".join(out)
232
233
234 class SphinxFunctionDoc(SphinxDocString, FunctionDoc):
235 def __init__(self, obj, doc=None, config=None):
236 if config is None:
237 config = {}
238 FunctionDoc.__init__(self, obj, doc=doc, config=config)
239
240
241 class SphinxClassDoc(SphinxDocString, ClassDoc):
242 def __init__(self, obj, doc=None, func_doc=None, name=None, config=None):
243 if config is None:
244 config = {}
245 self.name = name
246 ClassDoc.__init__(self, obj, doc=doc, func_doc=None, config=config)
247
248
249 class SphinxObjDoc(SphinxDocString):
250 def __init__(self, obj, doc=None, config=None):
251 if config is None:
252 config = {}
253 self._f = obj
254 SphinxDocString.__init__(self, doc, config=config)
255
256
257 def get_doc_object(obj, what=None, doc=None, name=None, config=None):
258 if config is None:
259 config = {}
260 if what is None:
261 if inspect.isclass(obj):
262 what = "class"
263 elif inspect.ismodule(obj):
264 what = "module"
265 elif callable(obj):
266 what = "function"
267 else:
268 what = "object"
269 if what == "class":
270 return SphinxClassDoc(
271 obj, func_doc=SphinxFunctionDoc, doc=doc, name=name, config=config
272 )
273 elif what in ("function", "method"):
274 return SphinxFunctionDoc(obj, doc=doc, config=config)
275 else:
276 if doc is None:
277 doc = pydoc.getdoc(obj)
278 return SphinxObjDoc(obj, doc, config=config)