Compare commits

...

35 Commits

Author SHA1 Message Date
Charlie Marsh
050f34dd25 Bump version to 0.0.104 2022-11-06 15:31:10 -05:00
Charlie Marsh
1cd82d588b Categorize functions in pep8-naming (#624) 2022-11-06 15:29:49 -05:00
Charlie Marsh
cea9e34942 Update CONTRIBUTING.md (#623) 2022-11-06 14:31:16 -05:00
Reiner Gerecke
1ede377402 Improve discoverability of dev commands (#621) 2022-11-06 14:25:59 -05:00
Reiner Gerecke
82eff641fb Remove utf-8 encoding declaration (#618) 2022-11-06 14:23:06 -05:00
Charlie Marsh
eb1bc9f092 Allow underscore names in N803 (#622) 2022-11-06 14:19:02 -05:00
Reiner Gerecke
df88504dea pyflakes F632 Autofix (#612) 2022-11-06 06:57:46 -05:00
Anders Kaseorg
b9ec3e9137 Correct source link in CONFUSABLES comment (#617) 2022-11-05 20:53:05 -04:00
Anders Kaseorg
b067b665ff Fix B015 false positive on comparison deep inside expression statement (#616) 2022-11-05 20:13:22 -04:00
Charlie Marsh
22cfd03b13 Bump ruff_dev to v0.0.103 2022-11-05 19:53:27 -04:00
Charlie Marsh
3ae408a364 Only track noqa directives for multi-line strings (#615) 2022-11-05 19:53:13 -04:00
Anders Kaseorg
95073b1586 Fix “Code” misspelling (#614) 2022-11-05 19:28:52 -04:00
Charlie Marsh
3597a94818 Add a README link to each plugin (#611) 2022-11-05 16:18:27 -04:00
Charlie Marsh
2727e5f3b7 Remove some usages of Ruff internals in ruff_dev (#610) 2022-11-05 16:07:21 -04:00
Charlie Marsh
de53b567f5 Add a list of projects using Ruff (#608) 2022-11-05 16:03:10 -04:00
Charlie Marsh
21479a151d Bump ruff_dev to v0.0.102 2022-11-05 16:00:24 -04:00
Charlie Marsh
d822458d97 Fix reference to src/checks_gen.rs 2022-11-05 15:59:51 -04:00
Charlie Marsh
6741ea9790 Create a separate dev crate for development scripts (#607) 2022-11-05 15:59:18 -04:00
Charlie Marsh
2e1799dd80 Automatically update README.md from generate_rules_table.rs (#606) 2022-11-05 15:33:47 -04:00
Reiner Gerecke
c48c7669a8 Remove rust version from CONTRIBUTING.md (#605) 2022-11-05 15:03:10 -04:00
Charlie Marsh
d5fbcd708d Automatically write to src/checks_gen.rs (#604) 2022-11-05 14:30:18 -04:00
Charlie Marsh
b335a6a5ec Bump version to 0.0.102 2022-11-05 14:13:02 -04:00
Charlie Marsh
f5cbee452a Increase flake8-bugbear count to 15/32 2022-11-05 14:12:35 -04:00
Harutaka Kawamura
5d1ea4410a Ignore ellipsis in B018 (#598) 2022-11-05 14:11:44 -04:00
Harutaka Kawamura
f27163d2c7 Remove needless return (#597) 2022-11-05 14:11:26 -04:00
Harutaka Kawamura
62c126f70e Implement B003 (#596) 2022-11-05 14:08:02 -04:00
Harutaka Kawamura
8344d5151c Implement B016 (#595) 2022-11-05 14:06:00 -04:00
Harutaka Kawamura
f7780eb720 Implement B008 (#594) 2022-11-05 14:05:04 -04:00
Charlie Marsh
c544d84b46 Rely on token locations for noqa map extraction (#603) 2022-11-05 10:51:19 -04:00
Charlie Marsh
fbdc075e5c Change Ruff's error prefix to RUF (#592) 2022-11-04 23:13:50 -04:00
Charlie Marsh
d3472104d0 Bump flake8-bugbear count to 12/32 2022-11-04 14:49:14 -04:00
Charlie Marsh
0c8b981216 Bump version to 0.0.101 2022-11-04 14:46:48 -04:00
Charlie Marsh
0e3f08aa68 Split ambiguous unicode detection into string vs. docstring rules (#590) 2022-11-04 14:46:20 -04:00
Charlie Marsh
a75b1c85ee Fix invalid escape handling for CRLF files (#589) 2022-11-04 14:26:39 -04:00
Harutaka Kawamura
726e6c68cf Implement B015 (#587) 2022-11-04 13:47:52 -04:00
82 changed files with 1854 additions and 596 deletions

2
.cargo/config.toml Normal file
View File

@@ -0,0 +1,2 @@
[alias]
dev = "run --package ruff_dev --bin ruff_dev"

View File

@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.100
rev: v0.0.104
hooks:
- id: ruff

View File

@@ -1,17 +1,17 @@
# Contributing to ruff
# Contributing to Ruff
Welcome! We're happy to have you here. Thank you in advance for your contribution to ruff.
Welcome! We're happy to have you here. Thank you in advance for your contribution to Ruff.
## The basics
ruff welcomes contributions in the form of Pull Requests. For small changes (e.g., bug fixes), feel
Ruff welcomes contributions in the form of Pull Requests. For small changes (e.g., bug fixes), feel
free to submit a PR. For larger changes (e.g., new lint rules, new functionality, new configuration
options), consider submitting an [Issue](https://github.com/charliermarsh/ruff/issues) outlining
your proposed change.
### Prerequisites
ruff is written in Rust (1.63.0). You'll need to install the
Ruff is written in Rust. You'll need to install the
[Rust toolchain](https://www.rust-lang.org/tools/install) for development.
You'll also need [Insta](https://insta.rs/docs/) to update snapshot tests:
@@ -22,7 +22,7 @@ cargo install cargo-insta
### Development
After cloning the repository, run ruff locally with:
After cloning the repository, run Ruff locally with:
```shell
cargo run resources/test/fixtures --no-cache
@@ -32,9 +32,9 @@ Prior to opening a pull request, ensure that your code has been auto-formatted,
both the lint and test validation checks:
```shell
cargo fmt # Auto-formatting...
cargo clippy # Linting...
cargo test # Testing...
cargo +nightly fmt --all # Auto-formatting...
cargo +nightly clippy --all # Linting...
cargo +nightly test --all # Testing...
```
These checks will run on GitHub Actions when you open your Pull Request, but running them locally
@@ -45,12 +45,13 @@ prior to merging.
### Example: Adding a new lint rule
There are three phases to adding a new lint rule:
There are four phases to adding a new lint rule:
1. Define the rule in `src/checks.rs`.
2. Define the _logic_ for triggering the rule in `src/check_ast.rs` (for AST-based checks)
or `src/check_lines.rs` (for text-based checks).
2. Define the _logic_ for triggering the rule in `src/check_ast.rs` (for AST-based checks),
`src/check_tokens.rs` (for token-based checks), or `src/check_lines.rs` (for text-based checks).
3. Add a test fixture.
4. Update the generated files (documentation and generated code).
To define the rule, open up `src/checks.rs`. You'll need to define both a `CheckCode` and
`CheckKind`. As an example, you can grep for `E402` and `ModuleImportNotAtTopOfFile`, and follow the
@@ -58,37 +59,33 @@ pattern implemented therein.
To trigger the rule, you'll likely want to augment the logic in `src/check_ast.rs`, which defines
the Python AST visitor, responsible for iterating over the abstract syntax tree and collecting
lint-rule violations as it goes. Grep for the `Check::new` invocations to understand how other,
similar rules are implemented.
lint-rule violations as it goes. If you need to inspect the AST, you can run `cargo dev print-ast`
with a Python file. Grep for the `Check::new` invocations to understand how other, similar rules
are implemented.
To add a test fixture, create a file under `resources/test/fixtures`, named to match the `CheckCode`
you defined earlier (e.g., `E402.py`). This file should contain a variety of violations and
non-violations designed to evaluate and demonstrate the behavior of your lint rule. Run ruff locally
with (e.g.) `cargo run resources/test/fixtures/E402.py`. Once you're satisfied with the output,
codify the behavior as a snapshot test by adding a new function to the `mod tests` section of
`src/linter.rs`, like so:
non-violations designed to evaluate and demonstrate the behavior of your lint rule. Run Ruff locally
with (e.g.) `cargo run resources/test/fixtures/E402.py --no-cache`. Once you're satisfied with the
output, codify the behavior as a snapshot test by adding a new `testcase` macro to the `mod tests`
section of `src/linter.rs`, like so:
```rust
#[test]
fn e402() -> Result<()> {
let mut checks = check_path(
Path::new("./resources/test/fixtures/E402.py"),
&settings::Settings::for_rule(CheckCode::E402),
&fixer::Mode::Generate,
)?;
checks.sort_by_key(|check| check.location);
insta::assert_yaml_snapshot!(checks);
Ok(())
}
#[test_case(CheckCode::A001, Path::new("A001.py"); "A001")]
...
```
Then, run `cargo test`. Your test will fail, but you'll be prompted to follow-up with
`cargo insta review`. Accept the generated snapshot, then commit the snapshot file alongside the
rest of your changes.
Finally, to update the documentation, run `cargo dev generate-rules-table` from the repo root. To
update the generated prefix map, run `cargo dev generate-check-code-prefix`. Both of these commands
should be run whenever a new check is added to the codebase.
### Example: Adding a new configuration option
ruff's user-facing settings live in two places: first, the command-line options defined with
Ruff's user-facing settings live in two places: first, the command-line options defined with
[clap](https://docs.rs/clap/latest/clap/) via the `Cli` struct in `src/main.rs`; and second, the
`Config` struct defined `src/pyproject.rs`, which is responsible for extracting user-defined
settings from a `pyproject.toml` file.
@@ -103,9 +100,9 @@ acceptable unused variables (e.g., `_`).
## Release process
As of now, ruff has an ad hoc release process: releases are cut with high frequency via GitHub
As of now, Ruff has an ad hoc release process: releases are cut with high frequency via GitHub
Actions, which automatically generates the appropriate wheels across architectures and publishes
them to [PyPI](https://pypi.org/project/ruff/).
ruff follows the [semver](https://semver.org/) versioning standard. However, as pre-1.0 software,
Ruff follows the [semver](https://semver.org/) versioning standard. However, as pre-1.0 software,
even patch releases may contain [non-backwards-compatible changes](https://semver.org/#spec-item-4).

21
Cargo.lock generated
View File

@@ -920,7 +920,7 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "flake8-to-ruff"
version = "0.0.100-dev.0"
version = "0.0.104-dev.0"
dependencies = [
"anyhow",
"clap 4.0.15",
@@ -2221,7 +2221,7 @@ dependencies = [
[[package]]
name = "ruff"
version = "0.0.100"
version = "0.0.104"
dependencies = [
"anyhow",
"assert_cmd",
@@ -2230,7 +2230,6 @@ dependencies = [
"chrono",
"clap 4.0.15",
"clearscreen",
"codegen",
"colored",
"common-path",
"criterion",
@@ -2265,6 +2264,22 @@ dependencies = [
"walkdir",
]
[[package]]
name = "ruff_dev"
version = "0.0.104"
dependencies = [
"anyhow",
"clap 4.0.15",
"codegen",
"itertools",
"ruff",
"rustpython-ast",
"rustpython-common",
"rustpython-parser",
"strum",
"strum_macros",
]
[[package]]
name = "rustls"
version = "0.20.6"

View File

@@ -1,11 +1,12 @@
[workspace]
members = [
"flake8_to_ruff",
"ruff_dev",
]
[package]
name = "ruff"
version = "0.0.100"
version = "0.0.104"
edition = "2021"
[lib]
@@ -56,7 +57,6 @@ getrandom = { version = "0.2.7", features = ["js"] }
[dev-dependencies]
assert_cmd = { version = "2.0.4" }
codegen = { version = "0.2.0" }
criterion = { version = "0.4.0" }
insta = { version = "1.19.1", features = ["yaml"] }
test-case = { version = "2.2.2" }

View File

@@ -31,6 +31,10 @@ of plugins), [`pydocstyle`](https://pypi.org/project/pydocstyle/), [`yesqa`](htt
and even a subset of [`pyupgrade`](https://pypi.org/project/pyupgrade/) and [`autoflake`](https://pypi.org/project/autoflake/)
all while executing tens or hundreds of times faster than any individual tool.
Ruff is actively developed and used in major open-source projects
like [Zulip](https://github.com/zulip/zulip), [pydantic](https://github.com/pydantic/pydantic),
and [Saleor](https://github.com/saleor/saleor).
Read the [launch blog post](https://notes.crmarsh.com/python-tooling-could-be-much-much-faster).
## Table of Contents
@@ -39,18 +43,17 @@ Read the [launch blog post](https://notes.crmarsh.com/python-tooling-could-be-mu
2. [Configuration](#configuration)
3. [Supported Rules](#supported-rules)
1. [Pyflakes](#pyflakes)
2. [pycodestyle (error)](#pycodestyle-error)
3. [pycodestyle (warning)](#pycodestyle-warning)
4. [pydocstyle](#pydocstyle)
5. [pyupgrade](#pyupgrade)
6. [pep8-naming](#pep8-naming)
7. [flake8-comprehensions](#flake8-comprehensions)
8. [flake8-bugbear](#flake8-bugbear)
9. [flake8-builtins](#flake8-builtins)
10. [flake8-print](#flake8-print)
11. [flake8-quotes](#flake8-quotes)
12. [Ruff-specific rules](#ruff-specific-rules)
13. [Meta rules](#meta-rules)
2. [pycodestyle](#pycodestyle)
3. [pydocstyle](#pydocstyle)
4. [pyupgrade](#pyupgrade)
5. [pep8-naming](#pep8-naming)
6. [flake8-comprehensions](#flake8-comprehensions)
7. [flake8-bugbear](#flake8-bugbear)
8. [flake8-builtins](#flake8-builtins)
9. [flake8-print](#flake8-print)
10. [flake8-quotes](#flake8-quotes)
11. [Ruff-specific rules](#ruff-specific-rules)
12. [Meta rules](#meta-rules)
5. [Editor Integrations](#editor-integrations)
6. [FAQ](#faq)
7. [Development](#development)
@@ -90,7 +93,7 @@ Ruff also works with [pre-commit](https://pre-commit.com):
```yaml
repos:
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.100
rev: v0.0.104
hooks:
- id: ruff
```
@@ -291,12 +294,19 @@ add `noqa` directives to all failing lines, with the appropriate error codes.**
## Supported Rules
Regardless of the rule's origin, Ruff re-implements every rule in Rust as a first-party feature.
By default, Ruff enables all `E` and `F` error codes, which correspond to those built-in to Flake8.
The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` command-line option.
<!-- Sections automatically generated by `cargo dev generate-rules-table`. -->
<!-- Begin auto-generated sections. -->
### Pyflakes
For more, see [Pyflakes](https://pypi.org/project/pyflakes/2.5.0/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| F401 | UnusedImport | `...` imported but unused | 🛠 |
@@ -312,7 +322,7 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
| F621 | ExpressionsInStarAssignment | Too many expressions in star-unpacking assignment | |
| F622 | TwoStarredExpressions | Two starred expressions in assignment | |
| F631 | AssertTuple | Assert test is a non-empty tuple, which is always `True` | |
| F632 | IsLiteral | Use `==` and `!=` to compare constant literals | |
| F632 | IsLiteral | Use `==` and `!=` to compare constant literals | 🛠 |
| F633 | InvalidPrintSyntax | Use of `>>` is invalid with `print` function | |
| F634 | IfTuple | If test is a tuple, which is always `True` | |
| F701 | BreakOutsideLoop | `break` outside loop | |
@@ -328,7 +338,9 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
| F841 | UnusedVariable | Local variable `...` is assigned to but never used | |
| F901 | RaiseNotImplemented | `raise NotImplemented` should be `raise NotImplementedError` | 🛠 |
### pycodestyle (error)
### pycodestyle
For more, see [pycodestyle](https://pypi.org/project/pycodestyle/2.9.1/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
@@ -346,16 +358,13 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
| E743 | AmbiguousFunctionName | Ambiguous function name: `...` | |
| E902 | IOError | IOError: `...` | |
| E999 | SyntaxError | SyntaxError: `...` | |
### pycodestyle (warning)
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| W292 | NoNewLineAtEndOfFile | No newline at end of file | |
| W605 | InvalidEscapeSequence | Invalid escape sequence: '\c' | |
### pydocstyle
For more, see [pydocstyle](https://pypi.org/project/pydocstyle/6.1.1/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| D100 | PublicModule | Missing docstring in public module | |
@@ -405,6 +414,8 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
### pyupgrade
For more, see [pyupgrade](https://pypi.org/project/pyupgrade/3.2.0/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| U001 | UselessMetaclassType | `__metaclass__ = type` is implied | 🛠 |
@@ -415,9 +426,12 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
| U006 | UsePEP585Annotation | Use `list` instead of `List` for type annotations | 🛠 |
| U007 | UsePEP604Annotation | Use `X \| Y` for type annotations | 🛠 |
| U008 | SuperCallWithParameters | Use `super()` instead of `super(__class__, self)` | 🛠 |
| U009 | PEP3120UnnecessaryCodingComment | utf-8 encoding declaration is unnecessary | 🛠 |
### pep8-naming
For more, see [pep8-naming](https://pypi.org/project/pep8-naming/0.13.2/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| N801 | InvalidClassName | Class name `...` should use CapWords convention | |
@@ -438,6 +452,8 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
### flake8-comprehensions
For more, see [flake8-comprehensions](https://pypi.org/project/flake8-comprehensions/3.10.1/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| C400 | UnnecessaryGeneratorList | Unnecessary generator (rewrite as a `list` comprehension) | 🛠 |
@@ -459,20 +475,28 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
### flake8-bugbear
For more, see [flake8-bugbear](https://pypi.org/project/flake8-bugbear/22.10.27/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| B002 | UnaryPrefixIncrement | Python does not support the unary prefix increment. | |
| B003 | AssignmentToOsEnviron | Assigning to `os.environ` doesn't clear the environment. | |
| B006 | MutableArgumentDefault | Do not use mutable data structures for argument defaults. | |
| B007 | UnusedLoopControlVariable | Loop control variable `i` not used within the loop body. | 🛠 |
| B008 | FunctionCallArgumentDefault | Do not perform function calls in argument defaults. | |
| B011 | DoNotAssertFalse | Do not `assert False` (`python -O` removes these calls), raise `AssertionError()` | 🛠 |
| B013 | RedundantTupleInExceptionHandler | A length-one tuple literal is redundant. Write `except ValueError:` instead of `except (ValueError,):`. | |
| B014 | DuplicateHandlerException | Exception handler with duplicate exception: `ValueError` | 🛠 |
| B015 | UselessComparison | Pointless comparison. This comparison does nothing but waste CPU instructions. Either prepend `assert` or remove it. | |
| B016 | CannotRaiseLiteral | Cannot raise a literal. Did you intend to return it or raise an Exception? | |
| B017 | NoAssertRaisesException | `assertRaises(Exception):` should be considered evil. | |
| B018 | UselessExpression | Found useless expression. Either assign it to a variable or remove it. | |
| B025 | DuplicateTryBlockException | try-except block with duplicate exception `Exception` | |
### flake8-builtins
For more, see [flake8-builtins](https://pypi.org/project/flake8-builtins/2.0.1/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| A001 | BuiltinVariableShadowing | Variable `...` is shadowing a python builtin | |
@@ -481,6 +505,8 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
### flake8-print
For more, see [flake8-print](https://pypi.org/project/flake8-print/5.0.0/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| T201 | PrintFound | `print` found | 🛠 |
@@ -488,6 +514,8 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
### flake8-quotes
For more, see [flake8-quotes](https://pypi.org/project/flake8-quotes/3.3.1/) on PyPI.
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| Q000 | BadQuotesInlineString | Single quotes found but double quotes preferred | |
@@ -499,7 +527,8 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
| Code | Name | Message | Fix |
| ---- | ---- | ------- | --- |
| X001 | AmbiguousUnicodeCharacter | Use of ambiguous unicode character '𝐁' (did you mean 'B'?) | 🛠 |
| RUF001 | AmbiguousUnicodeCharacterString | String contains ambiguous unicode character '𝐁' (did you mean 'B'?) | 🛠 |
| RUF002 | AmbiguousUnicodeCharacterDocstring | Docstring contains ambiguous unicode character '𝐁' (did you mean 'B'?) | 🛠 |
### Meta rules
@@ -507,6 +536,8 @@ The 🛠 emoji indicates that a rule is automatically fixable by the `--fix` com
| ---- | ---- | ------- | --- |
| M001 | UnusedNOQA | Unused `noqa` directive | 🛠 |
<!-- End auto-generated sections. -->
## Editor Integrations
### PyCharm
@@ -575,8 +606,8 @@ including:
- [`flake8-print`](https://pypi.org/project/flake8-print/)
- [`flake8-quotes`](https://pypi.org/project/flake8-quotes/)
- [`flake8-comprehensions`](https://pypi.org/project/flake8-comprehensions/)
- [`flake8-bugbear`](https://pypi.org/project/flake8-bugbear/) (10/32)
- [`pyupgrade`](https://pypi.org/project/pyupgrade/) (10/34)
- [`flake8-bugbear`](https://pypi.org/project/flake8-bugbear/) (15/32)
- [`pyupgrade`](https://pypi.org/project/pyupgrade/) (11/34)
- [`autoflake`](https://pypi.org/project/autoflake/) (1/7)
Beyond rule-set parity, Ruff suffers from the following limitations vis-à-vis Flake8:
@@ -597,10 +628,10 @@ Today, Ruff can be used to replace Flake8 when used with any of the following pl
- [`flake8-print`](https://pypi.org/project/flake8-print/)
- [`flake8-quotes`](https://pypi.org/project/flake8-quotes/)
- [`flake8-comprehensions`](https://pypi.org/project/flake8-comprehensions/)
- [`flake8-bugbear`](https://pypi.org/project/flake8-bugbear/) (10/32)
- [`flake8-bugbear`](https://pypi.org/project/flake8-bugbear/) (15/32)
Ruff also implements the functionality that you get from [`yesqa`](https://github.com/asottile/yesqa),
and a subset of the rules implemented in [`pyupgrade`](https://pypi.org/project/pyupgrade/) (10/34).
and a subset of the rules implemented in [`pyupgrade`](https://pypi.org/project/pyupgrade/) (11/34).
If you're looking to use Ruff, but rely on an unsupported Flake8 plugin, free to file an Issue.

View File

@@ -1,28 +0,0 @@
//! Generate a Markdown-compatible table of supported lint rules.
use ruff::checks::{CheckCategory, CheckCode};
use strum::IntoEnumIterator;
fn main() {
for check_category in CheckCategory::iter() {
println!("### {}", check_category.title());
println!();
println!("| Code | Name | Message | Fix |");
println!("| ---- | ---- | ------- | --- |");
for check_code in CheckCode::iter() {
if check_code.category() == check_category {
let check_kind = check_code.kind();
let fix_token = if check_kind.fixable() { "🛠" } else { "" };
println!(
"| {} | {} | {} | {} |",
check_kind.code().as_ref(),
check_kind.as_ref(),
check_kind.summary().replace("|", r"\|"),
fix_token
);
}
}
println!();
}
}

View File

@@ -771,7 +771,7 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
[[package]]
name = "flake8_to_ruff"
version = "0.0.100"
version = "0.0.104"
dependencies = [
"anyhow",
"clap",
@@ -1975,7 +1975,7 @@ dependencies = [
[[package]]
name = "ruff"
version = "0.0.100"
version = "0.0.104"
dependencies = [
"anyhow",
"bincode",

View File

@@ -1,6 +1,6 @@
[package]
name = "flake8-to-ruff"
version = "0.0.100-dev.0"
version = "0.0.104-dev.0"
edition = "2021"
[lib]

18
resources/test/fixtures/B003.py vendored Normal file
View File

@@ -0,0 +1,18 @@
"""
Should emit:
B003 - on line 9
"""
import os
from os import environ
os.environ = {}
environ = {} # that's fine, assigning a new meaning to the module-level name
class Object:
os = None
o = Object()
o.os.environ = {}

27
resources/test/fixtures/B015.py vendored Normal file
View File

@@ -0,0 +1,27 @@
assert 1 == 1
1 == 1
assert 1 in (1, 2)
1 in (1, 2)
if 1 == 2:
pass
def test():
assert 1 in (1, 2)
1 in (1, 2)
data = [x for x in [1, 2, 3] if x in (1, 2)]
class TestClass:
1 == 1
print(1 == 1)

11
resources/test/fixtures/B016.py vendored Normal file
View File

@@ -0,0 +1,11 @@
"""
Should emit:
B016 - on lines 6, 7, and 8
"""
raise False
raise 1
raise "string"
raise Exception(False)
raise Exception(1)
raise Exception("string")

View File

@@ -53,3 +53,7 @@ def foo3():
a = 2
"str"
3
def foo4():
...

View File

@@ -14,3 +14,38 @@ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor i
_ = "---------------------------------------------------------------------------AAAAAAA"
_ = "---------------------------------------------------------------------------亜亜亜亜亜亜亜"
def caller(string: str) -> None:
assert string is not None
caller(
"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
""",
)
caller(
"""
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
""", # noqa: E501
)
multiple_strings_per_line = {
# OK
"Lorem ipsum dolor": "sit amet",
# E501 Line too long
"Lorem ipsum dolor": "sit amet consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
# E501 Line too long
"Lorem ipsum dolor": """
sit amet consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
""",
# OK
"Lorem ipsum dolor": "sit amet consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.", # noqa: E501
# OK
"Lorem ipsum dolor": """
sit amet consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
""", # noqa: E501
}

View File

@@ -3,3 +3,6 @@ if x is "abc":
if 123 is not y:
pass
if "123" is x < 3:
pass

View File

@@ -1,7 +1,7 @@
def func(a, A):
return a, A
def func(_, a, A):
return _, a, A
class Class:
def method(self, a, A):
return a, A
def method(self, _, a, A):
return _, a, A

View File

@@ -1,19 +1,43 @@
from abc import ABCMeta
class Class:
@classmethod
def bad_class_method(this):
def bad_method(this):
pass
if False:
def extra_bad_method(this):
pass
def good_method(self):
pass
@classmethod
def good_class_method(cls):
pass
def method(self):
def class_method(cls):
pass
@staticmethod
def static_method(x):
return x
def __init__(self):
...
def __new__(cls, *args, **kwargs):
...
def __init_subclass__(self, default_name, **kwargs):
...
class MetaClass(ABCMeta):
def bad_method(self):
pass
def good_method(cls):
pass
def func(x):
return x

View File

@@ -1,11 +1,11 @@
import random
from abc import ABCMeta
class Class:
def bad_method(this):
pass
if random.random(0, 2) == 0:
if False:
def extra_bad_method(this):
pass
@@ -21,6 +21,23 @@ class Class:
def static_method(x):
return x
def __init__(self):
...
def __new__(cls, *args, **kwargs):
...
def __init_subclass__(self, default_name, **kwargs):
...
class MetaClass(ABCMeta):
def bad_method(self):
pass
def good_method(cls):
pass
def func(x):
return x

6
resources/test/fixtures/RUF002.py vendored Normal file
View File

@@ -0,0 +1,6 @@
x = "𝐁ad string"
def f():
"""Here's a comment with an unusual parenthesis: """
...

3
resources/test/fixtures/U009_0.py vendored Normal file
View File

@@ -0,0 +1,3 @@
# coding=utf8
print('Hello world')

4
resources/test/fixtures/U009_1.py vendored Normal file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/python
# -*- coding: utf-8 -*-
print('Hello world')

5
resources/test/fixtures/U009_2.py vendored Normal file
View File

@@ -0,0 +1,5 @@
#!/usr/bin/python
# A coding comment is only valid in the first two lines, so this one is not checked.
# -*- coding: utf-8 -*-
print('Hello world')

4
resources/test/fixtures/U009_3.py vendored Normal file
View File

@@ -0,0 +1,4 @@
#!/usr/bin/python
# -*- coding: something-else -*-
print('Hello world')

35
resources/test/fixtures/W605_1.py vendored Normal file
View File

@@ -0,0 +1,35 @@
#: W605:1:10
regex = '\.png$'
#: W605:2:1
regex = '''
\.png$
'''
#: W605:2:6
f(
'\_'
)
#: W605:4:6
"""
multi-line
literal
with \_ somewhere
in the middle
"""
#: Okay
regex = r'\.png$'
regex = '\\.png$'
regex = r'''
\.png$
'''
regex = r'''
\\.png$
'''
s = '\\'
regex = '\w' # noqa
regex = '''
\w
''' # noqa

16
ruff_dev/Cargo.toml Normal file
View File

@@ -0,0 +1,16 @@
[package]
name = "ruff_dev"
version = "0.0.104"
edition = "2021"
[dependencies]
anyhow = { version = "1.0.60" }
clap = { version = "4.0.1", features = ["derive"] }
codegen = { version = "0.2.0" }
itertools = { version = "0.10.5" }
ruff = { path = ".." }
rustpython-ast = { features = ["unparse"], git = "https://github.com/RustPython/RustPython.git", rev = "77b821a1941019fe34f73ce17cea013ae1b98fd0" }
rustpython-common = { git = "https://github.com/RustPython/RustPython.git", rev = "77b821a1941019fe34f73ce17cea013ae1b98fd0" }
rustpython-parser = { features = ["lalrpop"], git = "https://github.com/RustPython/RustPython.git", rev = "77b821a1941019fe34f73ce17cea013ae1b98fd0" }
strum = { version = "0.24.1", features = ["strum_macros"] }
strum_macros = { version = "0.24.3" }

View File

@@ -1,22 +1,39 @@
//! Generate the CheckCodePrefix enum.
//! Generate the `CheckCodePrefix` enum.
use std::collections::{BTreeMap, BTreeSet};
use std::fs::OpenOptions;
use std::io::Write;
use anyhow::Result;
use clap::Parser;
use codegen::{Scope, Type, Variant};
use itertools::Itertools;
use ruff::checks::CheckCode;
use strum::IntoEnumIterator;
fn main() {
const FILE: &str = "src/checks_gen.rs";
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
pub struct Cli {
/// Write the generated source code to stdout (rather than to
/// `src/checks_gen.rs`).
#[arg(long)]
dry_run: bool,
}
pub fn main(cli: &Cli) -> Result<()> {
// Build up a map from prefix to matching CheckCodes.
let mut prefix_to_codes: BTreeMap<String, BTreeSet<CheckCode>> = Default::default();
for check_code in CheckCode::iter() {
let as_ref = check_code.as_ref().to_string();
for i in 1..=as_ref.len() {
let as_ref: String = check_code.as_ref().to_string();
let prefix_len = as_ref
.chars()
.take_while(|char| char.is_alphabetic())
.count();
for i in prefix_len..=as_ref.len() {
let prefix = as_ref[..i].to_string();
let entry = prefix_to_codes
.entry(prefix)
.or_insert_with(|| Default::default());
let entry = prefix_to_codes.entry(prefix).or_default();
entry.insert(check_code.clone());
}
}
@@ -36,7 +53,7 @@ fn main() {
.derive("Clone")
.derive("Serialize")
.derive("Deserialize");
for (prefix, _) in &prefix_to_codes {
for prefix in prefix_to_codes.keys() {
gen = gen.push_variant(Variant::new(prefix.to_string()));
}
@@ -80,12 +97,13 @@ fn main() {
.ret(Type::new("PrefixSpecificity"))
.vis("pub")
.line("match self {");
for (prefix, _) in &prefix_to_codes {
let specificity = match prefix.len() {
4 => "Explicit",
3 => "Tens",
2 => "Hundreds",
1 => "Category",
for prefix in prefix_to_codes.keys() {
let num_numeric = prefix.chars().filter(|char| char.is_numeric()).count();
let specificity = match num_numeric {
3 => "Explicit",
2 => "Tens",
1 => "Hundreds",
0 => "Category",
_ => panic!("Invalid prefix: {}", prefix),
};
gen = gen.line(format!(
@@ -95,12 +113,28 @@ fn main() {
}
gen.line("}");
println!("//! File automatically generated by examples/generate_check_code_prefix.rs.");
println!();
println!("use serde::{{Serialize, Deserialize}};");
println!("use strum_macros::EnumString;");
println!();
println!("use crate::checks::CheckCode;");
println!();
println!("{}", scope.to_string());
// Construct the output contents.
let mut output = String::new();
output.push_str("//! File automatically generated by examples/generate_check_code_prefix.rs.");
output.push('\n');
output.push('\n');
output.push_str("use serde::{{Serialize, Deserialize}};");
output.push('\n');
output.push_str("use strum_macros::EnumString;");
output.push('\n');
output.push('\n');
output.push_str("use crate::checks::CheckCode;");
output.push('\n');
output.push('\n');
output.push_str(&scope.to_string());
// Write the output to `src/checks_gen.rs` (or stdout).
if cli.dry_run {
println!("{}", output);
} else {
let mut f = OpenOptions::new().write(true).truncate(true).open(FILE)?;
write!(f, "{}", output)?;
}
Ok(())
}

View File

@@ -0,0 +1,93 @@
//! Generate a Markdown-compatible table of supported lint rules.
use std::fs;
use std::fs::OpenOptions;
use std::io::Write;
use std::path::PathBuf;
use anyhow::Result;
use clap::Args;
use ruff::checks::{CheckCategory, CheckCode};
use strum::IntoEnumIterator;
const BEGIN_PRAGMA: &str = "<!-- Begin auto-generated sections. -->";
const END_PRAGMA: &str = "<!-- End auto-generated sections. -->";
#[derive(Args)]
pub struct Cli {
/// Write the generated table to stdout (rather than to `README.md`).
#[arg(long)]
dry_run: bool,
}
pub fn main(cli: &Cli) -> Result<()> {
// Generate the table string.
let mut output = String::new();
for check_category in CheckCategory::iter() {
output.push_str(&format!("### {}", check_category.title()));
output.push('\n');
output.push('\n');
if let Some(url) = check_category.url() {
output.push_str(&format!(
"For more, see [{}]({}) on PyPI.",
check_category.title(),
url
));
output.push('\n');
output.push('\n');
}
output.push_str("| Code | Name | Message | Fix |");
output.push('\n');
output.push_str("| ---- | ---- | ------- | --- |");
output.push('\n');
for check_code in CheckCode::iter() {
if check_code.category() == check_category {
let check_kind = check_code.kind();
let fix_token = if check_kind.fixable() { "🛠" } else { "" };
output.push_str(&format!(
"| {} | {} | {} | {} |",
check_kind.code().as_ref(),
check_kind.as_ref(),
check_kind.summary().replace('|', r"\|"),
fix_token
));
output.push('\n');
}
}
output.push('\n');
}
if cli.dry_run {
print!("{}", output);
} else {
// Read the existing file.
let file = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.parent()
.expect("Failed to find root directory")
.join("README.md");
let existing = fs::read_to_string(&file)?;
// Extract the prefix.
let index = existing
.find(BEGIN_PRAGMA)
.expect("Unable to find begin pragma.");
let prefix = &existing[..index + BEGIN_PRAGMA.len()];
// Extract the suffix.
let index = existing
.find(END_PRAGMA)
.expect("Unable to find end pragma.");
let suffix = &existing[index..];
// Write the prefix, new contents, and suffix.
let mut f = OpenOptions::new().write(true).truncate(true).open(&file)?;
write!(f, "{}\n\n", prefix)?;
write!(f, "{}", output)?;
write!(f, "{}", suffix)?;
}
Ok(())
}

View File

@@ -1,25 +1,25 @@
//! Run round-trip source code generation on a given Python file.
use std::fs;
use std::path::PathBuf;
use anyhow::Result;
use clap::Parser;
use clap::Args;
use ruff::code_gen::SourceGenerator;
use ruff::fs;
use rustpython_parser::parser;
#[derive(Debug, Parser)]
struct Cli {
#[derive(Args)]
pub struct Cli {
/// Python file to round-trip.
#[arg(required = true)]
file: PathBuf,
}
fn main() -> Result<()> {
let cli = Cli::parse();
let contents = fs::read_file(&cli.file)?;
pub fn main(cli: &Cli) -> Result<()> {
let contents = fs::read_to_string(&cli.file)?;
let python_ast = parser::parse_program(&contents, &cli.file.to_string_lossy())?;
let mut generator = SourceGenerator::new();
generator.unparse_suite(&python_ast)?;
println!("{}", generator.generate()?);
Ok(())
}

5
ruff_dev/src/lib.rs Normal file
View File

@@ -0,0 +1,5 @@
pub mod generate_check_code_prefix;
pub mod generate_rules_table;
pub mod generate_source_code;
pub mod print_ast;
pub mod print_tokens;

39
ruff_dev/src/main.rs Normal file
View File

@@ -0,0 +1,39 @@
use anyhow::Result;
use clap::{Parser, Subcommand};
use ruff_dev::{
generate_check_code_prefix, generate_rules_table, generate_source_code, print_ast, print_tokens,
};
#[derive(Parser)]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Generate the `CheckCodePrefix` enum.
GenerateCheckCodePrefix(generate_check_code_prefix::Cli),
/// Generate a Markdown-compatible table of supported lint rules.
GenerateRulesTable(generate_rules_table::Cli),
/// Run round-trip source code generation on a given Python file.
GenerateSourceCode(generate_source_code::Cli),
/// Print the AST for a given Python file.
PrintAST(print_ast::Cli),
/// Print the token stream for a given Python file.
PrintTokens(print_tokens::Cli),
}
fn main() -> Result<()> {
let cli = Cli::parse();
match &cli.command {
Commands::GenerateCheckCodePrefix(args) => generate_check_code_prefix::main(args)?,
Commands::GenerateRulesTable(args) => generate_rules_table::main(args)?,
Commands::GenerateSourceCode(args) => generate_source_code::main(args)?,
Commands::PrintAST(args) => print_ast::main(args)?,
Commands::PrintTokens(args) => print_tokens::main(args)?,
}
Ok(())
}

View File

@@ -1,25 +1,22 @@
//! Print the AST for a given Python file.
use std::fs;
use std::path::PathBuf;
use anyhow::Result;
use clap::Parser;
use ruff::fs;
use clap::Args;
use rustpython_parser::parser;
#[derive(Debug, Parser)]
struct Cli {
#[derive(Args)]
pub struct Cli {
/// Python file for which to generate the AST.
#[arg(required = true)]
file: PathBuf,
}
fn main() -> Result<()> {
let cli = Cli::parse();
let contents = fs::read_file(&cli.file)?;
pub fn main(cli: &Cli) -> Result<()> {
let contents = fs::read_to_string(&cli.file)?;
let python_ast = parser::parse_program(&contents, &cli.file.to_string_lossy())?;
println!("{:#?}", python_ast);
Ok(())
}

View File

@@ -1,25 +1,23 @@
//! Print the token stream for a given Python file.
use std::fs;
use std::path::PathBuf;
use anyhow::Result;
use clap::Parser;
use ruff::fs;
use clap::Args;
use rustpython_parser::lexer;
#[derive(Debug, Parser)]
struct Cli {
#[derive(Args)]
pub struct Cli {
/// Python file for which to generate the AST.
#[arg(required = true)]
file: PathBuf,
}
fn main() -> Result<()> {
let cli = Cli::parse();
let contents = fs::read_file(&cli.file)?;
pub fn main(cli: &Cli) -> Result<()> {
let contents = fs::read_to_string(&cli.file)?;
for (_, tok, _) in lexer::make_tokenizer(&contents).flatten() {
println!("{:#?}", tok);
}
Ok(())
}

View File

@@ -1,6 +1,7 @@
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use rustpython_ast::{Expr, Keyword};
use rustpython_parser::ast::{Located, Location};
fn id() -> usize {
@@ -30,24 +31,33 @@ pub struct FunctionScope {
pub uses_locals: bool,
}
#[derive(Clone, Debug)]
pub enum ScopeKind {
Class,
Function(FunctionScope),
Generator,
Module,
#[derive(Clone, Debug, Default)]
pub struct ClassScope<'a> {
pub name: &'a str,
pub bases: &'a [Expr],
pub keywords: &'a [Keyword],
pub decorator_list: &'a [Expr],
}
#[derive(Clone, Debug)]
pub struct Scope {
pub enum ScopeKind<'a> {
Class(ClassScope<'a>),
Function(FunctionScope),
Generator,
Module,
Arg,
}
#[derive(Clone, Debug)]
pub struct Scope<'a> {
pub id: usize,
pub kind: ScopeKind,
pub kind: ScopeKind<'a>,
pub import_starred: bool,
pub values: BTreeMap<String, Binding>,
}
impl Scope {
pub fn new(kind: ScopeKind) -> Self {
impl<'a> Scope<'a> {
pub fn new(kind: ScopeKind<'a>) -> Self {
Scope {
id: id(),
kind,

View File

@@ -15,8 +15,8 @@ use crate::ast::helpers::{extract_handler_names, match_name_or_attr_from_module}
use crate::ast::operations::extract_all_names;
use crate::ast::relocate::relocate_expr;
use crate::ast::types::{
Binding, BindingContext, BindingKind, CheckLocator, FunctionScope, ImportKind, Range, Scope,
ScopeKind,
Binding, BindingContext, BindingKind, CheckLocator, ClassScope, FunctionScope, ImportKind,
Range, Scope, ScopeKind,
};
use crate::ast::visitor::{walk_excepthandler, Visitor};
use crate::ast::{helpers, operations, visitor};
@@ -66,7 +66,7 @@ pub struct Checker<'a> {
// at various points in time.
pub(crate) parents: Vec<&'a Stmt>,
pub(crate) parent_stack: Vec<usize>,
scopes: Vec<Scope>,
scopes: Vec<Scope<'a>>,
scope_stack: Vec<usize>,
dead_scopes: Vec<usize>,
deferred_string_annotations: Vec<(Range, &'a str)>,
@@ -274,6 +274,7 @@ where
if let Some(check) =
pep8_naming::checks::invalid_first_argument_name_for_class_method(
self.current_scope(),
name,
decorator_list,
args,
&self.settings.pep8_naming,
@@ -286,6 +287,7 @@ where
if self.settings.enabled.contains(&CheckCode::N805) {
if let Some(check) = pep8_naming::checks::invalid_first_argument_name_for_method(
self.current_scope(),
name,
decorator_list,
args,
&self.settings.pep8_naming,
@@ -296,7 +298,7 @@ where
if self.settings.enabled.contains(&CheckCode::N807) {
if let Some(check) =
pep8_naming::checks::dunder_function_name(stmt, self.current_scope(), name)
pep8_naming::checks::dunder_function_name(self.current_scope(), stmt, name)
{
self.checks.push(check);
}
@@ -360,7 +362,7 @@ where
if self.settings.enabled.contains(&CheckCode::F706) {
if let Some(scope_index) = self.scope_stack.last().cloned() {
match self.scopes[scope_index].kind {
ScopeKind::Class | ScopeKind::Module => {
ScopeKind::Class(_) | ScopeKind::Module => {
self.checks.push(Check::new(
CheckKind::ReturnOutsideFunction,
self.locate_check(Range::from_located(stmt)),
@@ -377,7 +379,6 @@ where
keywords,
decorator_list,
body,
..
} => {
if self.settings.enabled.contains(&CheckCode::U004) {
pyupgrade::plugins::useless_object_inheritance(
@@ -427,7 +428,12 @@ where
for expr in decorator_list {
self.visit_expr(expr)
}
self.push_scope(Scope::new(ScopeKind::Class))
self.push_scope(Scope::new(ScopeKind::Class(ClassScope {
name,
bases,
keywords,
decorator_list,
})))
}
StmtKind::Import { names } => {
if self.settings.enabled.contains(&CheckCode::E402) {
@@ -733,6 +739,11 @@ where
pyflakes::plugins::raise_not_implemented(self, expr);
}
}
if self.settings.enabled.contains(&CheckCode::B016) {
if let Some(exc) = exc {
flake8_bugbear::plugins::cannot_raise_literal(self, exc);
}
}
}
StmtKind::AugAssign { target, .. } => {
self.handle_node_load(target);
@@ -787,6 +798,9 @@ where
if self.settings.enabled.contains(&CheckCode::U001) {
pyupgrade::plugins::useless_metaclass_type(self, stmt, value, targets);
}
if self.settings.enabled.contains(&CheckCode::B003) {
flake8_bugbear::plugins::assignment_to_os_environ(self, targets);
}
}
StmtKind::AnnAssign { value, .. } => {
if self.settings.enabled.contains(&CheckCode::E731) {
@@ -801,6 +815,11 @@ where
}
}
StmtKind::Delete { .. } => {}
StmtKind::Expr { value, .. } => {
if self.settings.enabled.contains(&CheckCode::B015) {
flake8_bugbear::plugins::useless_comparison(self, value)
}
}
_ => {}
}
@@ -1243,7 +1262,7 @@ where
ExprKind::Yield { .. } | ExprKind::YieldFrom { .. } | ExprKind::Await { .. } => {
let scope = self.current_scope();
if self.settings.enabled.contains(&CheckCode::F704) {
if matches!(scope.kind, ScopeKind::Class | ScopeKind::Module) {
if matches!(scope.kind, ScopeKind::Class(_) | ScopeKind::Module) {
self.checks.push(Check::new(
CheckKind::YieldOutsideFunction,
self.locate_check(Range::from_located(expr)),
@@ -1311,12 +1330,13 @@ where
}
if self.settings.enabled.contains(&CheckCode::F632) {
self.checks.extend(pyflakes::checks::is_literal(
pyflakes::plugins::invalid_literal_comparison(
self,
left,
ops,
comparators,
self.locate_check(Range::from_located(expr)),
));
);
}
if self.settings.enabled.contains(&CheckCode::E721) {
@@ -1657,6 +1677,9 @@ where
if self.settings.enabled.contains(&CheckCode::B006) {
flake8_bugbear::plugins::mutable_argument_default(self, arguments)
}
if self.settings.enabled.contains(&CheckCode::B008) {
flake8_bugbear::plugins::function_call_argument_default(self, arguments)
}
// Bind, but intentionally avoid walking default expressions, as we handle them
// upstream.
@@ -1700,7 +1723,7 @@ where
if self.settings.enabled.contains(&CheckCode::N803) {
if let Some(check) =
pep8_naming::checks::invalid_argument_name(Range::from_located(arg), &arg.node.arg)
pep8_naming::checks::invalid_argument_name(&arg.node.arg, Range::from_located(arg))
{
self.checks.push(check);
}
@@ -1774,7 +1797,7 @@ impl<'a> Checker<'a> {
.expect("Attempted to pop without scope.");
}
fn push_scope(&mut self, scope: Scope) {
fn push_scope(&mut self, scope: Scope<'a>) {
self.scope_stack.push(self.scopes.len());
self.scopes.push(scope);
}
@@ -1879,7 +1902,7 @@ impl<'a> Checker<'a> {
let mut import_starred = false;
for scope_index in self.scope_stack.iter().rev() {
let scope = &mut self.scopes[*scope_index];
if matches!(scope.kind, ScopeKind::Class) {
if matches!(scope.kind, ScopeKind::Class(_)) {
if id == "__class__" {
return;
} else if !first_iter && !in_generator {
@@ -2416,7 +2439,7 @@ impl<'a> Checker<'a> {
}
fn check_builtin_shadowing(&mut self, name: &str, location: Range, is_attribute: bool) {
if is_attribute && matches!(self.current_scope().kind, ScopeKind::Class) {
if is_attribute && matches!(self.current_scope().kind, ScopeKind::Class(_)) {
if self.settings.enabled.contains(&CheckCode::A003) {
if let Some(check) = flake8_builtins::checks::builtin_shadowing(
name,

View File

@@ -2,6 +2,8 @@
use std::collections::BTreeMap;
use once_cell::sync::Lazy;
use regex::Regex;
use rustpython_parser::ast::Location;
use crate::ast::types::Range;
@@ -11,6 +13,10 @@ use crate::noqa;
use crate::noqa::Directive;
use crate::settings::Settings;
// Regex from PEP263
static CODING_COMMENT_REGEX: Lazy<Regex> =
Lazy::new(|| Regex::new(r"^[ \t\f]*#.*?coding[:=][ \t]*utf-?8").expect("Invalid regex"));
/// Whether the given line is too long and should be reported.
fn should_enforce_line_length(line: &str, length: usize, limit: usize) -> bool {
if length > limit {
@@ -52,6 +58,27 @@ pub fn check_lines(
.map(|lineno| lineno - 1)
.unwrap_or(lineno);
if lineno < 2 {
// PEP3120 makes utf-8 the default encoding.
if CODING_COMMENT_REGEX.is_match(line) {
let line_length = line.len();
let mut check = Check::new(
CheckKind::PEP3120UnnecessaryCodingComment,
Range {
location: Location::new(lineno + 1, 0),
end_location: Location::new(lineno + 1, line_length + 1),
},
);
if autofix.patch() {
check.amend(Fix::deletion(
Location::new(lineno + 1, 0),
Location::new(lineno + 1, line_length + 1),
));
}
line_checks.push(check);
}
}
if enforce_noqa {
noqa_directives
.entry(noqa_lineno)

View File

@@ -4,7 +4,7 @@ use rustpython_parser::lexer::{LexResult, Tok};
use crate::autofix::fixer;
use crate::checks::{Check, CheckCode};
use crate::flake8_quotes::docstring_detection::StateMachine;
use crate::lex::docstring_detection::StateMachine;
use crate::source_code_locator::SourceCodeLocator;
use crate::{flake8_quotes, pycodestyle, rules, Settings};
@@ -15,39 +15,41 @@ pub fn check_tokens(
settings: &Settings,
autofix: &fixer::Mode,
) {
let enforce_ambiguous_unicode_character = settings.enabled.contains(&CheckCode::X001);
let enforce_invalid_escape_sequence = settings.enabled.contains(&CheckCode::W605);
let enforce_ambiguous_unicode_character = settings.enabled.contains(&CheckCode::RUF001)
|| settings.enabled.contains(&CheckCode::RUF002);
let enforce_quotes = settings.enabled.contains(&CheckCode::Q000)
| settings.enabled.contains(&CheckCode::Q001)
| settings.enabled.contains(&CheckCode::Q002)
| settings.enabled.contains(&CheckCode::Q003);
|| settings.enabled.contains(&CheckCode::Q001)
|| settings.enabled.contains(&CheckCode::Q002)
|| settings.enabled.contains(&CheckCode::Q003);
let enforce_invalid_escape_sequence = settings.enabled.contains(&CheckCode::W605);
let mut state_machine: StateMachine = Default::default();
for (start, tok, end) in tokens.iter().flatten() {
// X001
let is_docstring = if enforce_ambiguous_unicode_character || enforce_quotes {
state_machine.consume(tok)
} else {
false
};
// RUF001, RUF002
if enforce_ambiguous_unicode_character {
if matches!(tok, Tok::String { .. }) {
checks.extend(rules::checks::ambiguous_unicode_character(
for check in rules::checks::ambiguous_unicode_character(
locator,
start,
end,
is_docstring,
autofix.patch(),
));
}
}
// W605
if enforce_invalid_escape_sequence {
if matches!(tok, Tok::String { .. }) {
checks.extend(pycodestyle::checks::invalid_escape_sequence(
locator, start, end,
));
) {
if settings.enabled.contains(check.kind.code()) {
checks.push(check);
}
}
}
}
// flake8-quotes
if enforce_quotes {
let is_docstring = state_machine.consume(tok);
if matches!(tok, Tok::String { .. }) {
if let Some(check) = flake8_quotes::checks::quotes(
locator,
@@ -62,5 +64,14 @@ pub fn check_tokens(
}
}
}
// W605
if enforce_invalid_escape_sequence {
if matches!(tok, Tok::String { .. }) {
checks.extend(pycodestyle::checks::invalid_escape_sequence(
locator, start, end,
));
}
}
}
}

View File

@@ -78,11 +78,15 @@ pub enum CheckCode {
A003,
// flake8-bugbear
B002,
B003,
B006,
B007,
B008,
B011,
B013,
B014,
B015,
B016,
B017,
B018,
B025,
@@ -120,6 +124,7 @@ pub enum CheckCode {
U006,
U007,
U008,
U009,
// pydocstyle
D100,
D101,
@@ -182,7 +187,8 @@ pub enum CheckCode {
N817,
N818,
// Ruff
X001,
RUF001,
RUF002,
// Meta
M001,
}
@@ -190,8 +196,7 @@ pub enum CheckCode {
#[derive(EnumIter, Debug, PartialEq, Eq)]
pub enum CheckCategory {
Pyflakes,
PycodestyleError,
PycodestyleWarning,
Pycodestyle,
Pydocstyle,
Pyupgrade,
PEP8Naming,
@@ -207,8 +212,7 @@ pub enum CheckCategory {
impl CheckCategory {
pub fn title(&self) -> &'static str {
match self {
CheckCategory::PycodestyleError => "pycodestyle (error)",
CheckCategory::PycodestyleWarning => "pycodestyle (warning)",
CheckCategory::Pycodestyle => "pycodestyle",
CheckCategory::Pyflakes => "Pyflakes",
CheckCategory::Flake8Builtins => "flake8-builtins",
CheckCategory::Flake8Bugbear => "flake8-bugbear",
@@ -222,6 +226,29 @@ impl CheckCategory {
CheckCategory::Meta => "Meta rules",
}
}
pub fn url(&self) -> Option<&'static str> {
match self {
CheckCategory::Pycodestyle => Some("https://pypi.org/project/pycodestyle/2.9.1/"),
CheckCategory::Pyflakes => Some("https://pypi.org/project/pyflakes/2.5.0/"),
CheckCategory::Flake8Builtins => {
Some("https://pypi.org/project/flake8-builtins/2.0.1/")
}
CheckCategory::Flake8Bugbear => {
Some("https://pypi.org/project/flake8-bugbear/22.10.27/")
}
CheckCategory::Flake8Comprehensions => {
Some("https://pypi.org/project/flake8-comprehensions/3.10.1/")
}
CheckCategory::Flake8Print => Some("https://pypi.org/project/flake8-print/5.0.0/"),
CheckCategory::Flake8Quotes => Some("https://pypi.org/project/flake8-quotes/3.3.1/"),
CheckCategory::Pyupgrade => Some("https://pypi.org/project/pyupgrade/3.2.0/"),
CheckCategory::Pydocstyle => Some("https://pypi.org/project/pydocstyle/6.1.1/"),
CheckCategory::PEP8Naming => Some("https://pypi.org/project/pep8-naming/0.13.2/"),
CheckCategory::Ruff => None,
CheckCategory::Meta => None,
}
}
}
#[allow(clippy::upper_case_acronyms)]
@@ -293,11 +320,15 @@ pub enum CheckKind {
BuiltinAttributeShadowing(String),
// flake8-bugbear
UnaryPrefixIncrement,
AssignmentToOsEnviron,
MutableArgumentDefault,
UnusedLoopControlVariable(String),
FunctionCallArgumentDefault,
DoNotAssertFalse,
RedundantTupleInExceptionHandler(String),
DuplicateHandlerException(Vec<String>),
UselessComparison,
CannotRaiseLiteral,
NoAssertRaisesException,
UselessExpression,
DuplicateTryBlockException(String),
@@ -335,6 +366,7 @@ pub enum CheckKind {
UsePEP585Annotation(String),
UsePEP604Annotation,
SuperCallWithParameters,
PEP3120UnnecessaryCodingComment,
// pydocstyle
BlankLineAfterLastSection(String),
BlankLineAfterSection(String),
@@ -397,7 +429,8 @@ pub enum CheckKind {
CamelcaseImportedAsAcronym(String, String),
ErrorSuffixOnExceptionName(String),
// Ruff
AmbiguousUnicodeCharacter(char, char),
AmbiguousUnicodeCharacterString(char, char),
AmbiguousUnicodeCharacterDocstring(char, char),
// Meta
UnusedNOQA(Option<Vec<String>>),
}
@@ -407,13 +440,16 @@ impl CheckCode {
/// physical lines).
pub fn lint_source(&self) -> &'static LintSource {
match self {
CheckCode::E501 | CheckCode::W292 | CheckCode::M001 => &LintSource::Lines,
CheckCode::E501 | CheckCode::W292 | CheckCode::M001 | CheckCode::U009 => {
&LintSource::Lines
}
CheckCode::Q000
| CheckCode::Q001
| CheckCode::Q002
| CheckCode::Q003
| CheckCode::W605
| CheckCode::X001 => &LintSource::Tokens,
| CheckCode::RUF001
| CheckCode::RUF002 => &LintSource::Tokens,
CheckCode::E902 => &LintSource::FileSystem,
_ => &LintSource::AST,
}
@@ -477,13 +513,17 @@ impl CheckCode {
CheckCode::A003 => CheckKind::BuiltinAttributeShadowing("...".to_string()),
// flake8-bugbear
CheckCode::B002 => CheckKind::UnaryPrefixIncrement,
CheckCode::B003 => CheckKind::AssignmentToOsEnviron,
CheckCode::B006 => CheckKind::MutableArgumentDefault,
CheckCode::B007 => CheckKind::UnusedLoopControlVariable("i".to_string()),
CheckCode::B008 => CheckKind::FunctionCallArgumentDefault,
CheckCode::B011 => CheckKind::DoNotAssertFalse,
CheckCode::B013 => {
CheckKind::RedundantTupleInExceptionHandler("ValueError".to_string())
}
CheckCode::B014 => CheckKind::DuplicateHandlerException(vec!["ValueError".to_string()]),
CheckCode::B015 => CheckKind::UselessComparison,
CheckCode::B016 => CheckKind::CannotRaiseLiteral,
CheckCode::B017 => CheckKind::NoAssertRaisesException,
CheckCode::B018 => CheckKind::UselessExpression,
CheckCode::B025 => CheckKind::DuplicateTryBlockException("Exception".to_string()),
@@ -537,6 +577,7 @@ impl CheckCode {
CheckCode::U006 => CheckKind::UsePEP585Annotation("List".to_string()),
CheckCode::U007 => CheckKind::UsePEP604Annotation,
CheckCode::U008 => CheckKind::SuperCallWithParameters,
CheckCode::U009 => CheckKind::PEP3120UnnecessaryCodingComment,
// pydocstyle
CheckCode::D100 => CheckKind::PublicModule,
CheckCode::D101 => CheckKind::PublicClass,
@@ -615,7 +656,8 @@ impl CheckCode {
}
CheckCode::N818 => CheckKind::ErrorSuffixOnExceptionName("...".to_string()),
// Ruff
CheckCode::X001 => CheckKind::AmbiguousUnicodeCharacter('𝐁', 'B'),
CheckCode::RUF001 => CheckKind::AmbiguousUnicodeCharacterString('𝐁', 'B'),
CheckCode::RUF002 => CheckKind::AmbiguousUnicodeCharacterDocstring('𝐁', 'B'),
// Meta
CheckCode::M001 => CheckKind::UnusedNOQA(None),
}
@@ -623,22 +665,22 @@ impl CheckCode {
pub fn category(&self) -> CheckCategory {
match self {
CheckCode::E402 => CheckCategory::PycodestyleError,
CheckCode::E501 => CheckCategory::PycodestyleError,
CheckCode::E711 => CheckCategory::PycodestyleError,
CheckCode::E712 => CheckCategory::PycodestyleError,
CheckCode::E713 => CheckCategory::PycodestyleError,
CheckCode::E714 => CheckCategory::PycodestyleError,
CheckCode::E721 => CheckCategory::PycodestyleError,
CheckCode::E722 => CheckCategory::PycodestyleError,
CheckCode::E731 => CheckCategory::PycodestyleError,
CheckCode::E741 => CheckCategory::PycodestyleError,
CheckCode::E742 => CheckCategory::PycodestyleError,
CheckCode::E743 => CheckCategory::PycodestyleError,
CheckCode::E902 => CheckCategory::PycodestyleError,
CheckCode::E999 => CheckCategory::PycodestyleError,
CheckCode::W292 => CheckCategory::PycodestyleWarning,
CheckCode::W605 => CheckCategory::PycodestyleWarning,
CheckCode::E402 => CheckCategory::Pycodestyle,
CheckCode::E501 => CheckCategory::Pycodestyle,
CheckCode::E711 => CheckCategory::Pycodestyle,
CheckCode::E712 => CheckCategory::Pycodestyle,
CheckCode::E713 => CheckCategory::Pycodestyle,
CheckCode::E714 => CheckCategory::Pycodestyle,
CheckCode::E721 => CheckCategory::Pycodestyle,
CheckCode::E722 => CheckCategory::Pycodestyle,
CheckCode::E731 => CheckCategory::Pycodestyle,
CheckCode::E741 => CheckCategory::Pycodestyle,
CheckCode::E742 => CheckCategory::Pycodestyle,
CheckCode::E743 => CheckCategory::Pycodestyle,
CheckCode::E902 => CheckCategory::Pycodestyle,
CheckCode::E999 => CheckCategory::Pycodestyle,
CheckCode::W292 => CheckCategory::Pycodestyle,
CheckCode::W605 => CheckCategory::Pycodestyle,
CheckCode::F401 => CheckCategory::Pyflakes,
CheckCode::F402 => CheckCategory::Pyflakes,
CheckCode::F403 => CheckCategory::Pyflakes,
@@ -671,11 +713,15 @@ impl CheckCode {
CheckCode::A002 => CheckCategory::Flake8Builtins,
CheckCode::A003 => CheckCategory::Flake8Builtins,
CheckCode::B002 => CheckCategory::Flake8Bugbear,
CheckCode::B003 => CheckCategory::Flake8Bugbear,
CheckCode::B006 => CheckCategory::Flake8Bugbear,
CheckCode::B007 => CheckCategory::Flake8Bugbear,
CheckCode::B008 => CheckCategory::Flake8Bugbear,
CheckCode::B011 => CheckCategory::Flake8Bugbear,
CheckCode::B013 => CheckCategory::Flake8Bugbear,
CheckCode::B014 => CheckCategory::Flake8Bugbear,
CheckCode::B015 => CheckCategory::Flake8Bugbear,
CheckCode::B016 => CheckCategory::Flake8Bugbear,
CheckCode::B017 => CheckCategory::Flake8Bugbear,
CheckCode::B018 => CheckCategory::Flake8Bugbear,
CheckCode::B025 => CheckCategory::Flake8Bugbear,
@@ -709,6 +755,7 @@ impl CheckCode {
CheckCode::U006 => CheckCategory::Pyupgrade,
CheckCode::U007 => CheckCategory::Pyupgrade,
CheckCode::U008 => CheckCategory::Pyupgrade,
CheckCode::U009 => CheckCategory::Pyupgrade,
CheckCode::D100 => CheckCategory::Pydocstyle,
CheckCode::D101 => CheckCategory::Pydocstyle,
CheckCode::D102 => CheckCategory::Pydocstyle,
@@ -768,7 +815,8 @@ impl CheckCode {
CheckCode::N816 => CheckCategory::PEP8Naming,
CheckCode::N817 => CheckCategory::PEP8Naming,
CheckCode::N818 => CheckCategory::PEP8Naming,
CheckCode::X001 => CheckCategory::Ruff,
CheckCode::RUF001 => CheckCategory::Ruff,
CheckCode::RUF002 => CheckCategory::Ruff,
CheckCode::M001 => CheckCategory::Meta,
}
}
@@ -830,11 +878,15 @@ impl CheckKind {
CheckKind::BuiltinAttributeShadowing(_) => &CheckCode::A003,
// flake8-bugbear
CheckKind::UnaryPrefixIncrement => &CheckCode::B002,
CheckKind::AssignmentToOsEnviron => &CheckCode::B003,
CheckKind::MutableArgumentDefault => &CheckCode::B006,
CheckKind::UnusedLoopControlVariable(_) => &CheckCode::B007,
CheckKind::FunctionCallArgumentDefault => &CheckCode::B008,
CheckKind::DoNotAssertFalse => &CheckCode::B011,
CheckKind::RedundantTupleInExceptionHandler(_) => &CheckCode::B013,
CheckKind::DuplicateHandlerException(_) => &CheckCode::B014,
CheckKind::UselessComparison => &CheckCode::B015,
CheckKind::CannotRaiseLiteral => &CheckCode::B016,
CheckKind::NoAssertRaisesException => &CheckCode::B017,
CheckKind::UselessExpression => &CheckCode::B018,
CheckKind::DuplicateTryBlockException(_) => &CheckCode::B025,
@@ -872,6 +924,7 @@ impl CheckKind {
CheckKind::UsePEP604Annotation => &CheckCode::U007,
CheckKind::UselessObjectInheritance(_) => &CheckCode::U004,
CheckKind::SuperCallWithParameters => &CheckCode::U008,
CheckKind::PEP3120UnnecessaryCodingComment => &CheckCode::U009,
// pydocstyle
CheckKind::BlankLineAfterLastSection(_) => &CheckCode::D413,
CheckKind::BlankLineAfterSection(_) => &CheckCode::D410,
@@ -934,7 +987,8 @@ impl CheckKind {
CheckKind::CamelcaseImportedAsAcronym(..) => &CheckCode::N817,
CheckKind::ErrorSuffixOnExceptionName(..) => &CheckCode::N818,
// Ruff
CheckKind::AmbiguousUnicodeCharacter(..) => &CheckCode::X001,
CheckKind::AmbiguousUnicodeCharacterString(..) => &CheckCode::RUF001,
CheckKind::AmbiguousUnicodeCharacterDocstring(..) => &CheckCode::RUF002,
// Meta
CheckKind::UnusedNOQA(_) => &CheckCode::M001,
}
@@ -1095,6 +1149,9 @@ impl CheckKind {
increment. Writing `++n` is equivalent to \
`+(+(n))`, which equals `n`. You meant `n += 1`."
.to_string(),
CheckKind::AssignmentToOsEnviron => {
"Assigning to `os.environ` doesn't clear the environment.".to_string()
}
CheckKind::MutableArgumentDefault => {
"Do not use mutable data structures for argument defaults.".to_string()
}
@@ -1102,6 +1159,9 @@ impl CheckKind {
"Loop control variable `{name}` not used within the loop body. If this is \
intended, start the name with an underscore."
),
CheckKind::FunctionCallArgumentDefault => {
"Do not perform function calls in argument defaults.".to_string()
}
CheckKind::DoNotAssertFalse => "Do not `assert False` (`python -O` removes these \
calls), raise `AssertionError()`"
.to_string(),
@@ -1111,6 +1171,13 @@ impl CheckKind {
`except ({name},):`."
)
}
CheckKind::UselessComparison => "Pointless comparison. This comparison does nothing \
but waste CPU instructions. Either prepend `assert` \
or remove it."
.to_string(),
CheckKind::CannotRaiseLiteral => "Cannot raise a literal. Did you intend to return it \
or raise an Exception?"
.to_string(),
CheckKind::DuplicateHandlerException(names) => {
if names.len() == 1 {
let name = &names[0];
@@ -1418,10 +1485,19 @@ impl CheckKind {
CheckKind::ErrorSuffixOnExceptionName(name) => {
format!("Exception name `{name}` should be named with an Error suffix")
}
CheckKind::PEP3120UnnecessaryCodingComment => {
"utf-8 encoding declaration is unnecessary".to_string()
}
// Ruff
CheckKind::AmbiguousUnicodeCharacter(confusable, representant) => {
CheckKind::AmbiguousUnicodeCharacterString(confusable, representant) => {
format!(
"Use of ambiguous unicode character '{confusable}' (did you mean \
"String contains ambiguous unicode character '{confusable}' (did you mean \
'{representant}'?)"
)
}
CheckKind::AmbiguousUnicodeCharacterDocstring(confusable, representant) => {
format!(
"Docstring contains ambiguous unicode character '{confusable}' (did you mean \
'{representant}'?)"
)
}
@@ -1466,7 +1542,8 @@ impl CheckKind {
pub fn fixable(&self) -> bool {
matches!(
self,
CheckKind::AmbiguousUnicodeCharacter(_, _)
CheckKind::AmbiguousUnicodeCharacterString(_, _)
| CheckKind::AmbiguousUnicodeCharacterDocstring(_, _)
| CheckKind::BlankLineAfterLastSection(_)
| CheckKind::BlankLineAfterSection(_)
| CheckKind::BlankLineAfterSummary
@@ -1516,6 +1593,8 @@ impl CheckKind {
| CheckKind::UsePEP604Annotation
| CheckKind::UselessMetaclassType
| CheckKind::UselessObjectInheritance(_)
| CheckKind::PEP3120UnnecessaryCodingComment
| CheckKind::IsLiteral
)
}
}

View File

@@ -17,12 +17,16 @@ pub enum CheckCodePrefix {
B0,
B00,
B002,
B003,
B006,
B007,
B008,
B01,
B011,
B013,
B014,
B015,
B016,
B017,
B018,
B02,
@@ -205,6 +209,11 @@ pub enum CheckCodePrefix {
Q001,
Q002,
Q003,
RUF,
RUF0,
RUF00,
RUF001,
RUF002,
T,
T2,
T20,
@@ -221,6 +230,7 @@ pub enum CheckCodePrefix {
U006,
U007,
U008,
U009,
W,
W2,
W29,
@@ -228,10 +238,6 @@ pub enum CheckCodePrefix {
W6,
W60,
W605,
X,
X0,
X00,
X001,
}
#[derive(PartialEq, Eq, PartialOrd, Ord)]
@@ -253,40 +259,60 @@ impl CheckCodePrefix {
CheckCodePrefix::A003 => vec![CheckCode::A003],
CheckCodePrefix::B => vec![
CheckCode::B002,
CheckCode::B003,
CheckCode::B006,
CheckCode::B007,
CheckCode::B008,
CheckCode::B011,
CheckCode::B013,
CheckCode::B014,
CheckCode::B015,
CheckCode::B016,
CheckCode::B017,
CheckCode::B018,
CheckCode::B025,
],
CheckCodePrefix::B0 => vec![
CheckCode::B002,
CheckCode::B003,
CheckCode::B006,
CheckCode::B007,
CheckCode::B008,
CheckCode::B011,
CheckCode::B013,
CheckCode::B014,
CheckCode::B015,
CheckCode::B016,
CheckCode::B017,
CheckCode::B018,
CheckCode::B025,
],
CheckCodePrefix::B00 => vec![CheckCode::B002, CheckCode::B006, CheckCode::B007],
CheckCodePrefix::B00 => vec![
CheckCode::B002,
CheckCode::B003,
CheckCode::B006,
CheckCode::B007,
CheckCode::B008,
],
CheckCodePrefix::B002 => vec![CheckCode::B002],
CheckCodePrefix::B003 => vec![CheckCode::B003],
CheckCodePrefix::B006 => vec![CheckCode::B006],
CheckCodePrefix::B007 => vec![CheckCode::B007],
CheckCodePrefix::B008 => vec![CheckCode::B008],
CheckCodePrefix::B01 => vec![
CheckCode::B011,
CheckCode::B013,
CheckCode::B014,
CheckCode::B015,
CheckCode::B016,
CheckCode::B017,
CheckCode::B018,
],
CheckCodePrefix::B011 => vec![CheckCode::B011],
CheckCodePrefix::B013 => vec![CheckCode::B013],
CheckCodePrefix::B014 => vec![CheckCode::B014],
CheckCodePrefix::B015 => vec![CheckCode::B015],
CheckCodePrefix::B016 => vec![CheckCode::B016],
CheckCodePrefix::B017 => vec![CheckCode::B017],
CheckCodePrefix::B018 => vec![CheckCode::B018],
CheckCodePrefix::B02 => vec![CheckCode::B025],
@@ -833,6 +859,11 @@ impl CheckCodePrefix {
CheckCodePrefix::Q001 => vec![CheckCode::Q001],
CheckCodePrefix::Q002 => vec![CheckCode::Q002],
CheckCodePrefix::Q003 => vec![CheckCode::Q003],
CheckCodePrefix::RUF => vec![CheckCode::RUF001, CheckCode::RUF002],
CheckCodePrefix::RUF0 => vec![CheckCode::RUF001, CheckCode::RUF002],
CheckCodePrefix::RUF00 => vec![CheckCode::RUF001, CheckCode::RUF002],
CheckCodePrefix::RUF001 => vec![CheckCode::RUF001],
CheckCodePrefix::RUF002 => vec![CheckCode::RUF002],
CheckCodePrefix::T => vec![CheckCode::T201, CheckCode::T203],
CheckCodePrefix::T2 => vec![CheckCode::T201, CheckCode::T203],
CheckCodePrefix::T20 => vec![CheckCode::T201, CheckCode::T203],
@@ -847,6 +878,7 @@ impl CheckCodePrefix {
CheckCode::U006,
CheckCode::U007,
CheckCode::U008,
CheckCode::U009,
],
CheckCodePrefix::U0 => vec![
CheckCode::U001,
@@ -857,6 +889,7 @@ impl CheckCodePrefix {
CheckCode::U006,
CheckCode::U007,
CheckCode::U008,
CheckCode::U009,
],
CheckCodePrefix::U00 => vec![
CheckCode::U001,
@@ -867,6 +900,7 @@ impl CheckCodePrefix {
CheckCode::U006,
CheckCode::U007,
CheckCode::U008,
CheckCode::U009,
],
CheckCodePrefix::U001 => vec![CheckCode::U001],
CheckCodePrefix::U002 => vec![CheckCode::U002],
@@ -876,6 +910,7 @@ impl CheckCodePrefix {
CheckCodePrefix::U006 => vec![CheckCode::U006],
CheckCodePrefix::U007 => vec![CheckCode::U007],
CheckCodePrefix::U008 => vec![CheckCode::U008],
CheckCodePrefix::U009 => vec![CheckCode::U009],
CheckCodePrefix::W => vec![CheckCode::W292, CheckCode::W605],
CheckCodePrefix::W2 => vec![CheckCode::W292],
CheckCodePrefix::W29 => vec![CheckCode::W292],
@@ -883,10 +918,6 @@ impl CheckCodePrefix {
CheckCodePrefix::W6 => vec![CheckCode::W605],
CheckCodePrefix::W60 => vec![CheckCode::W605],
CheckCodePrefix::W605 => vec![CheckCode::W605],
CheckCodePrefix::X => vec![CheckCode::X001],
CheckCodePrefix::X0 => vec![CheckCode::X001],
CheckCodePrefix::X00 => vec![CheckCode::X001],
CheckCodePrefix::X001 => vec![CheckCode::X001],
}
}
}
@@ -904,12 +935,16 @@ impl CheckCodePrefix {
CheckCodePrefix::B0 => PrefixSpecificity::Hundreds,
CheckCodePrefix::B00 => PrefixSpecificity::Tens,
CheckCodePrefix::B002 => PrefixSpecificity::Explicit,
CheckCodePrefix::B003 => PrefixSpecificity::Explicit,
CheckCodePrefix::B006 => PrefixSpecificity::Explicit,
CheckCodePrefix::B007 => PrefixSpecificity::Explicit,
CheckCodePrefix::B008 => PrefixSpecificity::Explicit,
CheckCodePrefix::B01 => PrefixSpecificity::Tens,
CheckCodePrefix::B011 => PrefixSpecificity::Explicit,
CheckCodePrefix::B013 => PrefixSpecificity::Explicit,
CheckCodePrefix::B014 => PrefixSpecificity::Explicit,
CheckCodePrefix::B015 => PrefixSpecificity::Explicit,
CheckCodePrefix::B016 => PrefixSpecificity::Explicit,
CheckCodePrefix::B017 => PrefixSpecificity::Explicit,
CheckCodePrefix::B018 => PrefixSpecificity::Explicit,
CheckCodePrefix::B02 => PrefixSpecificity::Tens,
@@ -1092,6 +1127,11 @@ impl CheckCodePrefix {
CheckCodePrefix::Q001 => PrefixSpecificity::Explicit,
CheckCodePrefix::Q002 => PrefixSpecificity::Explicit,
CheckCodePrefix::Q003 => PrefixSpecificity::Explicit,
CheckCodePrefix::RUF => PrefixSpecificity::Category,
CheckCodePrefix::RUF0 => PrefixSpecificity::Hundreds,
CheckCodePrefix::RUF00 => PrefixSpecificity::Tens,
CheckCodePrefix::RUF001 => PrefixSpecificity::Explicit,
CheckCodePrefix::RUF002 => PrefixSpecificity::Explicit,
CheckCodePrefix::T => PrefixSpecificity::Category,
CheckCodePrefix::T2 => PrefixSpecificity::Hundreds,
CheckCodePrefix::T20 => PrefixSpecificity::Tens,
@@ -1108,6 +1148,7 @@ impl CheckCodePrefix {
CheckCodePrefix::U006 => PrefixSpecificity::Explicit,
CheckCodePrefix::U007 => PrefixSpecificity::Explicit,
CheckCodePrefix::U008 => PrefixSpecificity::Explicit,
CheckCodePrefix::U009 => PrefixSpecificity::Explicit,
CheckCodePrefix::W => PrefixSpecificity::Category,
CheckCodePrefix::W2 => PrefixSpecificity::Hundreds,
CheckCodePrefix::W29 => PrefixSpecificity::Tens,
@@ -1115,10 +1156,6 @@ impl CheckCodePrefix {
CheckCodePrefix::W6 => PrefixSpecificity::Hundreds,
CheckCodePrefix::W60 => PrefixSpecificity::Tens,
CheckCodePrefix::W605 => PrefixSpecificity::Explicit,
CheckCodePrefix::X => PrefixSpecificity::Category,
CheckCodePrefix::X0 => PrefixSpecificity::Hundreds,
CheckCodePrefix::X00 => PrefixSpecificity::Tens,
CheckCodePrefix::X001 => PrefixSpecificity::Explicit,
}
}
}

View File

@@ -1,9 +1,21 @@
use anyhow::Result;
use libcst_native::Module;
use libcst_native::{Expr, Module, SmallStatement, Statement};
pub fn match_module(module_text: &str) -> Result<Module> {
match libcst_native::parse_module(module_text, None) {
Ok(module) => Ok(module),
Err(_) => return Err(anyhow::anyhow!("Failed to extract CST from source.")),
Err(_) => Err(anyhow::anyhow!("Failed to extract CST from source.")),
}
}
pub fn match_expr<'a, 'b>(module: &'a mut Module<'b>) -> Result<&'a mut Expr<'b>> {
if let Some(Statement::Simple(expr)) = module.body.first_mut() {
if let Some(SmallStatement::Expr(expr)) = expr.body.first_mut() {
Ok(expr)
} else {
Err(anyhow::anyhow!("Expected node to be: SmallStatement::Expr"))
}
} else {
Err(anyhow::anyhow!("Expected node to be: Statement::Simple"))
}
}

View File

@@ -0,0 +1,24 @@
use rustpython_ast::{Expr, ExprKind};
use crate::ast::types::{CheckLocator, Range};
use crate::check_ast::Checker;
use crate::checks::{Check, CheckKind};
/// B003
pub fn assignment_to_os_environ(checker: &mut Checker, targets: &[Expr]) {
if targets.len() == 1 {
let target = &targets[0];
if let ExprKind::Attribute { value, attr, .. } = &target.node {
if attr == "environ" {
if let ExprKind::Name { id, .. } = &value.node {
if id == "os" {
checker.add_check(Check::new(
CheckKind::AssignmentToOsEnviron,
checker.locate_check(Range::from_located(target)),
));
}
}
}
}
}
}

View File

@@ -0,0 +1,15 @@
use rustpython_ast::{Expr, ExprKind};
use crate::ast::types::{CheckLocator, Range};
use crate::check_ast::Checker;
use crate::checks::{Check, CheckKind};
/// B016
pub fn cannot_raise_literal(checker: &mut Checker, expr: &Expr) {
if let ExprKind::Constant { .. } = &expr.node {
checker.add_check(Check::new(
CheckKind::CannotRaiseLiteral,
checker.locate_check(Range::from_located(expr)),
));
}
}

View File

@@ -0,0 +1,96 @@
use rustpython_ast::{Arguments, Constant, Expr, ExprKind};
use crate::ast::helpers::compose_call_path;
use crate::ast::types::{CheckLocator, Range};
use crate::ast::visitor;
use crate::ast::visitor::Visitor;
use crate::check_ast::Checker;
use crate::checks::{Check, CheckKind};
use crate::flake8_bugbear::plugins::mutable_argument_default::is_mutable_func;
const IMMUTABLE_FUNCS: [&str; 11] = [
"tuple",
"frozenset",
"operator.attrgetter",
"operator.itemgetter",
"operator.methodcaller",
"attrgetter",
"itemgetter",
"methodcaller",
"types.MappingProxyType",
"MappingProxyType",
"re.compile",
];
fn is_immutable_func(expr: &Expr) -> bool {
compose_call_path(expr).map_or_else(|| false, |func| IMMUTABLE_FUNCS.contains(&func.as_str()))
}
struct ArgumentDefaultVisitor {
checks: Vec<(CheckKind, Range)>,
}
impl<'a, 'b> Visitor<'b> for ArgumentDefaultVisitor
where
'b: 'a,
{
fn visit_expr(&mut self, expr: &'a Expr) {
match &expr.node {
ExprKind::Call { func, args, .. } => {
if !is_mutable_func(func)
&& !is_immutable_func(func)
&& !is_nan_or_infinity(func, args)
{
self.checks.push((
CheckKind::FunctionCallArgumentDefault,
Range::from_located(expr),
))
}
visitor::walk_expr(self, expr)
}
ExprKind::Lambda { .. } => {}
_ => visitor::walk_expr(self, expr),
}
}
}
fn is_nan_or_infinity(expr: &Expr, args: &[Expr]) -> bool {
if let ExprKind::Name { id, .. } = &expr.node {
if id == "float" {
if let Some(arg) = args.first() {
if let ExprKind::Constant {
value: Constant::Str(value),
..
} = &arg.node
{
let lowercased = value.to_lowercase();
return lowercased == "nan"
|| lowercased == "+nan"
|| lowercased == "-nan"
|| lowercased == "inf"
|| lowercased == "+inf"
|| lowercased == "-inf"
|| lowercased == "infinity"
|| lowercased == "+infinity"
|| lowercased == "-infinity";
}
}
}
}
false
}
/// B008
pub fn function_call_argument_default(checker: &mut Checker, arguments: &Arguments) {
let mut visitor = ArgumentDefaultVisitor { checks: vec![] };
for expr in arguments
.defaults
.iter()
.chain(arguments.kw_defaults.iter())
{
visitor.visit_expr(expr);
}
for (check, range) in visitor.checks {
checker.add_check(Check::new(check, checker.locate_check(range)));
}
}

View File

@@ -1,17 +1,25 @@
pub use assert_false::assert_false;
pub use assert_raises_exception::assert_raises_exception;
pub use assignment_to_os_environ::assignment_to_os_environ;
pub use cannot_raise_literal::cannot_raise_literal;
pub use duplicate_exceptions::{duplicate_exceptions, duplicate_handler_exceptions};
pub use function_call_argument_default::function_call_argument_default;
pub use mutable_argument_default::mutable_argument_default;
pub use redundant_tuple_in_exception_handler::redundant_tuple_in_exception_handler;
pub use unary_prefix_increment::unary_prefix_increment;
pub use unused_loop_control_variable::unused_loop_control_variable;
pub use useless_comparison::useless_comparison;
pub use useless_expression::useless_expression;
mod assert_false;
mod assert_raises_exception;
mod assignment_to_os_environ;
mod cannot_raise_literal;
mod duplicate_exceptions;
mod function_call_argument_default;
mod mutable_argument_default;
mod redundant_tuple_in_exception_handler;
mod unary_prefix_increment;
mod unused_loop_control_variable;
mod useless_comparison;
mod useless_expression;

View File

@@ -1,9 +1,34 @@
use rustpython_ast::{Arguments, ExprKind};
use rustpython_ast::{Arguments, Expr, ExprKind};
use crate::ast::types::{CheckLocator, Range};
use crate::check_ast::Checker;
use crate::checks::{Check, CheckKind};
pub fn is_mutable_func(expr: &Expr) -> bool {
match &expr.node {
ExprKind::Name { id, .. }
if id == "dict"
|| id == "list"
|| id == "set"
|| id == "Counter"
|| id == "OrderedDict"
|| id == "defaultdict"
|| id == "deque" =>
{
true
}
ExprKind::Attribute { value, attr, .. }
if (attr == "Counter"
|| attr == "OrderedDict"
|| attr == "defaultdict"
|| attr == "deque") =>
{
matches!(&value.node, ExprKind::Name { id, .. } if id == "collections")
}
_ => false,
}
}
/// B006
pub fn mutable_argument_default(checker: &mut Checker, arguments: &Arguments) {
for expr in arguments
@@ -23,39 +48,14 @@ pub fn mutable_argument_default(checker: &mut Checker, arguments: &Arguments) {
checker.locate_check(Range::from_located(expr)),
));
}
ExprKind::Call { func, .. } => match &func.node {
ExprKind::Name { id, .. }
if id == "dict"
|| id == "list"
|| id == "set"
|| id == "Counter"
|| id == "OrderedDict"
|| id == "defaultdict"
|| id == "deque" =>
{
ExprKind::Call { func, .. } => {
if is_mutable_func(func) {
checker.add_check(Check::new(
CheckKind::MutableArgumentDefault,
checker.locate_check(Range::from_located(expr)),
));
}
ExprKind::Attribute { value, attr, .. }
if (attr == "Counter"
|| attr == "OrderedDict"
|| attr == "defaultdict"
|| attr == "deque") =>
{
match &value.node {
ExprKind::Name { id, .. } if id == "collections" => {
checker.add_check(Check::new(
CheckKind::MutableArgumentDefault,
checker.locate_check(Range::from_located(expr)),
));
}
_ => {}
}
}
_ => {}
},
}
_ => {}
}
}

View File

@@ -0,0 +1,14 @@
use rustpython_ast::{Expr, ExprKind};
use crate::ast::types::{CheckLocator, Range};
use crate::check_ast::Checker;
use crate::checks::{Check, CheckKind};
pub fn useless_comparison(checker: &mut Checker, expr: &Expr) {
if let ExprKind::Compare { left, .. } = &expr.node {
checker.add_check(Check::new(
CheckKind::UselessComparison,
checker.locate_check(Range::from_located(left)),
));
}
}

View File

@@ -4,6 +4,7 @@ use crate::ast::types::{CheckLocator, Range};
use crate::check_ast::Checker;
use crate::checks::{Check, CheckKind};
// B018
pub fn useless_expression(checker: &mut Checker, body: &[Stmt]) {
for stmt in body {
if let StmtKind::Expr { value } = &stmt.node {
@@ -15,7 +16,7 @@ pub fn useless_expression(checker: &mut Checker, body: &[Stmt]) {
));
}
ExprKind::Constant { value: val, .. } => match &val {
Constant::Str { .. } => {}
Constant::Str { .. } | Constant::Ellipsis => {}
_ => {
checker.add_check(Check::new(
CheckKind::UselessExpression,

View File

@@ -1,28 +1,15 @@
use anyhow::Result;
use libcst_native::{
Arg, Call, Codegen, Dict, DictComp, DictElement, Element, Expr, Expression, LeftCurlyBrace,
LeftParen, LeftSquareBracket, List, ListComp, Module, Name, ParenthesizableWhitespace,
RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, SimpleString, SimpleWhitespace,
SmallStatement, Statement, Tuple,
LeftParen, LeftSquareBracket, List, ListComp, Name, ParenthesizableWhitespace, RightCurlyBrace,
RightParen, RightSquareBracket, Set, SetComp, SimpleString, SimpleWhitespace, Tuple,
};
use crate::ast::types::Range;
use crate::autofix::Fix;
use crate::cst::matchers::match_module;
use crate::cst::matchers::{match_expr, match_module};
use crate::source_code_locator::SourceCodeLocator;
fn match_expr<'a, 'b>(module: &'a mut Module<'b>) -> Result<&'a mut Expr<'b>> {
if let Some(Statement::Simple(expr)) = module.body.first_mut() {
if let Some(SmallStatement::Expr(expr)) = expr.body.first_mut() {
Ok(expr)
} else {
Err(anyhow::anyhow!("Expected node to be: SmallStatement::Expr"))
}
} else {
Err(anyhow::anyhow!("Expected node to be: Statement::Simple"))
}
}
fn match_call<'a, 'b>(expr: &'a mut Expr<'b>) -> Result<&'a mut Call<'b>> {
if let Expression::Call(call) = &mut expr.value {
Ok(call)

View File

@@ -1,3 +1,2 @@
pub mod checks;
pub mod docstring_detection;
pub mod settings;

View File

@@ -118,7 +118,7 @@ pub fn iter_python_files<'a>(
}
/// Create tree set with codes matching the pattern/code pairs.
pub fn ignores_from_path<'a>(
pub(crate) fn ignores_from_path<'a>(
path: &Path,
pattern_code_pairs: &'a [PerFileIgnore],
) -> Result<BTreeSet<&'a CheckCode>> {
@@ -138,7 +138,7 @@ pub fn ignores_from_path<'a>(
/// Convert any path to an absolute path (based on the current working
/// directory).
pub fn normalize_path(path: &Path) -> PathBuf {
pub(crate) fn normalize_path(path: &Path) -> PathBuf {
if let Ok(path) = path.absolutize() {
return path.to_path_buf();
}
@@ -146,7 +146,7 @@ pub fn normalize_path(path: &Path) -> PathBuf {
}
/// Convert any path to an absolute path (based on the specified project root).
pub fn normalize_path_to(path: &Path, project_root: &Path) -> PathBuf {
pub(crate) fn normalize_path_to(path: &Path, project_root: &Path) -> PathBuf {
if let Ok(path) = path.absolutize_from(project_root) {
return path.to_path_buf();
}
@@ -154,7 +154,7 @@ pub fn normalize_path_to(path: &Path, project_root: &Path) -> PathBuf {
}
/// Convert an absolute path to be relative to the current working directory.
pub fn relativize_path(path: &Path) -> Cow<str> {
pub(crate) fn relativize_path(path: &Path) -> Cow<str> {
if let Ok(path) = path.strip_prefix(path_dedot::CWD.deref()) {
return path.to_string_lossy();
}
@@ -162,7 +162,7 @@ pub fn relativize_path(path: &Path) -> Cow<str> {
}
/// Read a file's contents from disk.
pub fn read_file(path: &Path) -> Result<String> {
pub(crate) fn read_file(path: &Path) -> Result<String> {
let file = File::open(path)?;
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();

1
src/lex/mod.rs Normal file
View File

@@ -0,0 +1 @@
pub mod docstring_detection;

View File

@@ -31,6 +31,7 @@ mod flake8_comprehensions;
mod flake8_print;
pub mod flake8_quotes;
pub mod fs;
mod lex;
pub mod linter;
pub mod logging;
pub mod message;

View File

@@ -293,11 +293,15 @@ mod tests {
#[test_case(CheckCode::A002, Path::new("A002.py"); "A002")]
#[test_case(CheckCode::A003, Path::new("A003.py"); "A003")]
#[test_case(CheckCode::B002, Path::new("B002.py"); "B002")]
#[test_case(CheckCode::B003, Path::new("B003.py"); "B003")]
#[test_case(CheckCode::B006, Path::new("B006_B008.py"); "B006")]
#[test_case(CheckCode::B007, Path::new("B007.py"); "B007")]
#[test_case(CheckCode::B008, Path::new("B006_B008.py"); "B008")]
#[test_case(CheckCode::B011, Path::new("B011.py"); "B011")]
#[test_case(CheckCode::B013, Path::new("B013.py"); "B013")]
#[test_case(CheckCode::B014, Path::new("B014.py"); "B014")]
#[test_case(CheckCode::B015, Path::new("B015.py"); "B015")]
#[test_case(CheckCode::B016, Path::new("B016.py"); "B016")]
#[test_case(CheckCode::B017, Path::new("B017.py"); "B017")]
#[test_case(CheckCode::B018, Path::new("B018.py"); "B018")]
#[test_case(CheckCode::B025, Path::new("B025.py"); "B025")]
@@ -435,11 +439,17 @@ mod tests {
#[test_case(CheckCode::U006, Path::new("U006.py"); "U006")]
#[test_case(CheckCode::U007, Path::new("U007.py"); "U007")]
#[test_case(CheckCode::U008, Path::new("U008.py"); "U008")]
#[test_case(CheckCode::U009, Path::new("U009_0.py"); "U009_0")]
#[test_case(CheckCode::U009, Path::new("U009_1.py"); "U009_1")]
#[test_case(CheckCode::U009, Path::new("U009_2.py"); "U009_2")]
#[test_case(CheckCode::U009, Path::new("U009_3.py"); "U009_3")]
#[test_case(CheckCode::W292, Path::new("W292_0.py"); "W292_0")]
#[test_case(CheckCode::W292, Path::new("W292_1.py"); "W292_1")]
#[test_case(CheckCode::W292, Path::new("W292_2.py"); "W292_2")]
#[test_case(CheckCode::W605, Path::new("W605.py"); "W605")]
#[test_case(CheckCode::X001, Path::new("X001.py"); "X001")]
#[test_case(CheckCode::W605, Path::new("W605_0.py"); "W605_0")]
#[test_case(CheckCode::W605, Path::new("W605_1.py"); "W605_1")]
#[test_case(CheckCode::RUF001, Path::new("RUF001.py"); "RUF001")]
#[test_case(CheckCode::RUF002, Path::new("RUF002.py"); "RUF002")]
fn checks(check_code: CheckCode, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", check_code.as_ref(), path.to_string_lossy());
let mut checks = check_path(

View File

@@ -1,4 +1,3 @@
use std::cmp::{max, min};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::Path;
@@ -46,38 +45,21 @@ pub fn extract_noqa_directive(line: &str) -> Directive {
pub fn extract_noqa_line_for(lxr: &[LexResult]) -> Vec<usize> {
let mut noqa_line_for: Vec<usize> = vec![];
let mut min_line = usize::MAX;
let mut max_line = usize::MIN;
let mut in_string = false;
for (start, tok, end) in lxr.iter().flatten() {
if matches!(tok, Tok::EndOfFile) {
break;
}
if matches!(tok, Tok::Newline) {
min_line = min(min_line, start.row());
max_line = max(max_line, start.row());
// For now, we only care about preserving noqa directives across multi-line
// strings.
if in_string {
for i in (noqa_line_for.len())..(min_line - 1) {
noqa_line_for.push(i + 1);
}
noqa_line_for.extend(vec![max_line; (max_line + 1) - min_line]);
// For multi-line strings, we expect `noqa` directives on the last line of the
// string. By definition, we can't have multiple multi-line strings on
// the same line, so we don't need to verify that we haven't already
// traversed past the current line.
if matches!(tok, Tok::String { .. }) && end.row() > start.row() {
for i in (noqa_line_for.len())..(start.row() - 1) {
noqa_line_for.push(i + 1);
}
min_line = usize::MAX;
max_line = usize::MIN;
} else {
min_line = min(min_line, start.row());
max_line = max(max_line, end.row());
noqa_line_for.extend(vec![end.row(); (end.row() + 1) - start.row()]);
}
in_string = matches!(tok, Tok::String { .. });
}
noqa_line_for
}

View File

@@ -1,8 +1,9 @@
use itertools::Itertools;
use rustpython_ast::{Arguments, Expr, ExprKind, Stmt};
use crate::ast::types::{FunctionScope, Range, Scope, ScopeKind};
use crate::checks::{Check, CheckKind};
use crate::pep8_naming::helpers;
use crate::pep8_naming::helpers::FunctionType;
use crate::pep8_naming::settings::Settings;
/// N801
@@ -25,7 +26,7 @@ pub fn invalid_class_name(class_def: &Stmt, name: &str) -> Option<Check> {
/// N802
pub fn invalid_function_name(func_def: &Stmt, name: &str, settings: &Settings) -> Option<Check> {
if !is_lower(name)
if name.to_lowercase() != name
&& !settings
.ignore_names
.iter()
@@ -40,8 +41,8 @@ pub fn invalid_function_name(func_def: &Stmt, name: &str, settings: &Settings) -
}
/// N803
pub fn invalid_argument_name(location: Range, name: &str) -> Option<Check> {
if !is_lower(name) {
pub fn invalid_argument_name(name: &str, location: Range) -> Option<Check> {
if name.to_lowercase() != name {
return Some(Check::new(
CheckKind::InvalidArgumentName(name.to_string()),
location,
@@ -53,21 +54,15 @@ pub fn invalid_argument_name(location: Range, name: &str) -> Option<Check> {
/// N804
pub fn invalid_first_argument_name_for_class_method(
scope: &Scope,
name: &str,
decorator_list: &[Expr],
args: &Arguments,
settings: &Settings,
) -> Option<Check> {
if !matches!(scope.kind, ScopeKind::Class) {
return None;
}
if decorator_list.iter().any(|decorator| {
if let ExprKind::Name { id, .. } = &decorator.node {
settings.classmethod_decorators.contains(id)
} else {
false
}
}) {
if matches!(
helpers::function_type(scope, name, decorator_list, settings),
FunctionType::ClassMethod
) {
if let Some(arg) = args.args.first() {
if arg.node.arg != "cls" {
return Some(Check::new(
@@ -83,31 +78,22 @@ pub fn invalid_first_argument_name_for_class_method(
/// N805
pub fn invalid_first_argument_name_for_method(
scope: &Scope,
name: &str,
decorator_list: &[Expr],
args: &Arguments,
settings: &Settings,
) -> Option<Check> {
if !matches!(scope.kind, ScopeKind::Class) {
return None;
}
if decorator_list.iter().any(|decorator| {
if let ExprKind::Name { id, .. } = &decorator.node {
settings.classmethod_decorators.contains(id)
|| settings.staticmethod_decorators.contains(id)
} else {
false
}
}) {
return None;
}
if let Some(arg) = args.args.first() {
if arg.node.arg != "self" {
return Some(Check::new(
CheckKind::InvalidFirstArgumentNameForMethod,
Range::from_located(arg),
));
if matches!(
helpers::function_type(scope, name, decorator_list, settings),
FunctionType::Method
) {
if let Some(arg) = args.args.first() {
if arg.node.arg != "self" {
return Some(Check::new(
CheckKind::InvalidFirstArgumentNameForMethod,
Range::from_located(arg),
));
}
}
}
None
@@ -128,18 +114,16 @@ pub fn non_lowercase_variable_in_function(scope: &Scope, expr: &Expr, name: &str
}
/// N807
pub fn dunder_function_name(func_def: &Stmt, scope: &Scope, name: &str) -> Option<Check> {
if matches!(scope.kind, ScopeKind::Class) {
pub fn dunder_function_name(scope: &Scope, stmt: &Stmt, name: &str) -> Option<Check> {
if matches!(scope.kind, ScopeKind::Class(_)) {
return None;
}
if name.starts_with("__") && name.ends_with("__") {
return Some(Check::new(
CheckKind::DunderFunctionName,
Range::from_located(func_def),
Range::from_located(stmt),
));
}
None
}
@@ -149,7 +133,7 @@ pub fn constant_imported_as_non_constant(
name: &str,
asname: &str,
) -> Option<Check> {
if is_upper(name) && !is_upper(asname) {
if helpers::is_upper(name) && !helpers::is_upper(asname) {
return Some(Check::new(
CheckKind::ConstantImportedAsNonConstant(name.to_string(), asname.to_string()),
Range::from_located(import_from),
@@ -164,7 +148,7 @@ pub fn lowercase_imported_as_non_lowercase(
name: &str,
asname: &str,
) -> Option<Check> {
if is_lower(name) && asname.to_lowercase() != asname {
if !helpers::is_upper(name) && helpers::is_lower(name) && asname.to_lowercase() != asname {
return Some(Check::new(
CheckKind::LowercaseImportedAsNonLowercase(name.to_string(), asname.to_string()),
Range::from_located(import_from),
@@ -179,7 +163,7 @@ pub fn camelcase_imported_as_lowercase(
name: &str,
asname: &str,
) -> Option<Check> {
if is_camelcase(name) && is_lower(asname) {
if helpers::is_camelcase(name) && helpers::is_lower(asname) {
return Some(Check::new(
CheckKind::CamelcaseImportedAsLowercase(name.to_string(), asname.to_string()),
Range::from_located(import_from),
@@ -194,7 +178,11 @@ pub fn camelcase_imported_as_constant(
name: &str,
asname: &str,
) -> Option<Check> {
if is_camelcase(name) && is_upper(asname) && !is_acronym(name, asname) {
if helpers::is_camelcase(name)
&& !helpers::is_lower(asname)
&& helpers::is_upper(asname)
&& !helpers::is_acronym(name, asname)
{
return Some(Check::new(
CheckKind::CamelcaseImportedAsConstant(name.to_string(), asname.to_string()),
Range::from_located(import_from),
@@ -205,10 +193,10 @@ pub fn camelcase_imported_as_constant(
/// N815
pub fn mixed_case_variable_in_class_scope(scope: &Scope, expr: &Expr, name: &str) -> Option<Check> {
if !matches!(scope.kind, ScopeKind::Class) {
if !matches!(scope.kind, ScopeKind::Class(_)) {
return None;
}
if is_mixed_case(name) {
if helpers::is_mixed_case(name) {
return Some(Check::new(
CheckKind::MixedCaseVariableInClassScope(name.to_string()),
Range::from_located(expr),
@@ -226,7 +214,7 @@ pub fn mixed_case_variable_in_global_scope(
if !matches!(scope.kind, ScopeKind::Module) {
return None;
}
if is_mixed_case(name) {
if helpers::is_mixed_case(name) {
return Some(Check::new(
CheckKind::MixedCaseVariableInGlobalScope(name.to_string()),
Range::from_located(expr),
@@ -241,7 +229,11 @@ pub fn camelcase_imported_as_acronym(
name: &str,
asname: &str,
) -> Option<Check> {
if is_camelcase(name) && is_upper(asname) && is_acronym(name, asname) {
if helpers::is_camelcase(name)
&& !helpers::is_lower(asname)
&& helpers::is_upper(asname)
&& helpers::is_acronym(name, asname)
{
return Some(Check::new(
CheckKind::CamelcaseImportedAsAcronym(name.to_string(), asname.to_string()),
Range::from_located(import_from),
@@ -272,101 +264,3 @@ pub fn error_suffix_on_exception_name(
}
None
}
fn is_lower(s: &str) -> bool {
let mut cased = false;
for c in s.chars() {
if c.is_uppercase() {
return false;
} else if !cased && c.is_lowercase() {
cased = true;
}
}
cased
}
fn is_upper(s: &str) -> bool {
let mut cased = false;
for c in s.chars() {
if c.is_lowercase() {
return false;
} else if (!cased) && c.is_uppercase() {
cased = true;
}
}
cased
}
fn is_camelcase(name: &str) -> bool {
!is_lower(name) && !is_upper(name) && !name.contains('_')
}
fn is_mixed_case(name: &str) -> bool {
!is_lower(name)
&& name
.strip_prefix('_')
.unwrap_or(name)
.chars()
.next()
.map_or_else(|| false, |c| c.is_lowercase())
}
fn is_acronym(name: &str, asname: &str) -> bool {
name.chars().filter(|c| c.is_uppercase()).join("") == asname
}
#[cfg(test)]
mod tests {
use super::{is_acronym, is_camelcase, is_lower, is_mixed_case, is_upper};
#[test]
fn test_is_lower() -> () {
assert!(is_lower("abc"));
assert!(is_lower("a_b_c"));
assert!(is_lower("a2c"));
assert!(!is_lower("aBc"));
assert!(!is_lower("ABC"));
assert!(!is_lower(""));
assert!(!is_lower("_"));
}
#[test]
fn test_is_upper() -> () {
assert!(is_upper("ABC"));
assert!(is_upper("A_B_C"));
assert!(is_upper("A2C"));
assert!(!is_upper("aBc"));
assert!(!is_upper("abc"));
assert!(!is_upper(""));
assert!(!is_upper("_"));
}
#[test]
fn test_is_camelcase() -> () {
assert!(is_camelcase("Camel"));
assert!(is_camelcase("CamelCase"));
assert!(!is_camelcase("camel"));
assert!(!is_camelcase("camel_case"));
assert!(!is_camelcase("CAMEL"));
assert!(!is_camelcase("CAMEL_CASE"));
}
#[test]
fn test_is_mixed_case() -> () {
assert!(is_mixed_case("mixedCase"));
assert!(is_mixed_case("mixed_Case"));
assert!(is_mixed_case("_mixed_Case"));
assert!(!is_mixed_case("mixed_case"));
assert!(!is_mixed_case("MIXED_CASE"));
assert!(!is_mixed_case(""));
assert!(!is_mixed_case("_"));
}
#[test]
fn test_is_acronym() -> () {
assert!(is_acronym("AB", "AB"));
assert!(is_acronym("AbcDef", "AD"));
assert!(!is_acronym("AbcDef", "Ad"));
assert!(!is_acronym("AbcDef", "AB"));
}
}

160
src/pep8_naming/helpers.rs Normal file
View File

@@ -0,0 +1,160 @@
use itertools::Itertools;
use rustpython_ast::{Expr, ExprKind};
use crate::ast::helpers::match_name_or_attr;
use crate::ast::types::{Scope, ScopeKind};
use crate::pep8_naming::settings::Settings;
const CLASS_METHODS: [&str; 3] = ["__new__", "__init_subclass__", "__class_getitem__"];
const METACLASS_BASES: [&str; 2] = ["type", "ABCMeta"];
pub enum FunctionType {
Function,
Method,
ClassMethod,
StaticMethod,
}
/// Classify a function based on its scope, name, and decorators.
pub fn function_type(
scope: &Scope,
name: &str,
decorator_list: &[Expr],
settings: &Settings,
) -> FunctionType {
if let ScopeKind::Class(scope) = &scope.kind {
// Special-case class method, like `__new__`.
if CLASS_METHODS.contains(&name)
// The class itself extends a known metaclass, so all methods are class methods.
|| scope.bases.iter().any(|expr| {
METACLASS_BASES
.iter()
.any(|target| match_name_or_attr(expr, target))
})
// The method is decorated with a class method decorator (like `@classmethod`).
|| decorator_list.iter().any(|expr| {
if let ExprKind::Name { id, .. } = &expr.node {
settings.classmethod_decorators.contains(id)
} else {
false
}
}) {
FunctionType::ClassMethod
} else if decorator_list.iter().any(|expr| {
if let ExprKind::Name { id, .. } = &expr.node {
settings.staticmethod_decorators.contains(id)
} else {
false
}
}) {
// The method is decorated with a static method decorator (like
// `@staticmethod`).
FunctionType::StaticMethod
} else {
// It's an instance method.
FunctionType::Method
}
} else {
FunctionType::Function
}
}
pub fn is_lower(s: &str) -> bool {
let mut cased = false;
for c in s.chars() {
if c.is_uppercase() {
return false;
} else if !cased && c.is_lowercase() {
cased = true;
}
}
cased
}
pub fn is_upper(s: &str) -> bool {
let mut cased = false;
for c in s.chars() {
if c.is_lowercase() {
return false;
} else if !cased && c.is_uppercase() {
cased = true;
}
}
cased
}
pub fn is_camelcase(name: &str) -> bool {
!is_lower(name) && !is_upper(name) && !name.contains('_')
}
pub fn is_mixed_case(name: &str) -> bool {
!is_lower(name)
&& name
.strip_prefix('_')
.unwrap_or(name)
.chars()
.next()
.map_or_else(|| false, |c| c.is_lowercase())
}
pub fn is_acronym(name: &str, asname: &str) -> bool {
name.chars().filter(|c| c.is_uppercase()).join("") == asname
}
#[cfg(test)]
mod tests {
use crate::pep8_naming::helpers::{
is_acronym, is_camelcase, is_lower, is_mixed_case, is_upper,
};
#[test]
fn test_is_lower() -> () {
assert!(is_lower("abc"));
assert!(is_lower("a_b_c"));
assert!(is_lower("a2c"));
assert!(!is_lower("aBc"));
assert!(!is_lower("ABC"));
assert!(!is_lower(""));
assert!(!is_lower("_"));
}
#[test]
fn test_is_upper() -> () {
assert!(is_upper("ABC"));
assert!(is_upper("A_B_C"));
assert!(is_upper("A2C"));
assert!(!is_upper("aBc"));
assert!(!is_upper("abc"));
assert!(!is_upper(""));
assert!(!is_upper("_"));
}
#[test]
fn test_is_camelcase() -> () {
assert!(is_camelcase("Camel"));
assert!(is_camelcase("CamelCase"));
assert!(!is_camelcase("camel"));
assert!(!is_camelcase("camel_case"));
assert!(!is_camelcase("CAMEL"));
assert!(!is_camelcase("CAMEL_CASE"));
}
#[test]
fn test_is_mixed_case() -> () {
assert!(is_mixed_case("mixedCase"));
assert!(is_mixed_case("mixed_Case"));
assert!(is_mixed_case("_mixed_Case"));
assert!(!is_mixed_case("mixed_case"));
assert!(!is_mixed_case("MIXED_CASE"));
assert!(!is_mixed_case(""));
assert!(!is_mixed_case("_"));
}
#[test]
fn test_is_acronym() -> () {
assert!(is_acronym("AB", "AB"));
assert!(is_acronym("AbcDef", "AD"));
assert!(!is_acronym("AbcDef", "Ad"));
assert!(!is_acronym("AbcDef", "AB"));
}
}

View File

@@ -1,2 +1,3 @@
pub mod checks;
mod helpers;
pub mod settings;

View File

@@ -277,20 +277,26 @@ pub fn invalid_escape_sequence(
let body = &text[(quote_pos + quote.len())..(text.len() - quote.len())];
if !prefix.contains('r') {
let mut col_offset = 0;
let mut row_offset = 0;
let mut in_escape = false;
let mut chars = body.chars();
let mut current = chars.next();
let mut next = chars.next();
while let (Some(current_char), Some(next_char)) = (current, next) {
// If we see an escaped backslash, avoid treating the character _after_ the
// escaped backslash as itself an escaped character.
if in_escape {
in_escape = false;
} else {
in_escape = current_char == '\\' && next_char == '\\';
if current_char == '\\' && !VALID_ESCAPE_SEQUENCES.contains(&next_char) {
for (row_offset, line) in body.lines().enumerate() {
let chars: Vec<char> = line.chars().collect();
for col_offset in 0..chars.len() {
if chars[col_offset] == '\\' {
// If the previous character was also a backslash, skip.
if col_offset > 0 && chars[col_offset - 1] == '\\' {
continue;
}
// If we're at the end of the line, skip.
if col_offset == chars.len() - 1 {
continue;
}
// If the next character is a valid escape sequence, skip.
let next_char = chars[col_offset + 1];
if VALID_ESCAPE_SEQUENCES.contains(&next_char) {
continue;
}
// Compute the location of the escape sequence by offsetting the location of the
// string token by the characters we've seen thus far.
let location = if row_offset == 0 {
@@ -311,17 +317,6 @@ pub fn invalid_escape_sequence(
))
}
}
// Track the offset from the start position as we iterate over the body.
if current_char == '\n' {
col_offset = 0;
row_offset += 1;
} else {
col_offset += 1;
}
current = next;
next = chars.next();
}
}

View File

@@ -1,10 +1,8 @@
use std::collections::BTreeSet;
use itertools::izip;
use regex::Regex;
use rustpython_parser::ast::{
Arg, Arguments, Cmpop, Constant, Excepthandler, ExcepthandlerKind, Expr, ExprKind, Stmt,
StmtKind,
Arg, Arguments, Constant, Excepthandler, ExcepthandlerKind, Expr, ExprKind, Stmt, StmtKind,
};
use crate::ast::types::{BindingKind, CheckLocator, FunctionScope, Range, Scope, ScopeKind};
@@ -166,45 +164,6 @@ pub fn repeated_keys(
checks
}
fn is_constant(expr: &Expr) -> bool {
match &expr.node {
ExprKind::Constant { .. } => true,
ExprKind::Tuple { elts, .. } => elts.iter().all(is_constant),
_ => false,
}
}
fn is_singleton(expr: &Expr) -> bool {
matches!(
expr.node,
ExprKind::Constant {
value: Constant::None | Constant::Bool(_) | Constant::Ellipsis,
..
}
)
}
fn is_constant_non_singleton(expr: &Expr) -> bool {
is_constant(expr) && !is_singleton(expr)
}
/// F632
pub fn is_literal(left: &Expr, ops: &[Cmpop], comparators: &[Expr], location: Range) -> Vec<Check> {
let mut checks: Vec<Check> = vec![];
let mut left = left;
for (op, right) in izip!(ops, comparators) {
if matches!(op, Cmpop::Is | Cmpop::IsNot)
&& (is_constant_non_singleton(left) || is_constant_non_singleton(right))
{
checks.push(Check::new(CheckKind::IsLiteral, location));
}
left = right;
}
checks
}
/// F621, F622
pub fn starred_expressions(
elts: &[Expr],

View File

@@ -1,11 +1,14 @@
use anyhow::Result;
use libcst_native::{Codegen, ImportNames, NameOrAttribute, SmallStatement, Statement};
use libcst_native::{
Codegen, CompOp, Comparison, ComparisonTarget, Expr, Expression, ImportNames, NameOrAttribute,
SmallStatement, Statement,
};
use rustpython_ast::Stmt;
use crate::ast::types::Range;
use crate::autofix::{helpers, Fix};
use crate::cst::helpers::compose_module_path;
use crate::cst::matchers::match_module;
use crate::cst::matchers::{match_expr, match_module};
use crate::source_code_locator::SourceCodeLocator;
/// Generate a Fix to remove any unused imports from an `import` statement.
@@ -138,3 +141,66 @@ pub fn remove_unused_import_froms(
))
}
}
fn match_comparison<'a, 'b>(expr: &'a mut Expr<'b>) -> Result<&'a mut Comparison<'b>> {
if let Expression::Comparison(comparison) = &mut expr.value {
Ok(comparison)
} else {
Err(anyhow::anyhow!(
"Expected node to be: Expression::Comparison"
))
}
}
/// Generate a Fix to replace invalid is/is not comparisons with equal/not equal
pub fn fix_invalid_literal_comparison(locator: &SourceCodeLocator, location: Range) -> Result<Fix> {
let module_text = locator.slice_source_code_range(&location);
let mut tree = match_module(&module_text)?;
let mut expr = match_expr(&mut tree)?;
let cmp = match_comparison(expr)?;
let target = cmp
.comparisons
.get(0)
.ok_or_else(|| anyhow::anyhow!("Expected one ComparisonTarget"))?;
let new_operator = match &target.operator {
CompOp::Is {
whitespace_before: b,
whitespace_after: a,
} => Ok(CompOp::Equal {
whitespace_before: b.clone(),
whitespace_after: a.clone(),
}),
CompOp::IsNot {
whitespace_before: b,
whitespace_after: a,
whitespace_between: _,
} => Ok(CompOp::NotEqual {
whitespace_before: b.clone(),
whitespace_after: a.clone(),
}),
op => Err(anyhow::anyhow!(
"Unexpected operator: {:?}. Expected Is or IsNot.",
op
)),
}?;
expr.value = Expression::Comparison(Box::new(Comparison {
left: cmp.left.clone(),
comparisons: vec![ComparisonTarget {
operator: new_operator,
comparator: target.comparator.clone(),
}],
lpar: cmp.lpar.clone(),
rpar: cmp.rpar.clone(),
}));
let mut state = Default::default();
tree.codegen(&mut state);
Ok(Fix::replacement(
state.to_string(),
location.location,
location.end_location,
))
}

View File

@@ -0,0 +1,62 @@
use itertools::izip;
use log::error;
use rustpython_ast::{Cmpop, Constant, Expr, ExprKind};
use crate::ast::types::Range;
use crate::check_ast::Checker;
use crate::checks::{Check, CheckKind};
use crate::pyflakes::fixes::fix_invalid_literal_comparison;
fn is_singleton(expr: &Expr) -> bool {
matches!(
expr.node,
ExprKind::Constant {
value: Constant::None | Constant::Bool(_) | Constant::Ellipsis,
..
}
)
}
fn is_constant(expr: &Expr) -> bool {
match &expr.node {
ExprKind::Constant { .. } => true,
ExprKind::Tuple { elts, .. } => elts.iter().all(is_constant),
_ => false,
}
}
fn is_constant_non_singleton(expr: &Expr) -> bool {
is_constant(expr) && !is_singleton(expr)
}
/// F632
pub fn invalid_literal_comparison(
checker: &mut Checker,
left: &Expr,
ops: &[Cmpop],
comparators: &[Expr],
location: Range,
) {
let mut left = left;
for (op, right) in izip!(ops, comparators) {
if matches!(op, Cmpop::Is | Cmpop::IsNot)
&& (is_constant_non_singleton(left) || is_constant_non_singleton(right))
{
let mut check = Check::new(CheckKind::IsLiteral, location);
if checker.patch() {
match fix_invalid_literal_comparison(
checker.locator,
Range {
location: left.location,
end_location: right.end_location.unwrap(),
},
) {
Ok(fix) => check.amend(fix),
Err(e) => error!("Failed to fix invalid comparison: {}", e),
}
}
checker.add_check(check);
}
left = right;
}
}

View File

@@ -1,9 +1,11 @@
pub use assert_tuple::assert_tuple;
pub use if_tuple::if_tuple;
pub use invalid_literal_comparisons::invalid_literal_comparison;
pub use invalid_print_syntax::invalid_print_syntax;
pub use raise_not_implemented::raise_not_implemented;
mod assert_tuple;
mod if_tuple;
mod invalid_literal_comparisons;
mod invalid_print_syntax;
mod raise_not_implemented;

View File

@@ -9,7 +9,7 @@ use crate::checks::CheckKind;
use crate::source_code_locator::SourceCodeLocator;
use crate::Check;
/// See: https://github.com/microsoft/vscode/blob/095ddabc52b82498ee7f718a34f9dd11d59099a8/src/vs/base/common/strings.ts#L1195
/// See: https://github.com/microsoft/vscode/blob/095ddabc52b82498ee7f718a34f9dd11d59099a8/src/vs/base/common/strings.ts#L1094
static CONFUSABLES: Lazy<BTreeMap<u32, u32>> = Lazy::new(|| {
BTreeMap::from([
(8232, 32),
@@ -1600,6 +1600,7 @@ pub fn ambiguous_unicode_character(
locator: &SourceCodeLocator,
start: &Location,
end: &Location,
is_docstring: bool,
fix: bool,
) -> Vec<Check> {
let mut checks = vec![];
@@ -1622,7 +1623,11 @@ pub fn ambiguous_unicode_character(
};
let end_location = Location::new(location.row(), location.column() + 1);
let mut check = Check::new(
CheckKind::AmbiguousUnicodeCharacter(current_char, representant),
if is_docstring {
CheckKind::AmbiguousUnicodeCharacterDocstring(current_char, representant)
} else {
CheckKind::AmbiguousUnicodeCharacterString(current_char, representant)
},
Range {
location,
end_location,

View File

@@ -0,0 +1,13 @@
---
source: src/linter.rs
expression: checks
---
- kind: AssignmentToOsEnviron
location:
row: 9
column: 0
end_location:
row: 9
column: 10
fix: ~

View File

@@ -0,0 +1,125 @@
---
source: src/linter.rs
expression: checks
---
- kind: FunctionCallArgumentDefault
location:
row: 85
column: 60
end_location:
row: 85
column: 68
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 89
column: 63
end_location:
row: 89
column: 71
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 93
column: 59
end_location:
row: 93
column: 67
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 109
column: 38
end_location:
row: 109
column: 49
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 113
column: 11
end_location:
row: 113
column: 28
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 113
column: 31
end_location:
row: 113
column: 51
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 117
column: 29
end_location:
row: 117
column: 44
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 155
column: 33
end_location:
row: 155
column: 47
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 160
column: 29
end_location:
row: 160
column: 37
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 164
column: 44
end_location:
row: 164
column: 57
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 170
column: 20
end_location:
row: 170
column: 28
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 170
column: 30
end_location:
row: 170
column: 47
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 176
column: 21
end_location:
row: 176
column: 62
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 181
column: 18
end_location:
row: 181
column: 59
fix: ~
- kind: FunctionCallArgumentDefault
location:
row: 181
column: 36
end_location:
row: 181
column: 53
fix: ~

View File

@@ -0,0 +1,37 @@
---
source: src/linter.rs
expression: checks
---
- kind: UselessComparison
location:
row: 3
column: 0
end_location:
row: 3
column: 1
fix: ~
- kind: UselessComparison
location:
row: 7
column: 0
end_location:
row: 7
column: 1
fix: ~
- kind: UselessComparison
location:
row: 17
column: 4
end_location:
row: 17
column: 5
fix: ~
- kind: UselessComparison
location:
row: 24
column: 4
end_location:
row: 24
column: 5
fix: ~

View File

@@ -0,0 +1,29 @@
---
source: src/linter.rs
expression: checks
---
- kind: CannotRaiseLiteral
location:
row: 6
column: 6
end_location:
row: 6
column: 11
fix: ~
- kind: CannotRaiseLiteral
location:
row: 7
column: 6
end_location:
row: 7
column: 7
fix: ~
- kind: CannotRaiseLiteral
location:
row: 8
column: 6
end_location:
row: 8
column: 14
fix: ~

View File

@@ -13,4 +13,37 @@ expression: checks
row: 5
column: 123
fix: ~
- kind:
LineTooLong:
- 127
- 88
location:
row: 25
column: 0
end_location:
row: 25
column: 127
fix: ~
- kind:
LineTooLong:
- 132
- 88
location:
row: 40
column: 0
end_location:
row: 40
column: 132
fix: ~
- kind:
LineTooLong:
- 105
- 88
location:
row: 43
column: 0
end_location:
row: 43
column: 105
fix: ~

View File

@@ -9,7 +9,16 @@ expression: checks
end_location:
row: 1
column: 13
fix: ~
fix:
patch:
content: "x == \"abc\""
location:
row: 1
column: 3
end_location:
row: 1
column: 13
applied: false
- kind: IsLiteral
location:
row: 4
@@ -17,5 +26,31 @@ expression: checks
end_location:
row: 4
column: 15
fix: ~
fix:
patch:
content: 123 != y
location:
row: 4
column: 3
end_location:
row: 4
column: 15
applied: false
- kind: IsLiteral
location:
row: 7
column: 9
end_location:
row: 7
column: 17
fix:
patch:
content: "\"123\" == x"
location:
row: 7
column: 3
end_location:
row: 7
column: 13
applied: false

View File

@@ -6,18 +6,18 @@ expression: checks
InvalidArgumentName: A
location:
row: 1
column: 12
column: 15
end_location:
row: 1
column: 13
column: 16
fix: ~
- kind:
InvalidArgumentName: A
location:
row: 6
column: 24
column: 27
end_location:
row: 6
column: 25
column: 28
fix: ~

View File

@@ -4,10 +4,18 @@ expression: checks
---
- kind: InvalidFirstArgumentNameForClassMethod
location:
row: 3
column: 25
row: 30
column: 26
end_location:
row: 3
column: 29
row: 30
column: 30
fix: ~
- kind: InvalidFirstArgumentNameForClassMethod
location:
row: 35
column: 19
end_location:
row: 35
column: 23
fix: ~

View File

@@ -0,0 +1,25 @@
---
source: src/linter.rs
expression: checks
---
- kind:
AmbiguousUnicodeCharacterString:
- 𝐁
- B
location:
row: 1
column: 5
end_location:
row: 1
column: 6
fix:
patch:
content: B
location:
row: 1
column: 5
end_location:
row: 1
column: 6
applied: false

View File

@@ -0,0 +1,25 @@
---
source: src/linter.rs
expression: checks
---
- kind:
AmbiguousUnicodeCharacterDocstring:
-
- )
location:
row: 5
column: 53
end_location:
row: 5
column: 54
fix:
patch:
content: )
location:
row: 5
column: 53
end_location:
row: 5
column: 54
applied: false

View File

@@ -0,0 +1,22 @@
---
source: src/linter.rs
expression: checks
---
- kind: PEP3120UnnecessaryCodingComment
location:
row: 1
column: 0
end_location:
row: 1
column: 14
fix:
patch:
content: ""
location:
row: 1
column: 0
end_location:
row: 1
column: 14
applied: false

View File

@@ -0,0 +1,22 @@
---
source: src/linter.rs
expression: checks
---
- kind: PEP3120UnnecessaryCodingComment
location:
row: 2
column: 0
end_location:
row: 2
column: 24
fix:
patch:
content: ""
location:
row: 2
column: 0
end_location:
row: 2
column: 24
applied: false

View File

@@ -0,0 +1,6 @@
---
source: src/linter.rs
expression: checks
---
[]

View File

@@ -0,0 +1,6 @@
---
source: src/linter.rs
expression: checks
---
[]

View File

@@ -0,0 +1,41 @@
---
source: src/linter.rs
expression: checks
---
- kind:
InvalidEscapeSequence: "."
location:
row: 2
column: 9
end_location:
row: 2
column: 11
fix: ~
- kind:
InvalidEscapeSequence: "."
location:
row: 6
column: 0
end_location:
row: 6
column: 2
fix: ~
- kind:
InvalidEscapeSequence: _
location:
row: 11
column: 5
end_location:
row: 11
column: 7
fix: ~
- kind:
InvalidEscapeSequence: _
location:
row: 18
column: 5
end_location:
row: 18
column: 7
fix: ~

View File

@@ -1,45 +0,0 @@
---
source: src/linter.rs
expression: checks
---
- kind:
AmbiguousUnicodeCharacter:
- 𝐁
- B
location:
row: 1
column: 5
end_location:
row: 1
column: 6
fix:
patch:
content: B
location:
row: 1
column: 5
end_location:
row: 1
column: 6
applied: false
- kind:
AmbiguousUnicodeCharacter:
-
- )
location:
row: 5
column: 53
end_location:
row: 5
column: 54
fix:
patch:
content: )
location:
row: 5
column: 53
end_location:
row: 5
column: 54
applied: false