Debian Codegraph @

tools/refguide_check.py

raw
1 #!/usr/bin/env python3
2 """
3 refguide_check.py [OPTIONS] [-- ARGS]
4
5 - Check for a NumPy submodule whether the objects in its __all__ dict
6 correspond to the objects included in the reference guide.
7 - Check docstring examples
8 - Check example blocks in RST files
9
10 Example of usage::
11
12 $ python tools/refguide_check.py
13
14 Note that this is a helper script to be able to check if things are missing;
15 the output of this script does need to be checked manually. In some cases
16 objects are left out of the refguide for a good reason (it's an alias of
17 another function, or deprecated, or ...)
18
19 Another use of this helper script is to check validity of code samples
20 in docstrings::
21
22 $ python tools/refguide_check.py --doctests ma
23
24 or in RST-based documentations::
25
26 $ python tools/refguide_check.py --rst doc/source
27
28 """
29 import copy
30 import inspect
31 import io
32 import os
33 import re
34 import sys
35 import warnings
36 from argparse import ArgumentParser
37
38 import docutils.core
39 from docutils.parsers.rst import directives
40
41 sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'doc', 'sphinxext'))
42 from numpydoc.docscrape_sphinx import get_doc_object
43
44 # Enable specific Sphinx directives
45 from sphinx.directives.other import Only, SeeAlso
46
47 directives.register_directive('seealso', SeeAlso)
48 directives.register_directive('only', Only)
49
50
51 BASE_MODULE = "numpy"
52
53 PUBLIC_SUBMODULES = [
54 "f2py",
55 "linalg",
56 "lib",
57 "lib.format",
58 "lib.mixins",
59 "lib.recfunctions",
60 "lib.scimath",
61 "lib.stride_tricks",
62 "lib.npyio",
63 "lib.introspect",
64 "lib.array_utils",
65 "fft",
66 "char",
67 "rec",
68 "ma",
69 "ma.extras",
70 "ma.mrecords",
71 "polynomial",
72 "polynomial.chebyshev",
73 "polynomial.hermite",
74 "polynomial.hermite_e",
75 "polynomial.laguerre",
76 "polynomial.legendre",
77 "polynomial.polynomial",
78 "matrixlib",
79 "random",
80 "strings",
81 "testing",
82 ]
83
84 # Docs for these modules are included in the parent module
85 OTHER_MODULE_DOCS = {
86 'fftpack.convolve': 'fftpack',
87 'io.wavfile': 'io',
88 'io.arff': 'io',
89 }
90
91
92 # these names are not required to be present in ALL despite being in
93 # autosummary:: listing
94 REFGUIDE_ALL_SKIPLIST = [
95 r'scipy\.sparse\.linalg',
96 r'scipy\.spatial\.distance',
97 r'scipy\.linalg\.blas\.[sdczi].*',
98 r'scipy\.linalg\.lapack\.[sdczi].*',
99 ]
100
101 # these names are not required to be in an autosummary:: listing
102 # despite being in ALL
103 REFGUIDE_AUTOSUMMARY_SKIPLIST = [
104 # NOTE: should NumPy have a better match between autosummary
105 # listings and __all__? For now, TR isn't convinced this is a
106 # priority -- focus on just getting docstrings executed / correct
107 r'numpy\.*',
108 ]
109
110
111 def short_path(path, cwd=None):
112 """
113 Return relative or absolute path name, whichever is shortest.
114
115 Parameters
116 ----------
117 path : str or None
118 cwd : str or None
119
120 Returns
121 -------
122 str
123 Relative path or absolute path based on current working directory
124 """
125 if not isinstance(path, str):
126 return path
127 if cwd is None:
128 cwd = os.getcwd()
129 abspath = os.path.abspath(path)
130 relpath = os.path.relpath(path, cwd)
131 if len(abspath) <= len(relpath):
132 return abspath
133 return relpath
134
135
136 def find_names(module, names_dict):
137 """
138 Finds the occurrences of function names, special directives like data
139 and functions and scipy constants in the docstrings of `module`. The
140 following patterns are searched for:
141
142 * 3 spaces followed by function name, and maybe some spaces, some
143 dashes, and an explanation; only function names listed in
144 refguide are formatted like this (mostly, there may be some false
145 positives
146 * special directives, such as data and function
147 * (scipy.constants only): quoted list
148
149 The `names_dict` is updated by reference and accessible in calling method
150
151 Parameters
152 ----------
153 module : ModuleType
154 The module, whose docstrings is to be searched
155 names_dict : dict
156 Dictionary which contains module name as key and a set of found
157 function names and directives as value
158
159 Returns
160 -------
161 None
162 """
163 patterns = [
164 r"^\s\s\s([a-z_0-9A-Z]+)(\s+-+.*)?$",
165 r"^\.\. (?:data|function)::\s*([a-z_0-9A-Z]+)\s*$"
166 ]
167
168 if module.__name__ == 'scipy.constants':
169 patterns += ["^``([a-z_0-9A-Z]+)``"]
170
171 patterns = [re.compile(pattern) for pattern in patterns]
172 module_name = module.__name__
173
174 for line in module.__doc__.splitlines():
175 res = re.search(r"^\s*\.\. (?:currentmodule|module):: ([a-z0-9A-Z_.]+)\s*$",
176 line)
177 if res:
178 module_name = res.group(1)
179 continue
180
181 for pattern in patterns:
182 res = re.match(pattern, line)
183 if res is not None:
184 name = res.group(1)
185 entry = f'{module_name}.{name}'
186 names_dict.setdefault(module_name, set()).add(name)
187 break
188
189
190 def get_all_dict(module):
191 """
192 Return a copy of the __all__ dict with irrelevant items removed.
193
194 Parameters
195 ----------
196 module : ModuleType
197 The module whose __all__ dict has to be processed
198
199 Returns
200 -------
201 deprecated : list
202 List of callable and deprecated sub modules
203 not_deprecated : list
204 List of non callable or non deprecated sub modules
205 others : list
206 List of remaining types of sub modules
207 """
208 if hasattr(module, "__all__"):
209 all_dict = copy.deepcopy(module.__all__)
210 else:
211 all_dict = copy.deepcopy(dir(module))
212 all_dict = [name for name in all_dict
213 if not name.startswith("_")]
214 for name in ['absolute_import', 'division', 'print_function']:
215 try:
216 all_dict.remove(name)
217 except ValueError:
218 pass
219 if not all_dict:
220 # Must be a pure documentation module
221 all_dict.append('__doc__')
222
223 # Modules are almost always private; real submodules need a separate
224 # run of refguide_check.
225 all_dict = [name for name in all_dict
226 if not inspect.ismodule(getattr(module, name, None))]
227
228 deprecated = []
229 not_deprecated = []
230 for name in all_dict:
231 f = getattr(module, name, None)
232 if callable(f) and is_deprecated(f):
233 deprecated.append(name)
234 else:
235 not_deprecated.append(name)
236
237 others = set(dir(module)).difference(set(deprecated)).difference(set(not_deprecated)) # noqa: E501
238
239 return not_deprecated, deprecated, others
240
241
242 def compare(all_dict, others, names, module_name):
243 """
244 Return sets of objects from all_dict.
245 Will return three sets:
246 {in module_name.__all__},
247 {in REFGUIDE*},
248 and {missing from others}
249
250 Parameters
251 ----------
252 all_dict : list
253 List of non deprecated sub modules for module_name
254 others : list
255 List of sub modules for module_name
256 names : set
257 Set of function names or special directives present in
258 docstring of module_name
259 module_name : ModuleType
260
261 Returns
262 -------
263 only_all : set
264 only_ref : set
265 missing : set
266 """
267 only_all = set()
268 for name in all_dict:
269 if name not in names:
270 for pat in REFGUIDE_AUTOSUMMARY_SKIPLIST:
271 if re.match(pat, module_name + '.' + name):
272 break
273 else:
274 only_all.add(name)
275
276 only_ref = set()
277 missing = set()
278 for name in names:
279 if name not in all_dict:
280 for pat in REFGUIDE_ALL_SKIPLIST:
281 if re.match(pat, module_name + '.' + name):
282 if name not in others:
283 missing.add(name)
284 break
285 else:
286 only_ref.add(name)
287
288 return only_all, only_ref, missing
289
290
291 def is_deprecated(f):
292 """
293 Check if module `f` is deprecated
294
295 Parameters
296 ----------
297 f : ModuleType
298
299 Returns
300 -------
301 bool
302 """
303 with warnings.catch_warnings(record=True) as w:
304 warnings.simplefilter("error")
305 try:
306 f(**{"not a kwarg": None})
307 except DeprecationWarning:
308 return True
309 except Exception:
310 pass
311 return False
312
313
314 def check_items(all_dict, names, deprecated, others, module_name, dots=True):
315 """
316 Check that `all_dict` is consistent with the `names` in `module_name`
317 For instance, that there are no deprecated or extra objects.
318
319 Parameters
320 ----------
321 all_dict : list
322
323 names : set
324
325 deprecated : list
326
327 others : list
328
329 module_name : ModuleType
330
331 dots : bool
332 Whether to print a dot for each check
333
334 Returns
335 -------
336 list
337 List of [(name, success_flag, output)...]
338 """
339 num_all = len(all_dict)
340 num_ref = len(names)
341
342 output = ""
343
344 output += f"Non-deprecated objects in __all__: {num_all}\n"
345 output += f"Objects in refguide: {num_ref}\n\n"
346
347 only_all, only_ref, missing = compare(all_dict, others, names, module_name)
348 dep_in_ref = only_ref.intersection(deprecated)
349 only_ref = only_ref.difference(deprecated)
350
351 if len(dep_in_ref) > 0:
352 output += "Deprecated objects in refguide::\n\n"
353 for name in sorted(deprecated):
354 output += " " + name + "\n"
355
356 if len(only_all) == len(only_ref) == len(missing) == 0:
357 if dots:
358 output_dot('.')
359 return [(None, True, output)]
360 else:
361 if len(only_all) > 0:
362 output += f"ERROR: objects in {module_name}.__all__ but not in refguide::\n\n" # noqa: E501
363 for name in sorted(only_all):
364 output += " " + name + "\n"
365
366 output += "\nThis issue can be fixed by adding these objects to\n"
367 output += "the function listing in __init__.py for this module\n"
368
369 if len(only_ref) > 0:
370 output += f"ERROR: objects in refguide but not in {module_name}.__all__::\n\n" # noqa: E501
371 for name in sorted(only_ref):
372 output += " " + name + "\n"
373
374 output += "\nThis issue should likely be fixed by removing these objects\n"
375 output += "from the function listing in __init__.py for this module\n"
376 output += "or adding them to __all__.\n"
377
378 if len(missing) > 0:
379 output += "ERROR: missing objects::\n\n"
380 for name in sorted(missing):
381 output += " " + name + "\n"
382
383 if dots:
384 output_dot('F')
385 return [(None, False, output)]
386
387
388 def validate_rst_syntax(text, name, dots=True):
389 """
390 Validates the doc string in a snippet of documentation
391 `text` from file `name`
392 Parameters
393 ----------
394 text : str
395 Docstring text
396 name : str
397 File name for which the doc string is to be validated
398 dots : bool
399 Whether to print a dot symbol for each check
400 Returns
401 -------
402 (bool, str)
403 """
404 if text is None:
405 if dots:
406 output_dot('E')
407 return False, f"ERROR: {name}: no documentation"
408
409 ok_unknown_items = {
410 'mod', 'doc', 'currentmodule', 'autosummary', 'data', 'attr',
411 'obj', 'versionadded', 'versionchanged', 'module', 'class',
412 'ref', 'func', 'toctree', 'moduleauthor', 'term', 'c:member',
413 'sectionauthor', 'codeauthor', 'eq', 'doi', 'DOI', 'arXiv', 'arxiv'
414 }
415
416 # Run through docutils
417 error_stream = io.StringIO()
418
419 def resolve(name, is_label=False):
420 return ("http://foo", name)
421
422 token = '<RST-VALIDATE-SYNTAX-CHECK>'
423
424 docutils.core.publish_doctree(
425 text, token,
426 settings_overrides={'halt_level': 5,
427 'traceback': True,
428 'default_reference_context': 'title-reference',
429 'default_role': 'emphasis',
430 'link_base': '',
431 'resolve_name': resolve,
432 'stylesheet_path': '',
433 'raw_enabled': 0,
434 'file_insertion_enabled': 0,
435 'warning_stream': error_stream})
436
437 # Print errors, disregarding unimportant ones
438 error_msg = error_stream.getvalue()
439 errors = error_msg.split(token)
440 success = True
441 output = ""
442
443 for error in errors:
444 lines = error.splitlines()
445 if not lines:
446 continue
447
448 m = re.match(r'.*Unknown (?:interpreted text role|directive type) "(.*)".*$', lines[0]) # noqa: E501
449 if m:
450 if m.group(1) in ok_unknown_items:
451 continue
452
453 m = re.match(r'.*Error in "math" directive:.*unknown option: "label"', " ".join(lines), re.S) # noqa: E501
454 if m:
455 continue
456
457 output += name + lines[0] + "::\n " + "\n ".join(lines[1:]).rstrip() + "\n" # noqa: E501
458 success = False
459
460 if not success:
461 output += " " + "-" * 72 + "\n"
462 for lineno, line in enumerate(text.splitlines()):
463 output += " %-4d %s\n" % (lineno + 1, line)
464 output += " " + "-" * 72 + "\n\n"
465
466 if dots:
467 output_dot('.' if success else 'F')
468 return success, output
469
470
471 def output_dot(msg='.', stream=sys.stderr):
472 stream.write(msg)
473 stream.flush()
474
475
476 def check_rest(module, names, dots=True):
477 """
478 Check reStructuredText formatting of docstrings
479
480 Parameters
481 ----------
482 module : ModuleType
483
484 names : set
485
486 Returns
487 -------
488 result : list
489 List of [(module_name, success_flag, output),...]
490 """
491
492 skip_types = (dict, str, float, int)
493
494 results = []
495
496 if module.__name__[6:] not in OTHER_MODULE_DOCS:
497 results += [(module.__name__,) +
498 validate_rst_syntax(inspect.getdoc(module),
499 module.__name__, dots=dots)]
500
501 for name in names:
502 full_name = module.__name__ + '.' + name
503 obj = getattr(module, name, None)
504
505 if obj is None:
506 results.append((full_name, False, f"{full_name} has no docstring"))
507 continue
508 elif isinstance(obj, skip_types):
509 continue
510
511 if inspect.ismodule(obj):
512 text = inspect.getdoc(obj)
513 else:
514 try:
515 text = str(get_doc_object(obj))
516 except Exception:
517 import traceback
518 results.append((full_name, False,
519 "Error in docstring format!\n" +
520 traceback.format_exc()))
521 continue
522
523 m = re.search("([\x00-\x09\x0b-\x1f])", text) # noqa: RUF039
524 if m:
525 msg = ("Docstring contains a non-printable character %r! "
526 "Maybe forgot r\"\"\"?" % (m.group(1),))
527 results.append((full_name, False, msg))
528 continue
529
530 try:
531 src_file = short_path(inspect.getsourcefile(obj))
532 except TypeError:
533 src_file = None
534
535 if src_file:
536 file_full_name = src_file + ':' + full_name
537 else:
538 file_full_name = full_name
539
540 results.append((full_name,) +
541 validate_rst_syntax(text, file_full_name, dots=dots))
542
543 return results
544
545
546 def main(argv):
547 """
548 Validates the docstrings of all the pre decided set of
549 modules for errors and docstring standards.
550 """
551 parser = ArgumentParser(usage=__doc__.lstrip())
552 parser.add_argument("module_names", metavar="SUBMODULES", default=[],
553 nargs='*', help="Submodules to check (default: all public)")
554 parser.add_argument("-v", "--verbose", action="count", default=0)
555 args = parser.parse_args(argv)
556
557 modules = []
558 names_dict = {}
559
560 if not args.module_names:
561 args.module_names = list(PUBLIC_SUBMODULES) + [BASE_MODULE]
562
563 module_names = args.module_names + [
564 OTHER_MODULE_DOCS[name]
565 for name in args.module_names
566 if name in OTHER_MODULE_DOCS
567 ]
568 # remove duplicates while maintaining order
569 module_names = list(dict.fromkeys(module_names))
570
571 dots = True
572 success = True
573 results = []
574 errormsgs = []
575
576 for submodule_name in module_names:
577 prefix = BASE_MODULE + '.'
578 if not (
579 submodule_name.startswith(prefix) or
580 submodule_name == BASE_MODULE
581 ):
582 module_name = prefix + submodule_name
583 else:
584 module_name = submodule_name
585
586 __import__(module_name)
587 module = sys.modules[module_name]
588
589 if submodule_name not in OTHER_MODULE_DOCS:
590 find_names(module, names_dict)
591
592 if submodule_name in args.module_names:
593 modules.append(module)
594
595 if modules:
596 print(f"Running checks for {len(modules)} modules:")
597 for module in modules:
598 if dots:
599 sys.stderr.write(module.__name__ + ' ')
600 sys.stderr.flush()
601
602 all_dict, deprecated, others = get_all_dict(module)
603 names = names_dict.get(module.__name__, set())
604
605 mod_results = []
606 mod_results += check_items(all_dict, names, deprecated, others,
607 module.__name__)
608 mod_results += check_rest(module, set(names).difference(deprecated),
609 dots=dots)
610
611 for v in mod_results:
612 assert isinstance(v, tuple), v
613
614 results.append((module, mod_results))
615
616 if dots:
617 sys.stderr.write('\n')
618 sys.stderr.flush()
619
620 # Report results
621 for module, mod_results in results:
622 success = all(x[1] for x in mod_results)
623 if not success:
624 errormsgs.append(f'failed checking {module.__name__}')
625
626 if success and args.verbose == 0:
627 continue
628
629 print("")
630 print("=" * len(module.__name__))
631 print(module.__name__)
632 print("=" * len(module.__name__))
633 print("")
634
635 for name, success, output in mod_results:
636 if name is None:
637 if not success or args.verbose >= 1:
638 print(output.strip())
639 print("")
640 elif not success or (args.verbose >= 2 and output.strip()):
641 print(name)
642 print("-" * len(name))
643 print("")
644 print(output.strip())
645 print("")
646
647 if len(errormsgs) == 0:
648 print("\nOK: all checks passed!")
649 sys.exit(0)
650 else:
651 print('\nERROR: ', '\n '.join(errormsgs))
652 sys.exit(1)
653
654
655 if __name__ == '__main__':
656 main(argv=sys.argv[1:])