-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
mod.rs
5512 lines (5311 loc) · 237 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! [`Checker`] for AST-based lint rules.
//!
//! The [`Checker`] is responsible for traversing over the AST, building up the [`SemanticModel`],
//! and running any enabled [`Rule`]s at the appropriate place and time.
//!
//! The [`Checker`] is structured as a single pass over the AST that proceeds in "evaluation" order.
//! That is: the [`Checker`] typically iterates over nodes in the order in which they're evaluated
//! by the Python interpreter. This includes, e.g., deferring function body traversal until after
//! parent scopes have been fully traversed. Individual rules may also perform internal traversals
//! of the AST.
//!
//! While the [`Checker`] is typically passed by mutable reference to the individual lint rule
//! implementations, most of its constituent components are intended to be treated immutably, with
//! the exception of the [`Diagnostic`] vector, which is intended to be mutated by the individual
//! lint rules. In the future, this should be formalized in the API.
//!
//! The individual [`Visitor`] implementations within the [`Checker`] typically proceed in four
//! steps:
//!
//! 1. Analysis: Run any relevant lint rules on the current node.
//! 2. Binding: Bind any names introduced by the current node.
//! 3. Recursion: Recurse into the children of the current node.
//! 4. Clean-up: Perform any necessary clean-up after the current node has been fully traversed.
//!
//! The first step represents the lint-rule analysis phase, while the remaining steps together
//! compose the semantic analysis phase. In the future, these phases may be separated into distinct
//! passes over the AST.
use std::path::Path;
use itertools::Itertools;
use log::error;
use ruff_text_size::{TextRange, TextSize};
use rustpython_format::cformat::{CFormatError, CFormatErrorType};
use rustpython_parser::ast::{
self, Arg, ArgWithDefault, Arguments, Comprehension, Constant, ElifElseClause, ExceptHandler,
Expr, ExprContext, Keyword, Operator, Pattern, Ranged, Stmt, Suite, UnaryOp,
};
use ruff_diagnostics::{Diagnostic, Fix, IsolationLevel};
use ruff_python_ast::all::{extract_all_names, DunderAllFlags};
use ruff_python_ast::helpers::{extract_handled_exceptions, to_module_path};
use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::source_code::{Generator, Indexer, Locator, Quote, Stylist};
use ruff_python_ast::str::trailing_quote;
use ruff_python_ast::types::Node;
use ruff_python_ast::typing::{parse_type_annotation, AnnotationKind};
use ruff_python_ast::visitor::{walk_except_handler, walk_pattern, Visitor};
use ruff_python_ast::{cast, helpers, str, visitor};
use ruff_python_semantic::analyze::{branch_detection, typing, visibility};
use ruff_python_semantic::{
Binding, BindingFlags, BindingId, BindingKind, ContextualizedDefinition, Exceptions,
ExecutionContext, Export, FromImport, Globals, Import, Module, ModuleKind, ScopeId, ScopeKind,
SemanticModel, SemanticModelFlags, StarImport, SubmoduleImport,
};
use ruff_python_stdlib::builtins::{BUILTINS, MAGIC_GLOBALS};
use ruff_python_stdlib::path::is_python_stub_file;
use crate::checkers::ast::deferred::Deferred;
use crate::docstrings::extraction::ExtractionTarget;
use crate::docstrings::Docstring;
use crate::fs::relativize_path;
use crate::importer::Importer;
use crate::noqa::NoqaMapping;
use crate::registry::Rule;
use crate::rules::{
airflow, flake8_2020, flake8_annotations, flake8_async, flake8_bandit, flake8_blind_except,
flake8_boolean_trap, flake8_bugbear, flake8_builtins, flake8_comprehensions, flake8_datetimez,
flake8_debugger, flake8_django, flake8_errmsg, flake8_future_annotations, flake8_gettext,
flake8_implicit_str_concat, flake8_import_conventions, flake8_logging_format, flake8_pie,
flake8_print, flake8_pyi, flake8_pytest_style, flake8_raise, flake8_return, flake8_self,
flake8_simplify, flake8_slots, flake8_tidy_imports, flake8_type_checking,
flake8_unused_arguments, flake8_use_pathlib, flynt, mccabe, numpy, pandas_vet, pep8_naming,
perflint, pycodestyle, pydocstyle, pyflakes, pygrep_hooks, pylint, pyupgrade, ruff,
tryceratops,
};
use crate::settings::types::PythonVersion;
use crate::settings::{flags, Settings};
use crate::{docstrings, noqa, warn_user};
mod deferred;
pub(crate) struct Checker<'a> {
/// The [`Path`] to the file under analysis.
path: &'a Path,
/// The [`Path`] to the package containing the current file.
package: Option<&'a Path>,
/// The module representation of the current file (e.g., `foo.bar`).
module_path: Option<&'a [String]>,
/// Whether the current file is a stub (`.pyi`) file.
is_stub: bool,
/// The [`flags::Noqa`] for the current analysis (i.e., whether to respect suppression
/// comments).
noqa: flags::Noqa,
/// The [`NoqaMapping`] for the current analysis (i.e., the mapping from line number to
/// suppression commented line number).
noqa_line_for: &'a NoqaMapping,
/// The [`Settings`] for the current analysis, including the enabled rules.
pub(crate) settings: &'a Settings,
/// The [`Locator`] for the current file, which enables extraction of source code from byte
/// offsets.
locator: &'a Locator<'a>,
/// The [`Stylist`] for the current file, which detects the current line ending, quote, and
/// indentation style.
stylist: &'a Stylist<'a>,
/// The [`Indexer`] for the current file, which contains the offsets of all comments and more.
indexer: &'a Indexer,
/// The [`Importer`] for the current file, which enables importing of other modules.
importer: Importer<'a>,
/// The [`SemanticModel`], built up over the course of the AST traversal.
semantic: SemanticModel<'a>,
/// A set of deferred nodes to be processed after the current traversal (e.g., function bodies).
deferred: Deferred<'a>,
/// The cumulative set of diagnostics computed across all lint rules.
pub(crate) diagnostics: Vec<Diagnostic>,
/// The list of names already seen by flake8-bugbear diagnostics, to avoid duplicate violations..
pub(crate) flake8_bugbear_seen: Vec<&'a ast::ExprName>,
}
impl<'a> Checker<'a> {
#[allow(clippy::too_many_arguments)]
pub(crate) fn new(
settings: &'a Settings,
noqa_line_for: &'a NoqaMapping,
noqa: flags::Noqa,
path: &'a Path,
package: Option<&'a Path>,
module: Module<'a>,
locator: &'a Locator,
stylist: &'a Stylist,
indexer: &'a Indexer,
importer: Importer<'a>,
) -> Checker<'a> {
Checker {
settings,
noqa_line_for,
noqa,
path,
package,
module_path: module.path(),
is_stub: is_python_stub_file(path),
locator,
stylist,
indexer,
importer,
semantic: SemanticModel::new(&settings.typing_modules, path, module),
deferred: Deferred::default(),
diagnostics: Vec::default(),
flake8_bugbear_seen: Vec::default(),
}
}
}
impl<'a> Checker<'a> {
/// Return `true` if a patch should be generated for a given [`Rule`].
pub(crate) fn patch(&self, code: Rule) -> bool {
self.settings.rules.should_fix(code)
}
/// Return `true` if a [`Rule`] is disabled by a `noqa` directive.
pub(crate) fn rule_is_ignored(&self, code: Rule, offset: TextSize) -> bool {
// TODO(charlie): `noqa` directives are mostly enforced in `check_lines.rs`.
// However, in rare cases, we need to check them here. For example, when
// removing unused imports, we create a single fix that's applied to all
// unused members on a single import. We need to pre-emptively omit any
// members from the fix that will eventually be excluded by a `noqa`.
// Unfortunately, we _do_ want to register a `Diagnostic` for each
// eventually-ignored import, so that our `noqa` counts are accurate.
if !self.noqa.to_bool() {
return false;
}
noqa::rule_is_ignored(code, offset, self.noqa_line_for, self.locator)
}
/// Create a [`Generator`] to generate source code based on the current AST state.
pub(crate) fn generator(&self) -> Generator {
Generator::new(
self.stylist.indentation(),
self.f_string_quote_style().unwrap_or(self.stylist.quote()),
self.stylist.line_ending(),
)
}
/// Returns the appropriate quoting for f-string by reversing the one used outside of
/// the f-string.
///
/// If the current expression in the context is not an f-string, returns ``None``.
pub(crate) fn f_string_quote_style(&self) -> Option<Quote> {
let model = &self.semantic;
if !model.in_f_string() {
return None;
}
// Find the quote character used to start the containing f-string.
let expr = model.expr()?;
let string_range = self.indexer.f_string_range(expr.start())?;
let trailing_quote = trailing_quote(self.locator.slice(string_range))?;
// Invert the quote character, if it's a single quote.
match *trailing_quote {
"'" => Some(Quote::Double),
"\"" => Some(Quote::Single),
_ => None,
}
}
/// Returns the [`IsolationLevel`] for fixes in the current context.
///
/// The primary use-case for fix isolation is to ensure that we don't delete all statements
/// in a given indented block, which would cause a syntax error. We therefore need to ensure
/// that we delete at most one statement per indented block per fixer pass. Fix isolation should
/// thus be applied whenever we delete a statement, but can otherwise be omitted.
pub(crate) fn isolation(&self, parent: Option<&Stmt>) -> IsolationLevel {
parent
.and_then(|stmt| self.semantic.stmts.node_id(stmt))
.map_or(IsolationLevel::default(), |node_id| {
IsolationLevel::Group(node_id.into())
})
}
/// The [`Locator`] for the current file, which enables extraction of source code from byte
/// offsets.
pub(crate) const fn locator(&self) -> &'a Locator<'a> {
self.locator
}
/// The [`Stylist`] for the current file, which detects the current line ending, quote, and
/// indentation style.
pub(crate) const fn stylist(&self) -> &'a Stylist<'a> {
self.stylist
}
/// The [`Indexer`] for the current file, which contains the offsets of all comments and more.
pub(crate) const fn indexer(&self) -> &'a Indexer {
self.indexer
}
/// The [`Importer`] for the current file, which enables importing of other modules.
pub(crate) const fn importer(&self) -> &Importer<'a> {
&self.importer
}
/// The [`SemanticModel`], built up over the course of the AST traversal.
pub(crate) const fn semantic(&self) -> &SemanticModel<'a> {
&self.semantic
}
/// The [`Path`] to the file under analysis.
pub(crate) const fn path(&self) -> &'a Path {
self.path
}
/// The [`Path`] to the package containing the current file.
pub(crate) const fn package(&self) -> Option<&'a Path> {
self.package
}
/// Returns whether the given rule should be checked.
#[inline]
pub(crate) const fn enabled(&self, rule: Rule) -> bool {
self.settings.rules.enabled(rule)
}
/// Returns whether any of the given rules should be checked.
#[inline]
pub(crate) const fn any_enabled(&self, rules: &[Rule]) -> bool {
self.settings.rules.any_enabled(rules)
}
}
impl<'a, 'b> Visitor<'b> for Checker<'a>
where
'b: 'a,
{
fn visit_stmt(&mut self, stmt: &'b Stmt) {
// Step 0: Pre-processing
self.semantic.push_stmt(stmt);
// Track whether we've seen docstrings, non-imports, etc.
match stmt {
Stmt::ImportFrom(ast::StmtImportFrom { module, names, .. }) => {
// Allow __future__ imports until we see a non-__future__ import.
if let Some("__future__") = module.as_deref() {
if names
.iter()
.any(|alias| alias.name.as_str() == "annotations")
{
self.semantic.flags |= SemanticModelFlags::FUTURE_ANNOTATIONS;
}
} else {
self.semantic.flags |= SemanticModelFlags::FUTURES_BOUNDARY;
}
}
Stmt::Import(_) => {
self.semantic.flags |= SemanticModelFlags::FUTURES_BOUNDARY;
}
_ => {
self.semantic.flags |= SemanticModelFlags::FUTURES_BOUNDARY;
if !self.semantic.seen_import_boundary()
&& !helpers::is_assignment_to_a_dunder(stmt)
&& !helpers::in_nested_block(self.semantic.parents())
{
self.semantic.flags |= SemanticModelFlags::IMPORT_BOUNDARY;
}
}
}
// Track each top-level import, to guide import insertions.
if matches!(stmt, Stmt::Import(_) | Stmt::ImportFrom(_)) {
if self.semantic.at_top_level() {
self.importer.visit_import(stmt);
}
}
// Store the flags prior to any further descent, so that we can restore them after visiting
// the node.
let flags_snapshot = self.semantic.flags;
// Step 1: Analysis
match stmt {
Stmt::Global(ast::StmtGlobal { names, range: _ }) => {
if self.enabled(Rule::AmbiguousVariableName) {
self.diagnostics.extend(names.iter().filter_map(|name| {
pycodestyle::rules::ambiguous_variable_name(name, name.range())
}));
}
}
Stmt::Nonlocal(ast::StmtNonlocal { names, range: _ }) => {
if self.enabled(Rule::AmbiguousVariableName) {
self.diagnostics.extend(names.iter().filter_map(|name| {
pycodestyle::rules::ambiguous_variable_name(name, name.range())
}));
}
if self.enabled(Rule::NonlocalWithoutBinding) {
if !self.semantic.scope_id.is_global() {
for name in names {
if self.semantic.nonlocal(name).is_none() {
self.diagnostics.push(Diagnostic::new(
pylint::rules::NonlocalWithoutBinding {
name: name.to_string(),
},
name.range(),
));
}
}
}
}
}
Stmt::Break(_) => {
if self.enabled(Rule::BreakOutsideLoop) {
if let Some(diagnostic) = pyflakes::rules::break_outside_loop(
stmt,
&mut self.semantic.parents().skip(1),
) {
self.diagnostics.push(diagnostic);
}
}
}
Stmt::Continue(_) => {
if self.enabled(Rule::ContinueOutsideLoop) {
if let Some(diagnostic) = pyflakes::rules::continue_outside_loop(
stmt,
&mut self.semantic.parents().skip(1),
) {
self.diagnostics.push(diagnostic);
}
}
}
Stmt::FunctionDef(ast::StmtFunctionDef {
name,
decorator_list,
returns,
args,
body,
..
})
| Stmt::AsyncFunctionDef(ast::StmtAsyncFunctionDef {
name,
decorator_list,
returns,
args,
body,
..
}) => {
if self.enabled(Rule::DjangoNonLeadingReceiverDecorator) {
flake8_django::rules::non_leading_receiver_decorator(self, decorator_list);
}
if self.enabled(Rule::AmbiguousFunctionName) {
if let Some(diagnostic) = pycodestyle::rules::ambiguous_function_name(name) {
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::InvalidStrReturnType) {
pylint::rules::invalid_str_return(self, name, body);
}
if self.enabled(Rule::InvalidFunctionName) {
if let Some(diagnostic) = pep8_naming::rules::invalid_function_name(
stmt,
name,
decorator_list,
&self.settings.pep8_naming.ignore_names,
&self.semantic,
) {
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::InvalidFirstArgumentNameForClassMethod) {
if let Some(diagnostic) =
pep8_naming::rules::invalid_first_argument_name_for_class_method(
self,
self.semantic.scope(),
name,
decorator_list,
args,
)
{
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::InvalidFirstArgumentNameForMethod) {
if let Some(diagnostic) =
pep8_naming::rules::invalid_first_argument_name_for_method(
self,
self.semantic.scope(),
name,
decorator_list,
args,
)
{
self.diagnostics.push(diagnostic);
}
}
if self.is_stub {
if self.enabled(Rule::PassStatementStubBody) {
flake8_pyi::rules::pass_statement_stub_body(self, body);
}
if self.enabled(Rule::NonEmptyStubBody) {
flake8_pyi::rules::non_empty_stub_body(self, body);
}
if self.enabled(Rule::StubBodyMultipleStatements) {
flake8_pyi::rules::stub_body_multiple_statements(self, stmt, body);
}
if self.enabled(Rule::AnyEqNeAnnotation) {
flake8_pyi::rules::any_eq_ne_annotation(self, name, args);
}
if self.enabled(Rule::NonSelfReturnType) {
flake8_pyi::rules::non_self_return_type(
self,
stmt,
name,
decorator_list,
returns.as_ref().map(AsRef::as_ref),
args,
stmt.is_async_function_def_stmt(),
);
}
if self.enabled(Rule::StrOrReprDefinedInStub) {
flake8_pyi::rules::str_or_repr_defined_in_stub(self, stmt);
}
if self.enabled(Rule::NoReturnArgumentAnnotationInStub) {
flake8_pyi::rules::no_return_argument_annotation(self, args);
}
if self.enabled(Rule::BadExitAnnotation) {
flake8_pyi::rules::bad_exit_annotation(
self,
stmt.is_async_function_def_stmt(),
name,
args,
);
}
if self.enabled(Rule::RedundantNumericUnion) {
flake8_pyi::rules::redundant_numeric_union(self, args);
}
}
if self.enabled(Rule::DunderFunctionName) {
if let Some(diagnostic) = pep8_naming::rules::dunder_function_name(
self.semantic.scope(),
stmt,
name,
&self.settings.pep8_naming.ignore_names,
) {
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::GlobalStatement) {
pylint::rules::global_statement(self, name);
}
if self.enabled(Rule::LRUCacheWithoutParameters) {
if self.settings.target_version >= PythonVersion::Py38 {
pyupgrade::rules::lru_cache_without_parameters(self, decorator_list);
}
}
if self.enabled(Rule::LRUCacheWithMaxsizeNone) {
if self.settings.target_version >= PythonVersion::Py39 {
pyupgrade::rules::lru_cache_with_maxsize_none(self, decorator_list);
}
}
if self.enabled(Rule::CachedInstanceMethod) {
flake8_bugbear::rules::cached_instance_method(self, decorator_list);
}
if self.any_enabled(&[
Rule::UnnecessaryReturnNone,
Rule::ImplicitReturnValue,
Rule::ImplicitReturn,
Rule::UnnecessaryAssign,
Rule::SuperfluousElseReturn,
Rule::SuperfluousElseRaise,
Rule::SuperfluousElseContinue,
Rule::SuperfluousElseBreak,
]) {
flake8_return::rules::function(self, body, returns.as_ref().map(AsRef::as_ref));
}
if self.enabled(Rule::UselessReturn) {
pylint::rules::useless_return(
self,
stmt,
body,
returns.as_ref().map(AsRef::as_ref),
);
}
if self.enabled(Rule::ComplexStructure) {
if let Some(diagnostic) = mccabe::rules::function_is_too_complex(
stmt,
name,
body,
self.settings.mccabe.max_complexity,
) {
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::HardcodedPasswordDefault) {
flake8_bandit::rules::hardcoded_password_default(self, args);
}
if self.enabled(Rule::PropertyWithParameters) {
pylint::rules::property_with_parameters(self, stmt, decorator_list, args);
}
if self.enabled(Rule::TooManyArguments) {
pylint::rules::too_many_arguments(self, args, stmt);
}
if self.enabled(Rule::TooManyReturnStatements) {
if let Some(diagnostic) = pylint::rules::too_many_return_statements(
stmt,
body,
self.settings.pylint.max_returns,
) {
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::TooManyBranches) {
if let Some(diagnostic) = pylint::rules::too_many_branches(
stmt,
body,
self.settings.pylint.max_branches,
) {
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::TooManyStatements) {
if let Some(diagnostic) = pylint::rules::too_many_statements(
stmt,
body,
self.settings.pylint.max_statements,
) {
self.diagnostics.push(diagnostic);
}
}
if self.any_enabled(&[
Rule::PytestFixtureIncorrectParenthesesStyle,
Rule::PytestFixturePositionalArgs,
Rule::PytestExtraneousScopeFunction,
Rule::PytestMissingFixtureNameUnderscore,
Rule::PytestIncorrectFixtureNameUnderscore,
Rule::PytestFixtureParamWithoutValue,
Rule::PytestDeprecatedYieldFixture,
Rule::PytestFixtureFinalizerCallback,
Rule::PytestUselessYieldFixture,
Rule::PytestUnnecessaryAsyncioMarkOnFixture,
Rule::PytestErroneousUseFixturesOnFixture,
]) {
flake8_pytest_style::rules::fixture(
self,
stmt,
name,
args,
decorator_list,
body,
);
}
if self.any_enabled(&[
Rule::PytestParametrizeNamesWrongType,
Rule::PytestParametrizeValuesWrongType,
]) {
flake8_pytest_style::rules::parametrize(self, decorator_list);
}
if self.any_enabled(&[
Rule::PytestIncorrectMarkParenthesesStyle,
Rule::PytestUseFixturesWithoutParameters,
]) {
flake8_pytest_style::rules::marks(self, decorator_list);
}
if self.enabled(Rule::BooleanPositionalArgInFunctionDefinition) {
flake8_boolean_trap::rules::check_positional_boolean_in_def(
self,
name,
decorator_list,
args,
);
}
if self.enabled(Rule::BooleanDefaultValueInFunctionDefinition) {
flake8_boolean_trap::rules::check_boolean_default_value_in_function_definition(
self,
name,
decorator_list,
args,
);
}
if self.enabled(Rule::UnexpectedSpecialMethodSignature) {
pylint::rules::unexpected_special_method_signature(
self,
stmt,
name,
decorator_list,
args,
);
}
if self.enabled(Rule::FStringDocstring) {
flake8_bugbear::rules::f_string_docstring(self, body);
}
if self.enabled(Rule::YieldInForLoop) {
pyupgrade::rules::yield_in_for_loop(self, stmt);
}
if let ScopeKind::Class(class_def) = self.semantic.scope().kind {
if self.enabled(Rule::BuiltinAttributeShadowing) {
flake8_builtins::rules::builtin_attribute_shadowing(
self,
class_def,
name,
name.range(),
);
}
} else {
if self.enabled(Rule::BuiltinVariableShadowing) {
flake8_builtins::rules::builtin_variable_shadowing(
self,
name,
name.range(),
);
}
}
#[cfg(feature = "unreachable-code")]
if self.enabled(Rule::UnreachableCode) {
self.diagnostics
.extend(ruff::rules::unreachable::in_function(name, body));
}
}
Stmt::Return(_) => {
if self.enabled(Rule::ReturnOutsideFunction) {
pyflakes::rules::return_outside_function(self, stmt);
}
if self.enabled(Rule::ReturnInInit) {
pylint::rules::return_in_init(self, stmt);
}
}
Stmt::ClassDef(
class_def @ ast::StmtClassDef {
name,
bases,
keywords,
type_params: _,
decorator_list,
body,
range: _,
},
) => {
if self.enabled(Rule::DjangoNullableModelStringField) {
flake8_django::rules::nullable_model_string_field(self, body);
}
if self.enabled(Rule::DjangoExcludeWithModelForm) {
if let Some(diagnostic) =
flake8_django::rules::exclude_with_model_form(self, bases, body)
{
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::DjangoAllWithModelForm) {
if let Some(diagnostic) =
flake8_django::rules::all_with_model_form(self, bases, body)
{
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::DjangoUnorderedBodyContentInModel) {
flake8_django::rules::unordered_body_content_in_model(self, bases, body);
}
if !self.is_stub {
if self.enabled(Rule::DjangoModelWithoutDunderStr) {
flake8_django::rules::model_without_dunder_str(self, class_def);
}
}
if self.enabled(Rule::GlobalStatement) {
pylint::rules::global_statement(self, name);
}
if self.enabled(Rule::UselessObjectInheritance) {
pyupgrade::rules::useless_object_inheritance(self, class_def);
}
if self.enabled(Rule::UnnecessaryClassParentheses) {
pyupgrade::rules::unnecessary_class_parentheses(self, class_def);
}
if self.enabled(Rule::AmbiguousClassName) {
if let Some(diagnostic) = pycodestyle::rules::ambiguous_class_name(name) {
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::InvalidClassName) {
if let Some(diagnostic) = pep8_naming::rules::invalid_class_name(
stmt,
name,
&self.settings.pep8_naming.ignore_names,
) {
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::ErrorSuffixOnExceptionName) {
if let Some(diagnostic) = pep8_naming::rules::error_suffix_on_exception_name(
stmt,
bases,
name,
&self.settings.pep8_naming.ignore_names,
) {
self.diagnostics.push(diagnostic);
}
}
if !self.is_stub {
if self.any_enabled(&[
Rule::AbstractBaseClassWithoutAbstractMethod,
Rule::EmptyMethodWithoutAbstractDecorator,
]) {
flake8_bugbear::rules::abstract_base_class(
self, stmt, name, bases, keywords, body,
);
}
}
if self.is_stub {
if self.enabled(Rule::PassStatementStubBody) {
flake8_pyi::rules::pass_statement_stub_body(self, body);
}
if self.enabled(Rule::PassInClassBody) {
flake8_pyi::rules::pass_in_class_body(self, stmt, body);
}
if self.enabled(Rule::EllipsisInNonEmptyClassBody) {
flake8_pyi::rules::ellipsis_in_non_empty_class_body(self, stmt, body);
}
}
if self.enabled(Rule::PytestIncorrectMarkParenthesesStyle) {
flake8_pytest_style::rules::marks(self, decorator_list);
}
if self.enabled(Rule::DuplicateClassFieldDefinition) {
flake8_pie::rules::duplicate_class_field_definition(self, stmt, body);
}
if self.enabled(Rule::NonUniqueEnums) {
flake8_pie::rules::non_unique_enums(self, stmt, body);
}
if self.enabled(Rule::MutableClassDefault) {
ruff::rules::mutable_class_default(self, class_def);
}
if self.enabled(Rule::MutableDataclassDefault) {
ruff::rules::mutable_dataclass_default(self, class_def);
}
if self.enabled(Rule::FunctionCallInDataclassDefaultArgument) {
ruff::rules::function_call_in_dataclass_default(self, class_def);
}
if self.enabled(Rule::FStringDocstring) {
flake8_bugbear::rules::f_string_docstring(self, body);
}
if self.enabled(Rule::BuiltinVariableShadowing) {
flake8_builtins::rules::builtin_variable_shadowing(self, name, name.range());
}
if self.enabled(Rule::DuplicateBases) {
pylint::rules::duplicate_bases(self, name, bases);
}
if self.enabled(Rule::NoSlotsInStrSubclass) {
flake8_slots::rules::no_slots_in_str_subclass(self, stmt, class_def);
}
if self.enabled(Rule::NoSlotsInTupleSubclass) {
flake8_slots::rules::no_slots_in_tuple_subclass(self, stmt, class_def);
}
if self.enabled(Rule::NoSlotsInNamedtupleSubclass) {
flake8_slots::rules::no_slots_in_namedtuple_subclass(self, stmt, class_def);
}
if self.enabled(Rule::SingleStringSlots) {
pylint::rules::single_string_slots(self, class_def);
}
}
Stmt::Import(ast::StmtImport { names, range: _ }) => {
if self.enabled(Rule::MultipleImportsOnOneLine) {
pycodestyle::rules::multiple_imports_on_one_line(self, stmt, names);
}
if self.enabled(Rule::ModuleImportNotAtTopOfFile) {
pycodestyle::rules::module_import_not_at_top_of_file(self, stmt, self.locator);
}
if self.enabled(Rule::GlobalStatement) {
for name in names {
if let Some(asname) = name.asname.as_ref() {
pylint::rules::global_statement(self, asname);
} else {
pylint::rules::global_statement(self, &name.name);
}
}
}
if self.enabled(Rule::DeprecatedCElementTree) {
pyupgrade::rules::deprecated_c_element_tree(self, stmt);
}
if self.enabled(Rule::DeprecatedMockImport) {
pyupgrade::rules::deprecated_mock_import(self, stmt);
}
for alias in names {
if let Some(asname) = &alias.asname {
if self.enabled(Rule::BuiltinVariableShadowing) {
flake8_builtins::rules::builtin_variable_shadowing(
self,
asname,
asname.range(),
);
}
}
if self.enabled(Rule::Debugger) {
if let Some(diagnostic) =
flake8_debugger::rules::debugger_import(stmt, None, &alias.name)
{
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::BannedApi) {
flake8_tidy_imports::rules::name_or_parent_is_banned(
self,
&alias.name,
alias,
);
}
if !self.is_stub {
if self.enabled(Rule::UselessImportAlias) {
pylint::rules::useless_import_alias(self, alias);
}
}
if self.enabled(Rule::ManualFromImport) {
pylint::rules::manual_from_import(self, stmt, alias, names);
}
if self.enabled(Rule::ImportSelf) {
if let Some(diagnostic) =
pylint::rules::import_self(alias, self.module_path)
{
self.diagnostics.push(diagnostic);
}
}
if let Some(asname) = &alias.asname {
let name = alias.name.split('.').last().unwrap();
if self.enabled(Rule::ConstantImportedAsNonConstant) {
if let Some(diagnostic) =
pep8_naming::rules::constant_imported_as_non_constant(
name,
asname,
alias,
stmt,
&self.settings.pep8_naming.ignore_names,
)
{
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::LowercaseImportedAsNonLowercase) {
if let Some(diagnostic) =
pep8_naming::rules::lowercase_imported_as_non_lowercase(
name,
asname,
alias,
stmt,
&self.settings.pep8_naming.ignore_names,
)
{
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::CamelcaseImportedAsLowercase) {
if let Some(diagnostic) =
pep8_naming::rules::camelcase_imported_as_lowercase(
name,
asname,
alias,
stmt,
&self.settings.pep8_naming.ignore_names,
)
{
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::CamelcaseImportedAsConstant) {
if let Some(diagnostic) =
pep8_naming::rules::camelcase_imported_as_constant(
name,
asname,
alias,
stmt,
&self.settings.pep8_naming.ignore_names,
)
{
self.diagnostics.push(diagnostic);
}
}
if self.enabled(Rule::CamelcaseImportedAsAcronym) {
if let Some(diagnostic) =
pep8_naming::rules::camelcase_imported_as_acronym(
name,
asname,
alias,
stmt,
&self.settings.pep8_naming.ignore_names,
)
{
self.diagnostics.push(diagnostic);
}
}
}
if self.enabled(Rule::BannedImportAlias) {
if let Some(asname) = &alias.asname {
if let Some(diagnostic) =
flake8_import_conventions::rules::banned_import_alias(
stmt,
&alias.name,
asname,
&self.settings.flake8_import_conventions.banned_aliases,
)
{
self.diagnostics.push(diagnostic);
}
}
}
if self.enabled(Rule::PytestIncorrectPytestImport) {
if let Some(diagnostic) = flake8_pytest_style::rules::import(
stmt,
&alias.name,
alias.asname.as_deref(),
) {
self.diagnostics.push(diagnostic);
}
}
}
}
Stmt::ImportFrom(
import_from @ ast::StmtImportFrom {
names,
module,
level,
range: _,
},
) => {
let module = module.as_deref();
let level = level.map(|level| level.to_u32());
if self.enabled(Rule::ModuleImportNotAtTopOfFile) {
pycodestyle::rules::module_import_not_at_top_of_file(self, stmt, self.locator);
}
if self.enabled(Rule::GlobalStatement) {
for name in names {
if let Some(asname) = name.asname.as_ref() {
pylint::rules::global_statement(self, asname);
} else {
pylint::rules::global_statement(self, &name.name);
}
}
}
if self.enabled(Rule::UnnecessaryFutureImport) {
if self.settings.target_version >= PythonVersion::Py37 {
if let Some("__future__") = module {
pyupgrade::rules::unnecessary_future_import(self, stmt, names);
}
}
}
if self.enabled(Rule::DeprecatedMockImport) {
pyupgrade::rules::deprecated_mock_import(self, stmt);
}
if self.enabled(Rule::DeprecatedCElementTree) {
pyupgrade::rules::deprecated_c_element_tree(self, stmt);
}
if self.enabled(Rule::DeprecatedImport) {
pyupgrade::rules::deprecated_import(self, stmt, names, module, level);
}
if self.enabled(Rule::UnnecessaryBuiltinImport) {
if let Some(module) = module {
pyupgrade::rules::unnecessary_builtin_import(self, stmt, module, names);
}
}
if self.enabled(Rule::BannedApi) {
if let Some(module) =
helpers::resolve_imported_module_path(level, module, self.module_path)
{
flake8_tidy_imports::rules::name_or_parent_is_banned(self, &module, stmt);
for alias in names {