_docscrape.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. # copied from numpydoc/docscrape.py, commit 97a6026508e0dd5382865672e9563a72cc113bd2
  2. """Extract reference documentation from the NumPy source tree."""
  3. import copy
  4. import inspect
  5. import pydoc
  6. import re
  7. import sys
  8. import textwrap
  9. from collections import namedtuple
  10. from collections.abc import Callable, Mapping
  11. from functools import cached_property
  12. from warnings import warn
  13. def strip_blank_lines(l):
  14. "Remove leading and trailing blank lines from a list of lines"
  15. while l and not l[0].strip():
  16. del l[0]
  17. while l and not l[-1].strip():
  18. del l[-1]
  19. return l
  20. class Reader:
  21. """A line-based string reader."""
  22. def __init__(self, data):
  23. """
  24. Parameters
  25. ----------
  26. data : str
  27. String with lines separated by '\\n'.
  28. """
  29. if isinstance(data, list):
  30. self._str = data
  31. else:
  32. self._str = data.split("\n") # store string as list of lines
  33. self.reset()
  34. def __getitem__(self, n):
  35. return self._str[n]
  36. def reset(self):
  37. self._l = 0 # current line nr
  38. def read(self):
  39. if not self.eof():
  40. out = self[self._l]
  41. self._l += 1
  42. return out
  43. else:
  44. return ""
  45. def seek_next_non_empty_line(self):
  46. for l in self[self._l :]:
  47. if l.strip():
  48. break
  49. else:
  50. self._l += 1
  51. def eof(self):
  52. return self._l >= len(self._str)
  53. def read_to_condition(self, condition_func):
  54. start = self._l
  55. for line in self[start:]:
  56. if condition_func(line):
  57. return self[start : self._l]
  58. self._l += 1
  59. if self.eof():
  60. return self[start : self._l + 1]
  61. return []
  62. def read_to_next_empty_line(self):
  63. self.seek_next_non_empty_line()
  64. def is_empty(line):
  65. return not line.strip()
  66. return self.read_to_condition(is_empty)
  67. def read_to_next_unindented_line(self):
  68. def is_unindented(line):
  69. return line.strip() and (len(line.lstrip()) == len(line))
  70. return self.read_to_condition(is_unindented)
  71. def peek(self, n=0):
  72. if self._l + n < len(self._str):
  73. return self[self._l + n]
  74. else:
  75. return ""
  76. def is_empty(self):
  77. return not "".join(self._str).strip()
  78. class ParseError(Exception):
  79. def __str__(self):
  80. message = self.args[0]
  81. if hasattr(self, "docstring"):
  82. message = f"{message} in {self.docstring!r}"
  83. return message
  84. Parameter = namedtuple("Parameter", ["name", "type", "desc"])
  85. class NumpyDocString(Mapping):
  86. """Parses a numpydoc string to an abstract representation
  87. Instances define a mapping from section title to structured data.
  88. """
  89. sections = {
  90. "Signature": "",
  91. "Summary": [""],
  92. "Extended Summary": [],
  93. "Parameters": [],
  94. "Attributes": [],
  95. "Methods": [],
  96. "Returns": [],
  97. "Yields": [],
  98. "Receives": [],
  99. "Other Parameters": [],
  100. "Raises": [],
  101. "Warns": [],
  102. "Warnings": [],
  103. "See Also": [],
  104. "Notes": [],
  105. "References": "",
  106. "Examples": "",
  107. "index": {},
  108. }
  109. def __init__(self, docstring, config=None):
  110. orig_docstring = docstring
  111. docstring = textwrap.dedent(docstring).split("\n")
  112. self._doc = Reader(docstring)
  113. self._parsed_data = copy.deepcopy(self.sections)
  114. try:
  115. self._parse()
  116. except ParseError as e:
  117. e.docstring = orig_docstring
  118. raise
  119. def __getitem__(self, key):
  120. return self._parsed_data[key]
  121. def __setitem__(self, key, val):
  122. if key not in self._parsed_data:
  123. self._error_location(f"Unknown section {key}", error=False)
  124. else:
  125. self._parsed_data[key] = val
  126. def __iter__(self):
  127. return iter(self._parsed_data)
  128. def __len__(self):
  129. return len(self._parsed_data)
  130. def _is_at_section(self):
  131. self._doc.seek_next_non_empty_line()
  132. if self._doc.eof():
  133. return False
  134. l1 = self._doc.peek().strip() # e.g. Parameters
  135. if l1.startswith(".. index::"):
  136. return True
  137. l2 = self._doc.peek(1).strip() # ---------- or ==========
  138. if len(l2) >= 3 and (set(l2) in ({"-"}, {"="})) and len(l2) != len(l1):
  139. snip = "\n".join(self._doc._str[:2]) + "..."
  140. self._error_location(
  141. f"potentially wrong underline length... \n{l1} \n{l2} in \n{snip}",
  142. error=False,
  143. )
  144. return l2.startswith("-" * len(l1)) or l2.startswith("=" * len(l1))
  145. def _strip(self, doc):
  146. i = 0
  147. j = 0
  148. for i, line in enumerate(doc):
  149. if line.strip():
  150. break
  151. for j, line in enumerate(doc[::-1]):
  152. if line.strip():
  153. break
  154. return doc[i : len(doc) - j]
  155. def _read_to_next_section(self):
  156. section = self._doc.read_to_next_empty_line()
  157. while not self._is_at_section() and not self._doc.eof():
  158. if not self._doc.peek(-1).strip(): # previous line was empty
  159. section += [""]
  160. section += self._doc.read_to_next_empty_line()
  161. return section
  162. def _read_sections(self):
  163. while not self._doc.eof():
  164. data = self._read_to_next_section()
  165. name = data[0].strip()
  166. if name.startswith(".."): # index section
  167. yield name, data[1:]
  168. elif len(data) < 2:
  169. yield StopIteration
  170. else:
  171. yield name, self._strip(data[2:])
  172. def _parse_param_list(self, content, single_element_is_type=False):
  173. content = dedent_lines(content)
  174. r = Reader(content)
  175. params = []
  176. while not r.eof():
  177. header = r.read().strip()
  178. if " : " in header:
  179. arg_name, arg_type = header.split(" : ", maxsplit=1)
  180. else:
  181. # NOTE: param line with single element should never have a
  182. # a " :" before the description line, so this should probably
  183. # warn.
  184. if header.endswith(" :"):
  185. header = header[:-2]
  186. if single_element_is_type:
  187. arg_name, arg_type = "", header
  188. else:
  189. arg_name, arg_type = header, ""
  190. desc = r.read_to_next_unindented_line()
  191. desc = dedent_lines(desc)
  192. desc = strip_blank_lines(desc)
  193. params.append(Parameter(arg_name, arg_type, desc))
  194. return params
  195. # See also supports the following formats.
  196. #
  197. # <FUNCNAME>
  198. # <FUNCNAME> SPACE* COLON SPACE+ <DESC> SPACE*
  199. # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)+ (COMMA | PERIOD)? SPACE*
  200. # <FUNCNAME> ( COMMA SPACE+ <FUNCNAME>)* SPACE* COLON SPACE+ <DESC> SPACE*
  201. # <FUNCNAME> is one of
  202. # <PLAIN_FUNCNAME>
  203. # COLON <ROLE> COLON BACKTICK <PLAIN_FUNCNAME> BACKTICK
  204. # where
  205. # <PLAIN_FUNCNAME> is a legal function name, and
  206. # <ROLE> is any nonempty sequence of word characters.
  207. # Examples: func_f1 :meth:`func_h1` :obj:`~baz.obj_r` :class:`class_j`
  208. # <DESC> is a string describing the function.
  209. _role = r":(?P<role>(py:)?\w+):"
  210. _funcbacktick = r"`(?P<name>(?:~\w+\.)?[a-zA-Z0-9_\.-]+)`"
  211. _funcplain = r"(?P<name2>[a-zA-Z0-9_\.-]+)"
  212. _funcname = r"(" + _role + _funcbacktick + r"|" + _funcplain + r")"
  213. _funcnamenext = _funcname.replace("role", "rolenext")
  214. _funcnamenext = _funcnamenext.replace("name", "namenext")
  215. _description = r"(?P<description>\s*:(\s+(?P<desc>\S+.*))?)?\s*$"
  216. _func_rgx = re.compile(r"^\s*" + _funcname + r"\s*")
  217. _line_rgx = re.compile(
  218. r"^\s*"
  219. + r"(?P<allfuncs>"
  220. + _funcname # group for all function names
  221. + r"(?P<morefuncs>([,]\s+"
  222. + _funcnamenext
  223. + r")*)"
  224. + r")"
  225. + r"(?P<trailing>[,\.])?" # end of "allfuncs"
  226. + _description # Some function lists have a trailing comma (or period) '\s*'
  227. )
  228. # Empty <DESC> elements are replaced with '..'
  229. empty_description = ".."
  230. def _parse_see_also(self, content):
  231. """
  232. func_name : Descriptive text
  233. continued text
  234. another_func_name : Descriptive text
  235. func_name1, func_name2, :meth:`func_name`, func_name3
  236. """
  237. content = dedent_lines(content)
  238. items = []
  239. def parse_item_name(text):
  240. """Match ':role:`name`' or 'name'."""
  241. m = self._func_rgx.match(text)
  242. if not m:
  243. self._error_location(f"Error parsing See Also entry {line!r}")
  244. role = m.group("role")
  245. name = m.group("name") if role else m.group("name2")
  246. return name, role, m.end()
  247. rest = []
  248. for line in content:
  249. if not line.strip():
  250. continue
  251. line_match = self._line_rgx.match(line)
  252. description = None
  253. if line_match:
  254. description = line_match.group("desc")
  255. if line_match.group("trailing") and description:
  256. self._error_location(
  257. "Unexpected comma or period after function list at index %d of "
  258. 'line "%s"' % (line_match.end("trailing"), line),
  259. error=False,
  260. )
  261. if not description and line.startswith(" "):
  262. rest.append(line.strip())
  263. elif line_match:
  264. funcs = []
  265. text = line_match.group("allfuncs")
  266. while True:
  267. if not text.strip():
  268. break
  269. name, role, match_end = parse_item_name(text)
  270. funcs.append((name, role))
  271. text = text[match_end:].strip()
  272. if text and text[0] == ",":
  273. text = text[1:].strip()
  274. rest = list(filter(None, [description]))
  275. items.append((funcs, rest))
  276. else:
  277. self._error_location(f"Error parsing See Also entry {line!r}")
  278. return items
  279. def _parse_index(self, section, content):
  280. """
  281. .. index:: default
  282. :refguide: something, else, and more
  283. """
  284. def strip_each_in(lst):
  285. return [s.strip() for s in lst]
  286. out = {}
  287. section = section.split("::")
  288. if len(section) > 1:
  289. out["default"] = strip_each_in(section[1].split(","))[0]
  290. for line in content:
  291. line = line.split(":")
  292. if len(line) > 2:
  293. out[line[1]] = strip_each_in(line[2].split(","))
  294. return out
  295. def _parse_summary(self):
  296. """Grab signature (if given) and summary"""
  297. if self._is_at_section():
  298. return
  299. # If several signatures present, take the last one
  300. while True:
  301. summary = self._doc.read_to_next_empty_line()
  302. summary_str = " ".join([s.strip() for s in summary]).strip()
  303. compiled = re.compile(r"^([\w., ]+=)?\s*[\w\.]+\(.*\)$")
  304. if compiled.match(summary_str):
  305. self["Signature"] = summary_str
  306. if not self._is_at_section():
  307. continue
  308. break
  309. if summary is not None:
  310. self["Summary"] = summary
  311. if not self._is_at_section():
  312. self["Extended Summary"] = self._read_to_next_section()
  313. def _parse(self):
  314. self._doc.reset()
  315. self._parse_summary()
  316. sections = list(self._read_sections())
  317. section_names = {section for section, content in sections}
  318. has_yields = "Yields" in section_names
  319. # We could do more tests, but we are not. Arbitrarily.
  320. if not has_yields and "Receives" in section_names:
  321. msg = "Docstring contains a Receives section but not Yields."
  322. raise ValueError(msg)
  323. for section, content in sections:
  324. if not section.startswith(".."):
  325. section = (s.capitalize() for s in section.split(" "))
  326. section = " ".join(section)
  327. if self.get(section):
  328. self._error_location(
  329. "The section %s appears twice in %s"
  330. % (section, "\n".join(self._doc._str))
  331. )
  332. if section in ("Parameters", "Other Parameters", "Attributes", "Methods"):
  333. self[section] = self._parse_param_list(content)
  334. elif section in ("Returns", "Yields", "Raises", "Warns", "Receives"):
  335. self[section] = self._parse_param_list(
  336. content, single_element_is_type=True
  337. )
  338. elif section.startswith(".. index::"):
  339. self["index"] = self._parse_index(section, content)
  340. elif section == "See Also":
  341. self["See Also"] = self._parse_see_also(content)
  342. else:
  343. self[section] = content
  344. @property
  345. def _obj(self):
  346. if hasattr(self, "_cls"):
  347. return self._cls
  348. elif hasattr(self, "_f"):
  349. return self._f
  350. return None
  351. def _error_location(self, msg, error=True):
  352. if self._obj is not None:
  353. # we know where the docs came from:
  354. try:
  355. filename = inspect.getsourcefile(self._obj)
  356. except TypeError:
  357. filename = None
  358. # Make UserWarning more descriptive via object introspection.
  359. # Skip if introspection fails
  360. name = getattr(self._obj, "__name__", None)
  361. if name is None:
  362. name = getattr(getattr(self._obj, "__class__", None), "__name__", None)
  363. if name is not None:
  364. msg += f" in the docstring of {name}"
  365. msg += f" in {filename}." if filename else ""
  366. if error:
  367. raise ValueError(msg)
  368. else:
  369. warn(msg, stacklevel=3)
  370. # string conversion routines
  371. def _str_header(self, name, symbol="-"):
  372. return [name, len(name) * symbol]
  373. def _str_indent(self, doc, indent=4):
  374. return [" " * indent + line for line in doc]
  375. def _str_signature(self):
  376. if self["Signature"]:
  377. return [self["Signature"].replace("*", r"\*")] + [""]
  378. return [""]
  379. def _str_summary(self):
  380. if self["Summary"]:
  381. return self["Summary"] + [""]
  382. return []
  383. def _str_extended_summary(self):
  384. if self["Extended Summary"]:
  385. return self["Extended Summary"] + [""]
  386. return []
  387. def _str_param_list(self, name):
  388. out = []
  389. if self[name]:
  390. out += self._str_header(name)
  391. for param in self[name]:
  392. parts = []
  393. if param.name:
  394. parts.append(param.name)
  395. if param.type:
  396. parts.append(param.type)
  397. out += [" : ".join(parts)]
  398. if param.desc and "".join(param.desc).strip():
  399. out += self._str_indent(param.desc)
  400. out += [""]
  401. return out
  402. def _str_section(self, name):
  403. out = []
  404. if self[name]:
  405. out += self._str_header(name)
  406. out += self[name]
  407. out += [""]
  408. return out
  409. def _str_see_also(self, func_role):
  410. if not self["See Also"]:
  411. return []
  412. out = []
  413. out += self._str_header("See Also")
  414. out += [""]
  415. last_had_desc = True
  416. for funcs, desc in self["See Also"]:
  417. assert isinstance(funcs, list)
  418. links = []
  419. for func, role in funcs:
  420. if role:
  421. link = f":{role}:`{func}`"
  422. elif func_role:
  423. link = f":{func_role}:`{func}`"
  424. else:
  425. link = f"`{func}`_"
  426. links.append(link)
  427. link = ", ".join(links)
  428. out += [link]
  429. if desc:
  430. out += self._str_indent([" ".join(desc)])
  431. last_had_desc = True
  432. else:
  433. last_had_desc = False
  434. out += self._str_indent([self.empty_description])
  435. if last_had_desc:
  436. out += [""]
  437. out += [""]
  438. return out
  439. def _str_index(self):
  440. idx = self["index"]
  441. out = []
  442. output_index = False
  443. default_index = idx.get("default", "")
  444. if default_index:
  445. output_index = True
  446. out += [f".. index:: {default_index}"]
  447. for section, references in idx.items():
  448. if section == "default":
  449. continue
  450. output_index = True
  451. out += [f" :{section}: {', '.join(references)}"]
  452. if output_index:
  453. return out
  454. return ""
  455. def __str__(self, func_role=""):
  456. out = []
  457. out += self._str_signature()
  458. out += self._str_summary()
  459. out += self._str_extended_summary()
  460. out += self._str_param_list("Parameters")
  461. for param_list in ("Attributes", "Methods"):
  462. out += self._str_param_list(param_list)
  463. for param_list in (
  464. "Returns",
  465. "Yields",
  466. "Receives",
  467. "Other Parameters",
  468. "Raises",
  469. "Warns",
  470. ):
  471. out += self._str_param_list(param_list)
  472. out += self._str_section("Warnings")
  473. out += self._str_see_also(func_role)
  474. for s in ("Notes", "References", "Examples"):
  475. out += self._str_section(s)
  476. out += self._str_index()
  477. return "\n".join(out)
  478. def dedent_lines(lines):
  479. """Deindent a list of lines maximally"""
  480. return textwrap.dedent("\n".join(lines)).split("\n")
  481. class FunctionDoc(NumpyDocString):
  482. def __init__(self, func, role="func", doc=None, config=None):
  483. self._f = func
  484. self._role = role # e.g. "func" or "meth"
  485. if doc is None:
  486. if func is None:
  487. raise ValueError("No function or docstring given")
  488. doc = inspect.getdoc(func) or ""
  489. if config is None:
  490. config = {}
  491. NumpyDocString.__init__(self, doc, config)
  492. def get_func(self):
  493. func_name = getattr(self._f, "__name__", self.__class__.__name__)
  494. if inspect.isclass(self._f):
  495. func = getattr(self._f, "__call__", self._f.__init__)
  496. else:
  497. func = self._f
  498. return func, func_name
  499. def __str__(self):
  500. out = ""
  501. func, func_name = self.get_func()
  502. roles = {"func": "function", "meth": "method"}
  503. if self._role:
  504. if self._role not in roles:
  505. print(f"Warning: invalid role {self._role}")
  506. out += f".. {roles.get(self._role, '')}:: {func_name}\n \n\n"
  507. out += super().__str__(func_role=self._role)
  508. return out
  509. class ObjDoc(NumpyDocString):
  510. def __init__(self, obj, doc=None, config=None):
  511. self._f = obj
  512. if config is None:
  513. config = {}
  514. NumpyDocString.__init__(self, doc, config=config)
  515. class ClassDoc(NumpyDocString):
  516. extra_public_methods = ["__call__"]
  517. def __init__(self, cls, doc=None, modulename="", func_doc=FunctionDoc, config=None):
  518. if not inspect.isclass(cls) and cls is not None:
  519. raise ValueError(f"Expected a class or None, but got {cls!r}")
  520. self._cls = cls
  521. if "sphinx" in sys.modules:
  522. from sphinx.ext.autodoc import ALL
  523. else:
  524. ALL = object()
  525. if config is None:
  526. config = {}
  527. self.show_inherited_members = config.get("show_inherited_class_members", True)
  528. if modulename and not modulename.endswith("."):
  529. modulename += "."
  530. self._mod = modulename
  531. if doc is None:
  532. if cls is None:
  533. raise ValueError("No class or documentation string given")
  534. doc = pydoc.getdoc(cls)
  535. NumpyDocString.__init__(self, doc)
  536. _members = config.get("members", [])
  537. if _members is ALL:
  538. _members = None
  539. _exclude = config.get("exclude-members", [])
  540. if config.get("show_class_members", True) and _exclude is not ALL:
  541. def splitlines_x(s):
  542. if not s:
  543. return []
  544. else:
  545. return s.splitlines()
  546. for field, items in [
  547. ("Methods", self.methods),
  548. ("Attributes", self.properties),
  549. ]:
  550. if not self[field]:
  551. doc_list = []
  552. for name in sorted(items):
  553. if name in _exclude or (_members and name not in _members):
  554. continue
  555. try:
  556. doc_item = pydoc.getdoc(getattr(self._cls, name))
  557. doc_list.append(Parameter(name, "", splitlines_x(doc_item)))
  558. except AttributeError:
  559. pass # method doesn't exist
  560. self[field] = doc_list
  561. @property
  562. def methods(self):
  563. if self._cls is None:
  564. return []
  565. return [
  566. name
  567. for name, func in inspect.getmembers(self._cls)
  568. if (
  569. (not name.startswith("_") or name in self.extra_public_methods)
  570. and isinstance(func, Callable)
  571. and self._is_show_member(name)
  572. )
  573. ]
  574. @property
  575. def properties(self):
  576. if self._cls is None:
  577. return []
  578. return [
  579. name
  580. for name, func in inspect.getmembers(self._cls)
  581. if (
  582. not name.startswith("_")
  583. and not self._should_skip_member(name, self._cls)
  584. and (
  585. func is None
  586. or isinstance(func, property | cached_property)
  587. or inspect.isdatadescriptor(func)
  588. )
  589. and self._is_show_member(name)
  590. )
  591. ]
  592. @staticmethod
  593. def _should_skip_member(name, klass):
  594. return (
  595. # Namedtuples should skip everything in their ._fields as the
  596. # docstrings for each of the members is: "Alias for field number X"
  597. issubclass(klass, tuple)
  598. and hasattr(klass, "_asdict")
  599. and hasattr(klass, "_fields")
  600. and name in klass._fields
  601. )
  602. def _is_show_member(self, name):
  603. return (
  604. # show all class members
  605. self.show_inherited_members
  606. # or class member is not inherited
  607. or name in self._cls.__dict__
  608. )
  609. def get_doc_object(
  610. obj,
  611. what=None,
  612. doc=None,
  613. config=None,
  614. class_doc=ClassDoc,
  615. func_doc=FunctionDoc,
  616. obj_doc=ObjDoc,
  617. ):
  618. if what is None:
  619. if inspect.isclass(obj):
  620. what = "class"
  621. elif inspect.ismodule(obj):
  622. what = "module"
  623. elif isinstance(obj, Callable):
  624. what = "function"
  625. else:
  626. what = "object"
  627. if config is None:
  628. config = {}
  629. if what == "class":
  630. return class_doc(obj, func_doc=func_doc, doc=doc, config=config)
  631. elif what in ("function", "method"):
  632. return func_doc(obj, doc=doc, config=config)
  633. else:
  634. if doc is None:
  635. doc = pydoc.getdoc(obj)
  636. return obj_doc(obj, doc, config=config)