Debian Codegraph @

brian2/sphinxext/docscrape.py

raw
1 """Extract reference documentation from the NumPy source tree."""
2
3 import inspect
4 import pydoc
5 import re
6 import textwrap
7 from warnings import warn
8
9 from sphinx.pycode import ModuleAnalyzer
10
11
12 class Reader:
13 """A line-based string reader."""
14
15 def __init__(self, data):
16 """
17 Parameters
18 ----------
19 data : str
20 String with lines separated by '\n'.
21
22 """
23 if isinstance(data, list):
24 self._str = data
25 else:
26 self._str = data.split("\n") # store string as list of lines
27
28 self.reset()
29
30 def __getitem__(self, n):
31 return self._str[n]
32
33 def reset(self):
34 self._l = 0 # current line nr
35
36 def read(self):
37 if not self.eof():
38 out = self[self._l]
39 self._l += 1
40 return out
41 else:
42 return ""
43
44 def seek_next_non_empty_line(self):
45 for line in self[self._l :]:
46 if line.strip():
47 break
48 else:
49 self._l += 1
50
51 def eof(self):
52 return self._l >= len(self._str)
53
54 def read_to_condition(self, condition_func):
55 start = self._l
56 for line in self[start:]:
57 if condition_func(line):
58 return self[start : self._l]
59 self._l += 1
60 if self.eof():
61 return self[start : self._l + 1]
62 return []
63
64 def read_to_next_empty_line(self):
65 self.seek_next_non_empty_line()
66
67 def is_empty(line):
68 return not line.strip()
69
70 return self.read_to_condition(is_empty)
71
72 def read_to_next_unindented_line(self):
73 def is_unindented(line):
74 return line.strip() and (len(line.lstrip()) == len(line))
75
76 return self.read_to_condition(is_unindented)
77
78 def peek(self, n=0):
79 if self._l + n < len(self._str):
80 return self[self._l + n]
81 else:
82 return ""
83
84 def is_empty(self):
85 return not "".join(self._str).strip()
86
87
88 class NumpyDocString:
89 def __init__(self, docstring, config=None):
90 docstring = textwrap.dedent(docstring).split("\n")
91
92 self._doc = Reader(docstring)
93 self._parsed_data = {
94 "Signature": "",
95 "Summary": [""],
96 "Extended Summary": [],
97 "Parameters": [],
98 "Returns": [],
99 "Raises": [],
100 "Warns": [],
101 "Other Parameters": [],
102 "Attributes": [],
103 "Methods": [],
104 "See Also": [],
105 "Notes": [],
106 "Warnings": [],
107 "References": "",
108 "Examples": "",
109 "index": {},
110 }
111
112 self._parse()
113
114 def __getitem__(self, key):
115 return self._parsed_data[key]
116
117 def __setitem__(self, key, val):
118 if key not in self._parsed_data:
119 warn(f"Unknown section {key}")
120 else:
121 self._parsed_data[key] = val
122
123 def _is_at_section(self):
124 self._doc.seek_next_non_empty_line()
125
126 if self._doc.eof():
127 return False
128
129 l1 = self._doc.peek().strip() # e.g. Parameters
130
131 if l1.startswith(".. index::"):
132 return True
133
134 l2 = self._doc.peek(1).strip() # ---------- or ==========
135 return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1))
136
137 def _strip(self, doc):
138 start = stop = 0
139 for i, line in enumerate(doc):
140 if line.strip():
141 start = i
142 break
143
144 for i, line in enumerate(doc[::-1]):
145 if line.strip():
146 stop = i
147 break
148
149 return doc[start : len(doc) - stop]
150
151 def _read_to_next_section(self):
152 section = self._doc.read_to_next_empty_line()
153
154 while not self._is_at_section() and not self._doc.eof():
155 if not self._doc.peek(-1).strip(): # previous line was empty
156 section += [""]
157
158 section += self._doc.read_to_next_empty_line()
159
160 return section
161
162 def _read_sections(self):
163 while not self._doc.eof():
164 data = self._read_to_next_section()
165 name = data[0].strip()
166
167 if name.startswith(".."): # index section
168 yield name, data[1:]
169 elif len(data) < 2:
170 yield StopIteration
171 else:
172 yield name, self._strip(data[2:])
173
174 def _parse_param_list(self, content):
175 r = Reader(content)
176 params = []
177 while not r.eof():
178 header = r.read().strip()
179 if " : " in header:
180 arg_name, arg_type = header.split(" : ")[:2]
181 else:
182 arg_name, arg_type = header, ""
183
184 desc = r.read_to_next_unindented_line()
185 desc = dedent_lines(desc)
186
187 params.append((arg_name, arg_type, desc))
188
189 return params
190
191 _name_rgx = re.compile(
192 r"^\s*(:(?P<role>\w+):`(?P<name>[a-zA-Z0-9_.-]+)`|"
193 r" (?P<name2>[a-zA-Z0-9_.-]+))\s*",
194 re.X,
195 )
196
197 def _parse_see_also(self, content):
198 """
199 func_name : Descriptive text
200 continued text
201 another_func_name : Descriptive text
202 func_name1, func_name2, :meth:`func_name`, func_name3
203
204 """
205 items = []
206
207 def parse_item_name(text):
208 """Match ':role:`name`' or 'name'"""
209 m = self._name_rgx.match(text)
210 if m:
211 g = m.groups()
212 if g[1] is None:
213 return g[3], None
214 else:
215 return g[2], g[1]
216 raise ValueError(f"{text} is not a item name")
217
218 def push_item(name, rest):
219 if not name:
220 return
221 name, role = parse_item_name(name)
222 items.append((name, list(rest), role))
223 del rest[:]
224
225 current_func = None
226 rest = []
227
228 for line in content:
229 if not line.strip():
230 continue
231
232 m = self._name_rgx.match(line)
233 if m and line[m.end() :].strip().startswith(":"):
234 push_item(current_func, rest)
235 current_func, line = line[: m.end()], line[m.end() :]
236 rest = [line.split(":", 1)[1].strip()]
237 if not rest[0]:
238 rest = []
239 elif not line.startswith(" "):
240 push_item(current_func, rest)
241 current_func = None
242 if "," in line:
243 for func in line.split(","):
244 if func.strip():
245 push_item(func, [])
246 elif line.strip():
247 current_func = line
248 elif current_func is not None:
249 rest.append(line.strip())
250 push_item(current_func, rest)
251 return items
252
253 def _parse_index(self, section, content):
254 """
255 .. index: default
256 :refguide: something, else, and more
257
258 """
259
260 def strip_each_in(lst):
261 return [s.strip() for s in lst]
262
263 out = {}
264 section = section.split("::")
265 if len(section) > 1:
266 out["default"] = strip_each_in(section[1].split(","))[0]
267 for line in content:
268 line = line.split(":")
269 if len(line) > 2:
270 out[line[1]] = strip_each_in(line[2].split(","))
271 return out
272
273 def _parse_summary(self):
274 """Grab signature (if given) and summary"""
275 if self._is_at_section():
276 return
277
278 summary = self._doc.read_to_next_empty_line()
279 summary_str = " ".join([s.strip() for s in summary]).strip()
280 if re.compile(r"^([\w., ]+=)?\s*[\w.]+\(.*\)$").match(summary_str):
281 self["Signature"] = summary_str
282 if not self._is_at_section():
283 self["Summary"] = self._doc.read_to_next_empty_line()
284 else:
285 self["Summary"] = summary
286
287 if not self._is_at_section():
288 self["Extended Summary"] = self._read_to_next_section()
289
290 def _parse(self):
291 self._doc.reset()
292 self._parse_summary()
293
294 for section, content in self._read_sections():
295 if not section.startswith(".."):
296 section = " ".join([s.capitalize() for s in section.split(" ")])
297 if section in (
298 "Parameters",
299 "Returns",
300 "Raises",
301 "Warns",
302 "Other Parameters",
303 "Attributes",
304 "Methods",
305 ):
306 self[section] = self._parse_param_list(content)
307 elif section.startswith(".. index::"):
308 self["index"] = self._parse_index(section, content)
309 elif section == "See Also":
310 self["See Also"] = self._parse_see_also(content)
311 else:
312 self[section] = content
313
314 # string conversion routines
315
316 def _str_header(self, name, symbol="-"):
317 return [name, len(name) * symbol]
318
319 def _str_indent(self, doc, indent=4):
320 out = []
321 for line in doc:
322 out += [" " * indent + line]
323 return out
324
325 def _str_signature(self):
326 if self["Signature"]:
327 return [self["Signature"].replace("*", r"\*")] + [""]
328 else:
329 return [""]
330
331 def _str_summary(self):
332 if self["Summary"]:
333 return self["Summary"] + [""]
334 else:
335 return []
336
337 def _str_extended_summary(self):
338 if self["Extended Summary"]:
339 return self["Extended Summary"] + [""]
340 else:
341 return []
342
343 def _str_param_list(self, name):
344 out = []
345 if self[name]:
346 out += self._str_header(name)
347 for param, param_type, desc in self[name]:
348 out += [f"{param} : {param_type}"]
349 out += self._str_indent(desc)
350 out += [""]
351 return out
352
353 def _str_section(self, name):
354 out = []
355 if self[name]:
356 out += self._str_header(name)
357 out += self[name]
358 out += [""]
359 return out
360
361 def _str_see_also(self, func_role):
362 if not self["See Also"]:
363 return []
364 out = []
365 out += self._str_header("See Also")
366 last_had_desc = True
367 for func, desc, role in self["See Also"]:
368 if role:
369 link = f":{role}:`{func}`"
370 elif func_role:
371 link = f":{func_role}:`{func}`"
372 else:
373 link = f"`{func}`_"
374 if desc or last_had_desc:
375 out += [""]
376 out += [link]
377 else:
378 out[-1] += f", {link}"
379 if desc:
380 out += self._str_indent([" ".join(desc)])
381 last_had_desc = True
382 else:
383 last_had_desc = False
384 out += [""]
385 return out
386
387 def _str_index(self):
388 idx = self["index"]
389 out = []
390 out += [f".. index:: {idx.get('default', '')}"]
391 for section, references in idx.items():
392 if section == "default":
393 continue
394 out += [f" :{section}: {', '.join(references)}"]
395 return out
396
397 def __str__(self, func_role=""):
398 out = []
399 out += self._str_signature()
400 out += self._str_summary()
401 out += self._str_extended_summary()
402 for param_list in (
403 "Parameters",
404 "Returns",
405 "Other Parameters",
406 "Raises",
407 "Warns",
408 ):
409 out += self._str_param_list(param_list)
410 out += self._str_section("Warnings")
411 out += self._str_see_also(func_role)
412 for s in ("Notes", "References", "Examples"):
413 out += self._str_section(s)
414 for param_list in ("Attributes", "Methods"):
415 out += self._str_param_list(param_list)
416 out += self._str_index()
417 return "\n".join(out)
418
419
420 def indent(str, indent=4):
421 indent_str = " " * indent
422 if str is None:
423 return indent_str
424 lines = str.split("\n")
425 return "\n".join(indent_str + line for line in lines)
426
427
428 def dedent_lines(lines):
429 """Deindent a list of lines maximally"""
430 return textwrap.dedent("\n".join(lines)).split("\n")
431
432
433 def header(text, style="-"):
434 return f"{text}\n{style * len(text)}\n"
435
436
437 class FunctionDoc(NumpyDocString):
438 def __init__(self, func, role="func", doc=None, config=None):
439 self._f = func
440 self._role = role # e.g. "func" or "meth"
441
442 if doc is None:
443 if func is None:
444 raise ValueError("No function or docstring given")
445 doc = inspect.getdoc(func) or ""
446 NumpyDocString.__init__(self, doc)
447
448 if not self["Signature"] and func is not None:
449 func, func_name = self.get_func()
450 try:
451 # try to read signature
452 argspec = str(inspect.signature(func))
453 argspec = argspec.replace("*", r"\*")
454 signature = f"{func_name}{argspec}"
455 except (TypeError, ValueError):
456 signature = f"{func_name}()"
457 self["Signature"] = signature
458
459 def get_func(self):
460 func_name = getattr(self._f, "__name__", self.__class__.__name__)
461 if inspect.isclass(self._f):
462 if callable(self._f):
463 func = self._f.__call__
464 else:
465 func = self._f.__init__
466 else:
467 func = self._f
468 return func, func_name
469
470 def __str__(self):
471 out = ""
472
473 _, func_name = self.get_func()
474
475 roles = {"func": "function", "meth": "method"}
476
477 if self._role:
478 if self._role not in roles:
479 print(f"Warning: invalid role {self._role}")
480 out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n"
481
482 out += super().__str__(func_role=self._role)
483 return out
484
485
486 class ClassDoc(NumpyDocString):
487 extra_public_methods = ["__call__"]
488
489 def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None):
490 if not inspect.isclass(cls) and cls is not None:
491 raise ValueError(f"Expected a class or None, but got {cls!r}")
492 self._cls = cls
493
494 if modulename and not modulename.endswith("."):
495 modulename += "."
496 self._mod = modulename
497
498 if doc is None:
499 if cls is None:
500 raise ValueError("No class or documentation string given")
501 doc = pydoc.getdoc(cls)
502
503 NumpyDocString.__init__(self, doc)
504
505 if not self["Methods"]:
506 self["Methods"] = [(name, "", "") for name in sorted(self.methods)]
507 if not self["Attributes"]:
508 self["Attributes"] = [(name, "", "") for name in sorted(self.properties)]
509
510 @property
511 def methods(self):
512 if self._cls is None:
513 return []
514 methods = [
515 name
516 for name, func in self._cls.__dict__.items()
517 if (
518 (not name.startswith("_") or name in self.extra_public_methods)
519 and (
520 (callable(func) and not isinstance(func, type))
521 or inspect.ismethoddescriptor(func)
522 )
523 )
524 ]
525 return methods
526
527 @property
528 def properties(self):
529 if self._cls is None:
530 return []
531 analyzer = ModuleAnalyzer.for_module(self._cls.__module__)
532 instance_members = {
533 attr_name
534 for (class_name, attr_name) in analyzer.find_attr_docs().keys()
535 if class_name == self._cls.__name__
536 }
537 class_members = {
538 name
539 for name, func in self._cls.__dict__.items()
540 if not name.startswith("_")
541 and (func is None or inspect.isdatadescriptor(func))
542 }
543
544 return instance_members | class_members