-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
best_practices_verifier.dart
1996 lines (1800 loc) · 68.6 KB
/
best_practices_verifier.dart
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
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:collection';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/syntactic_entity.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/error/listener.dart';
import 'package:analyzer/src/dart/ast/extensions.dart';
import 'package:analyzer/src/dart/element/element.dart';
import 'package:analyzer/src/dart/element/extensions.dart';
import 'package:analyzer/src/dart/element/inheritance_manager3.dart';
import 'package:analyzer/src/dart/element/member.dart' show ExecutableMember;
import 'package:analyzer/src/dart/element/type.dart';
import 'package:analyzer/src/dart/element/type_provider.dart';
import 'package:analyzer/src/dart/element/type_system.dart';
import 'package:analyzer/src/dart/resolver/body_inference_context.dart';
import 'package:analyzer/src/dart/resolver/exit_detector.dart';
import 'package:analyzer/src/dart/resolver/scope.dart';
import 'package:analyzer/src/error/codes.dart';
import 'package:analyzer/src/error/deprecated_member_use_verifier.dart';
import 'package:analyzer/src/error/error_handler_verifier.dart';
import 'package:analyzer/src/error/must_call_super_verifier.dart';
import 'package:analyzer/src/generated/constant.dart';
import 'package:analyzer/src/generated/engine.dart';
import 'package:analyzer/src/generated/resolver.dart';
import 'package:analyzer/src/lint/linter.dart';
import 'package:analyzer/src/utilities/extensions/string.dart';
import 'package:analyzer/src/workspace/workspace.dart';
import 'package:meta/meta.dart';
import 'package:meta/meta_meta.dart';
/// Instances of the class `BestPracticesVerifier` traverse an AST structure
/// looking for violations of Dart best practices.
class BestPracticesVerifier extends RecursiveAstVisitor<void> {
static const String _TO_INT_METHOD_NAME = "toInt";
/// The class containing the AST nodes being visited, or `null` if we are not
/// in the scope of a class.
ClassElementImpl? _enclosingClass;
/// A flag indicating whether a surrounding member is annotated as
/// `@doNotStore`.
bool _inDoNotStoreMember = false;
/// The error reporter by which errors will be reported.
final ErrorReporter _errorReporter;
/// The type [Null].
final InterfaceType _nullType;
/// The type system primitives
final TypeSystemImpl _typeSystem;
/// The inheritance manager to access interface type hierarchy.
final InheritanceManager3 _inheritanceManager;
/// The current library
final LibraryElement _currentLibrary;
final _InvalidAccessVerifier _invalidAccessVerifier;
final DeprecatedMemberUseVerifier _deprecatedVerifier;
final MustCallSuperVerifier _mustCallSuperVerifier;
final ErrorHandlerVerifier _errorHandlerVerifier;
/// The [WorkspacePackage] in which [_currentLibrary] is declared.
final WorkspacePackage? _workspacePackage;
/// The [LinterContext] used for possible const calculations.
late final LinterContext _linterContext;
/// Is `true` if the library being analyzed is non-nullable by default.
final bool _isNonNullableByDefault;
/// True if inference failures should be reported, otherwise false.
final bool _strictInference;
/// Create a new instance of the [BestPracticesVerifier].
///
/// @param errorReporter the error reporter
BestPracticesVerifier(
this._errorReporter,
TypeProviderImpl typeProvider,
this._currentLibrary,
CompilationUnit unit,
String content, {
required TypeSystemImpl typeSystem,
required InheritanceManager3 inheritanceManager,
required DeclaredVariables declaredVariables,
required AnalysisOptions analysisOptions,
required WorkspacePackage? workspacePackage,
}) : _nullType = typeProvider.nullType,
_typeSystem = typeSystem,
_isNonNullableByDefault = typeSystem.isNonNullableByDefault,
_strictInference =
(analysisOptions as AnalysisOptionsImpl).strictInference,
_inheritanceManager = inheritanceManager,
_invalidAccessVerifier = _InvalidAccessVerifier(
_errorReporter, _currentLibrary, workspacePackage),
_deprecatedVerifier =
DeprecatedMemberUseVerifier(workspacePackage, _errorReporter),
_mustCallSuperVerifier = MustCallSuperVerifier(_errorReporter),
_errorHandlerVerifier =
ErrorHandlerVerifier(_errorReporter, typeProvider, typeSystem),
_workspacePackage = workspacePackage {
_deprecatedVerifier.pushInDeprecatedValue(_currentLibrary.hasDeprecated);
_inDoNotStoreMember = _currentLibrary.hasDoNotStore;
_linterContext = LinterContextImpl(
[],
LinterContextUnit(content, unit),
declaredVariables,
typeProvider,
_typeSystem,
_inheritanceManager,
analysisOptions,
_workspacePackage,
);
_invalidAccessVerifier._inTestDirectory = _linterContext.inTestDir(unit);
}
bool get _inPublicPackageApi {
return _workspacePackage != null &&
_workspacePackage!.sourceIsInPublicApi(_currentLibrary.source);
}
@override
void visitAnnotation(Annotation node) {
var element = node.elementAnnotation;
if (element == null) {
return;
}
AstNode parent = node.parent;
if (element.isFactory == true) {
if (parent is MethodDeclaration) {
_checkForInvalidFactory(parent);
} else {
_errorReporter
.reportErrorForNode(HintCode.INVALID_FACTORY_ANNOTATION, node, []);
}
} else if (element.isImmutable == true) {
if (parent is! ClassOrMixinDeclaration && parent is! ClassTypeAlias) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_IMMUTABLE_ANNOTATION, node, []);
}
} else if (element.isInternal) {
var parentElement = parent is Declaration ? parent.declaredElement : null;
if (parent is TopLevelVariableDeclaration) {
for (VariableDeclaration variable in parent.variables.variables) {
var element = variable.declaredElement as TopLevelVariableElement;
if (Identifier.isPrivateName(element.name)) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_INTERNAL_ANNOTATION, variable, []);
}
}
} else if (parent is FieldDeclaration) {
for (VariableDeclaration variable in parent.fields.variables) {
var element = variable.declaredElement as FieldElement;
if (Identifier.isPrivateName(element.name)) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_INTERNAL_ANNOTATION, variable, []);
}
}
} else if (parent is ConstructorDeclaration) {
var class_ = parent.declaredElement!.enclosingElement;
if (class_.isPrivate || (parentElement?.isPrivate ?? false)) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_INTERNAL_ANNOTATION, node, []);
}
} else if (parentElement?.isPrivate ?? false) {
_errorReporter
.reportErrorForNode(HintCode.INVALID_INTERNAL_ANNOTATION, node, []);
} else if (_inPublicPackageApi) {
_errorReporter
.reportErrorForNode(HintCode.INVALID_INTERNAL_ANNOTATION, node, []);
}
} else if (element.isLiteral == true) {
if (parent is! ConstructorDeclaration || parent.constKeyword == null) {
_errorReporter
.reportErrorForNode(HintCode.INVALID_LITERAL_ANNOTATION, node, []);
}
} else if (element.isNonVirtual == true) {
if (parent is FieldDeclaration) {
if (parent.isStatic) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_NON_VIRTUAL_ANNOTATION,
node,
[node.element!.name]);
}
} else if (parent is MethodDeclaration) {
if (parent.parent is ExtensionDeclaration ||
parent.isStatic ||
parent.isAbstract) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_NON_VIRTUAL_ANNOTATION,
node,
[node.element!.name]);
}
} else {
_errorReporter.reportErrorForNode(
HintCode.INVALID_NON_VIRTUAL_ANNOTATION,
node,
[node.element!.name]);
}
} else if (element.isSealed == true) {
if (!(parent is ClassDeclaration || parent is ClassTypeAlias)) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_SEALED_ANNOTATION, node, [node.element!.name]);
}
} else if (element.isVisibleForTemplate == true ||
element.isVisibleForTesting == true) {
if (parent is Declaration) {
void reportInvalidAnnotation(Element declaredElement) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_VISIBILITY_ANNOTATION,
node,
[declaredElement.name, node.name.name]);
}
if (parent is TopLevelVariableDeclaration) {
for (VariableDeclaration variable in parent.variables.variables) {
var element = variable.declaredElement as TopLevelVariableElement;
if (Identifier.isPrivateName(element.name)) {
reportInvalidAnnotation(element);
}
}
} else if (parent is FieldDeclaration) {
for (VariableDeclaration variable in parent.fields.variables) {
var element = variable.declaredElement as FieldElement;
if (Identifier.isPrivateName(element.name)) {
reportInvalidAnnotation(element);
}
}
} else if (parent.declaredElement != null &&
Identifier.isPrivateName(parent.declaredElement!.name!)) {
reportInvalidAnnotation(parent.declaredElement!);
}
} else {
// Something other than a declaration was annotated. Whatever this is,
// it probably warrants a Hint, but this has not been specified on
// visibleForTemplate or visibleForTesting, so leave it alone for now.
}
}
var kinds = _targetKindsFor(element);
if (kinds.isNotEmpty) {
if (!_isValidTarget(parent, kinds)) {
var invokedElement = element.element!;
var name = invokedElement.name;
if (invokedElement is ConstructorElement) {
var className = invokedElement.enclosingElement.name;
if (name!.isEmpty) {
name = className;
} else {
name = '$className.$name';
}
}
var kindNames = kinds.map((kind) => kind.displayString).toList()
..sort();
var validKinds = kindNames.commaSeparatedWithOr;
_errorReporter.reportErrorForNode(
HintCode.INVALID_ANNOTATION_TARGET, node.name, [name, validKinds]);
return;
}
}
super.visitAnnotation(node);
}
@override
void visitAsExpression(AsExpression node) {
if (isUnnecessaryCast(node, _typeSystem)) {
_errorReporter.reportErrorForNode(HintCode.UNNECESSARY_CAST, node);
}
super.visitAsExpression(node);
}
@override
void visitAssignmentExpression(AssignmentExpression node) {
_deprecatedVerifier.assignmentExpression(node);
super.visitAssignmentExpression(node);
}
@override
void visitBinaryExpression(BinaryExpression node) {
_checkForDivisionOptimizationHint(node);
_deprecatedVerifier.binaryExpression(node);
_checkForInvariantNullComparison(node);
super.visitBinaryExpression(node);
}
@override
void visitCatchClause(CatchClause node) {
super.visitCatchClause(node);
_checkForNullableTypeInCatchClause(node);
}
@override
void visitClassDeclaration(ClassDeclaration node) {
var element = node.declaredElement as ClassElementImpl;
_enclosingClass = element;
_invalidAccessVerifier._enclosingClass = element;
bool wasInDoNotStoreMember = _inDoNotStoreMember;
_deprecatedVerifier.pushInDeprecatedValue(element.hasDeprecated);
if (element.hasDoNotStore) {
_inDoNotStoreMember = true;
}
try {
// Commented out until we decide that we want this hint in the analyzer
// checkForOverrideEqualsButNotHashCode(node);
_checkForImmutable(node);
_checkForInvalidSealedSuperclass(node);
super.visitClassDeclaration(node);
} finally {
_enclosingClass = null;
_invalidAccessVerifier._enclosingClass = null;
_deprecatedVerifier.popInDeprecated();
_inDoNotStoreMember = wasInDoNotStoreMember;
}
}
@override
void visitClassTypeAlias(ClassTypeAlias node) {
_checkForImmutable(node);
_checkForInvalidSealedSuperclass(node);
super.visitClassTypeAlias(node);
}
@override
void visitConstructorDeclaration(ConstructorDeclaration node) {
var element = node.declaredElement as ConstructorElementImpl;
if (!_isNonNullableByDefault && node.declaredElement!.isFactory) {
if (node.body is BlockFunctionBody) {
// Check the block for a return statement, if not, create the hint.
if (!ExitDetector.exits(node.body)) {
_errorReporter.reportErrorForNode(
HintCode.MISSING_RETURN, node, [node.returnType.name]);
}
}
}
_checkStrictInferenceInParameters(node.parameters,
body: node.body, initializers: node.initializers);
_deprecatedVerifier.pushInDeprecatedValue(element.hasDeprecated);
try {
super.visitConstructorDeclaration(node);
} finally {
_deprecatedVerifier.popInDeprecated();
}
}
@override
void visitConstructorName(ConstructorName node) {
_deprecatedVerifier.constructorName(node);
super.visitConstructorName(node);
}
@override
void visitExportDirective(ExportDirective node) {
_deprecatedVerifier.exportDirective(node);
_checkForInternalExport(node);
_checkForUseOfNativeExtension(node);
super.visitExportDirective(node);
}
@override
void visitExpressionFunctionBody(ExpressionFunctionBody node) {
if (!_invalidAccessVerifier._inTestDirectory) {
_checkForReturnOfDoNotStore(node.expression);
}
super.visitExpressionFunctionBody(node);
}
@override
void visitFieldDeclaration(FieldDeclaration node) {
_deprecatedVerifier.pushInDeprecatedMetadata(node.metadata);
try {
super.visitFieldDeclaration(node);
for (var field in node.fields.variables) {
ExecutableElement? getOverriddenPropertyAccessor() {
final element = field.declaredElement;
if (element is PropertyAccessorElement || element is FieldElement) {
Name name = Name(_currentLibrary.source.uri, element!.name!);
Element enclosingElement = element.enclosingElement!;
if (enclosingElement is ClassElement) {
var overridden = _inheritanceManager
.getMember2(enclosingElement, name, forSuper: true);
// Check for a setter.
if (overridden == null) {
Name setterName =
Name(_currentLibrary.source.uri, '${element.name}=');
overridden = _inheritanceManager
.getMember2(enclosingElement, setterName, forSuper: true);
}
return overridden;
}
}
return null;
}
final overriddenElement = getOverriddenPropertyAccessor();
if (_hasNonVirtualAnnotation(overriddenElement)) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_OVERRIDE_OF_NON_VIRTUAL_MEMBER,
field.name,
[field.name, overriddenElement!.enclosingElement.name]);
}
if (!_invalidAccessVerifier._inTestDirectory) {
_checkForAssignmentOfDoNotStore(field.initializer);
}
}
} finally {
_deprecatedVerifier.popInDeprecated();
}
}
@override
void visitFormalParameterList(FormalParameterList node) {
_checkRequiredParameter(node);
super.visitFormalParameterList(node);
}
@override
void visitFunctionDeclaration(FunctionDeclaration node) {
bool wasInDoNotStoreMember = _inDoNotStoreMember;
ExecutableElement element = node.declaredElement!;
_deprecatedVerifier.pushInDeprecatedValue(element.hasDeprecated);
if (element.hasDoNotStore) {
_inDoNotStoreMember = true;
}
try {
_checkForMissingReturn(node.functionExpression.body, node);
// Return types are inferred only on non-recursive local functions.
if (node.parent is CompilationUnit && !node.isSetter) {
_checkStrictInferenceReturnType(node.returnType, node, node.name.name);
}
_checkStrictInferenceInParameters(node.functionExpression.parameters,
body: node.functionExpression.body);
super.visitFunctionDeclaration(node);
} finally {
_deprecatedVerifier.popInDeprecated();
_inDoNotStoreMember = wasInDoNotStoreMember;
}
}
@override
void visitFunctionDeclarationStatement(FunctionDeclarationStatement node) {
// TODO(srawlins): Check strict-inference return type on recursive
// local functions.
super.visitFunctionDeclarationStatement(node);
}
@override
void visitFunctionExpression(FunctionExpression node) {
if (node.parent is! FunctionDeclaration) {
_checkForMissingReturn(node.body, node);
}
var functionType = InferenceContext.getContext(node);
if (functionType is! FunctionType) {
_checkStrictInferenceInParameters(node.parameters, body: node.body);
}
super.visitFunctionExpression(node);
}
@override
void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) {
_deprecatedVerifier.functionExpressionInvocation(node);
super.visitFunctionExpressionInvocation(node);
}
@override
void visitFunctionTypeAlias(FunctionTypeAlias node) {
_checkStrictInferenceReturnType(node.returnType, node, node.name.name);
_checkStrictInferenceInParameters(node.parameters);
super.visitFunctionTypeAlias(node);
}
@override
void visitFunctionTypedFormalParameter(FunctionTypedFormalParameter node) {
_checkStrictInferenceReturnType(
node.returnType, node, node.identifier.name);
_checkStrictInferenceInParameters(node.parameters);
super.visitFunctionTypedFormalParameter(node);
}
@override
void visitGenericFunctionType(GenericFunctionType node) {
// GenericTypeAlias is handled in [visitGenericTypeAlias], where a proper
// name can be reported in any message.
if (node.parent is! GenericTypeAlias) {
_checkStrictInferenceReturnType(node.returnType, node, node.toString());
}
super.visitGenericFunctionType(node);
}
@override
void visitGenericTypeAlias(GenericTypeAlias node) {
if (node.functionType != null) {
_checkStrictInferenceReturnType(
node.functionType!.returnType, node, node.name.name);
}
super.visitGenericTypeAlias(node);
}
@override
void visitImportDirective(ImportDirective node) {
_deprecatedVerifier.importDirective(node);
var importElement = node.element;
if (importElement != null && importElement.isDeferred) {
_checkForLoadLibraryFunction(node, importElement);
}
_invalidAccessVerifier.verifyImport(node);
_checkForImportOfLegacyLibraryIntoNullSafe(node);
_checkForUseOfNativeExtension(node);
super.visitImportDirective(node);
}
@override
void visitIndexExpression(IndexExpression node) {
_deprecatedVerifier.indexExpression(node);
super.visitIndexExpression(node);
}
@override
void visitInstanceCreationExpression(InstanceCreationExpression node) {
_deprecatedVerifier.instanceCreationExpression(node);
_checkForLiteralConstructorUse(node);
super.visitInstanceCreationExpression(node);
}
@override
void visitIsExpression(IsExpression node) {
_checkAllTypeChecks(node);
super.visitIsExpression(node);
}
@override
void visitMethodDeclaration(MethodDeclaration node) {
bool wasInDoNotStoreMember = _inDoNotStoreMember;
var element = node.declaredElement!;
var enclosingElement = element.enclosingElement;
Name name = Name(_currentLibrary.source.uri, element.name);
bool elementIsOverride() =>
element is ClassMemberElement && enclosingElement is ClassElement
? _inheritanceManager.getOverridden2(enclosingElement, name) != null
: false;
ExecutableElement? getConcreteOverriddenElement() =>
element is ClassMemberElement && enclosingElement is ClassElement
? _inheritanceManager.getMember2(enclosingElement, name,
forSuper: true)
: null;
ExecutableElement? getOverriddenPropertyAccessor() =>
element is PropertyAccessorElement && enclosingElement is ClassElement
? _inheritanceManager.getMember2(enclosingElement, name,
forSuper: true)
: null;
_deprecatedVerifier.pushInDeprecatedValue(element.hasDeprecated);
if (element.hasDoNotStore) {
_inDoNotStoreMember = true;
}
try {
// This was determined to not be a good hint, see: dartbug.com/16029
//checkForOverridingPrivateMember(node);
_checkForMissingReturn(node.body, node);
_mustCallSuperVerifier.checkMethodDeclaration(node);
_checkForUnnecessaryNoSuchMethod(node);
if (!node.isSetter && !elementIsOverride()) {
_checkStrictInferenceReturnType(node.returnType, node, node.name.name);
}
_checkStrictInferenceInParameters(node.parameters, body: node.body);
var overriddenElement = getConcreteOverriddenElement();
if (overriddenElement == null && (node.isSetter || node.isGetter)) {
overriddenElement = getOverriddenPropertyAccessor();
}
if (_hasNonVirtualAnnotation(overriddenElement)) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_OVERRIDE_OF_NON_VIRTUAL_MEMBER,
node.name,
[node.name, overriddenElement!.enclosingElement.name]);
}
super.visitMethodDeclaration(node);
} finally {
_deprecatedVerifier.popInDeprecated();
_inDoNotStoreMember = wasInDoNotStoreMember;
}
}
@override
void visitMethodInvocation(MethodInvocation node) {
_deprecatedVerifier.methodInvocation(node);
_checkForNullAwareHints(node, node.operator);
_errorHandlerVerifier.verifyMethodInvocation(node);
super.visitMethodInvocation(node);
}
@override
void visitMixinDeclaration(MixinDeclaration node) {
var element = node.declaredElement as ClassElementImpl;
_enclosingClass = element;
_invalidAccessVerifier._enclosingClass = _enclosingClass;
_deprecatedVerifier.pushInDeprecatedValue(element.hasDeprecated);
try {
_checkForImmutable(node);
_checkForInvalidSealedSuperclass(node);
super.visitMixinDeclaration(node);
} finally {
_enclosingClass = null;
_invalidAccessVerifier._enclosingClass = null;
_deprecatedVerifier.popInDeprecated();
}
}
@override
void visitPostfixExpression(PostfixExpression node) {
_deprecatedVerifier.postfixExpression(node);
if (node.operator.type == TokenType.BANG &&
node.operand.typeOrThrow.isDartCoreNull) {
_errorReporter.reportErrorForNode(HintCode.NULL_CHECK_ALWAYS_FAILS, node);
}
super.visitPostfixExpression(node);
}
@override
void visitPrefixExpression(PrefixExpression node) {
_deprecatedVerifier.prefixExpression(node);
super.visitPrefixExpression(node);
}
@override
void visitPropertyAccess(PropertyAccess node) {
_checkForNullAwareHints(node, node.operator);
super.visitPropertyAccess(node);
}
@override
void visitRedirectingConstructorInvocation(
RedirectingConstructorInvocation node) {
_deprecatedVerifier.redirectingConstructorInvocation(node);
super.visitRedirectingConstructorInvocation(node);
}
@override
void visitReturnStatement(ReturnStatement node) {
if (!_invalidAccessVerifier._inTestDirectory) {
_checkForReturnOfDoNotStore(node.expression);
}
super.visitReturnStatement(node);
}
@override
void visitSetOrMapLiteral(SetOrMapLiteral node) {
_checkForDuplications(node);
super.visitSetOrMapLiteral(node);
}
@override
void visitSimpleIdentifier(SimpleIdentifier node) {
_deprecatedVerifier.simpleIdentifier(node);
_invalidAccessVerifier.verify(node);
super.visitSimpleIdentifier(node);
}
@override
void visitSuperConstructorInvocation(SuperConstructorInvocation node) {
_deprecatedVerifier.superConstructorInvocation(node);
_invalidAccessVerifier.verifySuperConstructorInvocation(node);
super.visitSuperConstructorInvocation(node);
}
@override
void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) {
_deprecatedVerifier.pushInDeprecatedMetadata(node.metadata);
if (!_invalidAccessVerifier._inTestDirectory) {
for (var decl in node.variables.variables) {
_checkForAssignmentOfDoNotStore(decl.initializer);
}
}
try {
super.visitTopLevelVariableDeclaration(node);
} finally {
_deprecatedVerifier.popInDeprecated();
}
}
@override
void visitTypeName(TypeName node) {
if (node.question != null) {
var name = node.name.name;
var type = node.typeOrThrow;
// Only report non-aliased, non-user-defined `Null?` and `dynamic?`. Do
// not report synthetic `dynamic` in place of an unresolved type.
if ((type.element == _nullType.element ||
(type.isDynamic && name == 'dynamic')) &&
type.aliasElement == null) {
_errorReporter.reportErrorForNode(
HintCode.UNNECESSARY_QUESTION_MARK, node, [name]);
}
}
super.visitTypeName(node);
}
/// Check for the passed is expression for the unnecessary type check hint
/// codes as well as null checks expressed using an is expression.
///
/// @param node the is expression to check
/// @return `true` if and only if a hint code is generated on the passed node
/// See [HintCode.TYPE_CHECK_IS_NOT_NULL], [HintCode.TYPE_CHECK_IS_NULL],
/// [HintCode.UNNECESSARY_TYPE_CHECK_TRUE], and
/// [HintCode.UNNECESSARY_TYPE_CHECK_FALSE].
bool _checkAllTypeChecks(IsExpression node) {
Expression expression = node.expression;
TypeAnnotation typeName = node.type;
var rhsType = typeName.type as TypeImpl;
var rhsNameStr = typeName is TypeName ? typeName.name.name : null;
// if x is dynamic
if (rhsType.isDynamic && rhsNameStr == Keyword.DYNAMIC.lexeme) {
if (node.notOperator == null) {
// the is case
_errorReporter.reportErrorForNode(
HintCode.UNNECESSARY_TYPE_CHECK_TRUE, node);
} else {
// the is not case
_errorReporter.reportErrorForNode(
HintCode.UNNECESSARY_TYPE_CHECK_FALSE, node);
}
return true;
}
// `is Null` or `is! Null`
if (rhsType.isDartCoreNull) {
if (expression is NullLiteral) {
if (node.notOperator == null) {
_errorReporter.reportErrorForNode(
HintCode.UNNECESSARY_TYPE_CHECK_TRUE,
node,
);
} else {
_errorReporter.reportErrorForNode(
HintCode.UNNECESSARY_TYPE_CHECK_FALSE,
node,
);
}
} else {
if (node.notOperator == null) {
_errorReporter.reportErrorForNode(
HintCode.TYPE_CHECK_IS_NULL,
node,
);
} else {
_errorReporter.reportErrorForNode(
HintCode.TYPE_CHECK_IS_NOT_NULL,
node,
);
}
}
return true;
}
// `is Object` or `is! Object`
if (rhsType.isDartCoreObject) {
var nullability = rhsType.nullabilitySuffix;
if (nullability == NullabilitySuffix.star ||
nullability == NullabilitySuffix.question) {
if (node.notOperator == null) {
_errorReporter.reportErrorForNode(
HintCode.UNNECESSARY_TYPE_CHECK_TRUE,
node,
);
} else {
_errorReporter.reportErrorForNode(
HintCode.UNNECESSARY_TYPE_CHECK_FALSE,
node,
);
}
return true;
}
}
return false;
}
void _checkForAssignmentOfDoNotStore(Expression? expression) {
var expressionMap = _getSubExpressionsMarkedDoNotStore(expression);
for (var entry in expressionMap.entries) {
_errorReporter.reportErrorForNode(
HintCode.ASSIGNMENT_OF_DO_NOT_STORE,
entry.key,
[entry.value.name],
);
}
}
/// Check for the passed binary expression for the
/// [HintCode.DIVISION_OPTIMIZATION].
///
/// @param node the binary expression to check
/// @return `true` if and only if a hint code is generated on the passed node
/// See [HintCode.DIVISION_OPTIMIZATION].
bool _checkForDivisionOptimizationHint(BinaryExpression node) {
// Return if the operator is not '/'
if (node.operator.type != TokenType.SLASH) {
return false;
}
// Return if the '/' operator is not defined in core, or if we don't know
// its static type
var methodElement = node.staticElement;
if (methodElement == null) {
return false;
}
LibraryElement libraryElement = methodElement.library;
if (!libraryElement.isDartCore) {
return false;
}
// Report error if the (x/y) has toInt() invoked on it
var parent = node.parent;
if (parent is ParenthesizedExpression) {
ParenthesizedExpression parenthesizedExpression =
_wrapParenthesizedExpression(parent);
var grandParent = parenthesizedExpression.parent;
if (grandParent is MethodInvocation) {
if (_TO_INT_METHOD_NAME == grandParent.methodName.name &&
grandParent.argumentList.arguments.isEmpty) {
_errorReporter.reportErrorForNode(
HintCode.DIVISION_OPTIMIZATION, grandParent);
return true;
}
}
}
return false;
}
/// Generate hints related to duplicate elements (keys) in sets (maps).
void _checkForDuplications(SetOrMapLiteral node) {
// This only checks for top-level elements. If, for, and spread elements
// that contribute duplicate values are not detected.
if (node.isConst) {
// This case is covered by the ErrorVerifier.
return;
}
final expressions = node.isSet
? node.elements.whereType<Expression>()
: node.elements.whereType<MapLiteralEntry>().map((entry) => entry.key);
final alreadySeen = <DartObject>{};
for (final expression in expressions) {
final constEvaluation = _linterContext.evaluateConstant(expression);
if (constEvaluation.errors.isEmpty) {
var value = constEvaluation.value;
if (value != null && !alreadySeen.add(value)) {
var errorCode = node.isSet
? HintCode.EQUAL_ELEMENTS_IN_SET
: HintCode.EQUAL_KEYS_IN_MAP;
_errorReporter.reportErrorForNode(errorCode, expression);
}
}
}
}
/// Checks whether [node] violates the rules of [immutable].
///
/// If [node] is marked with [immutable] or inherits from a class or mixin
/// marked with [immutable], this function searches the fields of [node] and
/// its superclasses, reporting a hint if any non-final instance fields are
/// found.
void _checkForImmutable(NamedCompilationUnitMember node) {
/// Return `true` if the given class [element] is annotated with the
/// `@immutable` annotation.
bool isImmutable(ClassElement element) {
for (ElementAnnotation annotation in element.metadata) {
if (annotation.isImmutable) {
return true;
}
}
return false;
}
/// Return `true` if the given class [element] or any superclass of it is
/// annotated with the `@immutable` annotation.
bool isOrInheritsImmutable(
ClassElement element, HashSet<ClassElement> visited) {
if (visited.add(element)) {
if (isImmutable(element)) {
return true;
}
for (InterfaceType interface in element.mixins) {
if (isOrInheritsImmutable(interface.element, visited)) {
return true;
}
}
for (InterfaceType mixin in element.interfaces) {
if (isOrInheritsImmutable(mixin.element, visited)) {
return true;
}
}
if (element.supertype != null) {
return isOrInheritsImmutable(element.supertype!.element, visited);
}
}
return false;
}
/// Return `true` if the given class [element] defines a non-final instance
/// field.
Iterable<String> nonFinalInstanceFields(ClassElement element) {
return element.fields
.where((FieldElement field) =>
!field.isSynthetic && !field.isFinal && !field.isStatic)
.map((FieldElement field) => '${element.name}.${field.name}');
}
/// Return `true` if the given class [element] defines or inherits a
/// non-final field.
Iterable<String> definedOrInheritedNonFinalInstanceFields(
ClassElement element, HashSet<ClassElement> visited) {
Iterable<String> nonFinalFields = [];
if (visited.add(element)) {
nonFinalFields = nonFinalInstanceFields(element);
nonFinalFields = nonFinalFields.followedBy(element.mixins.expand(
(InterfaceType mixin) => nonFinalInstanceFields(mixin.element)));
if (element.supertype != null) {
nonFinalFields = nonFinalFields.followedBy(
definedOrInheritedNonFinalInstanceFields(
element.supertype!.element, visited));
}
}
return nonFinalFields;
}
var element = node.declaredElement as ClassElement;
if (isOrInheritsImmutable(element, HashSet<ClassElement>())) {
Iterable<String> nonFinalFields =
definedOrInheritedNonFinalInstanceFields(
element, HashSet<ClassElement>());
if (nonFinalFields.isNotEmpty) {
_errorReporter.reportErrorForNode(
HintCode.MUST_BE_IMMUTABLE, node.name, [nonFinalFields.join(', ')]);
}
}
}
void _checkForImportOfLegacyLibraryIntoNullSafe(ImportDirective node) {
if (!_isNonNullableByDefault) {
return;
}
var importElement = node.element;
if (importElement == null) {
return;
}
var importedLibrary = importElement.importedLibrary;
if (importedLibrary == null || importedLibrary.isNonNullableByDefault) {
return;
}
_errorReporter.reportErrorForNode(
HintCode.IMPORT_OF_LEGACY_LIBRARY_INTO_NULL_SAFE,
node.uri,
[importedLibrary.source.uri],
);
}
/// Check that the namespace exported by [node] does not include any elements
/// annotated with `@internal`.
void _checkForInternalExport(ExportDirective node) {
if (!_inPublicPackageApi) return;
var libraryElement = node.uriElement;
if (libraryElement == null) return;
if (libraryElement.hasInternal) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_EXPORT_OF_INTERNAL_ELEMENT,
node,
[libraryElement.displayName]);
}
var exportNamespace =
NamespaceBuilder().createExportNamespaceForDirective(node.element!);
exportNamespace.definedNames.forEach((String name, Element element) {
if (element.hasInternal) {
_errorReporter.reportErrorForNode(
HintCode.INVALID_EXPORT_OF_INTERNAL_ELEMENT,
node,