PageRenderTime 40ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/pymode/libs/pylint/checkers/design_analysis.py

https://gitlab.com/vim-IDE/python-mode
Python | 331 lines | 247 code | 23 blank | 61 comment | 29 complexity | f07a40edae0d201cd9ccf7c2154733aa MD5 | raw file
  1. # Copyright (c) 2003-2013 LOGILAB S.A. (Paris, FRANCE).
  2. # http://www.logilab.fr/ -- mailto:contact@logilab.fr
  3. #
  4. # This program is free software; you can redistribute it and/or modify it under
  5. # the terms of the GNU General Public License as published by the Free Software
  6. # Foundation; either version 2 of the License, or (at your option) any later
  7. # version.
  8. #
  9. # This program is distributed in the hope that it will be useful, but WITHOUT
  10. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License along with
  14. # this program; if not, write to the Free Software Foundation, Inc.,
  15. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  16. """check for signs of poor design"""
  17. import re
  18. from collections import defaultdict
  19. from astroid import If, InferenceError
  20. from pylint.interfaces import IAstroidChecker
  21. from pylint.checkers import BaseChecker
  22. from pylint.checkers.utils import check_messages
  23. # regexp for ignored argument name
  24. IGNORED_ARGUMENT_NAMES = re.compile('_.*')
  25. MSGS = {
  26. 'R0901': ('Too many ancestors (%s/%s)',
  27. 'too-many-ancestors',
  28. 'Used when class has too many parent classes, try to reduce \
  29. this to get a simpler (and so easier to use) class.'),
  30. 'R0902': ('Too many instance attributes (%s/%s)',
  31. 'too-many-instance-attributes',
  32. 'Used when class has too many instance attributes, try to reduce \
  33. this to get a simpler (and so easier to use) class.'),
  34. 'R0903': ('Too few public methods (%s/%s)',
  35. 'too-few-public-methods',
  36. 'Used when class has too few public methods, so be sure it\'s \
  37. really worth it.'),
  38. 'R0904': ('Too many public methods (%s/%s)',
  39. 'too-many-public-methods',
  40. 'Used when class has too many public methods, try to reduce \
  41. this to get a simpler (and so easier to use) class.'),
  42. 'R0911': ('Too many return statements (%s/%s)',
  43. 'too-many-return-statements',
  44. 'Used when a function or method has too many return statement, \
  45. making it hard to follow.'),
  46. 'R0912': ('Too many branches (%s/%s)',
  47. 'too-many-branches',
  48. 'Used when a function or method has too many branches, \
  49. making it hard to follow.'),
  50. 'R0913': ('Too many arguments (%s/%s)',
  51. 'too-many-arguments',
  52. 'Used when a function or method takes too many arguments.'),
  53. 'R0914': ('Too many local variables (%s/%s)',
  54. 'too-many-locals',
  55. 'Used when a function or method has too many local variables.'),
  56. 'R0915': ('Too many statements (%s/%s)',
  57. 'too-many-statements',
  58. 'Used when a function or method has too many statements. You \
  59. should then split it in smaller functions / methods.'),
  60. 'R0923': ('Interface not implemented',
  61. 'interface-not-implemented',
  62. 'Used when an interface class is not implemented anywhere.'),
  63. }
  64. class MisdesignChecker(BaseChecker):
  65. """checks for sign of poor/misdesign:
  66. * number of methods, attributes, local variables...
  67. * size, complexity of functions, methods
  68. """
  69. __implements__ = (IAstroidChecker,)
  70. # configuration section name
  71. name = 'design'
  72. # messages
  73. msgs = MSGS
  74. priority = -2
  75. # configuration options
  76. options = (('max-args',
  77. {'default' : 5, 'type' : 'int', 'metavar' : '<int>',
  78. 'help': 'Maximum number of arguments for function / method'}
  79. ),
  80. ('ignored-argument-names',
  81. {'default' : IGNORED_ARGUMENT_NAMES,
  82. 'type' :'regexp', 'metavar' : '<regexp>',
  83. 'help' : 'Argument names that match this expression will be '
  84. 'ignored. Default to name with leading underscore'}
  85. ),
  86. ('max-locals',
  87. {'default' : 15, 'type' : 'int', 'metavar' : '<int>',
  88. 'help': 'Maximum number of locals for function / method body'}
  89. ),
  90. ('max-returns',
  91. {'default' : 6, 'type' : 'int', 'metavar' : '<int>',
  92. 'help': 'Maximum number of return / yield for function / '
  93. 'method body'}
  94. ),
  95. ('max-branches',
  96. {'default' : 12, 'type' : 'int', 'metavar' : '<int>',
  97. 'help': 'Maximum number of branch for function / method body'}
  98. ),
  99. ('max-statements',
  100. {'default' : 50, 'type' : 'int', 'metavar' : '<int>',
  101. 'help': 'Maximum number of statements in function / method '
  102. 'body'}
  103. ),
  104. ('max-parents',
  105. {'default' : 7,
  106. 'type' : 'int',
  107. 'metavar' : '<num>',
  108. 'help' : 'Maximum number of parents for a class (see R0901).'}
  109. ),
  110. ('max-attributes',
  111. {'default' : 7,
  112. 'type' : 'int',
  113. 'metavar' : '<num>',
  114. 'help' : 'Maximum number of attributes for a class \
  115. (see R0902).'}
  116. ),
  117. ('min-public-methods',
  118. {'default' : 2,
  119. 'type' : 'int',
  120. 'metavar' : '<num>',
  121. 'help' : 'Minimum number of public methods for a class \
  122. (see R0903).'}
  123. ),
  124. ('max-public-methods',
  125. {'default' : 20,
  126. 'type' : 'int',
  127. 'metavar' : '<num>',
  128. 'help' : 'Maximum number of public methods for a class \
  129. (see R0904).'}
  130. ),
  131. )
  132. def __init__(self, linter=None):
  133. BaseChecker.__init__(self, linter)
  134. self.stats = None
  135. self._returns = None
  136. self._branches = None
  137. self._used_ifaces = None
  138. self._ifaces = None
  139. self._stmts = 0
  140. def open(self):
  141. """initialize visit variables"""
  142. self.stats = self.linter.add_stats()
  143. self._returns = []
  144. self._branches = defaultdict(int)
  145. self._used_ifaces = {}
  146. self._ifaces = []
  147. def close(self):
  148. """check that interface classes are used"""
  149. for iface in self._ifaces:
  150. if not iface in self._used_ifaces:
  151. self.add_message('interface-not-implemented', node=iface)
  152. @check_messages('too-many-ancestors', 'too-many-instance-attributes',
  153. 'too-few-public-methods', 'too-many-public-methods',
  154. 'interface-not-implemented')
  155. def visit_class(self, node):
  156. """check size of inheritance hierarchy and number of instance attributes
  157. """
  158. # Is the total inheritance hierarchy is 7 or less?
  159. nb_parents = len(list(node.ancestors()))
  160. if nb_parents > self.config.max_parents:
  161. self.add_message('too-many-ancestors', node=node,
  162. args=(nb_parents, self.config.max_parents))
  163. # Does the class contain less than 20 attributes for
  164. # non-GUI classes (40 for GUI)?
  165. # FIXME detect gui classes
  166. if len(node.instance_attrs) > self.config.max_attributes:
  167. self.add_message('too-many-instance-attributes', node=node,
  168. args=(len(node.instance_attrs),
  169. self.config.max_attributes))
  170. # update interface classes structures
  171. if node.type == 'interface' and node.name != 'Interface':
  172. self._ifaces.append(node)
  173. for parent in node.ancestors(False):
  174. if parent.name == 'Interface':
  175. continue
  176. self._used_ifaces[parent] = 1
  177. try:
  178. for iface in node.interfaces():
  179. self._used_ifaces[iface] = 1
  180. except InferenceError:
  181. # XXX log ?
  182. pass
  183. @check_messages('too-few-public-methods', 'too-many-public-methods')
  184. def leave_class(self, node):
  185. """check number of public methods"""
  186. my_methods = sum(1 for method in node.mymethods()
  187. if not method.name.startswith('_'))
  188. all_methods = sum(1 for method in node.methods()
  189. if not method.name.startswith('_'))
  190. # Does the class contain less than n public methods ?
  191. # This checks only the methods defined in the current class,
  192. # since the user might not have control over the classes
  193. # from the ancestors. It avoids some false positives
  194. # for classes such as unittest.TestCase, which provides
  195. # a lot of assert methods. It doesn't make sense to warn
  196. # when the user subclasses TestCase to add his own tests.
  197. if my_methods > self.config.max_public_methods:
  198. self.add_message('too-many-public-methods', node=node,
  199. args=(my_methods,
  200. self.config.max_public_methods))
  201. # stop here for exception, metaclass and interface classes
  202. if node.type != 'class':
  203. return
  204. # Does the class contain more than n public methods ?
  205. # This checks all the methods defined by ancestors and
  206. # by the current class.
  207. if all_methods < self.config.min_public_methods:
  208. self.add_message('too-few-public-methods', node=node,
  209. args=(all_methods,
  210. self.config.min_public_methods))
  211. @check_messages('too-many-return-statements', 'too-many-branches',
  212. 'too-many-arguments', 'too-many-locals',
  213. 'too-many-statements')
  214. def visit_function(self, node):
  215. """check function name, docstring, arguments, redefinition,
  216. variable names, max locals
  217. """
  218. # init branch and returns counters
  219. self._returns.append(0)
  220. # check number of arguments
  221. args = node.args.args
  222. if args is not None:
  223. ignored_args_num = len(
  224. [arg for arg in args
  225. if self.config.ignored_argument_names.match(arg.name)])
  226. argnum = len(args) - ignored_args_num
  227. if argnum > self.config.max_args:
  228. self.add_message('too-many-arguments', node=node,
  229. args=(len(args), self.config.max_args))
  230. else:
  231. ignored_args_num = 0
  232. # check number of local variables
  233. locnum = len(node.locals) - ignored_args_num
  234. if locnum > self.config.max_locals:
  235. self.add_message('too-many-locals', node=node,
  236. args=(locnum, self.config.max_locals))
  237. # init statements counter
  238. self._stmts = 1
  239. @check_messages('too-many-return-statements', 'too-many-branches',
  240. 'too-many-arguments', 'too-many-locals',
  241. 'too-many-statements')
  242. def leave_function(self, node):
  243. """most of the work is done here on close:
  244. checks for max returns, branch, return in __init__
  245. """
  246. returns = self._returns.pop()
  247. if returns > self.config.max_returns:
  248. self.add_message('too-many-return-statements', node=node,
  249. args=(returns, self.config.max_returns))
  250. branches = self._branches[node]
  251. if branches > self.config.max_branches:
  252. self.add_message('too-many-branches', node=node,
  253. args=(branches, self.config.max_branches))
  254. # check number of statements
  255. if self._stmts > self.config.max_statements:
  256. self.add_message('too-many-statements', node=node,
  257. args=(self._stmts, self.config.max_statements))
  258. def visit_return(self, _):
  259. """count number of returns"""
  260. if not self._returns:
  261. return # return outside function, reported by the base checker
  262. self._returns[-1] += 1
  263. def visit_default(self, node):
  264. """default visit method -> increments the statements counter if
  265. necessary
  266. """
  267. if node.is_statement:
  268. self._stmts += 1
  269. def visit_tryexcept(self, node):
  270. """increments the branches counter"""
  271. branches = len(node.handlers)
  272. if node.orelse:
  273. branches += 1
  274. self._inc_branch(node, branches)
  275. self._stmts += branches
  276. def visit_tryfinally(self, node):
  277. """increments the branches counter"""
  278. self._inc_branch(node, 2)
  279. self._stmts += 2
  280. def visit_if(self, node):
  281. """increments the branches counter"""
  282. branches = 1
  283. # don't double count If nodes coming from some 'elif'
  284. if node.orelse and (len(node.orelse) > 1 or
  285. not isinstance(node.orelse[0], If)):
  286. branches += 1
  287. self._inc_branch(node, branches)
  288. self._stmts += branches
  289. def visit_while(self, node):
  290. """increments the branches counter"""
  291. branches = 1
  292. if node.orelse:
  293. branches += 1
  294. self._inc_branch(node, branches)
  295. visit_for = visit_while
  296. def _inc_branch(self, node, branchesnum=1):
  297. """increments the branches counter"""
  298. self._branches[node.scope()] += branchesnum
  299. def register(linter):
  300. """required method to auto register this checker """
  301. linter.register_checker(MisdesignChecker(linter))