[perflint] Add PERF401 and PERF402 rules (#5298)

## Summary

Adds `PERF401` and `PERF402` mirroring `W8401` and `W8402` from
https://github.com/tonybaloney/perflint

Implementation is not super smart but should be at parity with upstream
implementation judging by:
c07391c176/perflint/comprehension_checker.py (L42-L73)

It essentially checks:

- If the body of a for-loop is just one statement
- If that statement is an `if` and the if-statement contains a call to
`append()` we flag `PERF401` and suggest a list comprehension
- If that statement is a plain call to `append()` or `insert()` we flag
`PERF402` and suggest `list()` or `list.copy()`

I've set the violation to only flag the first append call in a long
`if-else` statement for `PERF401`. Happy to change this to some other
location or make it multiple violations if that makes more sense.

## Test Plan

Fixtures were added with the relevant scenarios for both rules

## Issue Links

Refers: https://github.com/astral-sh/ruff/issues/4789
This commit is contained in:
qdegraaf 2023-07-03 06:03:09 +02:00 committed by GitHub
parent 0bff4ed4d3
commit 93b2bd7184
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 248 additions and 11 deletions

View file

@ -186,10 +186,7 @@ def main(argv: Sequence[str] | None = None) -> int:
generate_docs()
# Get static docs
static_docs = []
for file in os.listdir("docs"):
if file.endswith(".md"):
static_docs.append(Path("docs") / file)
static_docs = [Path("docs") / f for f in os.listdir("docs") if f.endswith(".md")]
# Check rules generated
if not Path("docs/rules").exists():
@ -197,10 +194,9 @@ def main(argv: Sequence[str] | None = None) -> int:
return 1
# Get generated rules
generated_docs = []
for file in os.listdir("docs/rules"):
if file.endswith(".md"):
generated_docs.append(Path("docs/rules") / file)
generated_docs = [
Path("docs/rules") / f for f in os.listdir("docs/rules") if f.endswith(".md")
]
if len(generated_docs) == 0:
print("Please generate rules first.")

View file

@ -45,9 +45,7 @@ def format_confusables_rs(raw_data: dict[str, list[int]]) -> str:
for i in range(0, len(items), 2):
flattened_items.add((items[i], items[i + 1]))
tuples = []
for left, right in sorted(flattened_items):
tuples.append(f" {left}u32 => {right},\n")
tuples = [f" {left}u32 => {right},\n" for left, right in sorted(flattened_items)]
print(f"{len(tuples)} confusable tuples.")