Skip to content

Commit c9677f5

Browse files
authored
Fix unnecessary_parenthesis with null aware expressions. (dart-archive/linter#3902)
dart-lang/linter#3848
1 parent a14b8ad commit c9677f5

File tree

2 files changed

+14
-6
lines changed

2 files changed

+14
-6
lines changed

lib/src/rules/unnecessary_parenthesis.dart

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,16 +87,20 @@ class _Visitor extends SimpleAstVisitor<void> {
8787
void visitParenthesizedExpression(ParenthesizedExpression node) {
8888
var parent = node.parent;
8989
var expression = node.expression;
90-
if (expression is SimpleIdentifier) {
90+
if (expression is SimpleIdentifier ||
91+
(expression is CascadeExpression && expression.isNullAware) ||
92+
(expression is PropertyAccess && expression.isNullAware) ||
93+
(expression is MethodInvocation && expression.isNullAware) ||
94+
(expression is IndexExpression && expression.isNullAware)) {
9195
if (parent is PropertyAccess) {
92-
if (parent.propertyName.name == 'hashCode' ||
93-
parent.propertyName.name == 'runtimeType') {
96+
var name = parent.propertyName.name;
97+
if (name == 'hashCode' || name == 'runtimeType') {
9498
// Code like `(String).hashCode` is allowed.
9599
return;
96100
}
97101
} else if (parent is MethodInvocation) {
98-
if (parent.methodName.name == 'noSuchMethod' ||
99-
parent.methodName.name == 'toString') {
102+
var name = parent.methodName.name;
103+
if (name == 'noSuchMethod' || name == 'toString') {
100104
// Code like `(String).noSuchMethod()` is allowed.
101105
return;
102106
}
@@ -238,7 +242,7 @@ extension on Expression? {
238242
(self is InstanceCreationExpression && self.keyword != null) ||
239243
// No TypedLiteral (ListLiteral, MapLiteral, SetLiteral) accepts `-`
240244
// or `!` as a prefix operator, but this method can be called
241-
// rescursively, so this catches things like
245+
// recursively, so this catches things like
242246
// `!(const [].contains(42))`.
243247
(self is TypedLiteral && self.constKeyword != null) ||
244248
// As in, `!(const List(3).contains(7))`, and chains like

test_data/rules/unnecessary_parenthesis.dart

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,10 @@ main() async {
116116
List<String> list = <String>[];
117117
(list[list.length]).toString(); // LINT
118118

119+
(a?.sign).hashCode;
120+
(a?.abs()).hashCode;
121+
(a?..abs()).hashCode;
122+
(a?[0]).hashCode;
119123
}
120124

121125
Invocation? invocation() => null;

0 commit comments

Comments
 (0)