Tracks current function name and the number of lines in its body.
| 812 | |
| 813 | |
| 814 | class _FunctionState(object): |
| 815 | """Tracks current function name and the number of lines in its body.""" |
| 816 | |
| 817 | _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. |
| 818 | _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. |
| 819 | |
| 820 | def __init__(self): |
| 821 | self.in_a_function = False |
| 822 | self.lines_in_function = 0 |
| 823 | self.current_function = '' |
| 824 | |
| 825 | def Begin(self, function_name): |
| 826 | """Start analyzing function body. |
| 827 | |
| 828 | Args: |
| 829 | function_name: The name of the function being tracked. |
| 830 | """ |
| 831 | self.in_a_function = True |
| 832 | self.lines_in_function = 0 |
| 833 | self.current_function = function_name |
| 834 | |
| 835 | def Count(self): |
| 836 | """Count line in current function body.""" |
| 837 | if self.in_a_function: |
| 838 | self.lines_in_function += 1 |
| 839 | |
| 840 | def Check(self, error, filename, linenum): |
| 841 | """Report if too many lines in function body. |
| 842 | |
| 843 | Args: |
| 844 | error: The function to call with any errors found. |
| 845 | filename: The name of the current file. |
| 846 | linenum: The number of the line to check. |
| 847 | """ |
| 848 | if Match(r'T(EST|est)', self.current_function): |
| 849 | base_trigger = self._TEST_TRIGGER |
| 850 | else: |
| 851 | base_trigger = self._NORMAL_TRIGGER |
| 852 | trigger = base_trigger * 2**_VerboseLevel() |
| 853 | |
| 854 | if self.lines_in_function > trigger: |
| 855 | error_level = int(math.log(self.lines_in_function / base_trigger, 2)) |
| 856 | # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... |
| 857 | if error_level > 5: |
| 858 | error_level = 5 |
| 859 | error(filename, linenum, 'readability/fn_size', error_level, |
| 860 | 'Small and focused functions are preferred:' |
| 861 | ' %s has %d non-comment lines' |
| 862 | ' (error triggered by exceeding %d lines).' % ( |
| 863 | self.current_function, self.lines_in_function, trigger)) |
| 864 | |
| 865 | def End(self): |
| 866 | """Stop analyzing function body.""" |
| 867 | self.in_a_function = False |
| 868 | |
| 869 | |
| 870 | class _IncludeError(Exception): |