mccabe.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # Copyright (c) 2016-2020 Claudiu Popa <pcmanticore@gmail.com>
  2. # Copyright (c) 2016 Moises Lopez <moylop260@vauxoo.com>
  3. # Copyright (c) 2017, 2020 hippo91 <guillaume.peillex@gmail.com>
  4. # Copyright (c) 2019, 2021 Pierre Sassoulas <pierre.sassoulas@gmail.com>
  5. # Copyright (c) 2019 Hugo van Kemenade <hugovk@users.noreply.github.com>
  6. # Copyright (c) 2020 Anthony Sottile <asottile@umich.edu>
  7. # Copyright (c) 2021 Ville Skyttä <ville.skytta@iki.fi>
  8. # Copyright (c) 2021 Daniël van Noord <13665637+DanielNoord@users.noreply.github.com>
  9. # Copyright (c) 2021 Marc Mueller <30130371+cdce8p@users.noreply.github.com>
  10. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  11. # For details: https://github.com/PyCQA/pylint/blob/main/LICENSE
  12. """Module to add McCabe checker class for pylint. """
  13. from astroid import nodes
  14. from mccabe import PathGraph as Mccabe_PathGraph
  15. from mccabe import PathGraphingAstVisitor as Mccabe_PathGraphingAstVisitor
  16. from pylint import checkers
  17. from pylint.checkers.utils import check_messages
  18. from pylint.interfaces import HIGH, IAstroidChecker
  19. class PathGraph(Mccabe_PathGraph):
  20. def __init__(self, node):
  21. super().__init__(name="", entity="", lineno=1)
  22. self.root = node
  23. class PathGraphingAstVisitor(Mccabe_PathGraphingAstVisitor):
  24. def __init__(self):
  25. super().__init__()
  26. self._bottom_counter = 0
  27. def default(self, node, *args):
  28. for child in node.get_children():
  29. self.dispatch(child, *args)
  30. def dispatch(self, node, *args):
  31. self.node = node
  32. klass = node.__class__
  33. meth = self._cache.get(klass)
  34. if meth is None:
  35. class_name = klass.__name__
  36. meth = getattr(self.visitor, "visit" + class_name, self.default)
  37. self._cache[klass] = meth
  38. return meth(node, *args)
  39. def visitFunctionDef(self, node):
  40. if self.graph is not None:
  41. # closure
  42. pathnode = self._append_node(node)
  43. self.tail = pathnode
  44. self.dispatch_list(node.body)
  45. bottom = f"{self._bottom_counter}"
  46. self._bottom_counter += 1
  47. self.graph.connect(self.tail, bottom)
  48. self.graph.connect(node, bottom)
  49. self.tail = bottom
  50. else:
  51. self.graph = PathGraph(node)
  52. self.tail = node
  53. self.dispatch_list(node.body)
  54. self.graphs[f"{self.classname}{node.name}"] = self.graph
  55. self.reset()
  56. visitAsyncFunctionDef = visitFunctionDef
  57. def visitSimpleStatement(self, node):
  58. self._append_node(node)
  59. visitAssert = (
  60. visitAssign
  61. ) = (
  62. visitAugAssign
  63. ) = (
  64. visitDelete
  65. ) = (
  66. visitPrint
  67. ) = (
  68. visitRaise
  69. ) = (
  70. visitYield
  71. ) = (
  72. visitImport
  73. ) = (
  74. visitCall
  75. ) = (
  76. visitSubscript
  77. ) = (
  78. visitPass
  79. ) = (
  80. visitContinue
  81. ) = (
  82. visitBreak
  83. ) = visitGlobal = visitReturn = visitExpr = visitAwait = visitSimpleStatement
  84. def visitWith(self, node):
  85. self._append_node(node)
  86. self.dispatch_list(node.body)
  87. visitAsyncWith = visitWith
  88. def _append_node(self, node):
  89. if not self.tail:
  90. return None
  91. self.graph.connect(self.tail, node)
  92. self.tail = node
  93. return node
  94. def _subgraph(self, node, name, extra_blocks=()):
  95. """create the subgraphs representing any `if` and `for` statements"""
  96. if self.graph is None:
  97. # global loop
  98. self.graph = PathGraph(node)
  99. self._subgraph_parse(node, node, extra_blocks)
  100. self.graphs[f"{self.classname}{name}"] = self.graph
  101. self.reset()
  102. else:
  103. self._append_node(node)
  104. self._subgraph_parse(node, node, extra_blocks)
  105. def _subgraph_parse(self, node, pathnode, extra_blocks):
  106. """parse the body and any `else` block of `if` and `for` statements"""
  107. loose_ends = []
  108. self.tail = node
  109. self.dispatch_list(node.body)
  110. loose_ends.append(self.tail)
  111. for extra in extra_blocks:
  112. self.tail = node
  113. self.dispatch_list(extra.body)
  114. loose_ends.append(self.tail)
  115. if node.orelse:
  116. self.tail = node
  117. self.dispatch_list(node.orelse)
  118. loose_ends.append(self.tail)
  119. else:
  120. loose_ends.append(node)
  121. if node:
  122. bottom = f"{self._bottom_counter}"
  123. self._bottom_counter += 1
  124. for end in loose_ends:
  125. self.graph.connect(end, bottom)
  126. self.tail = bottom
  127. class McCabeMethodChecker(checkers.BaseChecker):
  128. """Checks McCabe complexity cyclomatic threshold in methods and functions
  129. to validate a too complex code.
  130. """
  131. __implements__ = IAstroidChecker
  132. name = "design"
  133. msgs = {
  134. "R1260": (
  135. "%s is too complex. The McCabe rating is %d",
  136. "too-complex",
  137. "Used when a method or function is too complex based on "
  138. "McCabe Complexity Cyclomatic",
  139. )
  140. }
  141. options = (
  142. (
  143. "max-complexity",
  144. {
  145. "default": 10,
  146. "type": "int",
  147. "metavar": "<int>",
  148. "help": "McCabe complexity cyclomatic threshold",
  149. },
  150. ),
  151. )
  152. @check_messages("too-complex")
  153. def visit_module(self, node: nodes.Module) -> None:
  154. """visit an astroid.Module node to check too complex rating and
  155. add message if is greater than max_complexity stored from options"""
  156. visitor = PathGraphingAstVisitor()
  157. for child in node.body:
  158. visitor.preorder(child, visitor)
  159. for graph in visitor.graphs.values():
  160. complexity = graph.complexity()
  161. node = graph.root
  162. if hasattr(node, "name"):
  163. node_name = f"'{node.name}'"
  164. else:
  165. node_name = f"This '{node.__class__.__name__.lower()}'"
  166. if complexity <= self.config.max_complexity:
  167. continue
  168. self.add_message(
  169. "too-complex", node=node, confidence=HIGH, args=(node_name, complexity)
  170. )
  171. def register(linter):
  172. """Required method to auto register this checker.
  173. :param linter: Main interface object for Pylint plugins
  174. :type linter: Pylint object
  175. """
  176. linter.register_checker(McCabeMethodChecker(linter))