This repository was archived by the owner on Nov 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 166
Lint that flags usages of implicitly-dynamic values #262
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,202 @@ | ||
// Copyright (c) 2015, 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. | ||
|
||
library linter.src.rules.annotate_types; | ||
|
||
import 'package:analyzer/dart/ast/ast.dart'; | ||
import 'package:analyzer/dart/ast/visitor.dart'; | ||
import 'package:analyzer/dart/element/element.dart'; | ||
import 'package:analyzer/dart/element/type.dart'; | ||
import 'package:linter/src/linter.dart'; | ||
import 'package:linter/src/util.dart'; | ||
|
||
const desc = 'Implicit use of dynamic.'; | ||
|
||
const details = ''' | ||
**AVOID** using "implicitly dynamic" values. | ||
|
||
Untyped / dynamic invocations may fail or be slower at runtime, but dynamic | ||
types often creep up unintentionally. Explicitly mark variables or return types | ||
as `dynamic` (instead of `var`) to express your intent unequivocally. | ||
|
||
Note: this works best with the --strong command-line flag and after disabling | ||
both `always_specify_types` and `always_declare_return_types` lints. | ||
|
||
**GOOD:** | ||
```dart | ||
String trim(String s) => s.trim(); | ||
|
||
main() { | ||
var s = trim(' a ').toUpperCase(); | ||
|
||
dynamic x; | ||
x = ... ; | ||
x.reallyNotSureThisExists(); | ||
} | ||
``` | ||
|
||
**BAD:** | ||
```dart | ||
trim(s) => s.trim(); | ||
|
||
main() { | ||
var s = trim(1).toUpperCase(); | ||
|
||
var x; | ||
x = ... ; | ||
x.reallyNotSureThisExists(); | ||
} | ||
``` | ||
'''; | ||
|
||
class NoImplicitDynamic extends LintRule { | ||
NoImplicitDynamic() | ||
: super( | ||
name: 'no_implicit_dynamic', | ||
description: desc, | ||
details: details, | ||
group: Group.style); | ||
|
||
@override | ||
AstVisitor getVisitor() => new Visitor(this); | ||
} | ||
|
||
// TODO(ochafik): Handle implicit return types of method declarations (vs. overrides). | ||
class Visitor extends SimpleAstVisitor { | ||
final LintRule rule; | ||
Visitor(this.rule); | ||
|
||
Element _getBestElement(Expression node) { | ||
if (node is SimpleIdentifier) return node.bestElement; | ||
if (node is PrefixedIdentifier) return node.bestElement; | ||
if (node is PropertyAccess) return node.propertyName.bestElement; | ||
return null; | ||
} | ||
|
||
bool _isImplicitDynamic(Expression node) { | ||
if (node == null) return false; | ||
while (node is ParenthesizedExpression) { | ||
node = node.expression; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consider call _isImplicitDynamic(node.expression) |
||
} | ||
|
||
if (node is AsExpression || node is Literal) return false; | ||
var t = node.bestType; | ||
if (!t.isDynamic && !t.isObject) return false; | ||
|
||
var e = _getBestElement(node); | ||
if (e is PropertyAccessorElement) e = e.variable; | ||
if (e is VariableElement) return e.hasImplicitType; | ||
|
||
if (node is ConditionalExpression) { | ||
return !node.thenExpression.bestType.isDynamic || | ||
!node.elseExpression.bestType.isDynamic; | ||
} | ||
if (node is MethodInvocation) { | ||
return node.methodName.bestElement?.hasImplicitReturnType != false; | ||
} | ||
|
||
return true; | ||
} | ||
|
||
void _checkTarget(Expression target, [token]) { | ||
if (_isImplicitDynamic(target)) { | ||
// Avoid double taxation (if `x` is dynamic, only lint `x.y.z` once). | ||
Expression subTarget; | ||
if (target is PropertyAccess) subTarget = target.realTarget; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Perhaps it would be good idea to create a method that return an iterable with all targets, for example when you have something like: a.b.foo().c.d.bar()[3].baz(); So if you can create a method, it could be also use in unnecessary_lambdas, where I had to do a similar check |
||
else if (target is MethodInvocation) subTarget = target.realTarget; | ||
else if (target is IndexExpression) subTarget = target.realTarget; | ||
else if (target is PrefixedIdentifier) subTarget = target.prefix; | ||
|
||
if (_isImplicitDynamic(subTarget)) return; | ||
|
||
_reportNodeOrToken(target, token); | ||
} | ||
} | ||
|
||
_reportNodeOrToken(AstNode node, token) { | ||
if (token != null) { | ||
rule.reportLintForToken(token); | ||
} else { | ||
rule.reportLint(node); | ||
} | ||
} | ||
|
||
@override | ||
visitPrefixedIdentifier(PrefixedIdentifier node) { | ||
if (_isObjectProperty(node.identifier)) return; | ||
_checkTarget(node.prefix, node.period); | ||
} | ||
|
||
@override | ||
visitPropertyAccess(PropertyAccess node) { | ||
if (_isObjectProperty(node.propertyName)) return; | ||
_checkTarget(node.realTarget, node.operator); | ||
} | ||
|
||
bool _isObjectProperty(SimpleIdentifier node) { | ||
var name = node.name; | ||
return name == 'runtimeType' || name == 'hashCode'; | ||
} | ||
|
||
@override | ||
visitIndexExpression(IndexExpression node) { | ||
_checkTarget(node.realTarget, node.leftBracket); | ||
} | ||
|
||
@override | ||
visitAssignmentExpression(AssignmentExpression node) { | ||
var rhs = node.rightHandSide; | ||
_checkAssignment(rhs, | ||
rhs.bestParameterElement ?? _getBestElement(node.leftHandSide)); | ||
} | ||
|
||
@override | ||
visitMethodInvocation(MethodInvocation node) { | ||
var methodName = node.methodName; | ||
_checkMethodInvocation(node.realTarget, methodName.bestElement, methodName.name, node.argumentList.arguments, node.operator); | ||
} | ||
|
||
_checkMethodInvocation(Expression target, ExecutableElement methodElement, String methodName, List<Expression> arguments, token) { | ||
for (var arg in arguments) { | ||
_checkAssignment(arg, arg.bestParameterElement); | ||
} | ||
|
||
if (methodElement != null) return; | ||
|
||
if (methodName == 'toString' && arguments.isEmpty || | ||
methodName == 'noSuchMethod' && arguments.size == 1) { | ||
return; | ||
} | ||
_checkTarget(target, token); | ||
} | ||
|
||
@override | ||
visitBinaryExpression(BinaryExpression node) { | ||
_checkMethodInvocation(node.leftOperand, node.bestElement, node.operator.toString(), [node.rightOperand], node.operator); | ||
} | ||
|
||
_checkAssignment(Expression arg, Element toElement) { | ||
if (!_isImplicitDynamic(arg)) return; | ||
|
||
if (toElement == null) return; | ||
|
||
if (_isDynamicOrObject(toElement.type)) return; | ||
|
||
rule.reportLint(arg); | ||
} | ||
|
||
_isDynamicOrObject(DartType t) => t.isDynamic || t.isObject; | ||
|
||
@override | ||
void visitConditionalExpression(ConditionalExpression node) { | ||
_checkTarget(node.condition); | ||
} | ||
|
||
@override | ||
visitDeclaredIdentifier(DeclaredIdentifier node) { | ||
if (node.type == null && node.identifier.bestType.isDynamic && node.element.type.isDynamic) { | ||
rule.reportLintForToken(node.keyword); | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
takeInt(int i) {} | ||
takeDynamic(dynamic i) {} | ||
takeObject(Object i) {} | ||
|
||
conditionals(implicitBool, bool explicitBool) { | ||
explicitBool ? 1 : 2; | ||
|
||
implicitBool //LINT | ||
? 1 : 2; | ||
|
||
takeInt(explicitBool ? 1 : "2"); //LINT | ||
} | ||
|
||
methodCalls() { | ||
var implicitDynamic; | ||
dynamic explicitDynamic; | ||
|
||
takeDynamic(1); | ||
takeObject(1); | ||
takeInt(1); | ||
|
||
takeDynamic(implicitDynamic); | ||
takeObject(implicitDynamic); | ||
takeInt(implicitDynamic); //LINT | ||
|
||
takeDynamic(explicitDynamic); | ||
takeObject(explicitDynamic); | ||
takeInt(explicitDynamic); | ||
} | ||
|
||
class Foo { | ||
var implicitDynamic; | ||
dynamic explicitDynamic; | ||
int i; | ||
} | ||
|
||
assignments() { | ||
Foo newFoo() => new Foo(); | ||
int i; | ||
var f = newFoo(); | ||
|
||
// Exercice prefixed identifiers path: | ||
f.i = f.i; | ||
f.i = f.implicitDynamic; //LINT | ||
f.i = f.explicitDynamic; | ||
|
||
// Exercice property access path: | ||
f.i = newFoo().i; | ||
f.i = newFoo().implicitDynamic; //LINT | ||
f.i = newFoo().explicitDynamic; | ||
|
||
i = f.i; | ||
i = f.implicitDynamic; //LINT | ||
i = f.explicitDynamic; | ||
} | ||
|
||
vars(implicitDynamic, dynamic explicitDynamic) { | ||
implicitDynamic.foo; //LINT | ||
implicitDynamic?.foo; //LINT | ||
implicitDynamic.foo(); //LINT | ||
implicitDynamic?.foo(); //LINT | ||
implicitDynamic['foo']; //LINT | ||
implicitDynamic.toString(); | ||
implicitDynamic.runtimeType; | ||
implicitDynamic.hashCode; | ||
|
||
(implicitDynamic as dynamic).foo; | ||
|
||
explicitDynamic.foo; | ||
explicitDynamic.foo(); | ||
explicitDynamic['foo']; | ||
explicitDynamic.toString(); | ||
explicitDynamic.runtimeType; | ||
explicitDynamic.hashCode; | ||
} | ||
|
||
operators(implicitDynamic, dynamic explicitDynamic) { | ||
implicitDynamic + 1; //LINT | ||
implicitDynamic * 1; //LINT | ||
|
||
explicitDynamic + 1; | ||
explicitDynamic + null; | ||
|
||
// int.operator+ expects an int parameter: | ||
1 + implicitDynamic; //LINT | ||
1 + explicitDynamic; | ||
} | ||
|
||
cascades() { | ||
var implicitDynamic; | ||
implicitDynamic | ||
..foo //LINT | ||
..foo() //LINT | ||
..['foo'] //LINT | ||
..toString() | ||
..runtimeType | ||
..hashCode; | ||
} | ||
|
||
dynamicMethods() { | ||
trim(s) => | ||
s.trim(); //LINT | ||
var s = trim(1) | ||
.toUpperCase(); //LINT | ||
|
||
implicit() {} | ||
implicit() | ||
.x //LINT | ||
.y; | ||
|
||
dynamic explicit() {} | ||
explicit().x; | ||
} | ||
|
||
chaining() { | ||
var x; | ||
// Only report the first implicit dynamic in a chain: | ||
x | ||
.y //LINT | ||
.z | ||
.w; | ||
|
||
dynamic y; | ||
// Calling an explicit dynamic is okay... | ||
y.z; | ||
y.z(); | ||
y['z']; | ||
// ... but returns an implicit dynamic. | ||
y.z.w; //LINT | ||
y.z().w; //LINT | ||
y['z'].w; //LINT | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider to use getCanonicalElementFromIdentifier method from DartTypeUtilities (if applies)