Compare commits

..

3 Commits

Author SHA1 Message Date
Micha Reiser
d1a76d0011 POC of assert formatting 2023-09-19 09:48:31 +02:00
Micha Reiser
86bc5394f1 Discard changes to crates/ruff_python_formatter/src/lib.rs 2023-09-19 09:48:30 +02:00
Micha Reiser
eea082462c Potential fix for overlong parenthesized content 2023-09-19 08:42:00 +02:00
52 changed files with 715 additions and 779 deletions

255
Cargo.lock generated
View File

@@ -172,12 +172,6 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
[[package]]
name = "base64"
version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8"
[[package]]
name = "base64"
version = "0.21.3"
@@ -220,15 +214,6 @@ version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "bstr"
version = "1.6.2"
@@ -328,9 +313,9 @@ dependencies = [
[[package]]
name = "clap"
version = "4.4.4"
version = "4.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1d7b8d5ec32af0fadc644bf1fd509a688c2103b185644bb1e29d164e0703136"
checksum = "84ed82781cea27b43c9b106a979fe450a13a31aab0500595fb3fc06616de08e6"
dependencies = [
"clap_builder",
"clap_derive",
@@ -338,9 +323,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.4.4"
version = "4.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5179bb514e4d7c2051749d8fcefa2ed6d06a9f4e6d69faf3805f5d80b8cf8d56"
checksum = "2bb9faaa7c2ef94b2743a21f5a29e6f0010dff4caa69ac8e9d6cf8b6fa74da08"
dependencies = [
"anstream",
"anstyle",
@@ -398,7 +383,7 @@ dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -510,15 +495,6 @@ version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636"
[[package]]
name = "cpufeatures"
version = "0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1"
dependencies = [
"libc",
]
[[package]]
name = "crc32fast"
version = "1.3.2"
@@ -540,7 +516,7 @@ dependencies = [
"clap",
"criterion-plot",
"is-terminal",
"itertools 0.10.5",
"itertools",
"num-traits",
"once_cell",
"oorandom",
@@ -559,7 +535,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
dependencies = [
"cast",
"itertools 0.10.5",
"itertools",
]
[[package]]
@@ -611,16 +587,6 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7"
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "darling"
version = "0.20.3"
@@ -642,7 +608,7 @@ dependencies = [
"proc-macro2",
"quote",
"strsim",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -653,7 +619,7 @@ checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5"
dependencies = [
"darling_core",
"quote",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -668,16 +634,6 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6184e33543162437515c2e2b48714794e37845ec9851711914eec9d308f6ebe8"
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "dirs"
version = "4.0.0"
@@ -764,18 +720,6 @@ version = "1.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
[[package]]
name = "embed-doc-image"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af36f591236d9d822425cb6896595658fa558fcebf5ee8accac1d4b92c47166e"
dependencies = [
"base64 0.13.1",
"proc-macro2",
"quote",
"syn 1.0.109",
]
[[package]]
name = "ena"
version = "0.14.2"
@@ -872,7 +816,7 @@ dependencies = [
"clap",
"colored",
"configparser",
"itertools 0.11.0",
"itertools",
"log",
"once_cell",
"pep440_rs",
@@ -928,16 +872,6 @@ dependencies = [
"libc",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.2.10"
@@ -1186,7 +1120,7 @@ dependencies = [
"pmutil 0.6.1",
"proc-macro2",
"quote",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -1209,15 +1143,6 @@ dependencies = [
"either",
]
[[package]]
name = "itertools"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1c173a5686ce8bfa551b3563d0c2170bf24ca44da99c7ca4bfdab5418c3fe57"
dependencies = [
"either",
]
[[package]]
name = "itoa"
version = "1.0.9"
@@ -1233,15 +1158,6 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "keccak"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f6d5ed8676d904364de097082f4e7d240b571b67989ced0240f08b7f966f940"
dependencies = [
"cpufeatures",
]
[[package]]
name = "kqueue"
version = "1.0.8"
@@ -1273,7 +1189,7 @@ dependencies = [
"diff",
"ena",
"is-terminal",
"itertools 0.10.5",
"itertools",
"lalrpop-util",
"petgraph",
"regex",
@@ -1395,41 +1311,6 @@ version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
[[package]]
name = "malachite"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9fa232412d927f518cd873073911726943f432bac1bbc1288316d240635dc51"
dependencies = [
"malachite-base",
"malachite-nz",
]
[[package]]
name = "malachite-base"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "606a61b226dc58b8b283399b74754460433c193b193f26eaaad92f7966abd72b"
dependencies = [
"getrandom",
"itertools 0.11.0",
"rand",
"rand_chacha",
"ryu",
"sha3",
]
[[package]]
name = "malachite-nz"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "863d06218c83cc2269c425186cc15094d6284b1333a1184d0890aecfddb8916b"
dependencies = [
"embed-doc-image",
"itertools 0.11.0",
"malachite-base",
]
[[package]]
name = "matchers"
version = "0.1.0"
@@ -1564,6 +1445,27 @@ dependencies = [
"winapi",
]
[[package]]
name = "num-bigint"
version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "608e7659b5c3d7cba262d894801b9ec9d00de989e8a82bd4bef91d08da45cdc0"
dependencies = [
"autocfg",
"num-integer",
"num-traits",
]
[[package]]
name = "num-integer"
version = "0.1.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9"
dependencies = [
"autocfg",
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.16"
@@ -1818,7 +1720,7 @@ checksum = "52a40bc70c2c58040d2d8b167ba9a5ff59fc9dab7ad44771cfde3dcfde7a09c6"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -1847,7 +1749,7 @@ checksum = "09963355b9f467184c04017ced4a2ba2d75cbcb4e7462690d388233253d4b1a9"
dependencies = [
"anstyle",
"difflib",
"itertools 0.10.5",
"itertools",
"predicates-core",
]
@@ -2133,12 +2035,12 @@ dependencies = [
"imperative",
"insta",
"is-macro",
"itertools 0.11.0",
"itertools",
"libcst",
"log",
"malachite",
"memchr",
"natord",
"num-bigint",
"num-traits",
"once_cell",
"path-absolutize",
@@ -2210,7 +2112,7 @@ dependencies = [
"filetime",
"glob",
"globset",
"itertools 0.11.0",
"itertools",
"regex",
"ruff_macros",
]
@@ -2237,7 +2139,7 @@ dependencies = [
"insta",
"insta-cmd",
"is-macro",
"itertools 0.11.0",
"itertools",
"itoa",
"log",
"mimalloc",
@@ -2284,7 +2186,7 @@ dependencies = [
"imara-diff",
"indicatif",
"indoc",
"itertools 0.11.0",
"itertools",
"libcst",
"once_cell",
"pretty_assertions",
@@ -2353,11 +2255,11 @@ dependencies = [
name = "ruff_macros"
version = "0.0.0"
dependencies = [
"itertools 0.11.0",
"itertools",
"proc-macro2",
"quote",
"ruff_python_trivia",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -2366,7 +2268,7 @@ version = "0.0.0"
dependencies = [
"anyhow",
"insta",
"itertools 0.11.0",
"itertools",
"once_cell",
"ruff_diagnostics",
"ruff_source_file",
@@ -2386,9 +2288,10 @@ dependencies = [
"bitflags 2.4.0",
"insta",
"is-macro",
"itertools 0.11.0",
"malachite",
"itertools",
"memchr",
"num-bigint",
"num-traits",
"once_cell",
"ruff_python_parser",
"ruff_python_trivia",
@@ -2420,7 +2323,7 @@ dependencies = [
"clap",
"countme",
"insta",
"itertools 0.11.0",
"itertools",
"memchr",
"once_cell",
"ruff_formatter",
@@ -2445,7 +2348,7 @@ dependencies = [
name = "ruff_python_index"
version = "0.0.0"
dependencies = [
"itertools 0.11.0",
"itertools",
"ruff_python_ast",
"ruff_python_parser",
"ruff_python_trivia",
@@ -2460,7 +2363,7 @@ dependencies = [
"bitflags 2.4.0",
"hexf-parse",
"is-macro",
"itertools 0.11.0",
"itertools",
"lexical-parse-float",
"num-traits",
"rand",
@@ -2474,10 +2377,11 @@ dependencies = [
"anyhow",
"insta",
"is-macro",
"itertools 0.11.0",
"itertools",
"lalrpop",
"lalrpop-util",
"malachite",
"num-bigint",
"num-traits",
"ruff_python_ast",
"ruff_text_size",
"rustc-hash",
@@ -2503,6 +2407,7 @@ version = "0.0.0"
dependencies = [
"bitflags 2.4.0",
"is-macro",
"num-traits",
"ruff_index",
"ruff_python_ast",
"ruff_python_parser",
@@ -2525,7 +2430,7 @@ name = "ruff_python_trivia"
version = "0.0.0"
dependencies = [
"insta",
"itertools 0.11.0",
"itertools",
"ruff_python_ast",
"ruff_python_parser",
"ruff_source_file",
@@ -2606,7 +2511,7 @@ dependencies = [
"glob",
"globset",
"ignore",
"itertools 0.11.0",
"itertools",
"log",
"path-absolutize",
"pep440_rs",
@@ -2707,9 +2612,9 @@ dependencies = [
[[package]]
name = "schemars"
version = "0.8.15"
version = "0.8.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f7b0ce13155372a76ee2e1c5ffba1fe61ede73fbea5630d61eee6fac4929c0c"
checksum = "763f8cd0d4c71ed8389c90cb8100cba87e763bd01a8e614d4f0af97bcd50a161"
dependencies = [
"dyn-clone",
"schemars_derive",
@@ -2719,9 +2624,9 @@ dependencies = [
[[package]]
name = "schemars_derive"
version = "0.8.15"
version = "0.8.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e85e2a16b12bdb763244c69ab79363d71db2b4b918a2def53f80b02e0574b13c"
checksum = "ec0f696e21e10fa546b7ffb1c9672c6de8fbc7a81acf59524386d8639bf12737"
dependencies = [
"proc-macro2",
"quote",
@@ -2785,7 +2690,7 @@ checksum = "4eca7ac642d82aa35b60049a6eccb4be6be75e599bd2e9adb5f875a737654af2"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -2847,17 +2752,7 @@ dependencies = [
"darling",
"proc-macro2",
"quote",
"syn 2.0.37",
]
[[package]]
name = "sha3"
version = "0.10.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60"
dependencies = [
"digest",
"keccak",
"syn 2.0.33",
]
[[package]]
@@ -2952,7 +2847,7 @@ dependencies = [
"proc-macro2",
"quote",
"rustversion",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -2968,9 +2863,9 @@ dependencies = [
[[package]]
name = "syn"
version = "2.0.37"
version = "2.0.33"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7303ef2c05cd654186cb250d29049a24840ca25d2747c25c0381c8d9e2f582e8"
checksum = "9caece70c63bfba29ec2fed841a09851b14a235c60010fa4de58089b6c025668"
dependencies = [
"proc-macro2",
"quote",
@@ -3057,7 +2952,7 @@ dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -3069,7 +2964,7 @@ dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
"syn 2.0.37",
"syn 2.0.33",
"test-case-core",
]
@@ -3090,7 +2985,7 @@ checksum = "49922ecae66cc8a249b77e68d1d0623c1b2c514f0060c27cdc68bd62a1219d35"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -3212,7 +3107,7 @@ checksum = "5f4f31f56159e98206da9efd823404b79b6ef3143b4a7ab76e67b1751b25a4ab"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -3272,12 +3167,6 @@ version = "2.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a"
[[package]]
name = "typenum"
version = "1.17.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42ff0bf0c66b8238c6f3b578df37d0b7848e55df8577b3f74f92a69acceeb825"
[[package]]
name = "unic-char-property"
version = "0.9.0"
@@ -3373,7 +3262,7 @@ version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b11c96ac7ee530603dcdf68ed1557050f374ce55a5a07193ebf8cbc9f8927e9"
dependencies = [
"base64 0.21.3",
"base64",
"flate2",
"log",
"once_cell",
@@ -3421,7 +3310,7 @@ checksum = "f7e1ba1f333bd65ce3c9f27de592fcbc256dafe3af2717f56d7c87761fbaccf4"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.37",
"syn 2.0.33",
]
[[package]]
@@ -3515,7 +3404,7 @@ dependencies = [
"once_cell",
"proc-macro2",
"quote",
"syn 2.0.37",
"syn 2.0.33",
"wasm-bindgen-shared",
]
@@ -3549,7 +3438,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.37",
"syn 2.0.33",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]

View File

@@ -15,7 +15,7 @@ license = "MIT"
anyhow = { version = "1.0.69" }
bitflags = { version = "2.3.1" }
chrono = { version = "0.4.31", default-features = false, features = ["clock"] }
clap = { version = "4.4.4", features = ["derive"] }
clap = { version = "4.4.3", features = ["derive"] }
colored = { version = "2.0.0" }
filetime = { version = "0.2.20" }
glob = { version = "0.3.1" }
@@ -23,10 +23,10 @@ globset = { version = "0.4.10" }
ignore = { version = "0.4.20" }
insta = { version = "1.31.0", feature = ["filters", "glob"] }
is-macro = { version = "0.3.0" }
itertools = { version = "0.11.0" }
itertools = { version = "0.10.5" }
log = { version = "0.4.17" }
malachite = { version = "0.4.0", default-features = false, features = ["naturals_and_integers"] }
memchr = "2.6.3"
num-bigint = { version = "0.4.3" }
num-traits = { version = "0.2.15" }
once_cell = { version = "1.17.1" }
path-absolutize = { version = "3.1.1" }
@@ -34,7 +34,7 @@ proc-macro2 = { version = "1.0.67" }
quote = { version = "1.0.23" }
regex = { version = "1.9.5" }
rustc-hash = { version = "1.1.0" }
schemars = { version = "0.8.15" }
schemars = { version = "0.8.12" }
serde = { version = "1.0.152", features = ["derive"] }
serde_json = { version = "1.0.107" }
shellexpand = { version = "3.0.0" }
@@ -43,7 +43,7 @@ smallvec = { version = "1.10.0" }
static_assertions = "1.1.0"
strum = { version = "0.25.0", features = ["strum_macros"] }
strum_macros = { version = "0.25.2" }
syn = { version = "2.0.37" }
syn = { version = "2.0.33" }
test-case = { version = "3.2.1" }
thiserror = { version = "1.0.48" }
toml = { version = "0.7.8" }

View File

@@ -45,9 +45,9 @@ is-macro = { workspace = true }
itertools = { workspace = true }
libcst = { workspace = true }
log = { workspace = true }
malachite = { workspace = true }
memchr = { workspace = true }
natord = { version = "1.0.9" }
num-bigint = { workspace = true }
num-traits = { workspace = true }
once_cell = { workspace = true }
path-absolutize = { workspace = true, features = [

View File

@@ -1,9 +0,0 @@
# formfeed indent
# https://github.com/astral-sh/ruff/issues/7455#issuecomment-1722458825
# This is technically a stylist bug (and has a test there), but it surfaced in B006
class FormFeedIndent:
def __init__(self, a=[]):
print(a)

View File

@@ -1,6 +1,8 @@
use num_bigint::BigInt;
use ruff_python_ast::{self as ast, CmpOp, Constant, Expr};
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, CmpOp, Constant, Expr};
use ruff_text_size::Ranged;
use crate::checkers::ast::Checker;
@@ -235,7 +237,7 @@ pub(crate) fn compare(checker: &mut Checker, left: &Expr, ops: &[CmpOp], compara
..
}) = slice.as_ref()
{
if *i == 0 {
if *i == BigInt::from(0) {
if let (
[CmpOp::Eq | CmpOp::NotEq],
[Expr::Constant(ast::ExprConstant {
@@ -244,13 +246,13 @@ pub(crate) fn compare(checker: &mut Checker, left: &Expr, ops: &[CmpOp], compara
})],
) = (ops, comparators)
{
if *n == 3 && checker.enabled(Rule::SysVersionInfo0Eq3) {
if *n == BigInt::from(3) && checker.enabled(Rule::SysVersionInfo0Eq3) {
checker
.diagnostics
.push(Diagnostic::new(SysVersionInfo0Eq3, left.range()));
}
}
} else if *i == 1 {
} else if *i == BigInt::from(1) {
if let (
[CmpOp::Lt | CmpOp::LtE | CmpOp::Gt | CmpOp::GtE],
[Expr::Constant(ast::ExprConstant {

View File

@@ -1,3 +1,4 @@
use num_bigint::BigInt;
use ruff_python_ast::{self as ast, Constant, Expr};
use ruff_diagnostics::{Diagnostic, Violation};
@@ -183,11 +184,11 @@ pub(crate) fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) {
..
}) = upper.as_ref()
{
if *i == 1 && checker.enabled(Rule::SysVersionSlice1) {
if *i == BigInt::from(1) && checker.enabled(Rule::SysVersionSlice1) {
checker
.diagnostics
.push(Diagnostic::new(SysVersionSlice1, value.range()));
} else if *i == 3 && checker.enabled(Rule::SysVersionSlice3) {
} else if *i == BigInt::from(3) && checker.enabled(Rule::SysVersionSlice3) {
checker
.diagnostics
.push(Diagnostic::new(SysVersionSlice3, value.range()));
@@ -199,11 +200,11 @@ pub(crate) fn subscript(checker: &mut Checker, value: &Expr, slice: &Expr) {
value: Constant::Int(i),
..
}) => {
if *i == 2 && checker.enabled(Rule::SysVersion2) {
if *i == BigInt::from(2) && checker.enabled(Rule::SysVersion2) {
checker
.diagnostics
.push(Diagnostic::new(SysVersion2, value.range()));
} else if *i == 0 && checker.enabled(Rule::SysVersion0) {
} else if *i == BigInt::from(0) && checker.enabled(Rule::SysVersion0) {
checker
.diagnostics
.push(Diagnostic::new(SysVersion0, value.range()));

View File

@@ -1,4 +1,4 @@
use malachite::Integer;
use num_traits::ToPrimitive;
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
@@ -36,7 +36,7 @@ use crate::checkers::ast::Checker;
/// - [Common Weakness Enumeration: CWE-732](https://cwe.mitre.org/data/definitions/732.html)
#[violation]
pub struct BadFilePermissions {
mask: Integer,
mask: u16,
}
impl Violation for BadFilePermissions {
@@ -56,9 +56,7 @@ pub(crate) fn bad_file_permissions(checker: &mut Checker, call: &ast::ExprCall)
{
if let Some(mode_arg) = call.arguments.find_argument("mode", 1) {
if let Some(int_value) = int_value(mode_arg, checker.semantic()) {
if (int_value.clone() & Integer::from(WRITE_WORLD) > 0)
|| (int_value.clone() & Integer::from(EXECUTE_GROUP) > 0)
{
if (int_value & WRITE_WORLD > 0) || (int_value & EXECUTE_GROUP > 0) {
checker.diagnostics.push(Diagnostic::new(
BadFilePermissions { mask: int_value },
mode_arg.range(),
@@ -115,17 +113,13 @@ fn py_stat(call_path: &CallPath) -> Option<u16> {
}
}
fn int_value(expr: &Expr, semantic: &SemanticModel) -> Option<Integer> {
fn int_value(expr: &Expr, semantic: &SemanticModel) -> Option<u16> {
match expr {
Expr::Constant(ast::ExprConstant {
value: Constant::Int(value),
..
}) => Some(value.clone()),
Expr::Attribute(_) => semantic
.resolve_call_path(expr)
.as_ref()
.and_then(py_stat)
.map(Integer::from),
}) => value.to_u16(),
Expr::Attribute(_) => semantic.resolve_call_path(expr).as_ref().and_then(py_stat),
Expr::BinOp(ast::ExprBinOp {
left,
op,

View File

@@ -67,23 +67,26 @@ pub(crate) fn flask_debug_true(checker: &mut Checker, call: &ExprCall) {
return;
};
if let Some(binding_id) = checker.semantic().resolve_name(name) {
if let Some(Stmt::Assign(StmtAssign { value, .. })) = checker
.semantic()
.binding(binding_id)
.statement(checker.semantic())
{
if let Expr::Call(ExprCall { func, .. }) = value.as_ref() {
if checker
.semantic()
.resolve_call_path(func)
.is_some_and(|call_path| matches!(call_path.as_slice(), ["flask", "Flask"]))
{
checker
.diagnostics
.push(Diagnostic::new(FlaskDebugTrue, debug_argument.range()));
checker
.semantic()
.resolve_name(name)
.map_or((), |binding_id| {
if let Some(Stmt::Assign(StmtAssign { value, .. })) = checker
.semantic()
.binding(binding_id)
.statement(checker.semantic())
{
if let Expr::Call(ExprCall { func, .. }) = value.as_ref() {
if checker
.semantic()
.resolve_call_path(func)
.is_some_and(|call_path| matches!(call_path.as_slice(), ["flask", "Flask"]))
{
checker
.diagnostics
.push(Diagnostic::new(FlaskDebugTrue, debug_argument.range()));
}
}
}
}
};
});
}

View File

@@ -1,3 +1,5 @@
use num_traits::{One, Zero};
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Constant, Expr};
@@ -55,7 +57,7 @@ pub(crate) fn snmp_insecure_version(checker: &mut Checker, call: &ast::ExprCall)
..
}) = &keyword.value
{
if *value == 0 || *value == 1 {
if value.is_zero() || value.is_one() {
checker
.diagnostics
.push(Diagnostic::new(SnmpInsecureVersion, keyword.range()));

View File

@@ -36,7 +36,6 @@ mod tests {
#[test_case(Rule::MutableArgumentDefault, Path::new("B006_1.py"))]
#[test_case(Rule::MutableArgumentDefault, Path::new("B006_2.py"))]
#[test_case(Rule::MutableArgumentDefault, Path::new("B006_3.py"))]
#[test_case(Rule::MutableArgumentDefault, Path::new("B006_4.py"))]
#[test_case(Rule::NoExplicitStacklevel, Path::new("B028.py"))]
#[test_case(Rule::RaiseLiteral, Path::new("B016.py"))]
#[test_case(Rule::RaiseWithoutFromInsideExcept, Path::new("B904.py"))]

View File

@@ -1,24 +0,0 @@
---
source: crates/ruff/src/rules/flake8_bugbear/mod.rs
---
B006_4.py:7:26: B006 [*] Do not use mutable data structures for argument defaults
|
6 | class FormFeedIndent:
7 | def __init__(self, a=[]):
| ^^ B006
8 | print(a)
|
= help: Replace with `None`; initialize within function
Possible fix
4 4 |
5 5 |
6 6 | class FormFeedIndent:
7 |- def __init__(self, a=[]):
7 |+ def __init__(self, a=None):
8 |+ if a is None:
9 |+ a = []
8 10 | print(a)
9 11 |

View File

@@ -1,3 +1,5 @@
use num_bigint::BigInt;
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Constant, Expr, UnaryOp};
@@ -91,7 +93,7 @@ pub(crate) fn unnecessary_subscript_reversal(
else {
return;
};
if *val != 1 {
if *val != BigInt::from(1) {
return;
};
checker.diagnostics.push(Diagnostic::new(

View File

@@ -1,3 +1,5 @@
use num_bigint::BigInt;
use ruff_diagnostics::Diagnostic;
use ruff_diagnostics::{AlwaysAutofixableViolation, Fix};
use ruff_macros::{derive_message_formats, violation};
@@ -73,7 +75,7 @@ pub(crate) fn unnecessary_range_start(checker: &mut Checker, call: &ast::ExprCal
else {
return;
};
if *value != 0 {
if *value != BigInt::from(0) {
return;
};

View File

@@ -1,3 +1,5 @@
use num_bigint::BigInt;
use num_traits::{One, Zero};
use ruff_python_ast::{self as ast, CmpOp, Constant, Expr};
use ruff_diagnostics::{Diagnostic, Violation};
@@ -247,10 +249,10 @@ impl ExpectedComparator {
..
}) = upper.as_ref()
{
if *upper == 1 {
if *upper == BigInt::one() {
return Some(ExpectedComparator::MajorTuple);
}
if *upper == 2 {
if *upper == BigInt::from(2) {
return Some(ExpectedComparator::MajorMinorTuple);
}
}
@@ -258,7 +260,7 @@ impl ExpectedComparator {
Expr::Constant(ast::ExprConstant {
value: Constant::Int(n),
..
}) if *n == 0 => {
}) if n.is_zero() => {
return Some(ExpectedComparator::MajorDigit);
}
_ => (),

View File

@@ -1,3 +1,4 @@
use num_traits::One;
use ruff_python_ast::{self as ast, CmpOp, Constant, Expr};
use ruff_diagnostics::Diagnostic;
@@ -114,7 +115,7 @@ pub(crate) fn nunique_constant_series_check(
fn is_constant_one(expr: &Expr) -> bool {
match expr {
Expr::Constant(constant) => match &constant.value {
Constant::Int(int) => *int == 1,
Constant::Int(int) => int.is_one(),
_ => false,
},
_ => false,

View File

@@ -1,7 +1,8 @@
use malachite::Integer;
use std::fmt;
use std::str::FromStr;
use num_bigint::BigInt;
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Constant, Expr};
@@ -46,7 +47,7 @@ impl From<LiteralType> for Constant {
value: Vec::new(),
implicit_concatenated: false,
}),
LiteralType::Int => Constant::Int(Integer::from(0)),
LiteralType::Int => Constant::Int(BigInt::from(0)),
LiteralType::Float => Constant::Float(0.0),
LiteralType::Bool => Constant::Bool(false),
}

View File

@@ -1,6 +1,6 @@
use std::cmp::Ordering;
use malachite::Integer;
use num_bigint::{BigInt, Sign};
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
@@ -122,24 +122,31 @@ pub(crate) fn outdated_version_block(checker: &mut Checker, stmt_if: &StmtIf) {
..
}) => {
if op == &CmpOp::Eq {
if *number == 2 {
let mut diagnostic =
Diagnostic::new(OutdatedVersionBlock, branch.test.range());
if checker.patch(diagnostic.kind.rule()) {
if let Some(fix) = fix_always_false_branch(checker, stmt_if, &branch) {
diagnostic.set_fix(fix);
match bigint_to_u32(number) {
2 => {
let mut diagnostic =
Diagnostic::new(OutdatedVersionBlock, branch.test.range());
if checker.patch(diagnostic.kind.rule()) {
if let Some(fix) =
fix_always_false_branch(checker, stmt_if, &branch)
{
diagnostic.set_fix(fix);
}
}
checker.diagnostics.push(diagnostic);
}
checker.diagnostics.push(diagnostic);
} else if *number == 3 {
let mut diagnostic =
Diagnostic::new(OutdatedVersionBlock, branch.test.range());
if checker.patch(diagnostic.kind.rule()) {
if let Some(fix) = fix_always_true_branch(checker, stmt_if, &branch) {
diagnostic.set_fix(fix);
3 => {
let mut diagnostic =
Diagnostic::new(OutdatedVersionBlock, branch.test.range());
if checker.patch(diagnostic.kind.rule()) {
if let Some(fix) = fix_always_true_branch(checker, stmt_if, &branch)
{
diagnostic.set_fix(fix);
}
}
checker.diagnostics.push(diagnostic);
}
checker.diagnostics.push(diagnostic);
_ => {}
}
}
}
@@ -149,7 +156,7 @@ pub(crate) fn outdated_version_block(checker: &mut Checker, stmt_if: &StmtIf) {
}
/// Returns true if the `target_version` is always less than the [`PythonVersion`].
fn compare_version(target_version: &[Integer], py_version: PythonVersion, or_equal: bool) -> bool {
fn compare_version(target_version: &[u32], py_version: PythonVersion, or_equal: bool) -> bool {
let mut target_version_iter = target_version.iter();
let Some(if_major) = target_version_iter.next() else {
@@ -158,7 +165,7 @@ fn compare_version(target_version: &[Integer], py_version: PythonVersion, or_equ
let (py_major, py_minor) = py_version.as_tuple();
match if_major.cmp(&Integer::from(py_major)) {
match if_major.cmp(&py_major) {
Ordering::Less => true,
Ordering::Greater => false,
Ordering::Equal => {
@@ -346,16 +353,26 @@ fn fix_always_true_branch(
}
}
/// Converts a `BigInt` to a `u32`. If the number is negative, it will return 0.
fn bigint_to_u32(number: &BigInt) -> u32 {
let the_number = number.to_u32_digits();
match the_number.0 {
Sign::Minus | Sign::NoSign => 0,
Sign::Plus => *the_number.1.first().unwrap(),
}
}
/// Gets the version from the tuple
fn extract_version(elts: &[Expr]) -> Vec<Integer> {
let mut version = Vec::new();
fn extract_version(elts: &[Expr]) -> Vec<u32> {
let mut version: Vec<u32> = vec![];
for elt in elts {
if let Expr::Constant(ast::ExprConstant {
value: Constant::Int(number),
value: Constant::Int(item),
..
}) = &elt
{
version.push(number.clone());
let number = bigint_to_u32(item);
version.push(number);
} else {
return version;
}
@@ -386,13 +403,6 @@ mod tests {
or_equal: bool,
expected: bool,
) {
let version_integers = version_vec
.iter()
.map(|x| Integer::from(*x))
.collect::<Vec<_>>();
assert_eq!(
compare_version(&version_integers, version, or_equal),
expected
);
assert_eq!(compare_version(version_vec, version, or_equal), expected);
}
}

View File

@@ -1,4 +1,4 @@
use malachite::Integer;
use num_traits::ToPrimitive;
use ruff_python_ast::{self as ast, Constant, Expr, UnaryOp};
use ruff_diagnostics::{Diagnostic, Violation};
@@ -46,11 +46,11 @@ impl Violation for PairwiseOverZipped {
#[derive(Debug)]
struct SliceInfo {
arg_name: String,
slice_start: Option<Integer>,
slice_start: Option<i64>,
}
impl SliceInfo {
pub(crate) fn new(arg_name: String, slice_start: Option<Integer>) -> Self {
pub(crate) fn new(arg_name: String, slice_start: Option<i64>) -> Self {
Self {
arg_name,
slice_start,
@@ -89,12 +89,12 @@ fn match_slice_info(expr: &Expr) -> Option<SliceInfo> {
))
}
fn to_bound(expr: &Expr) -> Option<Integer> {
fn to_bound(expr: &Expr) -> Option<i64> {
match expr {
Expr::Constant(ast::ExprConstant {
value: Constant::Int(value),
..
}) => Some(value.clone()),
}) => value.to_i64(),
Expr::UnaryOp(ast::ExprUnaryOp {
op: UnaryOp::USub | UnaryOp::Invert,
operand,
@@ -105,7 +105,7 @@ fn to_bound(expr: &Expr) -> Option<Integer> {
..
}) = operand.as_ref()
{
Some(-value.clone())
value.to_i64().map(|v| -v)
} else {
None
}
@@ -155,10 +155,7 @@ pub(crate) fn pairwise_over_zipped(checker: &mut Checker, func: &Expr, args: &[E
}
// Verify that the arguments are successive.
if second_arg_info.slice_start.unwrap_or(Integer::from(0))
- first_arg_info.slice_start.unwrap_or(Integer::from(0))
!= 1
{
if second_arg_info.slice_start.unwrap_or(0) - first_arg_info.slice_start.unwrap_or(0) != 1 {
return;
}

View File

@@ -1,5 +1,7 @@
use std::borrow::Cow;
use num_traits::Zero;
use ruff_diagnostics::{AlwaysAutofixableViolation, Diagnostic, Edit, Fix};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{self as ast, Arguments, Comprehension, Constant, Expr};
@@ -113,7 +115,7 @@ fn is_head_slice(expr: &Expr) -> bool {
..
}) = expr
{
*value == 0
value.is_zero()
} else {
false
}

View File

@@ -2155,15 +2155,18 @@ impl<Context> std::fmt::Debug for IndentIfGroupBreaks<'_, Context> {
}
}
/// Changes the definition of *fits* for `content`. Instead of measuring it in *flat*, measure it with
/// all line breaks expanded and test if no line exceeds the line width. The [`FitsExpanded`] acts
/// as a expands boundary similar to best fitting, meaning that a [`hard_line_break`] will not cause the parent group to expand.
/// Changes the definition of *fits* for `content`. It measures the width of all lines and allows
/// the content inside of the [`fits_expanded`] to exceed the configured line width. The content
/// coming before and after [`fits_expanded`] must fit into the configured line width.
///
/// The [`fits_expanded`] acts as a expands boundary similar to best fitting,
/// meaning that a [`hard_line_break`] will not cause the parent group to expand.
///
/// Useful in conjunction with a group with a condition.
///
/// ## Examples
/// The outer group with the binary expression remains *flat* regardless of the array expression
/// that spans multiple lines.
/// The outer group with the binary expression remains *flat* regardless of the array expression that
/// spans multiple lines with items exceeding the configured line width.
///
/// ```
/// # use ruff_formatter::{format, format_args, LineWidth, SimpleFormatOptions, write};
@@ -2183,7 +2186,7 @@ impl<Context> std::fmt::Debug for IndentIfGroupBreaks<'_, Context> {
/// token("["),
/// soft_block_indent(&format_args![
/// token("a,"), space(), token("# comment"), expand_parent(), soft_line_break_or_space(),
/// token("b")
/// token("'A very long string that exceeds the configured line width of 80 characters but the enclosing binary expression still fits.'")
/// ]),
/// token("]")
/// ]))
@@ -2194,7 +2197,7 @@ impl<Context> std::fmt::Debug for IndentIfGroupBreaks<'_, Context> {
/// let formatted = format!(SimpleFormatContext::default(), [content])?;
///
/// assert_eq!(
/// "a + [\n\ta, # comment\n\tb\n]",
/// "a + [\n\ta, # comment\n\t'A very long string that exceeds the configured line width of 80 characters but the enclosing binary expression still fits.'\n]",
/// formatted.print()?.as_code()
/// );
/// # Ok(())

View File

@@ -11,7 +11,7 @@ use unicode_width::UnicodeWidthChar;
use crate::format_element::tag::{GroupMode, LabelId, Tag};
use crate::source_code::SourceCodeSlice;
use crate::{IndentWidth, TagKind};
use crate::{GroupId, IndentWidth, TagKind};
use ruff_text_size::TextSize;
/// Language agnostic IR for formatting source code.
@@ -34,7 +34,9 @@ pub enum FormatElement {
SourcePosition(TextSize),
/// A ASCII only Token that contains no line breaks or tab characters.
Token { text: &'static str },
Token {
text: &'static str,
},
/// An arbitrary text that can contain tabs, newlines, and unicode characters.
Text {
@@ -57,6 +59,11 @@ pub enum FormatElement {
/// deep cloning the IR when using the `best_fitting!` macro or `if_group_fits_on_line` and `if_group_breaks`.
Interned(Interned),
GroupMode {
id: GroupId,
mode: PrintMode,
},
/// A list of different variants representing the same content. The printer picks the best fitting content.
/// Line breaks inside of a best fitting don't propagate to parent groups.
BestFitting {
@@ -97,6 +104,9 @@ impl std::fmt::Debug for FormatElement {
.field("variants", variants)
.field("mode", &mode)
.finish(),
FormatElement::GroupMode { id, mode } => {
fmt.debug_tuple("GroupMode").field(id).field(mode).finish()
}
FormatElement::Interned(interned) => fmt.debug_list().entries(&**interned).finish(),
FormatElement::Tag(tag) => fmt.debug_tuple("Tag").field(tag).finish(),
FormatElement::SourcePosition(position) => {
@@ -277,6 +287,7 @@ impl FormatElements for FormatElement {
FormatElement::LineSuffixBoundary
| FormatElement::Space
| FormatElement::Tag(_)
| FormatElement::GroupMode { .. }
| FormatElement::Token { .. }
| FormatElement::SourcePosition(_) => false,
}

View File

@@ -381,6 +381,17 @@ impl Format<IrFormatContext<'_>> for &[FormatElement] {
write!(f, [token("])")])?;
}
FormatElement::GroupMode { id, mode } => write!(
f,
[
token("group_mode("),
text(&std::format!("{id:?}"), None),
token(", "),
text(&std::format!("{mode:?}"), None),
token(")")
]
)?,
FormatElement::Interned(interned) => {
let interned_elements = &mut f.context_mut().printed_interned_elements;

View File

@@ -84,11 +84,14 @@ pub enum Tag {
StartFitsExpanded(FitsExpanded),
EndFitsExpanded,
/// Marks the start and end of a best-fitting variant.
StartBestFittingEntry,
EndBestFittingEntry,
/// Parenthesizes the content but only if adding the parentheses and indenting the content
/// makes the content fit in the configured line width.
///
/// See [`crate::builders::best_fit_parenthesize`] for an in-depth explanation.
StartBestFitParenthesize {
id: Option<GroupId>,
},

View File

@@ -1,5 +1,3 @@
#![allow(dead_code)]
use crate::prelude::*;
use std::cell::OnceCell;
use std::marker::PhantomData;

View File

@@ -141,6 +141,10 @@ impl<'a> Printer<'a> {
// Handled in `Document::propagate_expands()
}
FormatElement::GroupMode { id, mode } => {
self.state.group_modes.insert_print_mode(*id, *mode);
}
FormatElement::SourcePosition(position) => {
self.state.source_position = *position;
self.push_marker();
@@ -1183,7 +1187,7 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> {
// line break should be printed as regular line break
return Ok(Fits::Yes);
}
MeasureMode::AllLines => {
MeasureMode::AllLines | MeasureMode::AllLinesAllowTextOverflow => {
// Continue measuring on the next line
self.state.line_width = 0;
self.state.pending_indent = args.indention();
@@ -1219,6 +1223,10 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> {
}
}
FormatElement::GroupMode { id, mode } => {
self.group_modes_mut().insert_print_mode(*id, *mode);
}
FormatElement::ExpandParent => {
if self.must_be_flat {
return Ok(Fits::No);
@@ -1354,9 +1362,11 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> {
}
FormatElement::Tag(StartLineSuffix { reserved_width }) => {
self.state.line_width += reserved_width;
if self.state.line_width > self.options().line_width.into() {
return Ok(Fits::No);
if *reserved_width > 0 {
self.state.line_width += reserved_width;
if self.state.line_width > self.options().line_width.into() {
return Ok(Fits::No);
}
}
self.queue.skip_content(TagKind::LineSuffix);
self.state.has_line_suffix = true;
@@ -1370,32 +1380,42 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> {
condition,
propagate_expand,
})) => {
let condition_met = match condition {
Some(condition) => {
let group_mode = match condition.group_id {
Some(group_id) => self.group_modes().get_print_mode(group_id)?,
None => args.mode(),
match args.mode() {
PrintMode::Expanded => {
// As usual, nothing to measure
self.stack.push(TagKind::FitsExpanded, args);
}
PrintMode::Flat => {
let condition_met = match condition {
Some(condition) => {
let group_mode = match condition.group_id {
Some(group_id) => {
self.group_modes().get_print_mode(group_id)?
}
None => args.mode(),
};
condition.mode == group_mode
}
None => true,
};
condition.mode == group_mode
}
None => true,
};
if condition_met {
// Measure in fully expanded mode and allow overflows
self.stack.push(
TagKind::FitsExpanded,
args.with_measure_mode(MeasureMode::AllLinesAllowTextOverflow)
.with_print_mode(PrintMode::Expanded),
);
} else {
if propagate_expand.get() {
return Ok(Fits::No);
}
if condition_met {
// Measure in fully expanded mode.
self.stack.push(
TagKind::FitsExpanded,
args.with_print_mode(PrintMode::Expanded)
.with_measure_mode(MeasureMode::AllLines),
);
} else {
if propagate_expand.get() && args.mode().is_flat() {
return Ok(Fits::No);
// As usual
self.stack.push(TagKind::FitsExpanded, args);
}
}
// As usual
self.stack.push(TagKind::FitsExpanded, args);
}
}
@@ -1482,7 +1502,8 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> {
}
match args.measure_mode() {
MeasureMode::FirstLine => return Fits::Yes,
MeasureMode::AllLines => {
MeasureMode::AllLines
| MeasureMode::AllLinesAllowTextOverflow => {
self.state.line_width = 0;
continue;
}
@@ -1498,7 +1519,9 @@ impl<'a, 'print> FitsMeasurer<'a, 'print> {
}
}
if self.state.line_width > self.options().line_width.into() {
if self.state.line_width > self.options().line_width.into()
&& !args.measure_mode().allows_text_overflow()
{
return Fits::No;
}
@@ -1601,6 +1624,17 @@ enum MeasureMode {
/// The content only fits if none of the lines exceed the print width. Lines are terminated by either
/// a hard line break or a soft line break in [`PrintMode::Expanded`].
AllLines,
/// Measures all lines and allows lines to exceed the configured line width. Useful when it only matters
/// whether the content *before* and *after* fits.
AllLinesAllowTextOverflow,
}
impl MeasureMode {
/// Returns `true` if this mode allows text exceeding the configured line width.
const fn allows_text_overflow(self) -> bool {
matches!(self, MeasureMode::AllLinesAllowTextOverflow)
}
}
impl From<BestFittingMode> for MeasureMode {

View File

@@ -120,7 +120,6 @@ impl SourceMapGeneration {
}
}
#[allow(dead_code)]
#[derive(Copy, Clone, Debug, Eq, PartialEq, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum LineEnding {

View File

@@ -20,8 +20,9 @@ ruff_text_size = { path = "../ruff_text_size" }
bitflags = { workspace = true }
is-macro = { workspace = true }
itertools = { workspace = true }
malachite = { workspace = true }
memchr = { workspace = true }
num-bigint = { workspace = true }
num-traits = { workspace = true }
once_cell = { workspace = true }
rustc-hash = { workspace = true }
serde = { workspace = true, optional = true }

View File

@@ -15,8 +15,9 @@
//! an implicit concatenation of string literals, as these expressions are considered to
//! have the same shape in that they evaluate to the same value.
use num_bigint::BigInt;
use crate as ast;
use malachite::Integer;
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
pub enum ComparableBoolOp {
@@ -333,7 +334,7 @@ pub enum ComparableConstant<'a> {
Bool(&'a bool),
Str { value: &'a str, unicode: bool },
Bytes(&'a [u8]),
Int(&'a Integer),
Int(&'a BigInt),
Tuple(Vec<ComparableConstant<'a>>),
Float(u64),
Complex { real: u64, imag: u64 },

View File

@@ -1,6 +1,7 @@
use std::borrow::Cow;
use std::path::Path;
use num_traits::Zero;
use smallvec::SmallVec;
use ruff_text_size::{Ranged, TextRange};
@@ -1072,7 +1073,7 @@ impl Truthiness {
Constant::None => Some(false),
Constant::Str(ast::StringConstant { value, .. }) => Some(!value.is_empty()),
Constant::Bytes(bytes) => Some(!bytes.is_empty()),
Constant::Int(int) => Some(*int != 0),
Constant::Int(int) => Some(!int.is_zero()),
Constant::Float(float) => Some(*float != 0.0),
Constant::Complex { real, imag } => Some(*real != 0.0 || *imag != 0.0),
Constant::Ellipsis => Some(true),

View File

@@ -1,11 +1,12 @@
#![allow(clippy::derive_partial_eq_without_eq)]
use itertools::Itertools;
use malachite::Integer;
use std::fmt;
use std::fmt::Debug;
use std::ops::Deref;
use num_bigint::BigInt;
use ruff_text_size::{Ranged, TextRange, TextSize};
/// See also [mod](https://docs.python.org/3/library/ast.html#ast.mod)
@@ -2603,7 +2604,7 @@ pub enum Constant {
Bool(bool),
Str(StringConstant),
Bytes(BytesConstant),
Int(Integer),
Int(BigInt),
Float(f64),
Complex { real: f64, imag: f64 },
Ellipsis,

View File

@@ -84,21 +84,7 @@ fn detect_indention(tokens: &[LexResult], locator: &Locator) -> Indentation {
});
if let Some(indent_range) = indent_range {
let mut whitespace = locator.slice(*indent_range);
// https://docs.python.org/3/reference/lexical_analysis.html#indentation
// > A formfeed character may be present at the start of the line; it will be ignored for
// > the indentation calculations above. Formfeed characters occurring elsewhere in the
// > leading whitespace have an undefined effect (for instance, they may reset the space
// > count to zero).
// So there's UB in python lexer -.-
// In practice, they just reset the indentation:
// https://github.com/python/cpython/blob/df8b3a46a7aa369f246a09ffd11ceedf1d34e921/Parser/tokenizer.c#L1819-L1821
// https://github.com/astral-sh/ruff/blob/a41bb2733fe75a71f4cf6d4bb21e659fc4630b30/crates/ruff_python_parser/src/lexer.rs#L664-L667
// We also reset the indentation when we see a formfeed character.
// See also https://github.com/astral-sh/ruff/issues/7455#issuecomment-1722458825
if let Some((_before, after)) = whitespace.rsplit_once('\x0C') {
whitespace = after;
}
let whitespace = locator.slice(*indent_range);
Indentation(whitespace.to_string())
} else {
@@ -242,19 +228,6 @@ x = (
Stylist::from_tokens(&tokens, &locator).indentation(),
&Indentation::default()
);
// formfeed indent, see `detect_indention` comment.
let contents = r#"
class FormFeedIndent:
def __init__(self, a=[]):
print(a)
"#;
let locator = Locator::new(contents);
let tokens: Vec<_> = lex(contents, Mode::Module).collect();
assert_eq!(
Stylist::from_tokens(&tokens, &locator).indentation(),
&Indentation(" ".to_string())
);
}
#[test]

View File

@@ -394,3 +394,15 @@ z = (
# c: and this comment
+ a
)
# Test for https://github.com/astral-sh/ruff/issues/7431
if True:
if True:
if True:
if True:
msg += " " + _(
"Since the role is not mentionable, it will be momentarily made mentionable "
"when announcing a streamalert. Please make sure I have the correct "
"permissions to manage this role, or else members of this role won't receive "
"a notification."
)

View File

@@ -94,8 +94,3 @@ def f():
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = (
True
)
# Regression test for https://github.com/astral-sh/ruff/issues/7462
if grid is not None:
rgrid = (rgrid.rio.reproject_match(grid, nodata=fillvalue) # rio.reproject nodata is use to initlialize the destination array
.where(~grid.isnull()))

View File

@@ -153,3 +153,19 @@ def test():
key9: value9,
}
), "Not what we expected and the message is too long to fit in one lineeeeeeeeeeeeeee"
# Test for https://github.com/astral-sh/ruff/issues/7246
assert items == [
"a very very very very very very very very very very very very very very very long string",
]
assert package.files == [
{
"file": "pytest-3.5.0-py2.py3-none-any.whl",
"hash": "sha256:6266f87ab64692112e5477eba395cfedda53b1933ccd29478e671e73b420c19c", # noqa: E501
},
{
"file": "pytest-3.5.0.tar.gz",
"hash": "sha256:fae491d1874f199537fd5872b5e1f0e74a009b979df9d53d1553fd03da1703e1", # noqa: E501
},
]

View File

@@ -1,4 +1,4 @@
use ruff_formatter::{format_args, write, Argument, Arguments};
use ruff_formatter::{format_args, write, Argument, Arguments, GroupId};
use ruff_text_size::{Ranged, TextRange, TextSize};
use crate::context::{NodeLevel, WithNodeLevel};
@@ -12,11 +12,28 @@ where
{
ParenthesizeIfExpands {
inner: Argument::new(content),
group_id: None,
should_expand: false,
}
}
pub(crate) struct ParenthesizeIfExpands<'a, 'ast> {
inner: Argument<'a, PyFormatContext<'ast>>,
group_id: Option<GroupId>,
should_expand: bool,
}
impl ParenthesizeIfExpands<'_, '_> {
#[must_use]
pub(crate) fn should_expand(mut self, expand: bool) -> Self {
self.should_expand = expand;
self
}
pub(crate) fn with_group_id(mut self, group_id: GroupId) -> Self {
self.group_id = Some(group_id);
self
}
}
impl<'ast> Format<PyFormatContext<'ast>> for ParenthesizeIfExpands<'_, 'ast> {
@@ -30,7 +47,9 @@ impl<'ast> Format<PyFormatContext<'ast>> for ParenthesizeIfExpands<'_, 'ast> {
if_group_breaks(&token("(")),
soft_block_indent(&Arguments::from(&self.inner)),
if_group_breaks(&token(")")),
])]
])
.with_group_id(self.group_id)
.should_expand(self.should_expand)]
)
}
}

View File

@@ -12,7 +12,7 @@ use ruff_python_ast::{Constant, Expr, ExpressionRef, Operator};
use ruff_python_trivia::CommentRanges;
use crate::builders::parenthesize_if_expands;
use crate::comments::leading_comments;
use crate::comments::{leading_comments, LeadingDanglingTrailingComments};
use crate::context::{NodeLevel, WithNodeLevel};
use crate::expression::parentheses::{
is_expression_parenthesized, optional_parentheses, parenthesized, NeedsParentheses,
@@ -179,6 +179,45 @@ pub(crate) struct MaybeParenthesizeExpression<'a> {
parenthesize: Parenthesize,
}
impl MaybeParenthesizeExpression<'_> {
pub(crate) fn needs_parentheses(
&self,
context: &PyFormatContext,
node_comments: &LeadingDanglingTrailingComments,
) -> OptionalParentheses {
let MaybeParenthesizeExpression {
expression,
parent,
parenthesize,
} = self;
let preserve_parentheses = parenthesize.is_optional()
&& is_expression_parenthesized(
(*expression).into(),
context.comments().ranges(),
context.source(),
);
let has_comments = node_comments.has_leading() || node_comments.has_trailing_own_line();
// If the expression has comments, we always want to preserve the parentheses. This also
// ensures that we correctly handle parenthesized comments, and don't need to worry about
// them in the implementation below.
if preserve_parentheses || has_comments {
OptionalParentheses::Always
} else {
match expression.needs_parentheses(*parent, context) {
OptionalParentheses::Always => OptionalParentheses::Always,
// The reason to add parentheses is to avoid a syntax error when breaking an expression over multiple lines.
// Therefore, it is unnecessary to add an additional pair of parentheses if an outer expression
// is parenthesized.
_ if context.node_level().is_parenthesized() => OptionalParentheses::Never,
needs_parentheses => needs_parentheses,
}
}
}
}
impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> {
fn fmt(&self, f: &mut PyFormatter) -> FormatResult<()> {
let MaybeParenthesizeExpression {
@@ -188,34 +227,9 @@ impl Format<PyFormatContext<'_>> for MaybeParenthesizeExpression<'_> {
} = self;
let comments = f.context().comments();
let preserve_parentheses = parenthesize.is_optional()
&& is_expression_parenthesized(
(*expression).into(),
f.context().comments().ranges(),
f.context().source(),
);
let node_comments = comments.leading_dangling_trailing(*expression);
let has_comments = node_comments.has_leading() || node_comments.has_trailing_own_line();
// If the expression has comments, we always want to preserve the parentheses. This also
// ensures that we correctly handle parenthesized comments, and don't need to worry about
// them in the implementation below.
if preserve_parentheses || has_comments {
return expression.format().with_options(Parentheses::Always).fmt(f);
}
let needs_parentheses = match expression.needs_parentheses(*parent, f.context()) {
OptionalParentheses::Always => OptionalParentheses::Always,
// The reason to add parentheses is to avoid a syntax error when breaking an expression over multiple lines.
// Therefore, it is unnecessary to add an additional pair of parentheses if an outer expression
// is parenthesized.
_ if f.context().node_level().is_parenthesized() => OptionalParentheses::Never,
needs_parentheses => needs_parentheses,
};
match needs_parentheses {
match self.needs_parentheses(f.context(), &node_comments) {
OptionalParentheses::Multiline => match parenthesize {
Parenthesize::IfBreaksOrIfRequired => {
parenthesize_if_expands(&expression.format().with_options(Parentheses::Never))
@@ -342,7 +356,7 @@ impl<'ast> IntoFormat<PyFormatContext<'ast>> for Expr {
/// * The expression contains at least one parenthesized sub expression (optimization to avoid unnecessary work)
///
/// This mimics Black's [`_maybe_split_omitting_optional_parens`](https://github.com/psf/black/blob/d1248ca9beaf0ba526d265f4108836d89cf551b7/src/black/linegen.py#L746-L820)
fn can_omit_optional_parentheses(expr: &Expr, context: &PyFormatContext) -> bool {
pub(crate) fn can_omit_optional_parentheses(expr: &Expr, context: &PyFormatContext) -> bool {
let mut visitor = CanOmitOptionalParenthesesVisitor::new(context);
visitor.visit_subexpression(expr);

View File

@@ -1,5 +1,5 @@
use ruff_formatter::prelude::tag::Condition;
use ruff_formatter::{format_args, write, Argument, Arguments};
use ruff_formatter::{format_args, write, Argument, Arguments, GroupId};
use ruff_python_ast::node::AnyNodeRef;
use ruff_python_ast::ExpressionRef;
use ruff_python_trivia::CommentRanges;
@@ -155,32 +155,34 @@ impl<'content, 'ast> FormatParenthesized<'content, 'ast> {
impl<'ast> Format<PyFormatContext<'ast>> for FormatParenthesized<'_, 'ast> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> {
let inner = format_with(|f| {
let current_level = f.context().node_level();
let content = format_with(|f| {
group(&format_args![
token(self.left),
dangling_open_parenthesis_comments(self.comments),
soft_block_indent(&Arguments::from(&self.content)),
token(self.right)
soft_block_indent(&Arguments::from(&self.content))
])
.fmt(f)
});
let current_level = f.context().node_level();
let inner = format_with(|f| {
if let NodeLevel::Expression(Some(group_id)) = current_level {
// Use fits expanded if there's an enclosing group that adds the optional parentheses.
// This ensures that expanding this parenthesized expression does not expand the optional parentheses group.
write!(
f,
[fits_expanded(&content)
.with_condition(Some(Condition::if_group_fits_on_line(group_id)))]
)
} else {
// It's not necessary to wrap the content if it is not inside of an optional_parentheses group.
content.fmt(f)
}
});
let mut f = WithNodeLevel::new(NodeLevel::ParenthesizedExpression, f);
if let NodeLevel::Expression(Some(group_id)) = current_level {
// Use fits expanded if there's an enclosing group that adds the optional parentheses.
// This ensures that expanding this parenthesized expression does not expand the optional parentheses group.
write!(
f,
[fits_expanded(&inner)
.with_condition(Some(Condition::if_group_fits_on_line(group_id)))]
)
} else {
// It's not necessary to wrap the content if it is not inside of an optional_parentheses group.
write!(f, [inner])
}
write!(f, [token(self.left), inner, token(self.right)])
}
}
@@ -194,18 +196,29 @@ where
{
FormatOptionalParentheses {
content: Argument::new(content),
group_id: None,
}
}
pub(crate) struct FormatOptionalParentheses<'content, 'ast> {
content: Argument<'content, PyFormatContext<'ast>>,
group_id: Option<GroupId>,
}
impl FormatOptionalParentheses<'_, '_> {
pub(crate) fn with_group_id(mut self, group_id: GroupId) -> Self {
self.group_id = Some(group_id);
self
}
}
impl<'ast> Format<PyFormatContext<'ast>> for FormatOptionalParentheses<'_, 'ast> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'ast>>) -> FormatResult<()> {
// The group id is used as a condition in [`in_parentheses_only_group`] to create a
// conditional group that is only active if the optional parentheses group expands.
let parens_id = f.group_id("optional_parentheses");
let parens_id = self
.group_id
.unwrap_or_else(|| f.group_id("optional_parentheses"));
let mut f = WithNodeLevel::new(NodeLevel::Expression(Some(parens_id)), f);

View File

@@ -1,12 +1,13 @@
use ruff_formatter::prelude::{space, token};
use ruff_formatter::write;
use ruff_python_ast::StmtAssert;
use ruff_formatter::{format_args, write};
use ruff_python_ast::{Constant, Expr, ExprConstant, StmtAssert};
use crate::builders::parenthesize_if_expands;
use crate::comments::{SourceComment, SuppressionKind};
use crate::expression::maybe_parenthesize_expression;
use crate::expression::parentheses::Parenthesize;
use crate::context::{NodeLevel, WithNodeLevel};
use crate::expression::parentheses::{OptionalParentheses, Parentheses, Parenthesize};
use crate::expression::{can_omit_optional_parentheses, maybe_parenthesize_expression};
use crate::prelude::*;
use crate::FormatNodeRule;
#[derive(Default)]
pub struct FormatStmtAssert;
@@ -19,14 +20,102 @@ impl FormatNodeRule<StmtAssert> for FormatStmtAssert {
msg,
} = item;
write!(
f,
[
token("assert"),
space(),
maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks)
]
)?;
write!(f, [token("assert"), space()])?;
let parenthesize_test = maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks);
if let Some(
msg @ (Expr::FString(_)
| Expr::Constant(ExprConstant {
value: Constant::Str(_) | Constant::Bytes(_),
..
})),
) = msg.as_deref()
{
let parenthesize_message =
maybe_parenthesize_expression(msg, item, Parenthesize::IfBreaks);
let comments = f.context().comments();
let test_comments = comments.leading_dangling_trailing(test.as_ref());
let msg_comments = comments.leading_dangling_trailing(msg);
// TODO limit to can omit parentheses and has own parentheses
if parenthesize_test.needs_parentheses(f.context(), &test_comments)
== OptionalParentheses::Multiline
&& parenthesize_message.needs_parentheses(f.context(), &msg_comments)
== OptionalParentheses::BestFit
&& can_omit_optional_parentheses(test, f.context())
{
let test_group_id = f.group_id("optional_parentheses");
let mut format_test = test.format().with_options(Parentheses::Never).memoized();
let mut format_msg = msg.format().with_options(Parentheses::Never).memoized();
let test_breaks = {
let f = &mut WithNodeLevel::new(NodeLevel::Expression(Some(test_group_id)), f);
format_test.inspect(f)?.will_break()
};
return if test_breaks || format_msg.inspect(f)?.will_break() {
todo!()
} else {
best_fitting![
// ---------------------------------------------------------------------
// Variant 1:
// Try to fit both expressions without parentheses
format_args![
group(&format_test).with_group_id(Some(test_group_id)),
token(","),
space(),
format_msg
],
// ---------------------------------------------------------------------
// Variant 2:
// Try to parenthesize the string, but don't parenthesize the test just yet
format_args![
group(&format_test).with_group_id(Some(test_group_id)),
token(","),
space(),
parenthesize_if_expands(&format_msg).should_expand(true)
],
// ---------------------------------------------------------------------
// Variant 3:
// Try to parenthesize both test and message
format_args![
parenthesize_if_expands(&format_test)
.with_group_id(test_group_id)
.should_expand(true),
token(","),
space(),
parenthesize_if_expands(&format_msg).should_expand(true)
],
// ---------------------------------------------------------------------
// Variant 4:
// If it wasn't possible to make test and message fit by now, fallback to the first variant
// and omit any optional parentheses.
format_args![
// Create an empty group that always fits. Necessary because the content
// of format_test might refer the group id.
format_with(|f| {
f.write_element(FormatElement::GroupMode {
id: test_group_id,
mode: PrintMode::Flat,
});
Ok(())
}),
format_test,
token(","),
space(),
format_msg
],
]
.with_mode(BestFittingMode::AllLines)
.fmt(f)
};
}
}
maybe_parenthesize_expression(test, item, Parenthesize::IfBreaks).fmt(f)?;
if let Some(msg) = msg {
write!(

View File

@@ -193,41 +193,7 @@ class C:
```diff
--- Black
+++ Ruff
@@ -110,19 +110,20 @@
value, is_going_to_be="too long to fit in a single line", srsly=True
), "Not what we expected"
- assert {
- key1: value1,
- key2: value2,
- key3: value3,
- key4: value4,
- key5: value5,
- key6: value6,
- key7: value7,
- key8: value8,
- key9: value9,
- } == expected, (
- "Not what we expected and the message is too long to fit in one line"
- )
+ assert (
+ {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
+ key5: value5,
+ key6: value6,
+ key7: value7,
+ key8: value8,
+ key9: value9,
+ }
+ == expected
+ ), "Not what we expected and the message is too long to fit in one line"
assert expected(
value, is_going_to_be="too long to fit in a single line", srsly=True
@@ -161,9 +162,7 @@
@@ -161,9 +161,7 @@
8 STORE_ATTR 0 (x)
10 LOAD_CONST 0 (None)
12 RETURN_VALUE
@@ -355,20 +321,19 @@ class C:
value, is_going_to_be="too long to fit in a single line", srsly=True
), "Not what we expected"
assert (
{
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
}
== expected
), "Not what we expected and the message is too long to fit in one line"
assert {
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
} == expected, (
"Not what we expected and the message is too long to fit in one line"
)
assert expected(
value, is_going_to_be="too long to fit in a single line", srsly=True

View File

@@ -193,41 +193,7 @@ class C:
```diff
--- Black
+++ Ruff
@@ -110,19 +110,20 @@
value, is_going_to_be="too long to fit in a single line", srsly=True
), "Not what we expected"
- assert {
- key1: value1,
- key2: value2,
- key3: value3,
- key4: value4,
- key5: value5,
- key6: value6,
- key7: value7,
- key8: value8,
- key9: value9,
- } == expected, (
- "Not what we expected and the message is too long to fit in one line"
- )
+ assert (
+ {
+ key1: value1,
+ key2: value2,
+ key3: value3,
+ key4: value4,
+ key5: value5,
+ key6: value6,
+ key7: value7,
+ key8: value8,
+ key9: value9,
+ }
+ == expected
+ ), "Not what we expected and the message is too long to fit in one line"
assert expected(
value, is_going_to_be="too long to fit in a single line", srsly=True
@@ -161,9 +162,7 @@
@@ -161,9 +161,7 @@
8 STORE_ATTR 0 (x)
10 LOAD_CONST 0 (None)
12 RETURN_VALUE
@@ -355,20 +321,19 @@ class C:
value, is_going_to_be="too long to fit in a single line", srsly=True
), "Not what we expected"
assert (
{
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
}
== expected
), "Not what we expected and the message is too long to fit in one line"
assert {
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
} == expected, (
"Not what we expected and the message is too long to fit in one line"
)
assert expected(
value, is_going_to_be="too long to fit in a single line", srsly=True

View File

@@ -1,77 +0,0 @@
---
source: crates/ruff_python_formatter/tests/fixtures.rs
input_file: crates/ruff_python_formatter/resources/test/fixtures/black/simple_cases/trailing_comma_optional_parens3.py
---
## Input
```py
if True:
if True:
if True:
return _(
"qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweas "
+ "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.",
"qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe",
) % {"reported_username": reported_username, "report_reason": report_reason}
```
## Black Differences
```diff
--- Black
+++ Ruff
@@ -1,8 +1,14 @@
if True:
if True:
if True:
- return _(
- "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweas "
- + "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.",
- "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe",
- ) % {"reported_username": reported_username, "report_reason": report_reason}
+ return (
+ _(
+ "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweas "
+ + "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.",
+ "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe",
+ )
+ % {
+ "reported_username": reported_username,
+ "report_reason": report_reason,
+ }
+ )
```
## Ruff Output
```py
if True:
if True:
if True:
return (
_(
"qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweas "
+ "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.",
"qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe",
)
% {
"reported_username": reported_username,
"report_reason": report_reason,
}
)
```
## Black Output
```py
if True:
if True:
if True:
return _(
"qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweas "
+ "qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwegqweasdzxcqweasdzxc.",
"qweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqweasdzxcqwe",
) % {"reported_username": reported_username, "report_reason": report_reason}
```

View File

@@ -400,6 +400,18 @@ z = (
# c: and this comment
+ a
)
# Test for https://github.com/astral-sh/ruff/issues/7431
if True:
if True:
if True:
if True:
msg += " " + _(
"Since the role is not mentionable, it will be momentarily made mentionable "
"when announcing a streamalert. Please make sure I have the correct "
"permissions to manage this role, or else members of this role won't receive "
"a notification."
)
```
## Output
@@ -849,6 +861,18 @@ z = (
# c: and this comment
+ a
)
# Test for https://github.com/astral-sh/ruff/issues/7431
if True:
if True:
if True:
if True:
msg += " " + _(
"Since the role is not mentionable, it will be momentarily made mentionable "
"when announcing a streamalert. Please make sure I have the correct "
"permissions to manage this role, or else members of this role won't receive "
"a notification."
)
```

View File

@@ -100,11 +100,6 @@ def f():
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = (
True
)
# Regression test for https://github.com/astral-sh/ruff/issues/7462
if grid is not None:
rgrid = (rgrid.rio.reproject_match(grid, nodata=fillvalue) # rio.reproject nodata is use to initlialize the destination array
.where(~grid.isnull()))
```
## Output
@@ -227,15 +222,6 @@ def f():
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = (
True
)
# Regression test for https://github.com/astral-sh/ruff/issues/7462
if grid is not None:
rgrid = rgrid.rio.reproject_match(
grid, nodata=fillvalue
).where( # rio.reproject nodata is use to initlialize the destination array
~grid.isnull()
)
```

View File

@@ -159,6 +159,22 @@ def test():
key9: value9,
}
), "Not what we expected and the message is too long to fit in one lineeeeeeeeeeeeeee"
# Test for https://github.com/astral-sh/ruff/issues/7246
assert items == [
"a very very very very very very very very very very very very very very very long string",
]
assert package.files == [
{
"file": "pytest-3.5.0-py2.py3-none-any.whl",
"hash": "sha256:6266f87ab64692112e5477eba395cfedda53b1933ccd29478e671e73b420c19c", # noqa: E501
},
{
"file": "pytest-3.5.0.tar.gz",
"hash": "sha256:fae491d1874f199537fd5872b5e1f0e74a009b979df9d53d1553fd03da1703e1", # noqa: E501
},
]
```
## Output
@@ -195,80 +211,69 @@ assert (
def test():
assert (
{
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
}
== expected
), "Not what we expected and the message is too long to fit ineeeeee one line"
assert {
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
} == expected, (
"Not what we expected and the message is too long to fit ineeeeee one line"
)
assert (
{
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
}
== expected
), "Not what we expected and the message is too long to fit in one lineeeee"
assert {
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
} == expected, (
"Not what we expected and the message is too long to fit in one lineeeee"
)
assert (
{
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
}
== expected
), "Not what we expected and the message is too long to fit in one lineeeeeeeeeeeee"
assert {
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
} == expected, "Not what we expected and the message is too long to fit in one lineeeeeeeeeeeee"
assert (
{
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
}
== expectedeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
), "Not what we expected and the message is too long to fit in one lin"
assert {
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
} == expectedeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, "Not what we expected and the message is too long to fit in one lin"
assert (
{
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
}
== expectedeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
), "Not what we expected and the message is too long to fit in one lineeeeeeeeeeeeeeeee"
assert {
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
} == expectedeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee, "Not what we expected and the message is too long to fit in one lineeeeeeeeeeeeeeeee"
assert expected == {
key1: value1,
@@ -282,20 +287,17 @@ def test():
key9: value9,
}, "Not what we expected and the message is too long to fit ineeeeee one line"
assert (
expected
== {
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
}
), "Not what we expected and the message is too long to fit in one lineeeeeeeeeeeeeeeeeeee"
assert expected == {
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
}, "Not what we expected and the message is too long to fit in one lineeeeeeeeeeeeeeeeeeee"
assert (
expectedeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
@@ -310,22 +312,38 @@ def test():
key8: value8,
key9: value9,
}
), "Not what we expected and the message is too long to fit in one lin"
), (
"Not what we expected and the message is too long to fit in one lin"
)
assert (
expectedeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
== {
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
}
), "Not what we expected and the message is too long to fit in one lineeeeeeeeeeeeeee"
assert expectedeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee == {
key1: value1,
key2: value2,
key3: value3,
key4: value4,
key5: value5,
key6: value6,
key7: value7,
key8: value8,
key9: value9,
}, "Not what we expected and the message is too long to fit in one lineeeeeeeeeeeeeee"
# Test for https://github.com/astral-sh/ruff/issues/7246
assert items == [
"a very very very very very very very very very very very very very very very long string",
]
assert package.files == [
{
"file": "pytest-3.5.0-py2.py3-none-any.whl",
"hash": "sha256:6266f87ab64692112e5477eba395cfedda53b1933ccd29478e671e73b420c19c", # noqa: E501
},
{
"file": "pytest-3.5.0.tar.gz",
"hash": "sha256:fae491d1874f199537fd5872b5e1f0e74a009b979df9d53d1553fd03da1703e1", # noqa: E501
},
]
```

View File

@@ -1,5 +1,5 @@
use crate::Case;
use num_traits::Float;
use num_traits::{Float, Zero};
use std::f64;
pub fn parse_str(literal: &str) -> Option<f64> {
@@ -248,7 +248,7 @@ pub fn to_hex(value: f64) -> String {
let (mantissa, exponent, sign) = value.integer_decode();
let sign_fmt = if sign < 0 { "-" } else { "" };
match value {
value if value == 0.0 => format!("{sign_fmt}0x0.0p+0"),
value if value.is_zero() => format!("{sign_fmt}0x0.0p+0"),
value if value.is_infinite() => format!("{sign_fmt}inf"),
value if value.is_nan() => "nan".to_owned(),
_ => {

View File

@@ -21,7 +21,8 @@ anyhow = { workspace = true }
is-macro = { workspace = true }
itertools = { workspace = true }
lalrpop-util = { version = "0.20.0", default-features = false }
malachite = { workspace = true }
num-bigint = { workspace = true }
num-traits = { workspace = true }
unicode-ident = { workspace = true }
unicode_names2 = { version = "0.6.0", git = "https://github.com/youknowone/unicode_names2.git", rev = "4ce16aa85cbcdd9cc830410f1a72ef9a235f2fde" }
rustc-hash = { workspace = true }

View File

@@ -28,11 +28,11 @@
//!
//! [Lexical analysis]: https://docs.python.org/3/reference/lexical_analysis.html
use malachite::num::conversion::traits::FromStringBase;
use malachite::Integer;
use std::iter::FusedIterator;
use std::{char, cmp::Ordering, str::FromStr};
use num_bigint::BigInt;
use num_traits::{Num, Zero};
use ruff_python_ast::IpyEscapeKind;
use ruff_text_size::{TextLen, TextRange, TextSize};
use unicode_ident::{is_xid_continue, is_xid_start};
@@ -264,16 +264,11 @@ impl<'source> Lexer<'source> {
let mut number = LexedText::new(self.offset(), self.source);
self.radix_run(&mut number, radix);
let value = Integer::from_string_base(radix.as_u8(), number.as_str()).ok_or_else(|| {
LexicalError {
error: LexicalErrorType::OtherError(format!(
"'{}' is not a valid integer",
number.as_str()
)),
let value =
BigInt::from_str_radix(number.as_str(), radix.as_u32()).map_err(|e| LexicalError {
error: LexicalErrorType::OtherError(format!("{e:?}")),
location: self.token_range().start(),
}
})?;
})?;
Ok(Tok::Int { value })
}
@@ -344,19 +339,8 @@ impl<'source> Lexer<'source> {
let imag = f64::from_str(number.as_str()).unwrap();
Ok(Tok::Complex { real: 0.0, imag })
} else {
// Optimization: `Natural` and thereby `Integer` add up digits from bytes to convert
// from string. This is much less efficient than the highly optimized std
// string-to-number parser and we know that most numbers are small.
// i32::MAX is 2147483647 (10 digits), so all 9 digit numbers are representable as
// i32. We can't guarantee that `32_bit_limbs` isn't set, so we limit ourselves to
// i32 instead of i64.
let value = if number.as_str().len() < 10 {
Integer::from(i32::from_str(number.as_str()).unwrap())
} else {
Integer::from_str(number.as_str()).unwrap()
};
if start_is_zero && value != 0 {
let value = number.as_str().parse::<BigInt>().unwrap();
if start_is_zero && !value.is_zero() {
// leading zeros in decimal integer literals are not permitted
return Err(LexicalError {
error: LexicalErrorType::OtherError("Invalid Token".to_owned()),
@@ -1171,7 +1155,7 @@ impl State {
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
#[derive(Copy, Clone, Debug)]
enum Radix {
Binary,
Octal,
@@ -1180,7 +1164,7 @@ enum Radix {
}
impl Radix {
const fn as_u8(self) -> u8 {
const fn as_u32(self) -> u32 {
match self {
Radix::Binary => 2,
Radix::Octal => 8,

View File

@@ -3,6 +3,7 @@
// See also: file:///usr/share/doc/python/html/reference/compound_stmts.html#function-definitions
// See also: https://greentreesnakes.readthedocs.io/en/latest/nodes.html#keyword
use num_bigint::BigInt;
use ruff_text_size::{Ranged, TextSize};
use ruff_python_ast::{self as ast, IpyEscapeKind};
use crate::{
@@ -14,7 +15,6 @@ use crate::{
token::{self, StringKind},
};
use lalrpop_util::ParseError;
use malachite::Integer;
grammar(mode: Mode);
@@ -1928,7 +1928,7 @@ extern {
"True" => token::Tok::True,
"False" => token::Tok::False,
"None" => token::Tok::None,
int => token::Tok::Int { value: <Integer> },
int => token::Tok::Int { value: <BigInt> },
float => token::Tok::Float { value: <f64> },
complex => token::Tok::Complex { real: <f64>, imag: <f64> },
string => token::Tok::String {

View File

@@ -1,5 +1,6 @@
// auto-generated: "lalrpop 0.20.0"
// sha3: 5b982370860d3a79f183bc579ec6f5165211b83573141f4c9ceaec27436c30ad
// sha3: e8f3229288c1a13387ea6041355e2d8fe9ab788fbc7229032d2de92beb675944
use num_bigint::BigInt;
use ruff_text_size::{Ranged, TextSize};
use ruff_python_ast::{self as ast, IpyEscapeKind};
use crate::{
@@ -11,7 +12,6 @@ use crate::{
token::{self, StringKind},
};
use lalrpop_util::ParseError;
use malachite::Integer;
#[allow(unused_extern_crates)]
extern crate lalrpop_util as __lalrpop_util;
#[allow(unused_imports)]
@@ -23,6 +23,7 @@ extern crate alloc;
#[allow(non_snake_case, non_camel_case_types, unused_mut, unused_variables, unused_imports, unused_parens, clippy::all)]
mod __parse__Top {
use num_bigint::BigInt;
use ruff_text_size::{Ranged, TextSize};
use ruff_python_ast::{self as ast, IpyEscapeKind};
use crate::{
@@ -34,7 +35,6 @@ mod __parse__Top {
token::{self, StringKind},
};
use lalrpop_util::ParseError;
use malachite::Integer;
#[allow(unused_extern_crates)]
extern crate lalrpop_util as __lalrpop_util;
#[allow(unused_imports)]
@@ -48,7 +48,7 @@ mod __parse__Top {
Variant0(token::Tok),
Variant1((f64, f64)),
Variant2(f64),
Variant3(Integer),
Variant3(BigInt),
Variant4((IpyEscapeKind, String)),
Variant5(String),
Variant6((String, StringKind, bool)),
@@ -17716,7 +17716,7 @@ mod __parse__Top {
fn __pop_Variant3<
>(
__symbols: &mut alloc::vec::Vec<(TextSize,__Symbol<>,TextSize)>
) -> (TextSize, Integer, TextSize)
) -> (TextSize, BigInt, TextSize)
{
match __symbols.pop() {
Some((__l, __Symbol::Variant3(__v), __r)) => (__l, __v, __r),
@@ -34480,7 +34480,7 @@ fn __action232<
fn __action233<
>(
mode: Mode,
(_, value, _): (TextSize, Integer, TextSize),
(_, value, _): (TextSize, BigInt, TextSize),
) -> ast::Constant
{
ast::Constant::Int(value)

View File

@@ -5,7 +5,7 @@
//!
//! [CPython source]: https://github.com/python/cpython/blob/dfc2e065a2e71011017077e549cd2f9bf4944c54/Include/internal/pycore_token.h;
use crate::Mode;
use malachite::Integer;
use num_bigint::BigInt;
use ruff_python_ast::IpyEscapeKind;
use ruff_text_size::TextSize;
use std::fmt;
@@ -21,7 +21,7 @@ pub enum Tok {
/// Token value for an integer.
Int {
/// The integer value.
value: Integer,
value: BigInt,
},
/// Token value for a floating point number.
Float {

View File

@@ -21,6 +21,7 @@ ruff_text_size = { path = "../ruff_text_size" }
bitflags = { workspace = true }
is-macro = { workspace = true }
num-traits = { workspace = true }
rustc-hash = { workspace = true }
smallvec = { workspace = true }

View File

@@ -1,5 +1,6 @@
//! Analysis rules for the `typing` module.
use num_traits::identities::Zero;
use ruff_python_ast::{
self as ast, Constant, Expr, Operator, ParameterWithDefault, Parameters, Stmt,
};
@@ -318,7 +319,7 @@ pub fn is_type_checking_block(stmt: &ast::StmtIf, semantic: &SemanticModel) -> b
..
}) = test.as_ref()
{
if *value == 0 {
if value.is_zero() {
return true;
}
}