-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathdiagnostic.rs
More file actions
6697 lines (6276 loc) · 237 KB
/
diagnostic.rs
File metadata and controls
6697 lines (6276 loc) · 237 KB
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
use super::call::CallErrorKind;
use super::context::InferContext;
use super::mro::DuplicateBaseError;
use super::{
CallArguments, CallDunderError, ClassBase, ClassLiteral, KnownClass, StaticClassLiteral,
add_inferred_python_version_hint_to_diagnostic,
};
use crate::diagnostic::did_you_mean;
use crate::diagnostic::format_enumeration;
use crate::lint::{Level, LintRegistryBuilder, LintStatus};
use crate::place::{DefinedPlace, Place, place_from_bindings};
use crate::suppression::FileSuppressionId;
use crate::types::call::CallError;
use crate::types::class::{
CodeGeneratorKind, DisjointBase, DisjointBaseKind, ExpandedClassBaseEntry, MethodDecorator,
};
use crate::types::function::{FunctionDecorators, FunctionType, KnownFunction, OverloadLiteral};
use crate::types::infer::UnsupportedComparisonError;
use crate::types::overrides::MethodKind;
use crate::types::protocol_class::ProtocolMember;
use crate::types::string_annotation::{
ESCAPE_CHARACTER_IN_FORWARD_ANNOTATION, IMPLICIT_CONCATENATED_STRING_TYPE_ANNOTATION,
INVALID_SYNTAX_IN_FORWARD_ANNOTATION, RAW_STRING_TYPE_ANNOTATION,
};
use crate::types::tuple::TupleSpec;
use crate::types::typed_dict::TypedDictSchema;
use crate::types::typevar::TypeVarInstance;
use crate::types::{
BoundTypeVarInstance, ClassType, DynamicType, ErrorContextTree, LintDiagnosticGuard, Protocol,
ProtocolInstanceType, SpecialFormType, SubclassOfInner, Type, TypeContext, TypeVarVariance,
binding_type, protocol_class::ProtocolClass,
};
use crate::types::{KnownInstanceType, MemberLookupPolicy, TypedDictType, UnionType};
use crate::{Db, DisplaySettings, FxIndexMap, Program, declare_lint};
use itertools::Itertools;
use ruff_db::source::source_text;
use ruff_db::{
diagnostic::{Annotation, Diagnostic, Span, SubDiagnostic, SubDiagnosticSeverity},
parsed::parsed_module,
};
use ruff_diagnostics::{Edit, Fix, IsolationLevel};
use ruff_python_ast::name::Name;
use ruff_python_ast::token::parentheses_iterator;
use ruff_python_ast::{self as ast, AnyNodeRef, HasNodeIndex, PythonVersion, StringFlags};
use ruff_source_file::LineRanges;
use ruff_text_size::{Ranged, TextRange};
use rustc_hash::FxHashSet;
use std::fmt::{self, Formatter};
use ty_module_resolver::{KnownModule, Module, ModuleName, file_to_module};
use ty_python_core::definition::{Definition, DefinitionKind};
use ty_python_core::place::{PlaceTable, ScopedPlaceId};
use ty_python_core::{SemanticIndex, global_scope, place_table, use_def_map};
const RUNTIME_CHECKABLE_DOCS_URL: &str =
"https://docs.python.org/3/library/typing.html#typing.runtime_checkable";
/// Registers all known type check lints.
pub(crate) fn register_lints(registry: &mut LintRegistryBuilder) {
registry.register_lint(&AMBIGUOUS_PROTOCOL_MEMBER);
registry.register_lint(&CALL_NON_CALLABLE);
registry.register_lint(&CALL_TOP_CALLABLE);
registry.register_lint(&POSSIBLY_MISSING_IMPLICIT_CALL);
registry.register_lint(&INVALID_DATACLASS_OVERRIDE);
registry.register_lint(&INVALID_DATACLASS);
registry.register_lint(&CONFLICTING_ARGUMENT_FORMS);
registry.register_lint(&CONFLICTING_DECLARATIONS);
registry.register_lint(&CONFLICTING_METACLASS);
registry.register_lint(&CYCLIC_CLASS_DEFINITION);
registry.register_lint(&CYCLIC_TYPE_ALIAS_DEFINITION);
registry.register_lint(&DEPRECATED);
registry.register_lint(&DIVISION_BY_ZERO);
registry.register_lint(&DUPLICATE_BASE);
registry.register_lint(&DUPLICATE_KW_ONLY);
registry.register_lint(&DATACLASS_FIELD_ORDER);
registry.register_lint(&EMPTY_BODY);
registry.register_lint(&INSTANCE_LAYOUT_CONFLICT);
registry.register_lint(&INCONSISTENT_MRO);
registry.register_lint(&INDEX_OUT_OF_BOUNDS);
registry.register_lint(&INVALID_KEY);
registry.register_lint(&ISINSTANCE_AGAINST_PROTOCOL);
registry.register_lint(&ISINSTANCE_AGAINST_TYPED_DICT);
registry.register_lint(&INVALID_ARGUMENT_TYPE);
registry.register_lint(&INVALID_RETURN_TYPE);
registry.register_lint(&INVALID_YIELD);
registry.register_lint(&INVALID_ASSIGNMENT);
registry.register_lint(&INVALID_AWAIT);
registry.register_lint(&INVALID_BASE);
registry.register_lint(&INVALID_CONTEXT_MANAGER);
registry.register_lint(&INVALID_DECLARATION);
registry.register_lint(&INVALID_EXCEPTION_CAUGHT);
registry.register_lint(&INVALID_ENUM_MEMBER_ANNOTATION);
registry.register_lint(&INVALID_GENERIC_ENUM);
registry.register_lint(&INVALID_GENERIC_CLASS);
registry.register_lint(&INVALID_LEGACY_TYPE_VARIABLE);
registry.register_lint(&INVALID_PARAMSPEC);
registry.register_lint(&INVALID_TYPE_ALIAS_TYPE);
registry.register_lint(&INVALID_NEWTYPE);
registry.register_lint(&MISMATCHED_TYPE_NAME);
registry.register_lint(&INVALID_METACLASS);
registry.register_lint(&INVALID_OVERLOAD);
registry.register_lint(&USELESS_OVERLOAD_BODY);
registry.register_lint(&INVALID_PARAMETER_DEFAULT);
registry.register_lint(&INVALID_PROTOCOL);
registry.register_lint(&INVALID_NAMED_TUPLE);
registry.register_lint(&INVALID_NAMED_TUPLE_OVERRIDE);
registry.register_lint(&INVALID_RAISE);
registry.register_lint(&INVALID_SUPER_ARGUMENT);
registry.register_lint(&INVALID_TYPE_ARGUMENTS);
registry.register_lint(&INVALID_TYPE_CHECKING_CONSTANT);
registry.register_lint(&INVALID_TYPE_FORM);
registry.register_lint(&INVALID_MATCH_PATTERN);
registry.register_lint(&INVALID_TYPE_GUARD_DEFINITION);
registry.register_lint(&INVALID_TYPE_GUARD_CALL);
registry.register_lint(&INVALID_TYPE_VARIABLE_CONSTRAINTS);
registry.register_lint(&INVALID_TYPE_VARIABLE_BOUND);
registry.register_lint(&INVALID_TYPE_VARIABLE_DEFAULT);
registry.register_lint(&UNBOUND_TYPE_VARIABLE);
registry.register_lint(&MISSING_ARGUMENT);
registry.register_lint(&NO_MATCHING_OVERLOAD);
registry.register_lint(&NON_CALLABLE_INIT_SUBCLASS);
registry.register_lint(&NOT_SUBSCRIPTABLE);
registry.register_lint(&NOT_ITERABLE);
registry.register_lint(&UNSUPPORTED_BOOL_CONVERSION);
registry.register_lint(&PARAMETER_ALREADY_ASSIGNED);
registry.register_lint(&POSSIBLY_MISSING_ATTRIBUTE);
registry.register_lint(&POSSIBLY_MISSING_SUBMODULE);
registry.register_lint(&POSSIBLY_MISSING_IMPORT);
registry.register_lint(&POSSIBLY_UNRESOLVED_REFERENCE);
registry.register_lint(&SHADOWED_TYPE_VARIABLE);
registry.register_lint(&SUBCLASS_OF_FINAL_CLASS);
registry.register_lint(&OVERRIDE_OF_FINAL_METHOD);
registry.register_lint(&OVERRIDE_OF_FINAL_VARIABLE);
registry.register_lint(&INEFFECTIVE_FINAL);
registry.register_lint(&FINAL_ON_NON_METHOD);
registry.register_lint(&FINAL_WITHOUT_VALUE);
registry.register_lint(&ABSTRACT_METHOD_IN_FINAL_CLASS);
registry.register_lint(&CALL_ABSTRACT_METHOD);
registry.register_lint(&TYPE_ASSERTION_FAILURE);
registry.register_lint(&ASSERT_TYPE_UNSPELLABLE_SUBTYPE);
registry.register_lint(&TOO_MANY_POSITIONAL_ARGUMENTS);
registry.register_lint(&UNAVAILABLE_IMPLICIT_SUPER_ARGUMENTS);
registry.register_lint(&UNDEFINED_REVEAL);
registry.register_lint(&UNKNOWN_ARGUMENT);
registry.register_lint(&POSITIONAL_ONLY_PARAMETER_AS_KWARG);
registry.register_lint(&UNRESOLVED_ATTRIBUTE);
registry.register_lint(&UNRESOLVED_IMPORT);
registry.register_lint(&UNRESOLVED_REFERENCE);
registry.register_lint(&UNSUPPORTED_BASE);
registry.register_lint(&UNSUPPORTED_DYNAMIC_BASE);
registry.register_lint(&UNSUPPORTED_OPERATOR);
registry.register_lint(&UNUSED_AWAITABLE);
registry.register_lint(&ZERO_STEPSIZE_IN_SLICE);
registry.register_lint(&STATIC_ASSERT_ERROR);
registry.register_lint(&INVALID_ATTRIBUTE_ACCESS);
registry.register_lint(&REDUNDANT_CAST);
registry.register_lint(&REDUNDANT_FINAL_CLASSVAR);
registry.register_lint(&UNRESOLVED_GLOBAL);
registry.register_lint(&MISSING_TYPED_DICT_KEY);
registry.register_lint(&INVALID_TYPED_DICT_STATEMENT);
registry.register_lint(&INVALID_TYPED_DICT_FIELD);
registry.register_lint(&INVALID_TYPED_DICT_HEADER);
registry.register_lint(&INVALID_ATTRIBUTE_OVERRIDE);
registry.register_lint(&INVALID_METHOD_OVERRIDE);
registry.register_lint(&INVALID_EXPLICIT_OVERRIDE);
registry.register_lint(&SUPER_CALL_IN_NAMED_TUPLE_METHOD);
registry.register_lint(&INVALID_FROZEN_DATACLASS_SUBCLASS);
registry.register_lint(&INVALID_TOTAL_ORDERING);
registry.register_lint(&INVALID_LEGACY_POSITIONAL_PARAMETER);
// String annotations
registry.register_lint(&ESCAPE_CHARACTER_IN_FORWARD_ANNOTATION);
registry.register_lint(&IMPLICIT_CONCATENATED_STRING_TYPE_ANNOTATION);
registry.register_lint(&INVALID_SYNTAX_IN_FORWARD_ANNOTATION);
registry.register_lint(&RAW_STRING_TYPE_ANNOTATION);
}
declare_lint! {
/// ## What it does
/// Checks for calls to non-callable objects.
///
/// ## Why is this bad?
/// Calling a non-callable object will raise a `TypeError` at runtime.
///
/// ## Examples
/// ```python
/// 4() # TypeError: 'int' object is not callable
/// ```
pub(crate) static CALL_NON_CALLABLE = {
summary: "detects calls to non-callable objects",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for calls to objects typed as `Top[Callable[..., T]]` (the infinite union of all
/// callable types with return type `T`).
///
/// ## Why is this bad?
/// When an object is narrowed to `Top[Callable[..., object]]` (e.g., via `callable(x)` or
/// `isinstance(x, Callable)`), we know the object is callable, but we don't know its
/// precise signature. This type represents the set of all possible callable types
/// (including, e.g., functions that take no arguments and functions that require arguments),
/// so no specific set of arguments can be guaranteed to be valid.
///
/// ## Examples
/// ```python
/// def f(x: object):
/// if callable(x):
/// x() # error: We know `x` is callable, but not what arguments it accepts
/// ```
pub(crate) static CALL_TOP_CALLABLE = {
summary: "detects calls to the top callable type",
status: LintStatus::stable("0.0.7"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for implicit calls to possibly missing methods.
///
/// ## Why is this bad?
/// Expressions such as `x[y]` and `x * y` call methods
/// under the hood (`__getitem__` and `__mul__` respectively).
/// Calling a missing method will raise an `AttributeError` at runtime.
///
/// ## Examples
/// ```python
/// import datetime
///
/// class A:
/// if datetime.date.today().weekday() != 6:
/// def __getitem__(self, v): ...
///
/// A()[0] # TypeError: 'A' object is not subscriptable
/// ```
pub(crate) static POSSIBLY_MISSING_IMPLICIT_CALL = {
summary: "detects implicit calls to possibly missing methods",
status: LintStatus::stable("0.0.1-alpha.22"),
default_level: Level::Warn,
}
}
declare_lint! {
/// ## What it does
/// Checks whether an argument is used as both a value and a type form in a call.
///
/// ## Why is this bad?
/// Such calls have confusing semantics and often indicate a logic error.
///
/// ## Examples
/// ```python
/// from typing import reveal_type
/// from ty_extensions import is_singleton
///
/// if flag:
/// f = repr # Expects a value
/// else:
/// f = is_singleton # Expects a type form
///
/// f(int) # error
/// ```
pub(crate) static CONFLICTING_ARGUMENT_FORMS = {
summary: "detects when an argument is used as both a value and a type form in a call",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks whether a variable has been declared as two conflicting types.
///
/// ## Why is this bad
/// A variable with two conflicting declarations likely indicates a mistake.
/// Moreover, it could lead to incorrect or ill-defined type inference for
/// other code that relies on these variables.
///
/// ## Examples
/// ```python
/// if b:
/// a: int
/// else:
/// a: str
///
/// a = 1
/// ```
pub(crate) static CONFLICTING_DECLARATIONS = {
summary: "detects conflicting declarations",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for class definitions where the metaclass of the class
/// being created would not be a subclass of the metaclasses of
/// all the class's bases.
///
/// ## Why is it bad?
/// Such a class definition raises a `TypeError` at runtime.
///
/// ## Examples
/// ```python
/// class M1(type): ...
/// class M2(type): ...
/// class A(metaclass=M1): ...
/// class B(metaclass=M2): ...
///
/// # TypeError: metaclass conflict
/// class C(A, B): ...
/// ```
pub(crate) static CONFLICTING_METACLASS = {
summary: "detects conflicting metaclasses",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for class definitions in stub files that inherit
/// (directly or indirectly) from themselves.
///
/// ## Why is it bad?
/// Although forward references are natively supported in stub files,
/// inheritance cycles are still disallowed, as it is impossible to
/// resolve a consistent [method resolution order] for a class that
/// inherits from itself.
///
/// ## Examples
/// ```python
/// # foo.pyi
/// class A(B): ...
/// class B(A): ...
/// ```
///
/// [method resolution order]: https://docs.python.org/3/glossary.html#term-method-resolution-order
pub(crate) static CYCLIC_CLASS_DEFINITION = {
summary: "detects cyclic class definitions",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for type alias definitions that (directly or mutually) refer to themselves.
///
/// ## Why is it bad?
/// Although it is permitted to define a recursive type alias, it is not meaningful
/// to have a type alias whose expansion can only result in itself, and is therefore not allowed.
///
/// ## Examples
/// ```python
/// type Itself = Itself
///
/// type A = B
/// type B = A
/// ```
pub(crate) static CYCLIC_TYPE_ALIAS_DEFINITION = {
summary: "detects cyclic type alias definitions",
status: LintStatus::stable("0.0.1-alpha.29"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// It detects division by zero.
///
/// ## Why is this bad?
/// Dividing by zero raises a `ZeroDivisionError` at runtime.
///
/// ## Rule status
/// This rule is currently disabled by default because of the number of
/// false positives it can produce.
///
/// ## Examples
/// ```python
/// 5 / 0
/// ```
pub(crate) static DIVISION_BY_ZERO = {
summary: "detects division by zero",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Ignore,
}
}
declare_lint! {
/// ## What it does
/// Checks for uses of deprecated items
///
/// ## Why is this bad?
/// Deprecated items should no longer be used.
///
/// ## Examples
/// ```python
/// @warnings.deprecated("use new_func instead")
/// def old_func(): ...
///
/// old_func() # emits [deprecated] diagnostic
/// ```
pub(crate) static DEPRECATED = {
summary: "detects uses of deprecated items",
status: LintStatus::stable("0.0.1-alpha.16"),
default_level: Level::Warn,
}
}
declare_lint! {
/// ## What it does
/// Checks for class definitions with duplicate bases.
///
/// ## Why is this bad?
/// Class definitions with duplicate bases raise `TypeError` at runtime.
///
/// ## Examples
/// ```python
/// class A: ...
///
/// # TypeError: duplicate base class
/// class B(A, A): ...
/// ```
pub(crate) static DUPLICATE_BASE = {
summary: "detects class definitions with duplicate bases",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for dataclass definitions with more than one field
/// annotated with `KW_ONLY`.
///
/// ## Why is this bad?
/// `dataclasses.KW_ONLY` is a special marker used to
/// emulate the `*` syntax in normal signatures.
/// It can only be used once per dataclass.
///
/// Attempting to annotate two different fields with
/// it will lead to a runtime error.
///
/// ## Examples
/// ```python
/// from dataclasses import dataclass, KW_ONLY
///
/// @dataclass
/// class A: # Crash at runtime
/// b: int
/// _1: KW_ONLY
/// c: str
/// _2: KW_ONLY
/// d: bytes
/// ```
pub(crate) static DUPLICATE_KW_ONLY = {
summary: "detects dataclass definitions with more than one usage of `KW_ONLY`",
status: LintStatus::stable("0.0.1-alpha.12"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for dataclass definitions where required fields are defined after
/// fields with default values.
///
/// ## Why is this bad?
/// In dataclasses, all required fields (fields without default values) must be
/// defined before fields with default values. This is a Python requirement that
/// will raise a `TypeError` at runtime if violated.
///
/// ## Example
/// ```python
/// from dataclasses import dataclass
///
/// @dataclass
/// class Example:
/// x: int = 1 # Field with default value
/// y: str # Error: Required field after field with default
/// ```
pub(crate) static DATACLASS_FIELD_ORDER = {
summary: "detects dataclass definitions with required fields after fields with default values",
status: LintStatus::stable("0.0.15"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for dataclass definitions that have both `frozen=True` and a custom `__setattr__` or
/// `__delattr__` method defined.
///
/// ## Why is this bad?
/// Frozen dataclasses synthesize `__setattr__` and `__delattr__` methods which raise a
/// `FrozenInstanceError` to emulate immutability.
///
/// Overriding either of these methods raises a runtime error.
///
/// ## Examples
/// ```python
/// from dataclasses import dataclass
///
/// @dataclass(frozen=True)
/// class A:
/// def __setattr__(self, name: str, value: object) -> None: ...
/// ```
pub(crate) static INVALID_DATACLASS_OVERRIDE = {
summary: "detects dataclasses with `frozen=True` that have a custom `__setattr__` or `__delattr__` implementation",
status: LintStatus::stable("0.0.13"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for invalid applications of the `@dataclass` decorator.
///
/// ## Why is this bad?
/// Applying `@dataclass` to a class that inherits from `NamedTuple`, `TypedDict`,
/// `Enum`, or `Protocol` is invalid:
///
/// - `NamedTuple` and `TypedDict` classes will raise an exception at runtime when
/// instantiating the class.
/// - `Enum` classes with `@dataclass` are [explicitly not supported].
/// - `Protocol` classes define interfaces and cannot be instantiated.
///
/// ## Examples
/// ```python
/// from dataclasses import dataclass
/// from typing import NamedTuple
///
/// @dataclass # error: [invalid-dataclass]
/// class Foo(NamedTuple):
/// x: int
/// ```
///
/// [explicitly not supported]: https://docs.python.org/3/howto/enum.html#dataclass-support
pub(crate) static INVALID_DATACLASS = {
summary: "detects invalid `@dataclass` applications",
status: LintStatus::stable("0.0.12"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for classes definitions which will fail at runtime due to
/// "instance memory layout conflicts".
///
/// This error is usually caused by attempting to combine multiple classes
/// that define non-empty `__slots__` in a class's [Method Resolution Order]
/// (MRO), or by attempting to combine multiple builtin classes in a class's
/// MRO.
///
/// ## Why is this bad?
/// Inheriting from bases with conflicting instance memory layouts
/// will lead to a `TypeError` at runtime.
///
/// An instance memory layout conflict occurs when CPython cannot determine
/// the memory layout instances of a class should have, because the instance
/// memory layout of one of its bases conflicts with the instance memory layout
/// of one or more of its other bases.
///
/// For example, if a Python class defines non-empty `__slots__`, this will
/// impact the memory layout of instances of that class. Multiple inheritance
/// from more than one different class defining non-empty `__slots__` is not
/// allowed:
///
/// ```python
/// class A:
/// __slots__ = ("a", "b")
///
/// class B:
/// __slots__ = ("a", "b") # Even if the values are the same
///
/// # TypeError: multiple bases have instance lay-out conflict
/// class C(A, B): ...
/// ```
///
/// An instance layout conflict can also be caused by attempting to use
/// multiple inheritance with two builtin classes, due to the way that these
/// classes are implemented in a CPython C extension:
///
/// ```python
/// class A(int, float): ... # TypeError: multiple bases have instance lay-out conflict
/// ```
///
/// Note that pure-Python classes with no `__slots__`, or pure-Python classes
/// with empty `__slots__`, are always compatible:
///
/// ```python
/// class A: ...
/// class B:
/// __slots__ = ()
/// class C:
/// __slots__ = ("a", "b")
///
/// # fine
/// class D(A, B, C): ...
/// ```
///
/// ## Known problems
/// Classes that have "dynamic" definitions of `__slots__` (definitions do not consist
/// of string literals, or tuples of string literals) are not currently considered disjoint
/// bases by ty.
///
/// Additionally, this check is not exhaustive: many C extensions (including several in
/// the standard library) define classes that use extended memory layouts and thus cannot
/// coexist in a single MRO. Since it is currently not possible to represent this fact in
/// stub files, having a full knowledge of these classes is also impossible. When it comes
/// to classes that do not define `__slots__` at the Python level, therefore, ty, currently
/// only hard-codes a number of cases where it knows that a class will produce instances with
/// an atypical memory layout.
///
/// ## Further reading
/// - [CPython documentation: `__slots__`](https://docs.python.org/3/reference/datamodel.html#slots)
/// - [CPython documentation: Method Resolution Order](https://docs.python.org/3/glossary.html#term-method-resolution-order)
///
/// [Method Resolution Order]: https://docs.python.org/3/glossary.html#term-method-resolution-order
pub(crate) static INSTANCE_LAYOUT_CONFLICT = {
summary: "detects class definitions that raise `TypeError` due to instance layout conflict",
status: LintStatus::stable("0.0.1-alpha.12"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for protocol classes that will raise `TypeError` at runtime.
///
/// ## Why is this bad?
/// An invalidly defined protocol class may lead to the type checker inferring
/// unexpected things. It may also lead to `TypeError`s at runtime.
///
/// ## Examples
/// A `Protocol` class cannot inherit from a non-`Protocol` class;
/// this raises a `TypeError` at runtime:
///
/// ```pycon
/// >>> from typing import Protocol
/// >>> class Foo(int, Protocol): ...
/// ...
/// Traceback (most recent call last):
/// File "<python-input-1>", line 1, in <module>
/// class Foo(int, Protocol): ...
/// TypeError: Protocols can only inherit from other protocols, got <class 'int'>
/// ```
pub(crate) static INVALID_PROTOCOL = {
summary: "detects invalid protocol class definitions",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Error,
}
}
// Added in #17750.
declare_lint! {
/// ## What it does
/// Checks for protocol classes with members that will lead to ambiguous interfaces.
///
/// ## Why is this bad?
/// Assigning to an undeclared variable in a protocol class leads to an ambiguous
/// interface which may lead to the type checker inferring unexpected things. It's
/// recommended to ensure that all members of a protocol class are explicitly declared.
///
/// ## Examples
///
/// ```py
/// from typing import Protocol
///
/// class BaseProto(Protocol):
/// a: int # fine (explicitly declared as `int`)
/// def method_member(self) -> int: ... # fine: a method definition using `def` is considered a declaration
/// c = "some variable" # error: no explicit declaration, leading to ambiguity
/// b = method_member # error: no explicit declaration, leading to ambiguity
///
/// # error: this creates implicit assignments of `d` and `e` in the protocol class body.
/// # Were they really meant to be considered protocol members?
/// for d, e in enumerate(range(42)):
/// pass
///
/// class SubProto(BaseProto, Protocol):
/// a = 42 # fine (declared in superclass)
/// ```
pub(crate) static AMBIGUOUS_PROTOCOL_MEMBER = {
summary: "detects protocol classes with ambiguous interfaces",
status: LintStatus::stable("0.0.1-alpha.20"),
default_level: Level::Warn,
}
}
declare_lint! {
/// ## What it does
/// Checks for invalidly defined `NamedTuple` classes.
///
/// ## Why is this bad?
/// An invalidly defined `NamedTuple` class may lead to the type checker
/// drawing incorrect conclusions. It may also lead to `TypeError`s or
/// `AttributeError`s at runtime.
///
/// ## Examples
/// A class definition cannot combine `NamedTuple` with other base classes
/// in multiple inheritance; doing so raises a `TypeError` at runtime. The sole
/// exception to this rule is `Generic[]`, which can be used alongside `NamedTuple`
/// in a class's bases list.
///
/// ```pycon
/// >>> from typing import NamedTuple
/// >>> class Foo(NamedTuple, object): ...
/// TypeError: can only inherit from a NamedTuple type and Generic
/// ```
///
/// Further, `NamedTuple` field names cannot start with an underscore:
///
/// ```pycon
/// >>> from typing import NamedTuple
/// >>> class Foo(NamedTuple):
/// ... _bar: int
/// ValueError: Field names cannot start with an underscore: '_bar'
/// ```
///
/// `NamedTuple` classes also have certain synthesized attributes (like `_asdict`, `_make`,
/// `_replace`, etc.) that cannot be overwritten. Attempting to assign to these attributes
/// without a type annotation will raise an `AttributeError` at runtime.
///
/// ```pycon
/// >>> from typing import NamedTuple
/// >>> class Foo(NamedTuple):
/// ... x: int
/// ... _asdict = 42
/// AttributeError: Cannot overwrite NamedTuple attribute _asdict
/// ```
pub(crate) static INVALID_NAMED_TUPLE = {
summary: "detects invalid `NamedTuple` class definitions",
status: LintStatus::stable("0.0.1-alpha.19"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for subclass members that override inherited `NamedTuple` fields.
///
/// ## Why is this bad?
/// Reusing an inherited `NamedTuple` field name in a subclass creates a
/// class where tuple indexing and `repr()` still reflect the original
/// field, while attribute access follows the subclass member.
///
/// ## Default level
/// This rule is a warning by default because these overrides do not make
/// the class invalid at runtime.
///
/// ## Examples
/// ```python
/// from typing import NamedTuple
///
/// class User(NamedTuple):
/// name: str
///
/// class Admin(User):
/// name = "shadowed" # error: [invalid-named-tuple-override]
///
/// admin = Admin("Alice")
/// admin.name # "shadowed"
/// admin[0] # "Alice"
/// ```
pub(crate) static INVALID_NAMED_TUPLE_OVERRIDE = {
summary: "detects subclass members that override inherited `NamedTuple` fields",
status: LintStatus::stable("0.0.31"),
default_level: Level::Warn,
}
}
declare_lint! {
/// ## What it does
/// Checks for classes with an inconsistent [method resolution order] (MRO).
///
/// ## Why is this bad?
/// Classes with an inconsistent MRO will raise a `TypeError` at runtime.
///
/// ## Examples
/// ```python
/// class A: ...
/// class B(A): ...
///
/// # TypeError: Cannot create a consistent method resolution order
/// class C(A, B): ...
/// ```
///
/// [method resolution order]: https://docs.python.org/3/glossary.html#term-method-resolution-order
pub(crate) static INCONSISTENT_MRO = {
summary: "detects class definitions with an inconsistent MRO",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Checks for attempts to use an out of bounds index to get an item from
/// a container.
///
/// ## Why is this bad?
/// Using an out of bounds index will raise an `IndexError` at runtime.
///
/// ## Examples
/// ```python
/// t = (0, 1, 2)
/// t[3] # IndexError: tuple index out of range
/// ```
pub(crate) static INDEX_OUT_OF_BOUNDS = {
summary: "detects index out of bounds errors",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Error,
}
}
// Added in #19763.
declare_lint! {
/// ## What it does
/// Checks for subscript accesses with invalid keys and `TypedDict` construction with an
/// unknown key.
///
/// ## Why is this bad?
/// Subscripting with an invalid key will raise a `KeyError` at runtime.
///
/// Creating a `TypedDict` with an unknown key is likely a mistake; if the `TypedDict` is
/// `closed=true` it also violates the expectations of the type.
///
/// ## Examples
/// ```python
/// from typing import TypedDict
///
/// class Person(TypedDict):
/// name: str
/// age: int
///
/// alice = Person(name="Alice", age=30)
/// alice["height"] # KeyError: 'height'
///
/// bob: Person = { "namee": "Bob", "age": 30 } # typo!
///
/// carol = Person(name="Carol", aeg=25) # typo!
/// ```
pub(crate) static INVALID_KEY = {
summary: "detects invalid subscript accesses or TypedDict literal keys",
status: LintStatus::stable("0.0.1-alpha.17"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Reports invalid runtime checks against `Protocol` classes.
/// This includes explicit calls `isinstance()`/`issubclass()` against
/// non-runtime-checkable protocols, `issubclass()` calls against protocols
/// that have non-method members, and implicit `isinstance()` checks against
/// non-runtime-checkable protocols via pattern matching.
///
/// ## Why is this bad?
/// These calls (implicit or explicit) raise `TypeError` at runtime.
///
/// ## Examples
/// ```python
/// from typing_extensions import Protocol, runtime_checkable
///
/// class HasX(Protocol):
/// x: int
///
/// @runtime_checkable
/// class HasY(Protocol):
/// y: int
///
/// def f(arg: object, arg2: type):
/// isinstance(arg, HasX) # error: [isinstance-against-protocol] (not runtime-checkable)
/// issubclass(arg2, HasX) # error: [isinstance-against-protocol] (not runtime-checkable)
///
/// def g(arg: object):
/// match arg:
/// case HasX(): # error: [isinstance-against-protocol] (not runtime-checkable)
/// pass
///
/// def h(arg2: type):
/// isinstance(arg2, HasY) # fine (runtime-checkable)
///
/// # `HasY` is runtime-checkable, but has non-method members,
/// # so it still can't be used in `issubclass` checks)
/// issubclass(arg2, HasY) # error: [isinstance-against-protocol]
/// ```
///
/// ## References
/// - [Typing documentation: `@runtime_checkable`](https://docs.python.org/3/library/typing.html#typing.runtime_checkable)
pub(crate) static ISINSTANCE_AGAINST_PROTOCOL = {
summary: "reports invalid runtime checks against protocol classes",
status: LintStatus::stable("0.0.14"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Reports runtime checks against `TypedDict` classes.
/// This includes explicit calls to `isinstance()`/`issubclass()` and implicit
/// checks performed by `match` class patterns.
///
/// ## Why is this bad?
/// Using a `TypedDict` class in these contexts raises `TypeError` at runtime.
///
/// ## Examples
/// ```python
/// from typing_extensions import TypedDict
///
/// class Movie(TypedDict):
/// name: str
/// director: str
///
/// def f(arg: object, arg2: type):
/// isinstance(arg, Movie) # error: [isinstance-against-typed-dict]
/// issubclass(arg2, Movie) # error: [isinstance-against-typed-dict]
///
/// def g(arg: object):
/// match arg:
/// case Movie(): # error: [isinstance-against-typed-dict]
/// pass
/// ```
///
/// ## References
/// - [Typing specification: `TypedDict`](https://typing.python.org/en/latest/spec/typeddict.html)
pub(crate) static ISINSTANCE_AGAINST_TYPED_DICT = {
summary: "reports runtime checks against `TypedDict` classes",
status: LintStatus::stable("0.0.15"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Detects call arguments whose type is not assignable to the corresponding typed parameter.
///
/// ## Why is this bad?
/// Passing an argument of a type the function (or callable object) does not accept violates
/// the expectations of the function author and may cause unexpected runtime errors within the
/// body of the function.
///
/// ## Examples
/// ```python
/// def func(x: int): ...
/// func("foo") # error: [invalid-argument-type]
/// ```
pub(crate) static INVALID_ARGUMENT_TYPE = {
summary: "detects call arguments whose type is not assignable to the corresponding typed parameter",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Detects returned values that can't be assigned to the function's annotated return type.
///
/// Note that the special case of a function with a non-`None` return type and an empty body
/// is handled by the separate `empty-body` error code.
///
/// ## Why is this bad?
/// Returning an object of a type incompatible with the annotated return type
/// is unsound, and will lead to ty inferring incorrect types elsewhere.
///
/// ## Examples
/// ```python
/// def func() -> int:
/// return "a" # error: [invalid-return-type]
/// ```
pub(crate) static INVALID_RETURN_TYPE = {
summary: "detects returned values that can't be assigned to the function's annotated return type",
status: LintStatus::stable("0.0.1-alpha.1"),
default_level: Level::Error,
}
}
declare_lint! {
/// ## What it does
/// Detects `yield` and `yield from` expressions where the "yield" or "send" type
/// is incompatible with the generator function's annotated return type.
///
/// ## Why is this bad?
/// Yielding a value of a type that doesn't match the generator's declared yield type,
/// or using `yield from` with a sub-iterator whose yield or send type is incompatible,
/// is a type error that may cause downstream consumers of the generator to receive
/// values of an unexpected type.
///
/// ## Examples
/// ```python
/// from typing import Iterator
///
/// def gen() -> Iterator[int]:
/// yield "not an int" # error: [invalid-yield]