Skip to content

Commit

Permalink
fix pattern constant detection (#4056)
Browse files Browse the repository at this point in the history
* fix pattern constant detection

* ++

* + test
  • Loading branch information
pq committed Feb 8, 2023
1 parent c183522 commit 2a32d3f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 7 deletions.
11 changes: 4 additions & 7 deletions lib/src/rules/unnecessary_const.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
// 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 'package:analyzer/dart/analysis/features.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/ast/token.dart';
import 'package:analyzer/dart/ast/visitor.dart';
Expand Down Expand Up @@ -52,8 +51,7 @@ class UnnecessaryConst extends LintRule {
@override
void registerNodeProcessors(
NodeLintRegistry registry, LinterContext context) {
var visitor =
_Visitor(this, patternsEnabled: context.isEnabled(Feature.patterns));
var visitor = _Visitor(this);
registry.addInstanceCreationExpression(this, visitor);
registry.addListLiteral(this, visitor);
registry.addRecordLiteral(this, visitor);
Expand All @@ -63,8 +61,7 @@ class UnnecessaryConst extends LintRule {

class _Visitor extends SimpleAstVisitor {
final LintRule rule;
final bool patternsEnabled;
_Visitor(this.rule, {required this.patternsEnabled});
_Visitor(this.rule);

@override
void visitInstanceCreationExpression(InstanceCreationExpression node) {
Expand All @@ -77,7 +74,7 @@ class _Visitor extends SimpleAstVisitor {

@override
void visitListLiteral(ListLiteral node) {
if (patternsEnabled) return;
if (node.unParenthesized.parent is ConstantPattern) return;
_visitTypedLiteral(node);
}

Expand All @@ -92,7 +89,7 @@ class _Visitor extends SimpleAstVisitor {

@override
void visitSetOrMapLiteral(SetOrMapLiteral node) {
if (patternsEnabled) return;
if (node.unParenthesized.parent is ConstantPattern) return;
_visitTypedLiteral(node);
}

Expand Down
35 changes: 35 additions & 0 deletions test/rules/unnecessary_const_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,41 @@ void f(Object o) {
}
''');
}

test_constConstructor() async {
await assertDiagnostics(r'''
class C {
const C();
}
const c = const C();
''', [
lint(35, 9),
]);
}

test_listLiteral() async {
await assertDiagnostics(r'''
const l = const [];
''', [
lint(10, 8),
]);
}

test_mapLiteral() async {
await assertDiagnostics(r'''
const m = const {1: 1};
''', [
lint(10, 12),
]);
}

test_setLiteral() async {
await assertDiagnostics(r'''
const s = const {1};
''', [
lint(10, 9),
]);
}
}

@reflectiveTest
Expand Down

0 comments on commit 2a32d3f

Please sign in to comment.