Tracks current function name and the number of lines in its body.
| 1677 | |
| 1678 | |
| 1679 | class _FunctionState: |
| 1680 | """Tracks current function name and the number of lines in its body.""" |
| 1681 | |
| 1682 | _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. |
| 1683 | _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. |
| 1684 | |
| 1685 | def __init__(self): |
| 1686 | self.in_a_function = False |
| 1687 | self.lines_in_function = 0 |
| 1688 | self.current_function = "" |
| 1689 | |
| 1690 | def Begin(self, function_name): |
| 1691 | """Start analyzing function body. |
| 1692 | |
| 1693 | Args: |
| 1694 | function_name: The name of the function being tracked. |
| 1695 | """ |
| 1696 | self.in_a_function = True |
| 1697 | self.lines_in_function = 0 |
| 1698 | self.current_function = function_name |
| 1699 | |
| 1700 | def Count(self): |
| 1701 | """Count line in current function body.""" |
| 1702 | if self.in_a_function: |
| 1703 | self.lines_in_function += 1 |
| 1704 | |
| 1705 | def Check(self, error, filename, linenum): |
| 1706 | """Report if too many lines in function body. |
| 1707 | |
| 1708 | Args: |
| 1709 | error: The function to call with any errors found. |
| 1710 | filename: The name of the current file. |
| 1711 | linenum: The number of the line to check. |
| 1712 | """ |
| 1713 | if not self.in_a_function: |
| 1714 | return |
| 1715 | |
| 1716 | if re.match(r"T(EST|est)", self.current_function): |
| 1717 | base_trigger = self._TEST_TRIGGER |
| 1718 | else: |
| 1719 | base_trigger = self._NORMAL_TRIGGER |
| 1720 | trigger = base_trigger * 2 ** _VerboseLevel() |
| 1721 | |
| 1722 | if self.lines_in_function > trigger: |
| 1723 | error_level = int(math.log2(self.lines_in_function / base_trigger)) |
| 1724 | # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... |
| 1725 | error_level = min(error_level, 5) |
| 1726 | error( |
| 1727 | filename, |
| 1728 | linenum, |
| 1729 | "readability/fn_size", |
| 1730 | error_level, |
| 1731 | "Small and focused functions are preferred:" |
| 1732 | f" {self.current_function} has {self.lines_in_function} non-comment lines" |
| 1733 | f" (error triggered by exceeding {trigger} lines).", |
| 1734 | ) |
| 1735 | |
| 1736 | def End(self): |
no outgoing calls
no test coverage detected
searching dependent graphs…