Tracks current function name and the number of lines in its body.
| 672 | |
| 673 | |
| 674 | class _FunctionState(object): |
| 675 | """Tracks current function name and the number of lines in its body.""" |
| 676 | |
| 677 | _NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc. |
| 678 | _TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER. |
| 679 | |
| 680 | def __init__(self): |
| 681 | self.in_a_function = False |
| 682 | self.lines_in_function = 0 |
| 683 | self.current_function = '' |
| 684 | |
| 685 | def Begin(self, function_name): |
| 686 | """Start analyzing function body. |
| 687 | |
| 688 | Args: |
| 689 | function_name: The name of the function being tracked. |
| 690 | """ |
| 691 | self.in_a_function = True |
| 692 | self.lines_in_function = 0 |
| 693 | self.current_function = function_name |
| 694 | |
| 695 | def Count(self): |
| 696 | """Count line in current function body.""" |
| 697 | if self.in_a_function: |
| 698 | self.lines_in_function += 1 |
| 699 | |
| 700 | def Check(self, error, filename, linenum): |
| 701 | """Report if too many lines in function body. |
| 702 | |
| 703 | Args: |
| 704 | error: The function to call with any errors found. |
| 705 | filename: The name of the current file. |
| 706 | linenum: The number of the line to check. |
| 707 | """ |
| 708 | if Match(r'T(EST|est)', self.current_function): |
| 709 | base_trigger = self._TEST_TRIGGER |
| 710 | else: |
| 711 | base_trigger = self._NORMAL_TRIGGER |
| 712 | trigger = base_trigger * 2**_VerboseLevel() |
| 713 | |
| 714 | if self.lines_in_function > trigger: |
| 715 | error_level = int(math.log(self.lines_in_function / base_trigger, 2)) |
| 716 | # 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ... |
| 717 | if error_level > 5: |
| 718 | error_level = 5 |
| 719 | error(filename, linenum, 'readability/fn_size', error_level, |
| 720 | 'Small and focused functions are preferred:' |
| 721 | ' %s has %d non-comment lines' |
| 722 | ' (error triggered by exceeding %d lines).' % ( |
| 723 | self.current_function, self.lines_in_function, trigger)) |
| 724 | |
| 725 | def End(self): |
| 726 | """Stop analyzing function body.""" |
| 727 | self.in_a_function = False |
| 728 | |
| 729 | |
| 730 | class _IncludeError(Exception): |