-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
dataClasses.ts
1535 lines (1368 loc) · 60.9 KB
/
dataClasses.ts
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
/*
* dataClasses.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
* Author: Eric Traut
*
* Provides special-case logic for the construction of dataclass
* classes and dataclass transform.
*/
import { assert } from '../common/debug';
import { DiagnosticAddendum } from '../common/diagnostic';
import { DiagnosticRule } from '../common/diagnosticRules';
import { convertOffsetsToRange } from '../common/positionUtils';
import { PythonVersion, pythonVersion3_13 } from '../common/pythonVersion';
import { TextRange } from '../common/textRange';
import { LocMessage } from '../localization/localize';
import {
ArgCategory,
ArgumentNode,
CallNode,
ClassNode,
ExpressionNode,
NameNode,
ParamCategory,
ParseNode,
ParseNodeType,
TypeAnnotationNode,
} from '../parser/parseNodes';
import * as AnalyzerNodeInfo from './analyzerNodeInfo';
import { getFileInfo } from './analyzerNodeInfo';
import { ConstraintSolution } from './constraintSolution';
import { ConstraintTracker } from './constraintTracker';
import { createFunctionFromConstructor, getBoundInitMethod } from './constructors';
import { DeclarationType, VariableDeclaration } from './declaration';
import { updateNamedTupleBaseClass } from './namedTuples';
import { getClassFullName, getEnclosingClassOrFunction, getScopeIdForNode, getTypeSourceId } from './parseTreeUtils';
import { evaluateStaticBoolExpression } from './staticExpressions';
import { Symbol, SymbolFlags } from './symbol';
import { isPrivateName } from './symbolNameUtils';
import { Arg, EvalFlags, TypeEvaluator, TypeResult } from './typeEvaluatorTypes';
import {
AnyType,
ClassType,
ClassTypeFlags,
combineTypes,
DataClassBehaviors,
DataClassEntry,
FunctionParam,
FunctionParamFlags,
FunctionType,
FunctionTypeFlags,
isClass,
isClassInstance,
isFunction,
isInstantiableClass,
isOverloaded,
isUnion,
OverloadedType,
TupleTypeArg,
Type,
TypeVarType,
UnknownType,
} from './types';
import {
addSolutionForSelfType,
applySolvedTypeVars,
buildSolutionFromSpecializedClass,
computeMroLinearization,
convertToInstance,
doForEachSignature,
getTypeVarScopeId,
getTypeVarScopeIds,
isLiteralType,
isMetaclassInstance,
makeInferenceContext,
requiresSpecialization,
specializeTupleClass,
synthesizeTypeVarForSelfCls,
} from './typeUtils';
// Validates fields for compatibility with a dataclass and synthesizes
// an appropriate __new__ and __init__ methods plus __dataclass_fields__
// and __match_args__ class variables.
export function synthesizeDataClassMethods(
evaluator: TypeEvaluator,
node: ClassNode,
classType: ClassType,
isNamedTuple: boolean,
skipSynthesizeInit: boolean,
hasExistingInitMethod: boolean,
skipSynthesizeHash: boolean
) {
assert(ClassType.isDataClass(classType) || isNamedTuple);
const classTypeVar = synthesizeTypeVarForSelfCls(classType, /* isClsParam */ true);
const newType = FunctionType.createSynthesizedInstance('__new__', FunctionTypeFlags.ConstructorMethod);
newType.priv.constructorTypeVarScopeId = getTypeVarScopeId(classType);
const initType = FunctionType.createSynthesizedInstance('__init__');
initType.priv.constructorTypeVarScopeId = getTypeVarScopeId(classType);
// Generate both a __new__ and an __init__ method. The parameters of the
// __new__ method are based on field definitions for NamedTuple classes,
// and the parameters of the __init__ method are based on field definitions
// in other cases.
FunctionType.addParam(
newType,
FunctionParam.create(ParamCategory.Simple, classTypeVar, FunctionParamFlags.TypeDeclared, 'cls')
);
if (!isNamedTuple) {
FunctionType.addDefaultParams(newType);
newType.shared.flags |= FunctionTypeFlags.GradualCallableForm;
}
newType.shared.declaredReturnType = convertToInstance(classTypeVar);
const selfType = synthesizeTypeVarForSelfCls(classType, /* isClsParam */ false);
const selfParam = FunctionParam.create(ParamCategory.Simple, selfType, FunctionParamFlags.TypeDeclared, 'self');
FunctionType.addParam(initType, selfParam);
if (isNamedTuple) {
FunctionType.addDefaultParams(initType);
initType.shared.flags |= FunctionTypeFlags.GradualCallableForm;
}
initType.shared.declaredReturnType = evaluator.getNoneType();
// For Python 3.13 and newer, synthesize a __replace__ method.
let replaceType: FunctionType | undefined;
if (
PythonVersion.isGreaterOrEqualTo(
AnalyzerNodeInfo.getFileInfo(node).executionEnvironment.pythonVersion,
pythonVersion3_13
)
) {
replaceType = FunctionType.createSynthesizedInstance('__replace__');
FunctionType.addParam(replaceType, selfParam);
FunctionType.addKeywordOnlyParamSeparator(replaceType);
replaceType.shared.declaredReturnType = selfType;
}
// Maintain a list of all dataclass entries (including
// those from inherited classes) plus a list of only those
// entries added by this class.
const localDataClassEntries: DataClassEntry[] = [];
const fullDataClassEntries: DataClassEntry[] = [];
const namedTupleEntries = new Set<string>();
const allAncestorsKnown = addInheritedDataClassEntries(classType, fullDataClassEntries);
if (!allAncestorsKnown) {
// If one or more ancestor classes have an unknown type, we cannot
// safely determine the parameter list, so we'll accept any parameters
// to avoid a false positive.
FunctionType.addDefaultParams(initType);
if (replaceType) {
FunctionType.addDefaultParams(replaceType);
}
}
// Add field-based parameters to either the __new__ or __init__ method
// based on whether this is a NamedTuple or a dataclass.
const constructorType = isNamedTuple ? newType : initType;
// Maintain a list of "type evaluators".
type EntryTypeEvaluator = () => Type;
const localEntryTypeEvaluator: { entry: DataClassEntry; evaluator: EntryTypeEvaluator }[] = [];
let sawKeywordOnlySeparator = false;
ClassType.getSymbolTable(classType).forEach((symbol, name) => {
if (symbol.isIgnoredForProtocolMatch()) {
return;
}
// Apparently, `__hash__` is special-cased in a dataclass. I can't find
// this in the spec, but the runtime seems to treat is specially.
if (name === '__hash__') {
return;
}
// Only variables (not functions, classes, etc.) are considered.
const classVarDecl = symbol.getTypedDeclarations().find((decl) => {
if (decl.type !== DeclarationType.Variable) {
return false;
}
const container = getEnclosingClassOrFunction(decl.node);
if (!container || container.nodeType !== ParseNodeType.Class) {
return false;
}
return true;
});
if (classVarDecl) {
let statement: ParseNode | undefined = classVarDecl.node;
while (statement) {
if (statement.nodeType === ParseNodeType.Assignment) {
break;
}
if (statement.nodeType === ParseNodeType.TypeAnnotation) {
if (statement.parent?.nodeType === ParseNodeType.Assignment) {
statement = statement.parent;
}
break;
}
statement = statement.parent;
}
if (!statement) {
return;
}
let variableNameNode: NameNode | undefined;
let typeAnnotationNode: TypeAnnotationNode | undefined;
let aliasName: string | undefined;
let variableTypeEvaluator: EntryTypeEvaluator | undefined;
let hasDefault = false;
let isDefaultFactory = false;
let isKeywordOnly = ClassType.isDataClassKeywordOnly(classType) || sawKeywordOnlySeparator;
let defaultExpr: ExpressionNode | undefined;
let includeInInit = true;
let converter: ArgumentNode | undefined;
if (statement.nodeType === ParseNodeType.Assignment) {
if (
statement.d.leftExpr.nodeType === ParseNodeType.TypeAnnotation &&
statement.d.leftExpr.d.valueExpr.nodeType === ParseNodeType.Name
) {
variableNameNode = statement.d.leftExpr.d.valueExpr;
typeAnnotationNode = statement.d.leftExpr;
const assignmentStatement = statement;
variableTypeEvaluator = () =>
evaluator.getTypeOfAnnotation(
(assignmentStatement.d.leftExpr as TypeAnnotationNode).d.annotation,
{
varTypeAnnotation: true,
allowFinal: true,
allowClassVar: true,
}
);
}
hasDefault = true;
defaultExpr = statement.d.rightExpr;
// If the RHS of the assignment is assigning a field instance where the
// "init" parameter is set to false, do not include it in the init method.
if (statement.d.rightExpr.nodeType === ParseNodeType.Call) {
const callTypeResult = evaluator.getTypeOfExpression(
statement.d.rightExpr.d.leftExpr,
EvalFlags.CallBaseDefaults
);
const callType = callTypeResult.type;
if (
!isNamedTuple &&
isDataclassFieldConstructor(
callType,
classType.shared.dataClassBehaviors?.fieldDescriptorNames || []
)
) {
const initArg = statement.d.rightExpr.d.args.find((arg) => arg.d.name?.d.value === 'init');
if (initArg && initArg.d.valueExpr) {
const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
includeInInit =
evaluateStaticBoolExpression(
initArg.d.valueExpr,
fileInfo.executionEnvironment,
fileInfo.definedConstants
) ?? includeInInit;
} else {
includeInInit =
getDefaultArgValueForFieldSpecifier(
evaluator,
statement.d.rightExpr,
callTypeResult,
'init'
) ?? includeInInit;
}
const kwOnlyArg = statement.d.rightExpr.d.args.find((arg) => arg.d.name?.d.value === 'kw_only');
if (kwOnlyArg && kwOnlyArg.d.valueExpr) {
const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
isKeywordOnly =
evaluateStaticBoolExpression(
kwOnlyArg.d.valueExpr,
fileInfo.executionEnvironment,
fileInfo.definedConstants
) ?? isKeywordOnly;
} else {
isKeywordOnly =
getDefaultArgValueForFieldSpecifier(
evaluator,
statement.d.rightExpr,
callTypeResult,
'kw_only'
) ?? isKeywordOnly;
}
const defaultValueArg = statement.d.rightExpr.d.args.find(
(arg) => arg.d.name?.d.value === 'default'
);
hasDefault = !!defaultValueArg;
if (defaultValueArg?.d.valueExpr) {
defaultExpr = defaultValueArg.d.valueExpr;
}
const defaultFactoryArg = statement.d.rightExpr.d.args.find(
(arg) => arg.d.name?.d.value === 'default_factory' || arg.d.name?.d.value === 'factory'
);
if (defaultFactoryArg) {
hasDefault = true;
isDefaultFactory = true;
}
if (defaultFactoryArg?.d.valueExpr) {
defaultExpr = defaultFactoryArg.d.valueExpr;
}
const aliasArg = statement.d.rightExpr.d.args.find((arg) => arg.d.name?.d.value === 'alias');
if (aliasArg) {
const valueType = evaluator.getTypeOfExpression(aliasArg.d.valueExpr).type;
if (
isClassInstance(valueType) &&
ClassType.isBuiltIn(valueType, 'str') &&
isLiteralType(valueType)
) {
aliasName = valueType.priv.literalValue as string;
}
}
const converterArg = statement.d.rightExpr.d.args.find(
(arg) => arg.d.name?.d.value === 'converter'
);
if (converterArg && converterArg.d.valueExpr) {
converter = converterArg;
}
}
}
} else if (statement.nodeType === ParseNodeType.TypeAnnotation) {
if (statement.d.valueExpr.nodeType === ParseNodeType.Name) {
variableNameNode = statement.d.valueExpr;
typeAnnotationNode = statement;
const annotationStatement = statement;
variableTypeEvaluator = () =>
evaluator.getTypeOfAnnotation(annotationStatement.d.annotation, {
varTypeAnnotation: true,
allowFinal: true,
allowClassVar: true,
});
// Is this a KW_ONLY separator introduced in Python 3.10?
if (!isNamedTuple && statement.d.valueExpr.d.value === '_') {
const annotatedType = variableTypeEvaluator();
if (isClassInstance(annotatedType) && ClassType.isBuiltIn(annotatedType, 'KW_ONLY')) {
sawKeywordOnlySeparator = true;
variableNameNode = undefined;
typeAnnotationNode = undefined;
variableTypeEvaluator = undefined;
}
}
}
}
if (variableNameNode && variableTypeEvaluator) {
const variableName = variableNameNode.d.value;
// Don't include class vars. PEP 557 indicates that they shouldn't
// be considered data class entries.
const variableSymbol = ClassType.getSymbolTable(classType).get(variableName);
namedTupleEntries.add(variableName);
if (variableSymbol?.isClassVar() && !variableSymbol?.isFinalVarInClassBody()) {
// If an ancestor class declared an instance variable but this dataclass
// declares a ClassVar, delete the older one from the full data class entries.
// We exclude final variables here because a Final type annotation is implicitly
// considered a ClassVar by the binder, but dataclass rules are different.
const index = fullDataClassEntries.findIndex((p) => p.name === variableName);
if (index >= 0) {
fullDataClassEntries.splice(index, 1);
}
const dataClassEntry: DataClassEntry = {
name: variableName,
classType,
alias: aliasName,
isKeywordOnly: false,
hasDefault,
isDefaultFactory,
defaultExpr,
includeInInit,
nameNode: variableNameNode,
typeAnnotationNode: typeAnnotationNode,
type: UnknownType.create(),
isClassVar: true,
converter,
};
localDataClassEntries.push(dataClassEntry);
} else {
// Create a new data class entry, but defer evaluation of the type until
// we've compiled the full list of data class entries for this class. This
// allows us to handle circular references in types.
const dataClassEntry: DataClassEntry = {
name: variableName,
classType,
alias: aliasName,
isKeywordOnly,
hasDefault,
isDefaultFactory,
defaultExpr,
includeInInit,
nameNode: variableNameNode,
typeAnnotationNode: typeAnnotationNode,
type: UnknownType.create(),
isClassVar: false,
converter,
};
localEntryTypeEvaluator.push({ entry: dataClassEntry, evaluator: variableTypeEvaluator });
// Add the new entry to the local entry list.
let insertIndex = localDataClassEntries.findIndex((e) => e.name === variableName);
if (insertIndex >= 0) {
localDataClassEntries[insertIndex] = dataClassEntry;
} else {
localDataClassEntries.push(dataClassEntry);
}
// Add the new entry to the full entry list.
insertIndex = fullDataClassEntries.findIndex((p) => p.name === variableName);
if (insertIndex >= 0) {
const oldEntry = fullDataClassEntries[insertIndex];
// While this isn't documented behavior, it appears that the dataclass implementation
// causes overridden variables to "inherit" default values from parent classes.
if (!dataClassEntry.hasDefault && oldEntry.hasDefault && oldEntry.includeInInit) {
dataClassEntry.hasDefault = true;
dataClassEntry.defaultExpr = oldEntry.defaultExpr;
hasDefault = true;
// Warn the user of this case because it can result in type errors if the
// default value is incompatible with the new type.
evaluator.addDiagnostic(
DiagnosticRule.reportGeneralTypeIssues,
LocMessage.dataClassFieldInheritedDefault().format({ fieldName: variableName }),
variableNameNode
);
}
fullDataClassEntries[insertIndex] = dataClassEntry;
} else {
fullDataClassEntries.push(dataClassEntry);
insertIndex = fullDataClassEntries.length - 1;
}
// If we've already seen a entry with a default value defined,
// all subsequent entries must also have default values.
if (!isKeywordOnly && includeInInit && !skipSynthesizeInit && !hasDefault) {
const firstDefaultValueIndex = fullDataClassEntries.findIndex(
(p) => p.hasDefault && p.includeInInit && !p.isKeywordOnly
);
if (firstDefaultValueIndex >= 0 && firstDefaultValueIndex < insertIndex) {
evaluator.addDiagnostic(
DiagnosticRule.reportGeneralTypeIssues,
LocMessage.dataClassFieldWithDefault(),
variableNameNode
);
}
}
}
}
} else {
// The symbol had no declared type, so it is (mostly) ignored by dataclasses.
// However, if it is assigned a field descriptor, it will result in a
// runtime exception.
const declarations = symbol.getDeclarations();
if (declarations.length === 0) {
return;
}
const lastDecl = declarations[declarations.length - 1];
if (lastDecl.type !== DeclarationType.Variable) {
return;
}
const statement = lastDecl.node.parent;
if (!statement || statement.nodeType !== ParseNodeType.Assignment) {
return;
}
// If the RHS of the assignment is assigning a field instance where the
// "init" parameter is set to false, do not include it in the init method.
if (statement.d.rightExpr.nodeType === ParseNodeType.Call) {
const callType = evaluator.getTypeOfExpression(
statement.d.rightExpr.d.leftExpr,
EvalFlags.CallBaseDefaults
).type;
if (
isDataclassFieldConstructor(
callType,
classType.shared.dataClassBehaviors?.fieldDescriptorNames || []
)
) {
evaluator.addDiagnostic(
DiagnosticRule.reportGeneralTypeIssues,
LocMessage.dataClassFieldWithoutAnnotation(),
statement.d.rightExpr
);
}
}
}
});
if (isNamedTuple) {
classType.shared.namedTupleEntries = namedTupleEntries;
} else {
classType.shared.dataClassEntries = localDataClassEntries;
}
// Now that the dataClassEntries field has been set with a complete list
// of local data class entries for this class, perform deferred type
// evaluations. This could involve circular type dependencies, so it's
// required that the list be complete (even if types are not yet accurate)
// before we perform the type evaluations.
localEntryTypeEvaluator.forEach((entryEvaluator) => {
entryEvaluator.entry.type = entryEvaluator.evaluator();
});
const symbolTable = ClassType.getSymbolTable(classType);
const keywordOnlyParams: FunctionParam[] = [];
if (!skipSynthesizeInit && !hasExistingInitMethod) {
if (allAncestorsKnown) {
fullDataClassEntries.forEach((entry) => {
if (entry.includeInInit) {
let defaultType: Type | undefined;
// If the type refers to Self of the parent class, we need to
// transform it to refer to the Self of this subclass.
let effectiveType = entry.type;
if (entry.classType !== classType && requiresSpecialization(effectiveType)) {
const solution = new ConstraintSolution();
addSolutionForSelfType(solution, entry.classType, classType);
effectiveType = applySolvedTypeVars(effectiveType, solution);
}
// Is the field type a descriptor object? If so, we need to extract the corresponding
// type of the __init__ method parameter from the __set__ method.
effectiveType = transformDescriptorType(evaluator, effectiveType);
if (entry.converter) {
const fieldType = effectiveType;
effectiveType = getConverterInputType(evaluator, entry.converter, effectiveType, entry.name);
symbolTable.set(
entry.name,
getDescriptorForConverterField(
evaluator,
node,
entry.nameNode,
entry.typeAnnotationNode,
entry.converter,
entry.name,
fieldType,
effectiveType
)
);
if (entry.hasDefault) {
defaultType = entry.type;
}
} else {
if (entry.hasDefault) {
if (entry.isDefaultFactory || !entry.defaultExpr) {
defaultType = entry.type;
} else {
const defaultExpr = entry.defaultExpr;
const fileInfo = AnalyzerNodeInfo.getFileInfo(node);
const flags = fileInfo.isStubFile ? EvalFlags.ConvertEllipsisToAny : EvalFlags.None;
// Use speculative mode here so we don't cache the results.
// We'll want to re-evaluate this expression later, potentially
// with different evaluation flags.
defaultType = evaluator.useSpeculativeMode(defaultExpr, () => {
return evaluator.getTypeOfExpression(
defaultExpr,
flags,
makeInferenceContext(entry.type)
).type;
});
}
}
}
const effectiveName = entry.alias || entry.name;
if (!entry.alias && entry.nameNode && isPrivateName(entry.nameNode.d.value)) {
evaluator.addDiagnostic(
DiagnosticRule.reportGeneralTypeIssues,
LocMessage.dataClassFieldWithPrivateName(),
entry.nameNode
);
}
const param = FunctionParam.create(
ParamCategory.Simple,
effectiveType,
FunctionParamFlags.TypeDeclared,
effectiveName,
defaultType,
entry.defaultExpr
);
if (entry.isKeywordOnly) {
keywordOnlyParams.push(param);
} else {
FunctionType.addParam(constructorType, param);
}
if (replaceType) {
const paramWithDefault = FunctionParam.create(
param.category,
param._type,
param.flags,
param.name,
AnyType.create(/* isEllipsis */ true)
);
FunctionType.addParam(replaceType, paramWithDefault);
}
}
});
if (keywordOnlyParams.length > 0) {
FunctionType.addKeywordOnlyParamSeparator(constructorType);
keywordOnlyParams.forEach((param) => {
FunctionType.addParam(constructorType, param);
});
}
}
symbolTable.set('__init__', Symbol.createWithType(SymbolFlags.ClassMember, initType));
symbolTable.set('__new__', Symbol.createWithType(SymbolFlags.ClassMember, newType));
if (replaceType) {
symbolTable.set('__replace__', Symbol.createWithType(SymbolFlags.ClassMember, replaceType));
}
}
// Synthesize the __match_args__ class variable if it doesn't exist.
const strType = evaluator.getBuiltInType(node, 'str');
const tupleClassType = evaluator.getBuiltInType(node, 'tuple');
if (
tupleClassType &&
isInstantiableClass(tupleClassType) &&
strType &&
isInstantiableClass(strType) &&
!symbolTable.has('__match_args__')
) {
const matchArgsNames: string[] = [];
fullDataClassEntries.forEach((entry) => {
if (entry.includeInInit && !entry.isKeywordOnly) {
// Use the field name, not its alias (if it has one).
matchArgsNames.push(entry.name);
}
});
const literalTypes: TupleTypeArg[] = matchArgsNames.map((name) => {
return { type: ClassType.cloneAsInstance(ClassType.cloneWithLiteral(strType, name)), isUnbounded: false };
});
const matchArgsType = ClassType.cloneAsInstance(specializeTupleClass(tupleClassType, literalTypes));
symbolTable.set('__match_args__', Symbol.createWithType(SymbolFlags.ClassMember, matchArgsType));
}
const synthesizeComparisonMethod = (operator: string, paramType: Type) => {
const operatorMethod = FunctionType.createSynthesizedInstance(operator);
FunctionType.addParam(operatorMethod, selfParam);
FunctionType.addParam(
operatorMethod,
FunctionParam.create(ParamCategory.Simple, paramType, FunctionParamFlags.TypeDeclared, 'other')
);
operatorMethod.shared.declaredReturnType = evaluator.getBuiltInObject(node, 'bool');
// If a method of this name already exists, don't override it.
if (!symbolTable.get(operator)) {
symbolTable.set(operator, Symbol.createWithType(SymbolFlags.ClassMember, operatorMethod));
}
};
// Synthesize comparison operators.
if (!ClassType.isDataClassSkipGenerateEq(classType)) {
synthesizeComparisonMethod('__eq__', evaluator.getBuiltInObject(node, 'object'));
}
if (ClassType.isDataClassGenerateOrder(classType)) {
['__lt__', '__le__', '__gt__', '__ge__'].forEach((operator) => {
synthesizeComparisonMethod(operator, selfType);
});
}
let synthesizeHashFunction = ClassType.isDataClassFrozen(classType);
const synthesizeHashNone =
!isNamedTuple && !ClassType.isDataClassSkipGenerateEq(classType) && !ClassType.isDataClassFrozen(classType);
if (skipSynthesizeHash) {
synthesizeHashFunction = false;
}
// If the user has indicated that a hash function should be generated even if it's unsafe
// to do so or there is already a hash function present, override the default logic.
if (ClassType.isDataClassGenerateHash(classType)) {
synthesizeHashFunction = true;
}
if (synthesizeHashFunction) {
const hashMethod = FunctionType.createSynthesizedInstance('__hash__');
FunctionType.addParam(hashMethod, selfParam);
hashMethod.shared.declaredReturnType = evaluator.getBuiltInObject(node, 'int');
symbolTable.set(
'__hash__',
Symbol.createWithType(SymbolFlags.ClassMember | SymbolFlags.IgnoredForOverrideChecks, hashMethod)
);
} else if (synthesizeHashNone && !skipSynthesizeHash) {
symbolTable.set(
'__hash__',
Symbol.createWithType(
SymbolFlags.ClassMember | SymbolFlags.IgnoredForOverrideChecks,
evaluator.getNoneType()
)
);
}
let dictType = evaluator.getBuiltInType(node, 'dict');
if (isInstantiableClass(dictType)) {
dictType = ClassType.cloneAsInstance(
ClassType.specialize(dictType, [evaluator.getBuiltInObject(node, 'str'), AnyType.create()])
);
}
if (!isNamedTuple) {
symbolTable.set(
'__dataclass_fields__',
Symbol.createWithType(SymbolFlags.ClassMember | SymbolFlags.ClassVar, dictType)
);
}
if (ClassType.isDataClassGenerateSlots(classType) && classType.shared.localSlotsNames === undefined) {
classType.shared.localSlotsNames = localDataClassEntries.map((entry) => entry.name);
}
// Should we synthesize a __slots__ symbol?
if (ClassType.isDataClassGenerateSlots(classType)) {
let iterableType = evaluator.getTypingType(node, 'Iterable') ?? UnknownType.create();
if (isInstantiableClass(iterableType)) {
iterableType = ClassType.cloneAsInstance(
ClassType.specialize(iterableType, [evaluator.getBuiltInObject(node, 'str')])
);
}
symbolTable.set(
'__slots__',
Symbol.createWithType(SymbolFlags.ClassMember | SymbolFlags.ClassVar, iterableType)
);
}
// If this dataclass derived from a NamedTuple, update the NamedTuple with
// the specialized entry types.
if (
updateNamedTupleBaseClass(
classType,
fullDataClassEntries.map((entry) => entry.type),
/* isTypeArgExplicit */ true
)
) {
// Recompute the MRO based on the updated NamedTuple base class.
computeMroLinearization(classType);
}
}
// If a field specifier is used to define a field, it may define a default
// argument value (either True or False) for a supported keyword parameter.
// This function extracts that default value if present and returns it. If
// it's not present, it returns undefined.
function getDefaultArgValueForFieldSpecifier(
evaluator: TypeEvaluator,
callNode: CallNode,
callTypeResult: TypeResult,
paramName: string
): boolean | undefined {
const callType = callTypeResult.type;
let callTarget: FunctionType | undefined;
if (isFunction(callType)) {
callTarget = callType;
} else if (isOverloaded(callType)) {
callTarget = evaluator.getBestOverloadForArgs(
callNode,
{ type: callType, isIncomplete: callTypeResult.isIncomplete },
callNode.d.args.map((arg) => evaluator.convertNodeToArg(arg))
);
} else if (isInstantiableClass(callType)) {
const initMethodResult = getBoundInitMethod(evaluator, callNode, callType);
if (initMethodResult) {
if (isFunction(initMethodResult.type)) {
callTarget = initMethodResult.type;
} else if (isOverloaded(initMethodResult.type)) {
callTarget = evaluator.getBestOverloadForArgs(
callNode,
{ type: initMethodResult.type },
callNode.d.args.map((arg) => evaluator.convertNodeToArg(arg))
);
}
}
}
if (callTarget) {
const initParamIndex = callTarget.shared.parameters.findIndex((p) => p.name === paramName);
if (initParamIndex >= 0) {
const initParam = callTarget.shared.parameters[initParamIndex];
// Is the parameter type a literal bool?
const initParamType = FunctionType.getParamType(callTarget, initParamIndex);
if (
FunctionParam.isTypeDeclared(initParam) &&
isClass(initParamType) &&
typeof initParamType.priv.literalValue === 'boolean'
) {
return initParamType.priv.literalValue;
}
// Is the default argument value a literal bool?
const initParamDefaultType = FunctionType.getParamDefaultType(callTarget, initParamIndex);
if (
initParamDefaultType &&
isClass(initParamDefaultType) &&
typeof initParamDefaultType.priv.literalValue === 'boolean'
) {
return initParamDefaultType.priv.literalValue;
}
}
}
return undefined;
}
// Validates converter and, if valid, returns its input type. If invalid,
// fieldType is returned.
function getConverterInputType(
evaluator: TypeEvaluator,
converterNode: ArgumentNode,
fieldType: Type,
fieldName: string
): Type {
const converterType = getConverterAsFunction(
evaluator,
evaluator.getTypeOfExpression(converterNode.d.valueExpr).type
);
if (!converterType) {
return fieldType;
}
// Create synthesized function of the form Callable[[T], fieldType] which
// will be used to check compatibility of the provided converter.
const typeVar = TypeVarType.createInstance('__converterInput');
typeVar.priv.scopeId = getScopeIdForNode(converterNode);
const targetFunction = FunctionType.createSynthesizedInstance('');
targetFunction.shared.typeVarScopeId = typeVar.priv.scopeId;
targetFunction.shared.declaredReturnType = fieldType;
FunctionType.addParam(
targetFunction,
FunctionParam.create(
ParamCategory.Simple,
typeVar,
FunctionParamFlags.TypeDeclared | FunctionParamFlags.NameSynthesized,
'__input'
)
);
FunctionType.addPositionOnlyParamSeparator(targetFunction);
if (isFunction(converterType) || isOverloaded(converterType)) {
const acceptedTypes: Type[] = [];
const diagAddendum = new DiagnosticAddendum();
doForEachSignature(converterType, (signature) => {
const returnConstraints = new ConstraintTracker();
if (
evaluator.assignType(
FunctionType.getEffectiveReturnType(signature) ?? UnknownType.create(),
fieldType,
/* diag */ undefined,
returnConstraints
)
) {
signature = evaluator.solveAndApplyConstraints(signature, returnConstraints) as FunctionType;
}
const inputConstraints = new ConstraintTracker();
if (evaluator.assignType(targetFunction, signature, diagAddendum, inputConstraints)) {
const overloadSolution = evaluator.solveAndApplyConstraints(typeVar, inputConstraints, {
replaceUnsolved: {
scopeIds: getTypeVarScopeIds(typeVar),
tupleClassType: evaluator.getTupleClassType(),
},
});
acceptedTypes.push(overloadSolution);
}
});
if (acceptedTypes.length > 0) {
return combineTypes(acceptedTypes);
}
if (isFunction(converterType)) {
evaluator.addDiagnostic(
DiagnosticRule.reportGeneralTypeIssues,
LocMessage.dataClassConverterFunction().format({
argType: evaluator.printType(converterType),
fieldType: evaluator.printType(fieldType),
fieldName: fieldName,
}) + diagAddendum.getString(),
converterNode,
diagAddendum.getEffectiveTextRange() ?? converterNode
);
} else {
const overloads = OverloadedType.getOverloads(converterType);
evaluator.addDiagnostic(
DiagnosticRule.reportGeneralTypeIssues,
LocMessage.dataClassConverterOverloads().format({
funcName:
overloads.length > 0 && overloads[0].shared.name
? overloads[0].shared.name
: '<anonymous function>',
fieldType: evaluator.printType(fieldType),
fieldName: fieldName,
}) + diagAddendum.getString(),
converterNode
);
}
}
return fieldType;
}
function getConverterAsFunction(
evaluator: TypeEvaluator,
converterType: Type
): FunctionType | OverloadedType | undefined {
if (isFunction(converterType) || isOverloaded(converterType)) {
return converterType;
}
if (isClassInstance(converterType)) {
return evaluator.getBoundMagicMethod(converterType, '__call__');
}
if (isInstantiableClass(converterType)) {
let fromConstructor = createFunctionFromConstructor(evaluator, converterType);
if (fromConstructor) {
// If conversion to a constructor resulted in a union type, we'll
// choose the first of the two subtypes, which typically corresponds
// to the __init__ method (rather than the __new__ method).
if (isUnion(fromConstructor)) {
fromConstructor = fromConstructor.priv.subtypes[0];
}
if (isFunction(fromConstructor) || isOverloaded(fromConstructor)) {
return fromConstructor;
}
}
}
return undefined;
}
// Synthesizes an asymmetric descriptor class to be used in place of the
// annotated type of a field with a converter. The descriptor's __get__ method
// returns the declared type of the field and its __set__ method accepts the
// converter's input type. Returns the symbol for an instance of this descriptor
// type.
function getDescriptorForConverterField(
evaluator: TypeEvaluator,
dataclassNode: ParseNode,
fieldNameNode: NameNode | undefined,
fieldAnnotationNode: TypeAnnotationNode | undefined,
converterNode: ParseNode,
fieldName: string,
getType: Type,
setType: Type
): Symbol {
const fileInfo = getFileInfo(dataclassNode);
const typeMetaclass = evaluator.getBuiltInType(dataclassNode, 'type');
const descriptorName = `__converterDescriptor_${fieldName}`;
const descriptorClass = ClassType.createInstantiable(
descriptorName,
getClassFullName(converterNode, fileInfo.moduleName, descriptorName),
fileInfo.moduleName,
fileInfo.fileUri,
ClassTypeFlags.None,
getTypeSourceId(converterNode),