From 0abe619851ec32278a2935a602e6c362ae4c10fb Mon Sep 17 00:00:00 2001 From: Ahmed Ashour Date: Tue, 13 Dec 2022 09:59:13 +0100 Subject: [PATCH] Fix `unnecessary_parenthesis` with null aware expressions. #3848 --- lib/src/rules/unnecessary_parenthesis.dart | 16 ++++++++++------ test_data/rules/unnecessary_parenthesis.dart | 4 ++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/src/rules/unnecessary_parenthesis.dart b/lib/src/rules/unnecessary_parenthesis.dart index 7f7e8cd62..cd9340b88 100644 --- a/lib/src/rules/unnecessary_parenthesis.dart +++ b/lib/src/rules/unnecessary_parenthesis.dart @@ -87,16 +87,20 @@ class _Visitor extends SimpleAstVisitor { void visitParenthesizedExpression(ParenthesizedExpression node) { var parent = node.parent; var expression = node.expression; - if (expression is SimpleIdentifier) { + if (expression is SimpleIdentifier || + (expression is CascadeExpression && expression.isNullAware) || + (expression is PropertyAccess && expression.isNullAware) || + (expression is MethodInvocation && expression.isNullAware) || + (expression is IndexExpression && expression.isNullAware)) { if (parent is PropertyAccess) { - if (parent.propertyName.name == 'hashCode' || - parent.propertyName.name == 'runtimeType') { + var name = parent.propertyName.name; + if (name == 'hashCode' || name == 'runtimeType') { // Code like `(String).hashCode` is allowed. return; } } else if (parent is MethodInvocation) { - if (parent.methodName.name == 'noSuchMethod' || - parent.methodName.name == 'toString') { + var name = parent.methodName.name; + if (name == 'noSuchMethod' || name == 'toString') { // Code like `(String).noSuchMethod()` is allowed. return; } @@ -238,7 +242,7 @@ extension on Expression? { (self is InstanceCreationExpression && self.keyword != null) || // No TypedLiteral (ListLiteral, MapLiteral, SetLiteral) accepts `-` // or `!` as a prefix operator, but this method can be called - // rescursively, so this catches things like + // recursively, so this catches things like // `!(const [].contains(42))`. (self is TypedLiteral && self.constKeyword != null) || // As in, `!(const List(3).contains(7))`, and chains like diff --git a/test_data/rules/unnecessary_parenthesis.dart b/test_data/rules/unnecessary_parenthesis.dart index 47d16f59b..34ca613a6 100644 --- a/test_data/rules/unnecessary_parenthesis.dart +++ b/test_data/rules/unnecessary_parenthesis.dart @@ -116,6 +116,10 @@ main() async { List list = []; (list[list.length]).toString(); // LINT + (a?.sign).hashCode; + (a?.abs()).hashCode; + (a?..abs()).hashCode; + (a?[0]).hashCode; } Invocation? invocation() => null;