GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Ruff rules for comprehensions and performance by cclauss · Pull Request #329 · cpplint/cpplint

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.

Sign up for GitHub

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
aaronliu0130 merged 2 commits into develop from ruff-rules-C4-and-PERF
Mar 11, 2025

Uh oh!

There was an error while loading. Please reload this page.

Merged

Ruff rules for comprehensions and performance #329

Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
2 commits
Select commit Hold shift + click to select a range
b181eaa
Ruff rules for comprehensions and performance
cclauss Mar 7, 2025
5b91ea6
chore: add ruff stuff to changelog
aaronliu0130 Mar 11, 2025
File filter
Filter by extension


Clear filters
Conversations
Failed to load comments.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Jump to
Jump to file
Failed to load files.
Loading

Uh oh!

There was an error while loading. Please reload this page.

Diff view
Diff view

There are no files selected for viewing

1 change: 1 addition & 0 deletions 1 CHANGELOG.rst
Show comments
View file
Open in desktop
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 68 cpplint.py
Show comments
View file
Open in desktop
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()),
Comment thread Outdated

@jayvdb jayvdb Mar 8, 2025

Copy link
Copy Markdown
Member

There was a problem hiding this comment.

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

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions

@cclauss cclauss Mar 8, 2025

Copy link
Copy Markdown
Member Author

There was a problem hiding this comment.

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.

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

All reactions
','.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 26 cpplint_unittest.py
Show comments
View file
Open in desktop
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 2 pyproject.toml
Show comments
View file
Open in desktop
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
Add this suggestion to a batch that can be applied as a single commit. This suggestion is invalid because no changes were made to the code. Suggestions cannot be applied while the pull request is closed. Suggestions cannot be applied while viewing a subset of changes. Only one suggestion per line can be applied in a batch. Add this suggestion to a batch that can be applied as a single commit. Applying suggestions on deleted lines is not supported. You must change the existing code in this line in order to create a valid suggestion. Outdated suggestions cannot be applied. This suggestion has been applied or marked resolved. Suggestions cannot be applied from pending reviews. Suggestions cannot be applied on multi-line comments. Suggestions cannot be applied while the pull request is queued to merge. Suggestion cannot be applied right now. Please check back later.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.