Skip to content

Ruff rules for comprehensions and performance #329

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 11, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Yet another overdue... hotfix. Sorry this took so long.

* The false positive for indented function parameters in namespaces was eradicated. (https://github.com/cpplint/cpplint/pull/304)
* build/include-what-you-use now recognizes c-style headers, such as <stdio.h> for symbols from <cstdio>. (https://github.com/cpplint/cpplint/pull/319)
* Ruff was ran on the project to improve performance and reader comprehension thanks to @cclauss.

2.0 (2024-10-06)
================
Expand Down
68 changes: 30 additions & 38 deletions cpplint.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
import xml.etree.ElementTree

# if empty, use defaults
_valid_extensions = set([])
_valid_extensions = set()

__VERSION__ = '2.0.1'

Expand Down Expand Up @@ -826,7 +826,7 @@
]

# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
_CHECK_REPLACEMENT = dict([(macro_var, {}) for macro_var in _CHECK_MACROS])
_CHECK_REPLACEMENT = {macro_var: {} for macro_var in _CHECK_MACROS}

for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
('>=', 'GE'), ('>', 'GT'),
Expand Down Expand Up @@ -945,7 +945,7 @@

# Treat all headers starting with 'h' equally: .h, .hpp, .hxx etc.
# This is set by --headers flag.
_hpp_headers = set([])
_hpp_headers = set()

class ErrorSuppressions:
"""Class to track all error suppressions for cpplint"""
Expand Down Expand Up @@ -1038,13 +1038,12 @@ def GetHeaderExtensions():
return _hpp_headers
if _valid_extensions:
return {h for h in _valid_extensions if 'h' in h}
return set(['h', 'hh', 'hpp', 'hxx', 'h++', 'cuh'])
return {'h', 'hh', 'hpp', 'hxx', 'h++', 'cuh'}

# The allowed extensions for file names
# This is set by --extensions flag
def GetAllExtensions():
return GetHeaderExtensions().union(_valid_extensions or set(
['c', 'cc', 'cpp', 'cxx', 'c++', 'cu']))
return GetHeaderExtensions().union(_valid_extensions or {'c', 'cc', 'cpp', 'cxx', 'c++', 'cu'})

def ProcessExtensionsOption(val):
global _valid_extensions
Expand Down Expand Up @@ -1101,7 +1100,7 @@ def ProcessCategory(category):
if categories in (None, '(*)'): # => "suppress all"
ProcessCategory(None)
elif categories.startswith('(') and categories.endswith(')'):
for category in set(map(lambda c: c.strip(), categories[1:-1].split(','))):
for category in {c.strip() for c in categories[1:-1].split(',')}:
if category in _ERROR_CATEGORIES:
ProcessCategory(category)
elif any(c for c in _OTHER_NOLINT_CATEGORY_PREFIXES if category.startswith(c)):
Expand Down Expand Up @@ -6073,13 +6072,12 @@ def ExpectingFunctionArgs(clean_lines, linenum):

_re_pattern_headers_maybe_templates = []
for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
for _template in _templates:
# Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
# 'type::max()'.
_re_pattern_headers_maybe_templates.append(
(re.compile(r'((\bstd::)|[^>.:])\b' + _template + r'(<.*?>)?\([^\)]'),
_template,
_header))
# Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
# 'type::max()'.
_re_pattern_headers_maybe_templates.extend(
(re.compile(r'((\bstd::)|[^>.:])\b' + _template + r'(<.*?>)?\([^\)]'),
_template,
_header) for _template in _templates)

# Map is often overloaded. Only check, if it is fully qualified.
# Match 'std::map<type>(...)', but not 'map<type>(...)''
Expand All @@ -6091,29 +6089,26 @@ def ExpectingFunctionArgs(clean_lines, linenum):
# Other scripts may reach in and modify this pattern.
_re_pattern_templates = []
for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
for _template in _templates:
_re_pattern_templates.append(
(re.compile(r'((^|(^|\s|((^|\W)::))std::)|[^>.:]\b)' + _template + r'\s*\<'),
_template + '<>',
_header))
_re_pattern_templates.extend(
(re.compile(r'((^|(^|\s|((^|\W)::))std::)|[^>.:]\b)' + _template + r'\s*\<'),
_template + '<>',
_header) for _template in _templates)

_re_pattern_types_or_objs = []
for _header, _types_or_objs in _HEADERS_TYPES_OR_OBJS:
for _type_or_obj in _types_or_objs:
_re_pattern_types_or_objs.append(
(re.compile(r'\b' + _type_or_obj + r'\b'),
_type_or_obj,
_header))
_re_pattern_types_or_objs.extend(
(re.compile(r'\b' + _type_or_obj + r'\b'),
_type_or_obj,
_header) for _type_or_obj in _types_or_objs)

_re_pattern_functions = []
for _header, _functions in _HEADERS_FUNCTIONS:
for _function in _functions:
# Match printf(..., ...), but not foo->printf, foo.printf or
# 'type::printf()'.
_re_pattern_functions.append(
(re.compile(r'([^>.]|^)\b' + _function + r'\([^\)]'),
_function,
_header))
# Match printf(..., ...), but not foo->printf, foo.printf or
# 'type::printf()'.
_re_pattern_functions.extend(
(re.compile(r'([^>.]|^)\b' + _function + r'\([^\)]'),
_function,
_header) for _function in _functions)

def FilesBelongToSameModule(filename_cc, filename_h):
"""Check if these two filenames belong to the same module.
Expand Down Expand Up @@ -6750,8 +6745,8 @@ def PrintUsage(message):
Args:
message: The optional error message.
"""
sys.stderr.write(_USAGE % (sorted(list(GetAllExtensions())),
','.join(sorted(list(GetAllExtensions()))),
sys.stderr.write(_USAGE % (sorted(GetAllExtensions()),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

double space at "_USAGE " - odd that ruff isnt picking that up

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will be automatically fixed when we add ruff format to pre-commit.

','.join(sorted(GetAllExtensions())),
sorted(GetHeaderExtensions()),
','.join(sorted(GetHeaderExtensions()))))

Expand Down Expand Up @@ -6933,11 +6928,8 @@ def _ExpandDirectories(filenames):
fullname = fullname[len('.' + os.path.sep):]
expanded.add(fullname)

filtered = []
for filename in expanded:
if os.path.splitext(filename)[1][1:] in GetAllExtensions():
filtered.append(filename)
return filtered
return [filename for filename in expanded
if os.path.splitext(filename)[1][1:] in GetAllExtensions()]

def _FilterExcludedFiles(fnames):
"""Filters out files listed in the --exclude command line switch. File paths
Expand Down
26 changes: 13 additions & 13 deletions cpplint_unittest.py
Original file line number Diff line number Diff line change
Expand Up @@ -4260,27 +4260,27 @@ def testParseArguments(self):
self.assertEqual(['foo.h'],
cpplint.ParseArguments(['--linelength=120', 'foo.h']))
self.assertEqual(120, cpplint._line_length)
self.assertEqual(set(['h', 'hh', 'hpp', 'hxx', 'h++', 'cuh']), cpplint.GetHeaderExtensions()) # Default value
self.assertEqual({'h', 'hh', 'hpp', 'hxx', 'h++', 'cuh'}, cpplint.GetHeaderExtensions()) # Default value

cpplint._hpp_headers = old_headers
cpplint._valid_extensions = old_valid_extensions
self.assertEqual(['foo.h'],
cpplint.ParseArguments(['--headers=h', 'foo.h']))
self.assertEqual(set(['h', 'c', 'cc', 'cpp', 'cxx', 'c++', 'cu']), cpplint.GetAllExtensions())
self.assertEqual({'h', 'c', 'cc', 'cpp', 'cxx', 'c++', 'cu'}, cpplint.GetAllExtensions())

cpplint._hpp_headers = old_headers
cpplint._valid_extensions = old_valid_extensions
self.assertEqual(['foo.h'],
cpplint.ParseArguments(['--extensions=hpp,cpp,cpp', 'foo.h']))
self.assertEqual(set(['hpp', 'cpp']), cpplint.GetAllExtensions())
self.assertEqual(set(['hpp']), cpplint.GetHeaderExtensions())
self.assertEqual({'hpp', 'cpp'}, cpplint.GetAllExtensions())
self.assertEqual({'hpp'}, cpplint.GetHeaderExtensions())

cpplint._hpp_headers = old_headers
cpplint._valid_extensions = old_valid_extensions
self.assertEqual(['foo.h'],
cpplint.ParseArguments(['--extensions=cpp,cpp', '--headers=hpp,h', 'foo.h']))
self.assertEqual(set(['hpp', 'h']), cpplint.GetHeaderExtensions())
self.assertEqual(set(['hpp', 'h', 'cpp']), cpplint.GetAllExtensions())
self.assertEqual({'hpp', 'h'}, cpplint.GetHeaderExtensions())
self.assertEqual({'hpp', 'h', 'cpp'}, cpplint.GetAllExtensions())

finally:
sys.stdout = sys.__stdout__
Expand Down Expand Up @@ -4330,8 +4330,8 @@ def testRecursiveExcludeInvalidFileExtension(self):
finally:
os.chdir(working_dir)
shutil.rmtree(temp_dir)
cpplint._hpp_headers = set([])
cpplint._valid_extensions = set([])
cpplint._hpp_headers = set()
cpplint._valid_extensions = set()

def testRecursiveExclude(self):
working_dir = os.getcwd()
Expand All @@ -4356,7 +4356,7 @@ def testRecursiveExclude(self):
]
cpplint._excludes = None
actual = cpplint.ParseArguments(['src'])
self.assertEqual(set(['src']), set(actual))
self.assertEqual({'src'}, set(actual))

cpplint._excludes = None
actual = cpplint.ParseArguments(['--recursive', 'src'])
Expand All @@ -4374,11 +4374,11 @@ def testRecursiveExclude(self):
'--exclude=src/two.cc', '--exclude=src/three.cc', 'src'])
self.assertEqual(set(expected), set(actual))

expected = set([
expected = {
os.path.join('src2', 'one.cc'),
os.path.join('src2', 'two.cc'),
os.path.join('src2', 'three.cc')
])
}
cpplint._excludes = None
actual = cpplint.ParseArguments(['--recursive',
'--exclude=src', '.'])
Expand Down Expand Up @@ -5629,8 +5629,8 @@ def testClassifyInclude(self):
False))

def testTryDropCommonSuffixes(self):
cpplint._hpp_headers = set([])
cpplint._valid_extensions = set([])
cpplint._hpp_headers = set()
cpplint._valid_extensions = set()
self.assertEqual('foo/foo', cpplint._DropCommonSuffixes('foo/foo-inl.h'))
self.assertEqual('foo/foo', cpplint._DropCommonSuffixes('foo/foo-inl.hxx'))
self.assertEqual('foo/foo', cpplint._DropCommonSuffixes('foo/foo-inl.h++'))
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ lint.select = [
"ASYNC", # flake8-async
"B", # flake8-bugbear
"BLE", # flake8-blind-except
"C4", # flake8-comprehensions
"C90", # McCabe cyclomatic complexity
"DJ", # flake8-django
"DTZ", # flake8-datetimez
Expand Down Expand Up @@ -113,7 +114,6 @@ lint.select = [
"YTT", # flake8-2020
# "ANN", # flake8-annotations
# "ARG", # flake8-unused-arguments
# "C4", # flake8-comprehensions
# "COM", # flake8-commas
# "CPY", # flake8-copyright
# "D", # pydocstyle
Expand Down
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy