checker.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  1. """Parsed source code checkers for docstring violations."""
  2. import ast
  3. import string
  4. import tokenize as tk
  5. from collections import namedtuple
  6. from itertools import chain, takewhile
  7. from re import compile as re
  8. from textwrap import dedent
  9. from . import violations
  10. from .config import IllegalConfiguration
  11. from .parser import (
  12. AllError,
  13. Class,
  14. Definition,
  15. Function,
  16. Method,
  17. Module,
  18. NestedClass,
  19. NestedFunction,
  20. Package,
  21. ParseError,
  22. Parser,
  23. StringIO,
  24. )
  25. from .utils import (
  26. common_prefix_length,
  27. is_blank,
  28. log,
  29. pairwise,
  30. strip_non_alphanumeric,
  31. )
  32. from .wordlists import IMPERATIVE_BLACKLIST, IMPERATIVE_VERBS, stem
  33. __all__ = ('check',)
  34. def check_for(kind, terminal=False):
  35. def decorator(f):
  36. f._check_for = kind
  37. f._terminal = terminal
  38. return f
  39. return decorator
  40. class ConventionChecker:
  41. """Checker for PEP 257, NumPy and Google conventions.
  42. D10x: Missing docstrings
  43. D20x: Whitespace issues
  44. D30x: Docstring formatting
  45. D40x: Docstring content issues
  46. """
  47. NUMPY_SECTION_NAMES = (
  48. 'Short Summary',
  49. 'Extended Summary',
  50. 'Parameters',
  51. 'Returns',
  52. 'Yields',
  53. 'Other Parameters',
  54. 'Raises',
  55. 'See Also',
  56. 'Notes',
  57. 'References',
  58. 'Examples',
  59. 'Attributes',
  60. 'Methods',
  61. )
  62. GOOGLE_SECTION_NAMES = (
  63. 'Args',
  64. 'Arguments',
  65. 'Attention',
  66. 'Attributes',
  67. 'Caution',
  68. 'Danger',
  69. 'Error',
  70. 'Example',
  71. 'Examples',
  72. 'Hint',
  73. 'Important',
  74. 'Keyword Args',
  75. 'Keyword Arguments',
  76. 'Methods',
  77. 'Note',
  78. 'Notes',
  79. 'Return',
  80. 'Returns',
  81. 'Raises',
  82. 'References',
  83. 'See Also',
  84. 'Tip',
  85. 'Todo',
  86. 'Warning',
  87. 'Warnings',
  88. 'Warns',
  89. 'Yield',
  90. 'Yields',
  91. )
  92. # Examples that will be matched -
  93. # " random: Test" where random will be captured as the param
  94. # " random : test" where random will be captured as the param
  95. # " random_t (Test) : test " where random_t will be captured as the param
  96. # Matches anything that fulfills all the following conditions:
  97. GOOGLE_ARGS_REGEX = re(
  98. # Begins with 0 or more whitespace characters
  99. r"^\s*"
  100. # Followed by 1 or more unicode chars, numbers or underscores
  101. # The above is captured as the first group as this is the paramater name.
  102. r"(\w+)"
  103. # Followed by 0 or more whitespace characters
  104. r"\s*"
  105. # Matches patterns contained within round brackets.
  106. # The `.*?`matches any sequence of characters in a non-greedy
  107. # way (denoted by the `*?`)
  108. r"(\(.*?\))?"
  109. # Followed by 0 or more whitespace chars
  110. r"\s*"
  111. # Followed by a colon
  112. r":"
  113. # Might have a new line and leading whitespace
  114. r"\n?\s*"
  115. # Followed by 1 or more characters - which is the docstring for the parameter
  116. ".+"
  117. )
  118. def check_source(
  119. self,
  120. source,
  121. filename,
  122. ignore_decorators=None,
  123. property_decorators=None,
  124. ignore_inline_noqa=False,
  125. ignore_self_only_init=False,
  126. ):
  127. self.property_decorators = (
  128. {} if property_decorators is None else property_decorators
  129. )
  130. self.ignore_self_only_init = ignore_self_only_init
  131. module = parse(StringIO(source), filename)
  132. for definition in module:
  133. for this_check in self.checks:
  134. terminate = False
  135. if isinstance(definition, this_check._check_for):
  136. skipping_all = definition.skipped_error_codes == 'all'
  137. decorator_skip = ignore_decorators is not None and any(
  138. len(ignore_decorators.findall(dec.name)) > 0
  139. for dec in definition.decorators
  140. )
  141. if (
  142. ignore_inline_noqa or not skipping_all
  143. ) and not decorator_skip:
  144. error = this_check(
  145. self, definition, definition.docstring
  146. )
  147. else:
  148. error = None
  149. errors = error if hasattr(error, '__iter__') else [error]
  150. for error in errors:
  151. if error is not None and (
  152. ignore_inline_noqa
  153. or error.code not in definition.skipped_error_codes
  154. ):
  155. partition = this_check.__doc__.partition('.\n')
  156. message, _, explanation = partition
  157. error.set_context(
  158. explanation=explanation, definition=definition
  159. )
  160. yield error
  161. if this_check._terminal:
  162. terminate = True
  163. break
  164. if terminate:
  165. break
  166. @property
  167. def checks(self):
  168. all = [
  169. this_check
  170. for this_check in vars(type(self)).values()
  171. if hasattr(this_check, '_check_for')
  172. ]
  173. return sorted(all, key=lambda this_check: not this_check._terminal)
  174. @check_for(Definition, terminal=True)
  175. def check_docstring_missing(self, definition, docstring):
  176. """D10{0,1,2,3}: Public definitions should have docstrings.
  177. All modules should normally have docstrings. [...] all functions and
  178. classes exported by a module should also have docstrings. Public
  179. methods (including the __init__ constructor) should also have
  180. docstrings.
  181. Note: Public (exported) definitions are either those with names listed
  182. in __all__ variable (if present), or those that do not start
  183. with a single underscore.
  184. """
  185. def method_violation():
  186. if definition.is_magic:
  187. return violations.D105()
  188. if definition.is_init:
  189. if (
  190. self.ignore_self_only_init
  191. and len(definition.param_names) == 1
  192. ):
  193. return None
  194. return violations.D107()
  195. if not definition.is_overload:
  196. return violations.D102()
  197. return None
  198. if not docstring and definition.is_public:
  199. codes = {
  200. Module: violations.D100,
  201. Class: violations.D101,
  202. NestedClass: violations.D106,
  203. Method: method_violation,
  204. NestedFunction: violations.D103,
  205. Function: (
  206. lambda: violations.D103()
  207. if not definition.is_overload
  208. else None
  209. ),
  210. Package: violations.D104,
  211. }
  212. return codes[type(definition)]()
  213. @check_for(Definition, terminal=True)
  214. def check_docstring_empty(self, definition, docstring):
  215. """D419: Docstring is empty.
  216. If the user provided a docstring but it was empty, it is like they never provided one.
  217. NOTE: This used to report as D10X errors.
  218. """
  219. if docstring and is_blank(ast.literal_eval(docstring)):
  220. return violations.D419()
  221. @check_for(Definition)
  222. def check_one_liners(self, definition, docstring):
  223. """D200: One-liner docstrings should fit on one line with quotes.
  224. The closing quotes are on the same line as the opening quotes.
  225. This looks better for one-liners.
  226. """
  227. if docstring:
  228. lines = ast.literal_eval(docstring).split('\n')
  229. if len(lines) > 1:
  230. non_empty_lines = sum(1 for l in lines if not is_blank(l))
  231. if non_empty_lines == 1:
  232. return violations.D200(len(lines))
  233. @check_for(Function)
  234. def check_no_blank_before(self, function, docstring): # def
  235. """D20{1,2}: No blank lines allowed around function/method docstring.
  236. There's no blank line either before or after the docstring unless directly
  237. followed by an inner function or class.
  238. """
  239. if docstring:
  240. before, _, after = function.source.partition(docstring)
  241. blanks_before = list(map(is_blank, before.split('\n')[:-1]))
  242. blanks_after = list(map(is_blank, after.split('\n')[1:]))
  243. blanks_before_count = sum(takewhile(bool, reversed(blanks_before)))
  244. blanks_after_count = sum(takewhile(bool, blanks_after))
  245. if blanks_before_count != 0:
  246. yield violations.D201(blanks_before_count)
  247. if not all(blanks_after) and blanks_after_count != 0:
  248. # Report a D202 violation if the docstring is followed by a blank line
  249. # and the blank line is not itself followed by an inner function or
  250. # class.
  251. if not (
  252. blanks_after_count == 1
  253. and re(r"\s+(?:(?:class|def|async def)\s|@)").match(after)
  254. ):
  255. yield violations.D202(blanks_after_count)
  256. @check_for(Class)
  257. def check_blank_before_after_class(self, class_, docstring):
  258. """D20{3,4}: Class docstring should have 1 blank line around them.
  259. Insert a blank line before and after all docstrings (one-line or
  260. multi-line) that document a class -- generally speaking, the class's
  261. methods are separated from each other by a single blank line, and the
  262. docstring needs to be offset from the first method by a blank line;
  263. for symmetry, put a blank line between the class header and the
  264. docstring.
  265. """
  266. # NOTE: this gives false-positive in this case
  267. # class Foo:
  268. #
  269. # """Docstring."""
  270. #
  271. #
  272. # # comment here
  273. # def foo(): pass
  274. if docstring:
  275. before, _, after = class_.source.partition(docstring)
  276. blanks_before = list(map(is_blank, before.split('\n')[:-1]))
  277. blanks_after = list(map(is_blank, after.split('\n')[1:]))
  278. blanks_before_count = sum(takewhile(bool, reversed(blanks_before)))
  279. blanks_after_count = sum(takewhile(bool, blanks_after))
  280. if blanks_before_count != 0:
  281. yield violations.D211(blanks_before_count)
  282. if blanks_before_count != 1:
  283. yield violations.D203(blanks_before_count)
  284. if not all(blanks_after) and blanks_after_count != 1:
  285. yield violations.D204(blanks_after_count)
  286. @check_for(Definition)
  287. def check_blank_after_summary(self, definition, docstring):
  288. """D205: Put one blank line between summary line and description.
  289. Multi-line docstrings consist of a summary line just like a one-line
  290. docstring, followed by a blank line, followed by a more elaborate
  291. description. The summary line may be used by automatic indexing tools;
  292. it is important that it fits on one line and is separated from the
  293. rest of the docstring by a blank line.
  294. """
  295. if docstring:
  296. lines = ast.literal_eval(docstring).strip().split('\n')
  297. if len(lines) > 1:
  298. post_summary_blanks = list(map(is_blank, lines[1:]))
  299. blanks_count = sum(takewhile(bool, post_summary_blanks))
  300. if blanks_count != 1:
  301. return violations.D205(blanks_count)
  302. @staticmethod
  303. def _get_docstring_indent(definition, docstring):
  304. """Return the indentation of the docstring's opening quotes."""
  305. before_docstring, _, _ = definition.source.partition(docstring)
  306. _, _, indent = before_docstring.rpartition('\n')
  307. return indent
  308. @check_for(Definition)
  309. def check_indent(self, definition, docstring):
  310. """D20{6,7,8}: The entire docstring should be indented same as code.
  311. The entire docstring is indented the same as the quotes at its
  312. first line.
  313. """
  314. if docstring:
  315. indent = self._get_docstring_indent(definition, docstring)
  316. lines = docstring.split('\n')
  317. if len(lines) > 1:
  318. # First line and line continuations need no indent.
  319. lines = [
  320. line
  321. for i, line in enumerate(lines)
  322. if i and not lines[i - 1].endswith('\\')
  323. ]
  324. indents = [leading_space(l) for l in lines if not is_blank(l)]
  325. if set(' \t') == set(''.join(indents) + indent):
  326. yield violations.D206()
  327. if (len(indents) > 1 and min(indents[:-1]) > indent) or (
  328. len(indents) > 0 and indents[-1] > indent
  329. ):
  330. yield violations.D208()
  331. if len(indents) > 0 and min(indents) < indent:
  332. yield violations.D207()
  333. @check_for(Definition)
  334. def check_newline_after_last_paragraph(self, definition, docstring):
  335. """D209: Put multi-line docstring closing quotes on separate line.
  336. Unless the entire docstring fits on a line, place the closing
  337. quotes on a line by themselves.
  338. """
  339. if docstring:
  340. lines = [
  341. l
  342. for l in ast.literal_eval(docstring).split('\n')
  343. if not is_blank(l)
  344. ]
  345. if len(lines) > 1:
  346. if docstring.split("\n")[-1].strip() not in ['"""', "'''"]:
  347. return violations.D209()
  348. @check_for(Definition)
  349. def check_surrounding_whitespaces(self, definition, docstring):
  350. """D210: No whitespaces allowed surrounding docstring text."""
  351. if docstring:
  352. lines = ast.literal_eval(docstring).split('\n')
  353. if (
  354. lines[0].startswith(' ')
  355. or len(lines) == 1
  356. and lines[0].endswith(' ')
  357. ):
  358. return violations.D210()
  359. @check_for(Definition)
  360. def check_multi_line_summary_start(self, definition, docstring):
  361. """D21{2,3}: Multi-line docstring summary style check.
  362. A multi-line docstring summary should start either at the first,
  363. or separately at the second line of a docstring.
  364. """
  365. if docstring:
  366. start_triple = [
  367. '"""',
  368. "'''",
  369. 'u"""',
  370. "u'''",
  371. 'r"""',
  372. "r'''",
  373. 'ur"""',
  374. "ur'''",
  375. ]
  376. lines = ast.literal_eval(docstring).split('\n')
  377. if len(lines) > 1:
  378. first = docstring.split("\n")[0].strip().lower()
  379. if first in start_triple:
  380. return violations.D212()
  381. else:
  382. return violations.D213()
  383. @check_for(Definition)
  384. def check_triple_double_quotes(self, definition, docstring):
  385. r'''D300: Use """triple double quotes""".
  386. For consistency, always use """triple double quotes""" around
  387. docstrings. Use r"""raw triple double quotes""" if you use any
  388. backslashes in your docstrings. For Unicode docstrings, use
  389. u"""Unicode triple-quoted strings""".
  390. Note: Exception to this is made if the docstring contains
  391. """ quotes in its body.
  392. '''
  393. if docstring:
  394. if '"""' in ast.literal_eval(docstring):
  395. # Allow ''' quotes if docstring contains """, because
  396. # otherwise """ quotes could not be expressed inside
  397. # docstring. Not in PEP 257.
  398. regex = re(r"[uU]?[rR]?'''[^'].*")
  399. else:
  400. regex = re(r'[uU]?[rR]?"""[^"].*')
  401. if not regex.match(docstring):
  402. illegal_matcher = re(r"""[uU]?[rR]?("+|'+).*""")
  403. illegal_quotes = illegal_matcher.match(docstring).group(1)
  404. return violations.D300(illegal_quotes)
  405. @check_for(Definition)
  406. def check_backslashes(self, definition, docstring):
  407. r'''D301: Use r""" if any backslashes in a docstring.
  408. Use r"""raw triple double quotes""" if you use any backslashes
  409. (\) in your docstrings.
  410. Exceptions are backslashes for line-continuation and unicode escape
  411. sequences \N... and \u... These are considered intended unescaped
  412. content in docstrings.
  413. '''
  414. # Just check that docstring is raw, check_triple_double_quotes
  415. # ensures the correct quotes.
  416. if (
  417. docstring
  418. and re(r'\\[^\nuN]').search(docstring)
  419. and not docstring.startswith(('r', 'ur'))
  420. ):
  421. return violations.D301()
  422. @staticmethod
  423. def _check_ends_with(docstring, chars, violation):
  424. """First line ends with one of `chars`.
  425. First line of the docstring should end with one of the characters in `chars`.
  426. `chars` supports either a `str` or an `Iterable[str]`. If the condition is
  427. evaluated to be false, it raises `violation`.
  428. """
  429. if docstring:
  430. summary_line = ast.literal_eval(docstring).strip().split('\n')[0]
  431. if not summary_line.endswith(chars):
  432. return violation(summary_line[-1])
  433. @check_for(Definition)
  434. def check_ends_with_period(self, definition, docstring):
  435. """D400: First line should end with a period.
  436. The [first line of a] docstring is a phrase ending in a period.
  437. """
  438. return self._check_ends_with(docstring, '.', violations.D400)
  439. @check_for(Definition)
  440. def check_ends_with_punctuation(self, definition, docstring):
  441. """D415: should end with proper punctuation.
  442. The [first line of a] docstring is a phrase ending in a period,
  443. question mark, or exclamation point
  444. """
  445. return self._check_ends_with(
  446. docstring, ('.', '!', '?'), violations.D415
  447. )
  448. @check_for(Function)
  449. def check_imperative_mood(self, function, docstring): # def context
  450. """D401: First line should be in imperative mood: 'Do', not 'Does'.
  451. [Docstring] prescribes the function or method's effect as a command:
  452. ("Do this", "Return that"), not as a description; e.g. don't write
  453. "Returns the pathname ...".
  454. """
  455. if (
  456. docstring
  457. and not function.is_test
  458. and not function.is_property(self.property_decorators)
  459. ):
  460. stripped = ast.literal_eval(docstring).strip()
  461. if stripped:
  462. first_word = strip_non_alphanumeric(stripped.split()[0])
  463. check_word = first_word.lower()
  464. if check_word in IMPERATIVE_BLACKLIST:
  465. return violations.D401b(first_word)
  466. correct_forms = IMPERATIVE_VERBS.get(stem(check_word))
  467. if correct_forms and check_word not in correct_forms:
  468. best = max(
  469. correct_forms,
  470. key=lambda f: common_prefix_length(check_word, f),
  471. )
  472. return violations.D401(best.capitalize(), first_word)
  473. @check_for(Function)
  474. def check_no_signature(self, function, docstring): # def context
  475. """D402: First line should not be function's or method's "signature".
  476. The one-line docstring should NOT be a "signature" reiterating the
  477. function/method parameters (which can be obtained by introspection).
  478. """
  479. if docstring:
  480. first_line = ast.literal_eval(docstring).strip().split('\n')[0]
  481. if function.name + '(' in first_line.replace(' ', ''):
  482. return violations.D402()
  483. @check_for(Function)
  484. def check_capitalized(self, function, docstring):
  485. """D403: First word of the first line should be properly capitalized.
  486. The [first line of a] docstring is a phrase ending in a period.
  487. """
  488. if docstring:
  489. first_word = ast.literal_eval(docstring).split()[0]
  490. if first_word == first_word.upper():
  491. return
  492. for char in first_word:
  493. if char not in string.ascii_letters and char != "'":
  494. return
  495. if first_word != first_word.capitalize():
  496. return violations.D403(first_word.capitalize(), first_word)
  497. @check_for(Function)
  498. def check_if_needed(self, function, docstring):
  499. """D418: Function decorated with @overload shouldn't contain a docstring.
  500. Functions that are decorated with @overload are definitions,
  501. and are for the benefit of the type checker only,
  502. since they will be overwritten by the non-@overload-decorated definition.
  503. """
  504. if docstring and function.is_overload:
  505. return violations.D418()
  506. @check_for(Definition)
  507. def check_starts_with_this(self, function, docstring):
  508. """D404: First word of the docstring should not be `This`.
  509. Docstrings should use short, simple language. They should not begin
  510. with "This class is [..]" or "This module contains [..]".
  511. """
  512. if not docstring:
  513. return
  514. stripped = ast.literal_eval(docstring).strip()
  515. if not stripped:
  516. return
  517. first_word = strip_non_alphanumeric(stripped.split()[0])
  518. if first_word.lower() == 'this':
  519. return violations.D404()
  520. @staticmethod
  521. def _is_docstring_section(context):
  522. """Check if the suspected context is really a section header.
  523. Lets have a look at the following example docstring:
  524. '''Title.
  525. Some part of the docstring that specifies what the function
  526. returns. <----- Not a real section name. It has a suffix and the
  527. previous line is not empty and does not end with
  528. a punctuation sign.
  529. This is another line in the docstring. It describes stuff,
  530. but we forgot to add a blank line between it and the section name.
  531. Parameters <-- A real section name. The previous line ends with
  532. ---------- a period, therefore it is in a new
  533. grammatical context.
  534. param : int
  535. examples : list <------- Not a section - previous line doesn't end
  536. A list of examples. with punctuation.
  537. notes : list <---------- Not a section - there's text after the
  538. A list of notes. colon.
  539. Notes: <--- Suspected as a context because there's a suffix to the
  540. ----- section, but it's a colon so it's probably a mistake.
  541. Bla.
  542. '''
  543. To make sure this is really a section we check these conditions:
  544. * There's no suffix to the section name or it's just a colon AND
  545. * The previous line is empty OR it ends with punctuation.
  546. If one of the conditions is true, we will consider the line as
  547. a section name.
  548. """
  549. section_name_suffix = (
  550. context.line.strip().lstrip(context.section_name.strip()).strip()
  551. )
  552. section_suffix_is_only_colon = section_name_suffix == ':'
  553. punctuation = [',', ';', '.', '-', '\\', '/', ']', '}', ')']
  554. prev_line_ends_with_punctuation = any(
  555. context.previous_line.strip().endswith(x) for x in punctuation
  556. )
  557. this_line_looks_like_a_section_name = (
  558. is_blank(section_name_suffix) or section_suffix_is_only_colon
  559. )
  560. prev_line_looks_like_end_of_paragraph = (
  561. prev_line_ends_with_punctuation or is_blank(context.previous_line)
  562. )
  563. return (
  564. this_line_looks_like_a_section_name
  565. and prev_line_looks_like_end_of_paragraph
  566. )
  567. @classmethod
  568. def _check_blanks_and_section_underline(
  569. cls, section_name, context, indentation
  570. ):
  571. """D4{07,08,09,12,14}, D215: Section underline checks.
  572. Check for correct formatting for docstring sections. Checks that:
  573. * The line that follows the section name contains
  574. dashes (D40{7,8}).
  575. * The amount of dashes is equal to the length of the section
  576. name (D409).
  577. * The section's content does not begin in the line that follows
  578. the section header (D412).
  579. * The section has no content (D414).
  580. * The indentation of the dashed line is equal to the docstring's
  581. indentation (D215).
  582. """
  583. blank_lines_after_header = 0
  584. for line in context.following_lines:
  585. if not is_blank(line):
  586. break
  587. blank_lines_after_header += 1
  588. else:
  589. # There are only blank lines after the header.
  590. yield violations.D407(section_name)
  591. yield violations.D414(section_name)
  592. return
  593. non_empty_line = context.following_lines[blank_lines_after_header]
  594. dash_line_found = ''.join(set(non_empty_line.strip())) == '-'
  595. if not dash_line_found:
  596. yield violations.D407(section_name)
  597. if blank_lines_after_header > 0:
  598. yield violations.D412(section_name)
  599. else:
  600. if blank_lines_after_header > 0:
  601. yield violations.D408(section_name)
  602. if non_empty_line.strip() != "-" * len(section_name):
  603. yield violations.D409(
  604. len(section_name),
  605. section_name,
  606. len(non_empty_line.strip()),
  607. )
  608. if leading_space(non_empty_line) > indentation:
  609. yield violations.D215(section_name)
  610. line_after_dashes_index = blank_lines_after_header + 1
  611. # If the line index after the dashes is in range (perhaps we have
  612. # a header + underline followed by another section header).
  613. if line_after_dashes_index < len(context.following_lines):
  614. line_after_dashes = context.following_lines[
  615. line_after_dashes_index
  616. ]
  617. if is_blank(line_after_dashes):
  618. rest_of_lines = context.following_lines[
  619. line_after_dashes_index:
  620. ]
  621. if not is_blank(''.join(rest_of_lines)):
  622. yield violations.D412(section_name)
  623. else:
  624. yield violations.D414(section_name)
  625. else:
  626. yield violations.D414(section_name)
  627. @classmethod
  628. def _check_common_section(
  629. cls, docstring, definition, context, valid_section_names
  630. ):
  631. """D4{05,10,11,13}, D214: Section name checks.
  632. Check for valid section names. Checks that:
  633. * The section name is properly capitalized (D405).
  634. * The section is not over-indented (D214).
  635. * There's a blank line after the section (D410, D413).
  636. * There's a blank line before the section (D411).
  637. Also yields all the errors from `_check_blanks_and_section_underline`.
  638. """
  639. indentation = cls._get_docstring_indent(definition, docstring)
  640. capitalized_section = context.section_name.title()
  641. if (
  642. context.section_name not in valid_section_names
  643. and capitalized_section in valid_section_names
  644. ):
  645. yield violations.D405(capitalized_section, context.section_name)
  646. if leading_space(context.line) > indentation:
  647. yield violations.D214(capitalized_section)
  648. if not context.following_lines or not is_blank(
  649. context.following_lines[-1]
  650. ):
  651. if context.is_last_section:
  652. yield violations.D413(capitalized_section)
  653. else:
  654. yield violations.D410(capitalized_section)
  655. if not is_blank(context.previous_line):
  656. yield violations.D411(capitalized_section)
  657. yield from cls._check_blanks_and_section_underline(
  658. capitalized_section, context, indentation
  659. )
  660. @classmethod
  661. def _check_numpy_section(cls, docstring, definition, context):
  662. """D406: NumPy-style section name checks.
  663. Check for valid section names. Checks that:
  664. * The section name has no superfluous suffix to it (D406).
  665. Additionally, also yield all violations from `_check_common_section`
  666. which are style-agnostic section checks.
  667. """
  668. indentation = cls._get_docstring_indent(definition, docstring)
  669. capitalized_section = context.section_name.title()
  670. yield from cls._check_common_section(
  671. docstring, definition, context, cls.NUMPY_SECTION_NAMES
  672. )
  673. suffix = context.line.strip().lstrip(context.section_name)
  674. if suffix:
  675. yield violations.D406(capitalized_section, context.line.strip())
  676. if capitalized_section == "Parameters":
  677. yield from cls._check_parameters_section(
  678. docstring, definition, context
  679. )
  680. @staticmethod
  681. def _check_parameters_section(docstring, definition, context):
  682. """D417: `Parameters` section check for numpy style.
  683. Check for a valid `Parameters` section. Checks that:
  684. * The section documents all function arguments (D417)
  685. except `self` or `cls` if it is a method.
  686. """
  687. docstring_args = set()
  688. section_level_indent = leading_space(context.line)
  689. # Join line continuations, then resplit by line.
  690. content = (
  691. '\n'.join(context.following_lines).replace('\\\n', '').split('\n')
  692. )
  693. for current_line, next_line in zip(content, content[1:]):
  694. # All parameter definitions in the Numpy parameters
  695. # section must be at the same indent level as the section
  696. # name.
  697. # Also, we ensure that the following line is indented,
  698. # and has some string, to ensure that the parameter actually
  699. # has a description.
  700. # This means, this is a parameter doc with some description
  701. if (
  702. (leading_space(current_line) == section_level_indent)
  703. and (
  704. len(leading_space(next_line))
  705. > len(leading_space(current_line))
  706. )
  707. and next_line.strip()
  708. ):
  709. # In case the parameter has type definitions, it
  710. # will have a colon
  711. if ":" in current_line:
  712. parameters, parameter_type = current_line.split(":", 1)
  713. # Else, we simply have the list of parameters defined
  714. # on the current line.
  715. else:
  716. parameters = current_line.strip()
  717. # Numpy allows grouping of multiple parameters of same
  718. # type in the same line. They are comma separated.
  719. parameter_list = parameters.split(",")
  720. for parameter in parameter_list:
  721. docstring_args.add(parameter.strip())
  722. yield from ConventionChecker._check_missing_args(
  723. docstring_args, definition
  724. )
  725. @staticmethod
  726. def _check_args_section(docstring, definition, context):
  727. """D417: `Args` section checks.
  728. Check for a valid `Args` or `Argument` section. Checks that:
  729. * The section documents all function arguments (D417)
  730. except `self` or `cls` if it is a method.
  731. Documentation for each arg should start at the same indentation
  732. level. For example, in this case x and y are distinguishable::
  733. Args:
  734. x: Lorem ipsum dolor sit amet
  735. y: Ut enim ad minim veniam
  736. In the case below, we only recognize x as a documented parameter
  737. because the rest of the content is indented as if it belongs
  738. to the description for x::
  739. Args:
  740. x: Lorem ipsum dolor sit amet
  741. y: Ut enim ad minim veniam
  742. """
  743. docstring_args = set()
  744. # normalize leading whitespace
  745. if context.following_lines:
  746. # any lines with shorter indent than the first one should be disregarded
  747. first_line = context.following_lines[0]
  748. leading_whitespaces = first_line[: -len(first_line.lstrip())]
  749. args_content = dedent(
  750. "\n".join(
  751. [
  752. line
  753. for line in context.following_lines
  754. if line.startswith(leading_whitespaces) or line == ""
  755. ]
  756. )
  757. ).strip()
  758. args_sections = []
  759. for line in args_content.splitlines(keepends=True):
  760. if not line[:1].isspace():
  761. # This line is the start of documentation for the next
  762. # parameter because it doesn't start with any whitespace.
  763. args_sections.append(line)
  764. else:
  765. # This is a continuation of documentation for the last
  766. # parameter because it does start with whitespace.
  767. args_sections[-1] += line
  768. for section in args_sections:
  769. match = ConventionChecker.GOOGLE_ARGS_REGEX.match(section)
  770. if match:
  771. docstring_args.add(match.group(1))
  772. yield from ConventionChecker._check_missing_args(
  773. docstring_args, definition
  774. )
  775. @staticmethod
  776. def _check_missing_args(docstring_args, definition):
  777. """D417: Yield error for missing arguments in docstring.
  778. Given a list of arguments found in the docstring and the
  779. callable definition, it checks if all the arguments of the
  780. callable are present in the docstring, else it yields a
  781. D417 with a list of missing arguments.
  782. """
  783. if isinstance(definition, Function):
  784. function_args = get_function_args(definition.source)
  785. # If the method isn't static, then we skip the first
  786. # positional argument as it is `cls` or `self`
  787. if definition.kind == 'method' and not definition.is_static:
  788. function_args = function_args[1:]
  789. # Filtering out any arguments prefixed with `_` marking them
  790. # as private.
  791. function_args = [
  792. arg_name
  793. for arg_name in function_args
  794. if not is_def_arg_private(arg_name)
  795. ]
  796. missing_args = set(function_args) - docstring_args
  797. if missing_args:
  798. yield violations.D417(
  799. ", ".join(sorted(missing_args)), definition.name
  800. )
  801. @classmethod
  802. def _check_google_section(cls, docstring, definition, context):
  803. """D416: Google-style section name checks.
  804. Check for valid section names. Checks that:
  805. * The section does not contain any blank line between its name
  806. and content (D412).
  807. * The section is not empty (D414).
  808. * The section name has colon as a suffix (D416).
  809. Additionally, also yield all violations from `_check_common_section`
  810. which are style-agnostic section checks.
  811. """
  812. capitalized_section = context.section_name.title()
  813. yield from cls._check_common_section(
  814. docstring, definition, context, cls.GOOGLE_SECTION_NAMES
  815. )
  816. suffix = context.line.strip().lstrip(context.section_name)
  817. if suffix != ":":
  818. yield violations.D416(
  819. capitalized_section + ":", context.line.strip()
  820. )
  821. if capitalized_section in ("Args", "Arguments"):
  822. yield from cls._check_args_section(docstring, definition, context)
  823. @staticmethod
  824. def _get_section_contexts(lines, valid_section_names):
  825. """Generate `SectionContext` objects for valid sections.
  826. Given a list of `valid_section_names`, generate an
  827. `Iterable[SectionContext]` which provides:
  828. * Section Name
  829. * String value of the previous line
  830. * The section line
  831. * Following lines till the next section
  832. * Line index of the beginning of the section in the docstring
  833. * Boolean indicating whether the section is the last section.
  834. for each valid section.
  835. """
  836. lower_section_names = [s.lower() for s in valid_section_names]
  837. def _suspected_as_section(_line):
  838. result = get_leading_words(_line.lower())
  839. return result in lower_section_names
  840. # Finding our suspects.
  841. suspected_section_indices = [
  842. i for i, line in enumerate(lines) if _suspected_as_section(line)
  843. ]
  844. SectionContext = namedtuple(
  845. 'SectionContext',
  846. (
  847. 'section_name',
  848. 'previous_line',
  849. 'line',
  850. 'following_lines',
  851. 'original_index',
  852. 'is_last_section',
  853. ),
  854. )
  855. # First - create a list of possible contexts. Note that the
  856. # `following_lines` member is until the end of the docstring.
  857. contexts = (
  858. SectionContext(
  859. get_leading_words(lines[i].strip()),
  860. lines[i - 1],
  861. lines[i],
  862. lines[i + 1 :],
  863. i,
  864. False,
  865. )
  866. for i in suspected_section_indices
  867. )
  868. # Now that we have manageable objects - rule out false positives.
  869. contexts = (
  870. c for c in contexts if ConventionChecker._is_docstring_section(c)
  871. )
  872. # Now we shall trim the `following lines` field to only reach the
  873. # next section name.
  874. for a, b in pairwise(contexts, None):
  875. end = -1 if b is None else b.original_index
  876. yield SectionContext(
  877. a.section_name,
  878. a.previous_line,
  879. a.line,
  880. lines[a.original_index + 1 : end],
  881. a.original_index,
  882. b is None,
  883. )
  884. def _check_numpy_sections(self, lines, definition, docstring):
  885. """NumPy-style docstring sections checks.
  886. Check the general format of a sectioned docstring:
  887. '''This is my one-liner.
  888. Short Summary
  889. -------------
  890. This is my summary.
  891. Returns
  892. -------
  893. None.
  894. '''
  895. Section names appear in `NUMPY_SECTION_NAMES`.
  896. Yields all violation from `_check_numpy_section` for each valid
  897. Numpy-style section.
  898. """
  899. found_any_numpy_section = False
  900. for ctx in self._get_section_contexts(lines, self.NUMPY_SECTION_NAMES):
  901. found_any_numpy_section = True
  902. yield from self._check_numpy_section(docstring, definition, ctx)
  903. return found_any_numpy_section
  904. def _check_google_sections(self, lines, definition, docstring):
  905. """Google-style docstring section checks.
  906. Check the general format of a sectioned docstring:
  907. '''This is my one-liner.
  908. Note:
  909. This is my summary.
  910. Returns:
  911. None.
  912. '''
  913. Section names appear in `GOOGLE_SECTION_NAMES`.
  914. Yields all violation from `_check_google_section` for each valid
  915. Google-style section.
  916. """
  917. for ctx in self._get_section_contexts(
  918. lines, self.GOOGLE_SECTION_NAMES
  919. ):
  920. yield from self._check_google_section(docstring, definition, ctx)
  921. @check_for(Definition)
  922. def check_docstring_sections(self, definition, docstring):
  923. """Check for docstring sections."""
  924. if not docstring:
  925. return
  926. lines = docstring.split("\n")
  927. if len(lines) < 2:
  928. return
  929. found_numpy = yield from self._check_numpy_sections(
  930. lines, definition, docstring
  931. )
  932. if not found_numpy:
  933. yield from self._check_google_sections(
  934. lines, definition, docstring
  935. )
  936. parse = Parser()
  937. def check(
  938. filenames,
  939. select=None,
  940. ignore=None,
  941. ignore_decorators=None,
  942. property_decorators=None,
  943. ignore_inline_noqa=False,
  944. ignore_self_only_init=False,
  945. ):
  946. """Generate docstring errors that exist in `filenames` iterable.
  947. By default, the PEP-257 convention is checked. To specifically define the
  948. set of error codes to check for, supply either `select` or `ignore` (but
  949. not both). In either case, the parameter should be a collection of error
  950. code strings, e.g., {'D100', 'D404'}.
  951. When supplying `select`, only specified error codes will be reported.
  952. When supplying `ignore`, all error codes which were not specified will be
  953. reported.
  954. Note that ignored error code refer to the entire set of possible
  955. error codes, which is larger than just the PEP-257 convention. To your
  956. convenience, you may use `pydocstyle.violations.conventions.pep257` as
  957. a base set to add or remove errors from.
  958. `ignore_inline_noqa` controls if `# noqa` comments are respected or not.
  959. `ignore_self_only_init` controls if D107 is reported on __init__ only containing `self`.
  960. Examples
  961. ---------
  962. >>> check(['pydocstyle.py'])
  963. <generator object check at 0x...>
  964. >>> check(['pydocstyle.py'], select=['D100'])
  965. <generator object check at 0x...>
  966. >>> check(['pydocstyle.py'], ignore=conventions.pep257 - {'D100'})
  967. <generator object check at 0x...>
  968. """
  969. if select is not None and ignore is not None:
  970. raise IllegalConfiguration(
  971. 'Cannot pass both select and ignore. '
  972. 'They are mutually exclusive.'
  973. )
  974. elif select is not None:
  975. checked_codes = select
  976. elif ignore is not None:
  977. checked_codes = list(
  978. set(violations.ErrorRegistry.get_error_codes()) - set(ignore)
  979. )
  980. else:
  981. checked_codes = violations.conventions.pep257
  982. for filename in filenames:
  983. log.info('Checking file %s.', filename)
  984. try:
  985. with tk.open(filename) as file:
  986. source = file.read()
  987. for error in ConventionChecker().check_source(
  988. source,
  989. filename,
  990. ignore_decorators,
  991. property_decorators,
  992. ignore_inline_noqa,
  993. ignore_self_only_init,
  994. ):
  995. code = getattr(error, 'code', None)
  996. if code in checked_codes:
  997. yield error
  998. except (OSError, AllError, ParseError) as error:
  999. log.warning('Error in file %s: %s', filename, error)
  1000. yield error
  1001. except tk.TokenError:
  1002. yield SyntaxError('invalid syntax in file %s' % filename)
  1003. def is_ascii(string):
  1004. """Return a boolean indicating if `string` only has ascii characters."""
  1005. return all(ord(char) < 128 for char in string)
  1006. def leading_space(string):
  1007. """Return any leading space from `string`."""
  1008. return re(r'\s*').match(string).group()
  1009. def get_leading_words(line):
  1010. """Return any leading set of words from `line`.
  1011. For example, if `line` is " Hello world!!!", returns "Hello world".
  1012. """
  1013. result = re(r"[\w ]+").match(line.strip())
  1014. if result is not None:
  1015. return result.group()
  1016. def is_def_arg_private(arg_name):
  1017. """Return a boolean indicating if the argument name is private."""
  1018. return arg_name.startswith("_")
  1019. def get_function_args(function_source):
  1020. """Return the function arguments given the source-code string."""
  1021. # We are stripping the whitespace from the left of the
  1022. # function source.
  1023. # This is so that if the docstring has incorrectly
  1024. # indented lines, which are at a lower indent than the
  1025. # function source, we still dedent the source correctly
  1026. # and the AST parser doesn't throw an error.
  1027. try:
  1028. function_arg_node = ast.parse(function_source.lstrip()).body[0].args
  1029. except SyntaxError:
  1030. # If we still get a syntax error, we don't want the
  1031. # the checker to crash. Instead we just return a blank list.
  1032. return []
  1033. arg_nodes = function_arg_node.args
  1034. kwonly_arg_nodes = function_arg_node.kwonlyargs
  1035. return [arg_node.arg for arg_node in chain(arg_nodes, kwonly_arg_nodes)]