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