PageRenderTime 46ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/pymode/libs/pylint/checkers/base.py

https://gitlab.com/vim-IDE/python-mode
Python | 1140 lines | 1082 code | 21 blank | 37 comment | 35 complexity | 10e7797e176c640cae4b9d7124e1f292 MD5 | raw file
  1. # Copyright (c) 2003-2013 LOGILAB S.A. (Paris, FRANCE).
  2. # http://www.logilab.fr/ -- mailto:contact@logilab.fr
  3. # Copyright (c) 2009-2010 Arista Networks, Inc.
  4. #
  5. # This program is free software; you can redistribute it and/or modify it under
  6. # the terms of the GNU General Public License as published by the Free Software
  7. # Foundation; either version 2 of the License, or (at your option) any later
  8. # version.
  9. #
  10. # This program is distributed in the hope that it will be useful, but WITHOUT
  11. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  12. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License along with
  15. # this program; if not, write to the Free Software Foundation, Inc.,
  16. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. """basic checker for Python code"""
  18. import collections
  19. import itertools
  20. import sys
  21. import re
  22. import six
  23. from six.moves import zip # pylint: disable=redefined-builtin
  24. from logilab.common.ureports import Table
  25. import astroid
  26. import astroid.bases
  27. from astroid import are_exclusive, InferenceError
  28. from pylint.interfaces import IAstroidChecker, INFERENCE, INFERENCE_FAILURE, HIGH
  29. from pylint.utils import EmptyReport
  30. from pylint.reporters import diff_string
  31. from pylint.checkers import BaseChecker
  32. from pylint.checkers.utils import (
  33. check_messages,
  34. clobber_in_except,
  35. is_builtin_object,
  36. is_inside_except,
  37. overrides_a_method,
  38. safe_infer,
  39. get_argument_from_call,
  40. has_known_bases,
  41. NoSuchArgumentError,
  42. is_import_error,
  43. unimplemented_abstract_methods,
  44. )
  45. # regex for class/function/variable/constant name
  46. CLASS_NAME_RGX = re.compile('[A-Z_][a-zA-Z0-9]+$')
  47. MOD_NAME_RGX = re.compile('(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$')
  48. CONST_NAME_RGX = re.compile('(([A-Z_][A-Z0-9_]*)|(__.*__))$')
  49. COMP_VAR_RGX = re.compile('[A-Za-z_][A-Za-z0-9_]*$')
  50. DEFAULT_NAME_RGX = re.compile('[a-z_][a-z0-9_]{2,30}$')
  51. CLASS_ATTRIBUTE_RGX = re.compile(r'([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$')
  52. # do not require a doc string on system methods
  53. NO_REQUIRED_DOC_RGX = re.compile('__.*__')
  54. REVERSED_METHODS = (('__getitem__', '__len__'),
  55. ('__reversed__', ))
  56. PY33 = sys.version_info >= (3, 3)
  57. PY3K = sys.version_info >= (3, 0)
  58. BAD_FUNCTIONS = ['map', 'filter']
  59. if sys.version_info < (3, 0):
  60. BAD_FUNCTIONS.append('input')
  61. # Name categories that are always consistent with all naming conventions.
  62. EXEMPT_NAME_CATEGORIES = set(('exempt', 'ignore'))
  63. # A mapping from builtin-qname -> symbol, to be used when generating messages
  64. # about dangerous default values as arguments
  65. DEFAULT_ARGUMENT_SYMBOLS = dict(
  66. zip(['.'.join([astroid.bases.BUILTINS, x]) for x in ('set', 'dict', 'list')],
  67. ['set()', '{}', '[]'])
  68. )
  69. del re
  70. def _redefines_import(node):
  71. """ Detect that the given node (AssName) is inside an
  72. exception handler and redefines an import from the tryexcept body.
  73. Returns True if the node redefines an import, False otherwise.
  74. """
  75. current = node
  76. while current and not isinstance(current.parent, astroid.ExceptHandler):
  77. current = current.parent
  78. if not current or not is_import_error(current.parent):
  79. return False
  80. try_block = current.parent.parent
  81. for import_node in try_block.nodes_of_class((astroid.From, astroid.Import)):
  82. for name, alias in import_node.names:
  83. if alias:
  84. if alias == node.name:
  85. return True
  86. elif name == node.name:
  87. return True
  88. return False
  89. def in_loop(node):
  90. """return True if the node is inside a kind of for loop"""
  91. parent = node.parent
  92. while parent is not None:
  93. if isinstance(parent, (astroid.For, astroid.ListComp, astroid.SetComp,
  94. astroid.DictComp, astroid.GenExpr)):
  95. return True
  96. parent = parent.parent
  97. return False
  98. def in_nested_list(nested_list, obj):
  99. """return true if the object is an element of <nested_list> or of a nested
  100. list
  101. """
  102. for elmt in nested_list:
  103. if isinstance(elmt, (list, tuple)):
  104. if in_nested_list(elmt, obj):
  105. return True
  106. elif elmt == obj:
  107. return True
  108. return False
  109. def _loop_exits_early(loop):
  110. """Returns true if a loop has a break statement in its body."""
  111. loop_nodes = (astroid.For, astroid.While)
  112. # Loop over body explicitly to avoid matching break statements
  113. # in orelse.
  114. for child in loop.body:
  115. if isinstance(child, loop_nodes):
  116. # break statement may be in orelse of child loop.
  117. # pylint: disable=superfluous-parens
  118. for orelse in (child.orelse or ()):
  119. for _ in orelse.nodes_of_class(astroid.Break, skip_klass=loop_nodes):
  120. return True
  121. continue
  122. for _ in child.nodes_of_class(astroid.Break, skip_klass=loop_nodes):
  123. return True
  124. return False
  125. def _is_multi_naming_match(match, node_type, confidence):
  126. return (match is not None and
  127. match.lastgroup is not None and
  128. match.lastgroup not in EXEMPT_NAME_CATEGORIES
  129. and (node_type != 'method' or confidence != INFERENCE_FAILURE))
  130. if sys.version_info < (3, 0):
  131. PROPERTY_CLASSES = set(('__builtin__.property', 'abc.abstractproperty'))
  132. else:
  133. PROPERTY_CLASSES = set(('builtins.property', 'abc.abstractproperty'))
  134. def _determine_function_name_type(node):
  135. """Determine the name type whose regex the a function's name should match.
  136. :param node: A function node.
  137. :returns: One of ('function', 'method', 'attr')
  138. """
  139. if not node.is_method():
  140. return 'function'
  141. if node.decorators:
  142. decorators = node.decorators.nodes
  143. else:
  144. decorators = []
  145. for decorator in decorators:
  146. # If the function is a property (decorated with @property
  147. # or @abc.abstractproperty), the name type is 'attr'.
  148. if (isinstance(decorator, astroid.Name) or
  149. (isinstance(decorator, astroid.Getattr) and
  150. decorator.attrname == 'abstractproperty')):
  151. infered = safe_infer(decorator)
  152. if infered and infered.qname() in PROPERTY_CLASSES:
  153. return 'attr'
  154. # If the function is decorated using the prop_method.{setter,getter}
  155. # form, treat it like an attribute as well.
  156. elif (isinstance(decorator, astroid.Getattr) and
  157. decorator.attrname in ('setter', 'deleter')):
  158. return 'attr'
  159. return 'method'
  160. def _has_abstract_methods(node):
  161. """
  162. Determine if the given `node` has abstract methods.
  163. The methods should be made abstract by decorating them
  164. with `abc` decorators.
  165. """
  166. return len(unimplemented_abstract_methods(node)) > 0
  167. def report_by_type_stats(sect, stats, old_stats):
  168. """make a report of
  169. * percentage of different types documented
  170. * percentage of different types with a bad name
  171. """
  172. # percentage of different types documented and/or with a bad name
  173. nice_stats = {}
  174. for node_type in ('module', 'class', 'method', 'function'):
  175. try:
  176. total = stats[node_type]
  177. except KeyError:
  178. raise EmptyReport()
  179. nice_stats[node_type] = {}
  180. if total != 0:
  181. try:
  182. documented = total - stats['undocumented_'+node_type]
  183. percent = (documented * 100.) / total
  184. nice_stats[node_type]['percent_documented'] = '%.2f' % percent
  185. except KeyError:
  186. nice_stats[node_type]['percent_documented'] = 'NC'
  187. try:
  188. percent = (stats['badname_'+node_type] * 100.) / total
  189. nice_stats[node_type]['percent_badname'] = '%.2f' % percent
  190. except KeyError:
  191. nice_stats[node_type]['percent_badname'] = 'NC'
  192. lines = ('type', 'number', 'old number', 'difference',
  193. '%documented', '%badname')
  194. for node_type in ('module', 'class', 'method', 'function'):
  195. new = stats[node_type]
  196. old = old_stats.get(node_type, None)
  197. if old is not None:
  198. diff_str = diff_string(old, new)
  199. else:
  200. old, diff_str = 'NC', 'NC'
  201. lines += (node_type, str(new), str(old), diff_str,
  202. nice_stats[node_type].get('percent_documented', '0'),
  203. nice_stats[node_type].get('percent_badname', '0'))
  204. sect.append(Table(children=lines, cols=6, rheaders=1))
  205. def redefined_by_decorator(node):
  206. """return True if the object is a method redefined via decorator.
  207. For example:
  208. @property
  209. def x(self): return self._x
  210. @x.setter
  211. def x(self, value): self._x = value
  212. """
  213. if node.decorators:
  214. for decorator in node.decorators.nodes:
  215. if (isinstance(decorator, astroid.Getattr) and
  216. getattr(decorator.expr, 'name', None) == node.name):
  217. return True
  218. return False
  219. class _BasicChecker(BaseChecker):
  220. __implements__ = IAstroidChecker
  221. name = 'basic'
  222. class BasicErrorChecker(_BasicChecker):
  223. msgs = {
  224. 'E0100': ('__init__ method is a generator',
  225. 'init-is-generator',
  226. 'Used when the special class method __init__ is turned into a '
  227. 'generator by a yield in its body.'),
  228. 'E0101': ('Explicit return in __init__',
  229. 'return-in-init',
  230. 'Used when the special class method __init__ has an explicit '
  231. 'return value.'),
  232. 'E0102': ('%s already defined line %s',
  233. 'function-redefined',
  234. 'Used when a function / class / method is redefined.'),
  235. 'E0103': ('%r not properly in loop',
  236. 'not-in-loop',
  237. 'Used when break or continue keywords are used outside a loop.'),
  238. 'E0104': ('Return outside function',
  239. 'return-outside-function',
  240. 'Used when a "return" statement is found outside a function or '
  241. 'method.'),
  242. 'E0105': ('Yield outside function',
  243. 'yield-outside-function',
  244. 'Used when a "yield" statement is found outside a function or '
  245. 'method.'),
  246. 'E0106': ('Return with argument inside generator',
  247. 'return-arg-in-generator',
  248. 'Used when a "return" statement with an argument is found '
  249. 'outside in a generator function or method (e.g. with some '
  250. '"yield" statements).',
  251. {'maxversion': (3, 3)}),
  252. 'E0107': ("Use of the non-existent %s operator",
  253. 'nonexistent-operator',
  254. "Used when you attempt to use the C-style pre-increment or"
  255. "pre-decrement operator -- and ++, which doesn't exist in Python."),
  256. 'E0108': ('Duplicate argument name %s in function definition',
  257. 'duplicate-argument-name',
  258. 'Duplicate argument names in function definitions are syntax'
  259. ' errors.'),
  260. 'E0110': ('Abstract class %r with abstract methods instantiated',
  261. 'abstract-class-instantiated',
  262. 'Used when an abstract class with `abc.ABCMeta` as metaclass '
  263. 'has abstract methods and is instantiated.'),
  264. 'W0120': ('Else clause on loop without a break statement',
  265. 'useless-else-on-loop',
  266. 'Loops should only have an else clause if they can exit early '
  267. 'with a break statement, otherwise the statements under else '
  268. 'should be on the same scope as the loop itself.'),
  269. }
  270. @check_messages('function-redefined')
  271. def visit_class(self, node):
  272. self._check_redefinition('class', node)
  273. @check_messages('init-is-generator', 'return-in-init',
  274. 'function-redefined', 'return-arg-in-generator',
  275. 'duplicate-argument-name')
  276. def visit_function(self, node):
  277. if not redefined_by_decorator(node):
  278. self._check_redefinition(node.is_method() and 'method' or 'function', node)
  279. # checks for max returns, branch, return in __init__
  280. returns = node.nodes_of_class(astroid.Return,
  281. skip_klass=(astroid.Function, astroid.Class))
  282. if node.is_method() and node.name == '__init__':
  283. if node.is_generator():
  284. self.add_message('init-is-generator', node=node)
  285. else:
  286. values = [r.value for r in returns]
  287. # Are we returning anything but None from constructors
  288. if [v for v in values
  289. if not (v is None or
  290. (isinstance(v, astroid.Const) and v.value is None) or
  291. (isinstance(v, astroid.Name) and v.name == 'None')
  292. )]:
  293. self.add_message('return-in-init', node=node)
  294. elif node.is_generator():
  295. # make sure we don't mix non-None returns and yields
  296. if not PY33:
  297. for retnode in returns:
  298. if isinstance(retnode.value, astroid.Const) and \
  299. retnode.value.value is not None:
  300. self.add_message('return-arg-in-generator', node=node,
  301. line=retnode.fromlineno)
  302. # Check for duplicate names
  303. args = set()
  304. for name in node.argnames():
  305. if name in args:
  306. self.add_message('duplicate-argument-name', node=node, args=(name,))
  307. else:
  308. args.add(name)
  309. @check_messages('return-outside-function')
  310. def visit_return(self, node):
  311. if not isinstance(node.frame(), astroid.Function):
  312. self.add_message('return-outside-function', node=node)
  313. @check_messages('yield-outside-function')
  314. def visit_yield(self, node):
  315. if not isinstance(node.frame(), (astroid.Function, astroid.Lambda)):
  316. self.add_message('yield-outside-function', node=node)
  317. @check_messages('not-in-loop')
  318. def visit_continue(self, node):
  319. self._check_in_loop(node, 'continue')
  320. @check_messages('not-in-loop')
  321. def visit_break(self, node):
  322. self._check_in_loop(node, 'break')
  323. @check_messages('useless-else-on-loop')
  324. def visit_for(self, node):
  325. self._check_else_on_loop(node)
  326. @check_messages('useless-else-on-loop')
  327. def visit_while(self, node):
  328. self._check_else_on_loop(node)
  329. @check_messages('nonexistent-operator')
  330. def visit_unaryop(self, node):
  331. """check use of the non-existent ++ and -- operator operator"""
  332. if ((node.op in '+-') and
  333. isinstance(node.operand, astroid.UnaryOp) and
  334. (node.operand.op == node.op)):
  335. self.add_message('nonexistent-operator', node=node, args=node.op*2)
  336. @check_messages('abstract-class-instantiated')
  337. def visit_callfunc(self, node):
  338. """ Check instantiating abstract class with
  339. abc.ABCMeta as metaclass.
  340. """
  341. try:
  342. infered = next(node.func.infer())
  343. except astroid.InferenceError:
  344. return
  345. if not isinstance(infered, astroid.Class):
  346. return
  347. # __init__ was called
  348. metaclass = infered.metaclass()
  349. abstract_methods = _has_abstract_methods(infered)
  350. if metaclass is None:
  351. # Python 3.4 has `abc.ABC`, which won't be detected
  352. # by ClassNode.metaclass()
  353. for ancestor in infered.ancestors():
  354. if ancestor.qname() == 'abc.ABC' and abstract_methods:
  355. self.add_message('abstract-class-instantiated',
  356. args=(infered.name, ),
  357. node=node)
  358. break
  359. return
  360. if metaclass.qname() == 'abc.ABCMeta' and abstract_methods:
  361. self.add_message('abstract-class-instantiated',
  362. args=(infered.name, ),
  363. node=node)
  364. def _check_else_on_loop(self, node):
  365. """Check that any loop with an else clause has a break statement."""
  366. if node.orelse and not _loop_exits_early(node):
  367. self.add_message('useless-else-on-loop', node=node,
  368. # This is not optimal, but the line previous
  369. # to the first statement in the else clause
  370. # will usually be the one that contains the else:.
  371. line=node.orelse[0].lineno - 1)
  372. def _check_in_loop(self, node, node_name):
  373. """check that a node is inside a for or while loop"""
  374. _node = node.parent
  375. while _node:
  376. if isinstance(_node, (astroid.For, astroid.While)):
  377. break
  378. _node = _node.parent
  379. else:
  380. self.add_message('not-in-loop', node=node, args=node_name)
  381. def _check_redefinition(self, redeftype, node):
  382. """check for redefinition of a function / method / class name"""
  383. defined_self = node.parent.frame()[node.name]
  384. if defined_self is not node and not are_exclusive(node, defined_self):
  385. self.add_message('function-redefined', node=node,
  386. args=(redeftype, defined_self.fromlineno))
  387. class BasicChecker(_BasicChecker):
  388. """checks for :
  389. * doc strings
  390. * number of arguments, local variables, branches, returns and statements in
  391. functions, methods
  392. * required module attributes
  393. * dangerous default values as arguments
  394. * redefinition of function / method / class
  395. * uses of the global statement
  396. """
  397. __implements__ = IAstroidChecker
  398. name = 'basic'
  399. msgs = {
  400. 'W0101': ('Unreachable code',
  401. 'unreachable',
  402. 'Used when there is some code behind a "return" or "raise" '
  403. 'statement, which will never be accessed.'),
  404. 'W0102': ('Dangerous default value %s as argument',
  405. 'dangerous-default-value',
  406. 'Used when a mutable value as list or dictionary is detected in '
  407. 'a default value for an argument.'),
  408. 'W0104': ('Statement seems to have no effect',
  409. 'pointless-statement',
  410. 'Used when a statement doesn\'t have (or at least seems to) '
  411. 'any effect.'),
  412. 'W0105': ('String statement has no effect',
  413. 'pointless-string-statement',
  414. 'Used when a string is used as a statement (which of course '
  415. 'has no effect). This is a particular case of W0104 with its '
  416. 'own message so you can easily disable it if you\'re using '
  417. 'those strings as documentation, instead of comments.'),
  418. 'W0106': ('Expression "%s" is assigned to nothing',
  419. 'expression-not-assigned',
  420. 'Used when an expression that is not a function call is assigned '
  421. 'to nothing. Probably something else was intended.'),
  422. 'W0108': ('Lambda may not be necessary',
  423. 'unnecessary-lambda',
  424. 'Used when the body of a lambda expression is a function call '
  425. 'on the same argument list as the lambda itself; such lambda '
  426. 'expressions are in all but a few cases replaceable with the '
  427. 'function being called in the body of the lambda.'),
  428. 'W0109': ("Duplicate key %r in dictionary",
  429. 'duplicate-key',
  430. 'Used when a dictionary expression binds the same key multiple '
  431. 'times.'),
  432. 'W0122': ('Use of exec',
  433. 'exec-used',
  434. 'Used when you use the "exec" statement (function for Python '
  435. '3), to discourage its usage. That doesn\'t '
  436. 'mean you can not use it !'),
  437. 'W0123': ('Use of eval',
  438. 'eval-used',
  439. 'Used when you use the "eval" function, to discourage its '
  440. 'usage. Consider using `ast.literal_eval` for safely evaluating '
  441. 'strings containing Python expressions '
  442. 'from untrusted sources. '),
  443. 'W0141': ('Used builtin function %r',
  444. 'bad-builtin',
  445. 'Used when a black listed builtin function is used (see the '
  446. 'bad-function option). Usual black listed functions are the ones '
  447. 'like map, or filter , where Python offers now some cleaner '
  448. 'alternative like list comprehension.'),
  449. 'W0150': ("%s statement in finally block may swallow exception",
  450. 'lost-exception',
  451. 'Used when a break or a return statement is found inside the '
  452. 'finally clause of a try...finally block: the exceptions raised '
  453. 'in the try clause will be silently swallowed instead of being '
  454. 're-raised.'),
  455. 'W0199': ('Assert called on a 2-uple. Did you mean \'assert x,y\'?',
  456. 'assert-on-tuple',
  457. 'A call of assert on a tuple will always evaluate to true if '
  458. 'the tuple is not empty, and will always evaluate to false if '
  459. 'it is.'),
  460. 'C0121': ('Missing required attribute "%s"', # W0103
  461. 'missing-module-attribute',
  462. 'Used when an attribute required for modules is missing.'),
  463. 'E0109': ('Missing argument to reversed()',
  464. 'missing-reversed-argument',
  465. 'Used when reversed() builtin didn\'t receive an argument.'),
  466. 'E0111': ('The first reversed() argument is not a sequence',
  467. 'bad-reversed-sequence',
  468. 'Used when the first argument to reversed() builtin '
  469. 'isn\'t a sequence (does not implement __reversed__, '
  470. 'nor __getitem__ and __len__'),
  471. }
  472. options = (('required-attributes',
  473. {'default' : (), 'type' : 'csv',
  474. 'metavar' : '<attributes>',
  475. 'help' : 'Required attributes for module, separated by a '
  476. 'comma'}
  477. ),
  478. ('bad-functions',
  479. {'default' : BAD_FUNCTIONS,
  480. 'type' :'csv', 'metavar' : '<builtin function names>',
  481. 'help' : 'List of builtins function names that should not be '
  482. 'used, separated by a comma'}
  483. ),
  484. )
  485. reports = (('RP0101', 'Statistics by type', report_by_type_stats),)
  486. def __init__(self, linter):
  487. _BasicChecker.__init__(self, linter)
  488. self.stats = None
  489. self._tryfinallys = None
  490. def open(self):
  491. """initialize visit variables and statistics
  492. """
  493. self._tryfinallys = []
  494. self.stats = self.linter.add_stats(module=0, function=0,
  495. method=0, class_=0)
  496. @check_messages('missing-module-attribute')
  497. def visit_module(self, node):
  498. """check module name, docstring and required arguments
  499. """
  500. self.stats['module'] += 1
  501. for attr in self.config.required_attributes:
  502. if attr not in node:
  503. self.add_message('missing-module-attribute', node=node, args=attr)
  504. def visit_class(self, node): # pylint: disable=unused-argument
  505. """check module name, docstring and redefinition
  506. increment branch counter
  507. """
  508. self.stats['class'] += 1
  509. @check_messages('pointless-statement', 'pointless-string-statement',
  510. 'expression-not-assigned')
  511. def visit_discard(self, node):
  512. """check for various kind of statements without effect"""
  513. expr = node.value
  514. if isinstance(expr, astroid.Const) and isinstance(expr.value,
  515. six.string_types):
  516. # treat string statement in a separated message
  517. # Handle PEP-257 attribute docstrings.
  518. # An attribute docstring is defined as being a string right after
  519. # an assignment at the module level, class level or __init__ level.
  520. scope = expr.scope()
  521. if isinstance(scope, (astroid.Class, astroid.Module, astroid.Function)):
  522. if isinstance(scope, astroid.Function) and scope.name != '__init__':
  523. pass
  524. else:
  525. sibling = expr.previous_sibling()
  526. if (sibling is not None and sibling.scope() is scope and
  527. isinstance(sibling, astroid.Assign)):
  528. return
  529. self.add_message('pointless-string-statement', node=node)
  530. return
  531. # ignore if this is :
  532. # * a direct function call
  533. # * the unique child of a try/except body
  534. # * a yield (which are wrapped by a discard node in _ast XXX)
  535. # warn W0106 if we have any underlying function call (we can't predict
  536. # side effects), else pointless-statement
  537. if (isinstance(expr, (astroid.Yield, astroid.CallFunc)) or
  538. (isinstance(node.parent, astroid.TryExcept) and
  539. node.parent.body == [node])):
  540. return
  541. if any(expr.nodes_of_class(astroid.CallFunc)):
  542. self.add_message('expression-not-assigned', node=node,
  543. args=expr.as_string())
  544. else:
  545. self.add_message('pointless-statement', node=node)
  546. @check_messages('unnecessary-lambda')
  547. def visit_lambda(self, node):
  548. """check whether or not the lambda is suspicious
  549. """
  550. # if the body of the lambda is a call expression with the same
  551. # argument list as the lambda itself, then the lambda is
  552. # possibly unnecessary and at least suspicious.
  553. if node.args.defaults:
  554. # If the arguments of the lambda include defaults, then a
  555. # judgment cannot be made because there is no way to check
  556. # that the defaults defined by the lambda are the same as
  557. # the defaults defined by the function called in the body
  558. # of the lambda.
  559. return
  560. call = node.body
  561. if not isinstance(call, astroid.CallFunc):
  562. # The body of the lambda must be a function call expression
  563. # for the lambda to be unnecessary.
  564. return
  565. # XXX are lambda still different with astroid >= 0.18 ?
  566. # *args and **kwargs need to be treated specially, since they
  567. # are structured differently between the lambda and the function
  568. # call (in the lambda they appear in the args.args list and are
  569. # indicated as * and ** by two bits in the lambda's flags, but
  570. # in the function call they are omitted from the args list and
  571. # are indicated by separate attributes on the function call node).
  572. ordinary_args = list(node.args.args)
  573. if node.args.kwarg:
  574. if (not call.kwargs
  575. or not isinstance(call.kwargs, astroid.Name)
  576. or node.args.kwarg != call.kwargs.name):
  577. return
  578. elif call.kwargs:
  579. return
  580. if node.args.vararg:
  581. if (not call.starargs
  582. or not isinstance(call.starargs, astroid.Name)
  583. or node.args.vararg != call.starargs.name):
  584. return
  585. elif call.starargs:
  586. return
  587. # The "ordinary" arguments must be in a correspondence such that:
  588. # ordinary_args[i].name == call.args[i].name.
  589. if len(ordinary_args) != len(call.args):
  590. return
  591. for i in range(len(ordinary_args)):
  592. if not isinstance(call.args[i], astroid.Name):
  593. return
  594. if node.args.args[i].name != call.args[i].name:
  595. return
  596. if (isinstance(node.body.func, astroid.Getattr) and
  597. isinstance(node.body.func.expr, astroid.CallFunc)):
  598. # Chained call, the intermediate call might
  599. # return something else (but we don't check that, yet).
  600. return
  601. self.add_message('unnecessary-lambda', line=node.fromlineno, node=node)
  602. @check_messages('dangerous-default-value')
  603. def visit_function(self, node):
  604. """check function name, docstring, arguments, redefinition,
  605. variable names, max locals
  606. """
  607. self.stats[node.is_method() and 'method' or 'function'] += 1
  608. self._check_dangerous_default(node)
  609. def _check_dangerous_default(self, node):
  610. # check for dangerous default values as arguments
  611. is_iterable = lambda n: isinstance(n, (astroid.List,
  612. astroid.Set,
  613. astroid.Dict))
  614. for default in node.args.defaults:
  615. try:
  616. value = next(default.infer())
  617. except astroid.InferenceError:
  618. continue
  619. if (isinstance(value, astroid.Instance) and
  620. value.qname() in DEFAULT_ARGUMENT_SYMBOLS):
  621. if value is default:
  622. msg = DEFAULT_ARGUMENT_SYMBOLS[value.qname()]
  623. elif type(value) is astroid.Instance or is_iterable(value):
  624. # We are here in the following situation(s):
  625. # * a dict/set/list/tuple call which wasn't inferred
  626. # to a syntax node ({}, () etc.). This can happen
  627. # when the arguments are invalid or unknown to
  628. # the inference.
  629. # * a variable from somewhere else, which turns out to be a list
  630. # or a dict.
  631. if is_iterable(default):
  632. msg = value.pytype()
  633. elif isinstance(default, astroid.CallFunc):
  634. msg = '%s() (%s)' % (value.name, value.qname())
  635. else:
  636. msg = '%s (%s)' % (default.as_string(), value.qname())
  637. else:
  638. # this argument is a name
  639. msg = '%s (%s)' % (default.as_string(),
  640. DEFAULT_ARGUMENT_SYMBOLS[value.qname()])
  641. self.add_message('dangerous-default-value',
  642. node=node,
  643. args=(msg, ))
  644. @check_messages('unreachable', 'lost-exception')
  645. def visit_return(self, node):
  646. """1 - check is the node has a right sibling (if so, that's some
  647. unreachable code)
  648. 2 - check is the node is inside the finally clause of a try...finally
  649. block
  650. """
  651. self._check_unreachable(node)
  652. # Is it inside final body of a try...finally bloc ?
  653. self._check_not_in_finally(node, 'return', (astroid.Function,))
  654. @check_messages('unreachable')
  655. def visit_continue(self, node):
  656. """check is the node has a right sibling (if so, that's some unreachable
  657. code)
  658. """
  659. self._check_unreachable(node)
  660. @check_messages('unreachable', 'lost-exception')
  661. def visit_break(self, node):
  662. """1 - check is the node has a right sibling (if so, that's some
  663. unreachable code)
  664. 2 - check is the node is inside the finally clause of a try...finally
  665. block
  666. """
  667. # 1 - Is it right sibling ?
  668. self._check_unreachable(node)
  669. # 2 - Is it inside final body of a try...finally bloc ?
  670. self._check_not_in_finally(node, 'break', (astroid.For, astroid.While,))
  671. @check_messages('unreachable')
  672. def visit_raise(self, node):
  673. """check if the node has a right sibling (if so, that's some unreachable
  674. code)
  675. """
  676. self._check_unreachable(node)
  677. @check_messages('exec-used')
  678. def visit_exec(self, node):
  679. """just print a warning on exec statements"""
  680. self.add_message('exec-used', node=node)
  681. @check_messages('bad-builtin', 'eval-used',
  682. 'exec-used', 'missing-reversed-argument',
  683. 'bad-reversed-sequence')
  684. def visit_callfunc(self, node):
  685. """visit a CallFunc node -> check if this is not a blacklisted builtin
  686. call and check for * or ** use
  687. """
  688. if isinstance(node.func, astroid.Name):
  689. name = node.func.name
  690. # ignore the name if it's not a builtin (i.e. not defined in the
  691. # locals nor globals scope)
  692. if not (name in node.frame() or
  693. name in node.root()):
  694. if name == 'exec':
  695. self.add_message('exec-used', node=node)
  696. elif name == 'reversed':
  697. self._check_reversed(node)
  698. elif name == 'eval':
  699. self.add_message('eval-used', node=node)
  700. if name in self.config.bad_functions:
  701. self.add_message('bad-builtin', node=node, args=name)
  702. @check_messages('assert-on-tuple')
  703. def visit_assert(self, node):
  704. """check the use of an assert statement on a tuple."""
  705. if node.fail is None and isinstance(node.test, astroid.Tuple) and \
  706. len(node.test.elts) == 2:
  707. self.add_message('assert-on-tuple', node=node)
  708. @check_messages('duplicate-key')
  709. def visit_dict(self, node):
  710. """check duplicate key in dictionary"""
  711. keys = set()
  712. for k, _ in node.items:
  713. if isinstance(k, astroid.Const):
  714. key = k.value
  715. if key in keys:
  716. self.add_message('duplicate-key', node=node, args=key)
  717. keys.add(key)
  718. def visit_tryfinally(self, node):
  719. """update try...finally flag"""
  720. self._tryfinallys.append(node)
  721. def leave_tryfinally(self, node): # pylint: disable=unused-argument
  722. """update try...finally flag"""
  723. self._tryfinallys.pop()
  724. def _check_unreachable(self, node):
  725. """check unreachable code"""
  726. unreach_stmt = node.next_sibling()
  727. if unreach_stmt is not None:
  728. self.add_message('unreachable', node=unreach_stmt)
  729. def _check_not_in_finally(self, node, node_name, breaker_classes=()):
  730. """check that a node is not inside a finally clause of a
  731. try...finally statement.
  732. If we found before a try...finally bloc a parent which its type is
  733. in breaker_classes, we skip the whole check."""
  734. # if self._tryfinallys is empty, we're not a in try...finally bloc
  735. if not self._tryfinallys:
  736. return
  737. # the node could be a grand-grand...-children of the try...finally
  738. _parent = node.parent
  739. _node = node
  740. while _parent and not isinstance(_parent, breaker_classes):
  741. if hasattr(_parent, 'finalbody') and _node in _parent.finalbody:
  742. self.add_message('lost-exception', node=node, args=node_name)
  743. return
  744. _node = _parent
  745. _parent = _node.parent
  746. def _check_reversed(self, node):
  747. """ check that the argument to `reversed` is a sequence """
  748. try:
  749. argument = safe_infer(get_argument_from_call(node, position=0))
  750. except NoSuchArgumentError:
  751. self.add_message('missing-reversed-argument', node=node)
  752. else:
  753. if argument is astroid.YES:
  754. return
  755. if argument is None:
  756. # Nothing was infered.
  757. # Try to see if we have iter().
  758. if isinstance(node.args[0], astroid.CallFunc):
  759. try:
  760. func = next(node.args[0].func.infer())
  761. except InferenceError:
  762. return
  763. if (getattr(func, 'name', None) == 'iter' and
  764. is_builtin_object(func)):
  765. self.add_message('bad-reversed-sequence', node=node)
  766. return
  767. if isinstance(argument, astroid.Instance):
  768. if (argument._proxied.name == 'dict' and
  769. is_builtin_object(argument._proxied)):
  770. self.add_message('bad-reversed-sequence', node=node)
  771. return
  772. elif any(ancestor.name == 'dict' and is_builtin_object(ancestor)
  773. for ancestor in argument._proxied.ancestors()):
  774. # mappings aren't accepted by reversed()
  775. self.add_message('bad-reversed-sequence', node=node)
  776. return
  777. for methods in REVERSED_METHODS:
  778. for meth in methods:
  779. try:
  780. argument.getattr(meth)
  781. except astroid.NotFoundError:
  782. break
  783. else:
  784. break
  785. else:
  786. # Check if it is a .deque. It doesn't seem that
  787. # we can retrieve special methods
  788. # from C implemented constructs.
  789. if argument._proxied.qname().endswith(".deque"):
  790. return
  791. self.add_message('bad-reversed-sequence', node=node)
  792. elif not isinstance(argument, (astroid.List, astroid.Tuple)):
  793. # everything else is not a proper sequence for reversed()
  794. self.add_message('bad-reversed-sequence', node=node)
  795. _NAME_TYPES = {
  796. 'module': (MOD_NAME_RGX, 'module'),
  797. 'const': (CONST_NAME_RGX, 'constant'),
  798. 'class': (CLASS_NAME_RGX, 'class'),
  799. 'function': (DEFAULT_NAME_RGX, 'function'),
  800. 'method': (DEFAULT_NAME_RGX, 'method'),
  801. 'attr': (DEFAULT_NAME_RGX, 'attribute'),
  802. 'argument': (DEFAULT_NAME_RGX, 'argument'),
  803. 'variable': (DEFAULT_NAME_RGX, 'variable'),
  804. 'class_attribute': (CLASS_ATTRIBUTE_RGX, 'class attribute'),
  805. 'inlinevar': (COMP_VAR_RGX, 'inline iteration'),
  806. }
  807. def _create_naming_options():
  808. name_options = []
  809. for name_type, (rgx, human_readable_name) in six.iteritems(_NAME_TYPES):
  810. name_type = name_type.replace('_', '-')
  811. name_options.append((
  812. '%s-rgx' % (name_type,),
  813. {'default': rgx, 'type': 'regexp', 'metavar': '<regexp>',
  814. 'help': 'Regular expression matching correct %s names' % (human_readable_name,)}))
  815. name_options.append((
  816. '%s-name-hint' % (name_type,),
  817. {'default': rgx.pattern, 'type': 'string', 'metavar': '<string>',
  818. 'help': 'Naming hint for %s names' % (human_readable_name,)}))
  819. return tuple(name_options)
  820. class NameChecker(_BasicChecker):
  821. msgs = {
  822. 'C0102': ('Black listed name "%s"',
  823. 'blacklisted-name',
  824. 'Used when the name is listed in the black list (unauthorized '
  825. 'names).'),
  826. 'C0103': ('Invalid %s name "%s"%s',
  827. 'invalid-name',
  828. 'Used when the name doesn\'t match the regular expression '
  829. 'associated to its type (constant, variable, class...).'),
  830. }
  831. options = (('good-names',
  832. {'default' : ('i', 'j', 'k', 'ex', 'Run', '_'),
  833. 'type' :'csv', 'metavar' : '<names>',
  834. 'help' : 'Good variable names which should always be accepted,'
  835. ' separated by a comma'}
  836. ),
  837. ('bad-names',
  838. {'default' : ('foo', 'bar', 'baz', 'toto', 'tutu', 'tata'),
  839. 'type' :'csv', 'metavar' : '<names>',
  840. 'help' : 'Bad variable names which should always be refused, '
  841. 'separated by a comma'}
  842. ),
  843. ('name-group',
  844. {'default' : (),
  845. 'type' :'csv', 'metavar' : '<name1:name2>',
  846. 'help' : ('Colon-delimited sets of names that determine each'
  847. ' other\'s naming style when the name regexes'
  848. ' allow several styles.')}
  849. ),
  850. ('include-naming-hint',
  851. {'default': False, 'type' : 'yn', 'metavar' : '<y_or_n>',
  852. 'help': 'Include a hint for the correct naming format with invalid-name'}
  853. ),
  854. ) + _create_naming_options()
  855. def __init__(self, linter):
  856. _BasicChecker.__init__(self, linter)
  857. self._name_category = {}
  858. self._name_group = {}
  859. self._bad_names = {}
  860. def open(self):
  861. self.stats = self.linter.add_stats(badname_module=0,
  862. badname_class=0, badname_function=0,
  863. badname_method=0, badname_attr=0,
  864. badname_const=0,
  865. badname_variable=0,
  866. badname_inlinevar=0,
  867. badname_argument=0,
  868. badname_class_attribute=0)
  869. for group in self.config.name_group:
  870. for name_type in group.split(':'):
  871. self._name_group[name_type] = 'group_%s' % (group,)
  872. @check_messages('blacklisted-name', 'invalid-name')
  873. def visit_module(self, node):
  874. self._check_name('module', node.name.split('.')[-1], node)
  875. self._bad_names = {}
  876. def leave_module(self, node): # pylint: disable=unused-argument
  877. for all_groups in six.itervalues(self._bad_names):
  878. if len(all_groups) < 2:
  879. continue
  880. groups = collections.defaultdict(list)
  881. min_warnings = sys.maxsize
  882. for group in six.itervalues(all_groups):
  883. groups[len(group)].append(group)
  884. min_warnings = min(len(group), min_warnings)
  885. if len(groups[min_warnings]) > 1:
  886. by_line = sorted(groups[min_warnings],
  887. key=lambda group: min(warning[0].lineno for warning in group))
  888. warnings = itertools.chain(*by_line[1:])
  889. else:
  890. warnings = groups[min_warnings][0]
  891. for args in warnings:
  892. self._raise_name_warning(*args)
  893. @check_messages('blacklisted-name', 'invalid-name')
  894. def visit_class(self, node):
  895. self._check_name('class', node.name, node)
  896. for attr, anodes in six.iteritems(node.instance_attrs):
  897. if not list(node.instance_attr_ancestors(attr)):
  898. self._check_name('attr', attr, anodes[0])
  899. @check_messages('blacklisted-name', 'invalid-name')
  900. def visit_function(self, node):
  901. # Do not emit any warnings if the method is just an implementation
  902. # of a base class method.
  903. confidence = HIGH
  904. if node.is_method():
  905. if overrides_a_method(node.parent.frame(), node.name):
  906. return
  907. confidence = (INFERENCE if has_known_bases(node.parent.frame())
  908. else INFERENCE_FAILURE)
  909. self._check_name(_determine_function_name_type(node),
  910. node.name, node, confidence)
  911. # Check argument names
  912. args = node.args.args
  913. if args is not None:
  914. self._recursive_check_names(args, node)
  915. @check_messages('blacklisted-name', 'invalid-name')
  916. def visit_global(self, node):
  917. for name in node.names:
  918. self._check_name('const', name, node)
  919. @check_messages('blacklisted-name', 'invalid-name')
  920. def visit_assname(self, node):
  921. """check module level assigned names"""
  922. frame = node.frame()
  923. ass_type = node.ass_type()
  924. if isinstance(ass_type, astroid.Comprehension):
  925. self._check_name('inlinevar', node.name, node)
  926. elif isinstance(frame, astroid.Module):
  927. if isinstance(ass_type, astroid.Assign) and not in_loop(ass_type):
  928. if isinstance(safe_infer(ass_type.value), astroid.Class):
  929. self._check_name('class', node.name, node)
  930. else:
  931. if not _redefines_import(node):
  932. # Don't emit if the name redefines an import
  933. # in an ImportError except handler.
  934. self._check_name('const', node.name, node)
  935. elif isinstance(ass_type, astroid.ExceptHandler):
  936. self._check_name('variable', node.name, node)
  937. elif isinstance(frame, astroid.Function):
  938. # global introduced variable aren't in the function locals
  939. if node.name in frame and node.name not in frame.argnames():
  940. if not _redefines_import(node):
  941. self._check_name('variable', node.name, node)
  942. elif isinstance(frame, astroid.Class):
  943. if not list(frame.local_attr_ancestors(node.name)):
  944. self._check_name('class_attribute', node.name, node)
  945. def _recursive_check_names(self, args, node):
  946. """check names in a possibly recursive list <arg>"""
  947. for arg in args:
  948. if isinstance(arg, astroid.AssName):
  949. self._check_name('argument', arg.name, node)
  950. else:
  951. self._recursive_check_names(arg.elts, node)
  952. def _find_name_group(self, node_type):
  953. return self._name_group.get(node_type, node_type)
  954. def _raise_name_warning(self, node, node_type, name, confidence):
  955. type_label = _NAME_TYPES[node_type][1]
  956. hint = ''
  957. if self.config.include_naming_hint:
  958. hint = ' (hint: %s)' % (getattr(self.config, node_type + '_name_hint'))
  959. self.add_message('invalid-name', node=node, args=(type_label, name, hint),
  960. confidence=confidence)
  961. self.stats['badname_' + node_type] += 1
  962. def _check_name(self, node_type, name, node, confidence=HIGH):
  963. """check for a name using the type's regexp"""
  964. if is_inside_except(node):
  965. clobbering, _ = clobber_in_except(node)
  966. if clobbering:
  967. return
  968. if name in self.config.good_names:
  969. return
  970. if name in self.config.bad_names:
  971. self.stats['badname_' + node_type] += 1
  972. self.add_message('blacklisted-name', node=node, args=name)
  973. return
  974. regexp = getattr(self.config, node_type + '_rgx')
  975. match = regexp.match(name)
  976. if _is_multi_naming_match(match, node_type, confidence):
  977. name_group = self._find_name_group(node_type)
  978. bad_name_group = self._bad_names.setdefault(name_group, {})
  979. warnings = bad_name_group.setdefault(match.lastgroup, [])
  980. warnings.append((node, node_type, name, confidence))
  981. if match is None:
  982. self._raise_name_warning(node, node_type, name, confidence)
  983. class DocStringChecker(_BasicChecker):
  984. msgs = {
  985. 'C0111': ('Missing %s docstring', # W0131
  986. 'missing-docstring',
  987. 'Used when a module, function, class or method has no docstring.'
  988. 'Some special methods like __init__ doesn\'t necessary require a '
  989. 'docstring.'),
  990. 'C0112': ('Empty %s docstring', # W0132
  991. 'empty-docstring',
  992. 'Used when a module, function, class or method has an empty '
  993. 'docstring (it would be too easy ;).'),
  994. }
  995. options = (('no-docstring-rgx',
  996. {'default' : NO_REQUIRED_DOC_RGX,
  997. 'type' : 'regexp', 'metavar' : '<regexp>',
  998. 'help' : 'Regular expression which should only match '
  999. 'function or class names that do not require a '
  1000. 'docstring.'}
  1001. ),
  1002. ('docstring-min-length',
  1003. {'default' : -1,
  1004. 'type' : 'int', 'metavar' : '<int>',
  1005. 'help': ('Minimum line length for functions/classes that'
  1006. ' require docstrings, shorter ones are exempt.')}
  1007. ),
  1008. )
  1009. def open(self):
  1010. self.stats = self.linter.add_stats(undocumented_module=0,
  1011. undocumented_function=0,
  1012. undocumented_method=0,
  1013. undocumented_class=0)
  1014. @check_messages('missing-docstring', 'empty-docstring')
  1015. def visit_module(self, node):
  1016. self._check_docstring('module', node)
  1017. @check_messages('missing-docstring', 'empty-docstring')
  1018. def visit_class(self, node):
  1019. if self.config.no_docstring_rgx.match(node.name) is None:
  1020. self._check_docstring('class', node)
  1021. @check_messages('missing-docstring', 'empty-docstring')
  1022. def visit_function(self, node):
  1023. if self.config.no_docstring_rgx.match(node.name) is None:
  1024. ftype = node.is_method() and 'method' or 'function'
  1025. if isinstance(node.parent.frame(), astroid.Class):
  1026. overridden = False
  1027. confidence = (INFERENCE if has_known_bases(node.parent.frame())
  1028. else INFERENCE_FAILURE)
  1029. # check if node is from a method overridden by its ancestor
  1030. for ancestor in node.parent.frame().ancestors():
  1031. if node.name in ancestor and \
  1032. isinstance(ancestor[node.name], astroid.Function):
  1033. overridden = True
  1034. break
  1035. self._chec