Tracks current function name and the number of lines in its body.
| 1036 | _cpplint_state.RestoreFilters() |
| 1037 | |
| 1038 | class _FunctionState(object): |
| 1039 | """Tracks current function name and the number of lines in its body.""" |
| 1040 | |
| 1041 | _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. |
| 1042 | _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. |
| 1043 | |
| 1044 | def __init__(self): |
| 1045 | self.in_a_function = False |
| 1046 | self.lines_in_function = 0 |
| 1047 | self.current_function = '' |
| 1048 | |
| 1049 | def Begin(self, function_name): |
| 1050 | """Start analyzing function body. |
| 1051 | |
| 1052 | Args: |
| 1053 | function_name: The name of the function being tracked. |
| 1054 | """ |
| 1055 | self.in_a_function = True |
| 1056 | self.lines_in_function = 0 |
| 1057 | self.current_function = function_name |
| 1058 | |
| 1059 | def Count(self): |
| 1060 | """Count line in current function body.""" |
| 1061 | if self.in_a_function: |
| 1062 | self.lines_in_function += 1 |
| 1063 | |
| 1064 | def Check(self, error, filename, linenum): |
| 1065 | """Report if too many lines in function body. |
| 1066 | |
| 1067 | Args: |
| 1068 | error: The function to call with any errors found. |
| 1069 | filename: The name of the current file. |
| 1070 | linenum: The number of the line to check. |
| 1071 | """ |
| 1072 | if not self.in_a_function: |
| 1073 | return |
| 1074 | |
| 1075 | if Match(r'T(EST|est)', self.current_function): |
| 1076 | base_trigger = self._TEST_TRIGGER |
| 1077 | else: |
| 1078 | base_trigger = self._NORMAL_TRIGGER |
| 1079 | trigger = base_trigger * 2**_VerboseLevel() |
| 1080 | |
| 1081 | if self.lines_in_function > trigger: |
| 1082 | error_level = int(math.log(self.lines_in_function / base_trigger, 2)) |
| 1083 | # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... |
| 1084 | if error_level > 5: |
| 1085 | error_level = 5 |
| 1086 | error(filename, linenum, 'readability/fn_size', error_level, |
| 1087 | 'Small and focused functions are preferred:' |
| 1088 | ' %s has %d non-comment lines' |
| 1089 | ' (error triggered by exceeding %d lines).' % ( |
| 1090 | self.current_function, self.lines_in_function, trigger)) |
| 1091 | |
| 1092 | def End(self): |
| 1093 | """Stop analyzing function body.""" |
| 1094 | self.in_a_function = False |
| 1095 |