Checks for a C-style cast by looking for the pattern. Args: filename: The name of the current file. clean_lines: A CleansedLines instance containing the file. linenum: The number of the line to check. cast_type: The string for the C++ cast to recommend. This is either reint
(filename, clean_lines, linenum, cast_type, pattern, error)
| 5823 | |
| 5824 | |
| 5825 | def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error): |
| 5826 | """Checks for a C-style cast by looking for the pattern. |
| 5827 | |
| 5828 | Args: |
| 5829 | filename: The name of the current file. |
| 5830 | clean_lines: A CleansedLines instance containing the file. |
| 5831 | linenum: The number of the line to check. |
| 5832 | cast_type: The string for the C++ cast to recommend. This is either |
| 5833 | reinterpret_cast, static_cast, or const_cast, depending. |
| 5834 | pattern: The regular expression used to find C-style casts. |
| 5835 | error: The function to call with any errors found. |
| 5836 | |
| 5837 | Returns: |
| 5838 | True if an error was emitted. |
| 5839 | False otherwise. |
| 5840 | """ |
| 5841 | line = clean_lines.elided[linenum] |
| 5842 | match = Search(pattern, line) |
| 5843 | if not match: |
| 5844 | return False |
| 5845 | |
| 5846 | # Exclude lines with keywords that tend to look like casts |
| 5847 | context = line[0:match.start(1) - 1] |
| 5848 | if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context): |
| 5849 | return False |
| 5850 | |
| 5851 | # Try expanding current context to see if we one level of |
| 5852 | # parentheses inside a macro. |
| 5853 | if linenum > 0: |
| 5854 | for i in xrange(linenum - 1, max(0, linenum - 5), -1): |
| 5855 | context = clean_lines.elided[i] + context |
| 5856 | if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context): |
| 5857 | return False |
| 5858 | |
| 5859 | # operator++(int) and operator--(int) |
| 5860 | if context.endswith(' operator++') or context.endswith(' operator--'): |
| 5861 | return False |
| 5862 | |
| 5863 | # A single unnamed argument for a function tends to look like old style cast. |
| 5864 | # If we see those, don't issue warnings for deprecated casts. |
| 5865 | remainder = line[match.end(0):] |
| 5866 | if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)', |
| 5867 | remainder): |
| 5868 | return False |
| 5869 | |
| 5870 | # At this point, all that should be left is actual casts. |
| 5871 | error(filename, linenum, 'readability/casting', 4, |
| 5872 | 'Using C-style cast. Use %s<%s>(...) instead' % |
| 5873 | (cast_type, match.group(1))) |
| 5874 | |
| 5875 | return True |
| 5876 | |
| 5877 | |
| 5878 | def ExpectingFunctionArgs(clean_lines, linenum): |
no test coverage detected