Skip to content

Commit 5b5f65c

Browse files
authored
fix literal_only_boolean_expressions if-case false positives (dart-archive/linter#4355)
1 parent 12edbb9 commit 5b5f65c

File tree

2 files changed

+72
-0
lines changed

2 files changed

+72
-0
lines changed

lib/src/rules/literal_only_boolean_expressions.dart

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,7 @@ class _Visitor extends SimpleAstVisitor<void> {
160160

161161
@override
162162
void visitIfStatement(IfStatement node) {
163+
if (node.caseClause != null) return;
163164
if (_onlyLiterals(node.expression)) {
164165
rule.reportLint(node);
165166
}

test/rules/literal_only_boolean_expressions_test.dart

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,77 @@ class LiteralOnlyBooleanExpressionsTestLanguage300 extends LintRuleTest
3636
@override
3737
String get lintRule => 'literal_only_boolean_expressions';
3838

39+
test_ifCase_intLiteral() async {
40+
await assertDiagnostics(r'''
41+
void f() {
42+
if (1 case {1:0}) {
43+
print('');
44+
}
45+
}
46+
''', [
47+
// No lint
48+
error(WarningCode.PATTERN_NEVER_MATCHES_VALUE_TYPE, 24, 5),
49+
]);
50+
}
51+
52+
test_ifCase_listLiteral() async {
53+
await assertNoDiagnostics(r'''
54+
void f() {
55+
if ([1] case [1]) {
56+
print('');
57+
}
58+
}
59+
''');
60+
}
61+
62+
test_ifCase_mapLiteral() async {
63+
await assertNoDiagnostics(r'''
64+
void f() {
65+
if ({1:0} case {1:0}) {
66+
print('');
67+
}
68+
}
69+
''');
70+
}
71+
72+
test_ifCase_objectInstantiation() async {
73+
await assertNoDiagnostics(r'''
74+
class A {
75+
final int a;
76+
A(this.a);
77+
}
78+
79+
void f() {
80+
if (A(1) case A(a: 1)) {
81+
print('');
82+
}
83+
}
84+
''');
85+
}
86+
87+
/// https://github.com/dart-lang/linter/issues/4352
88+
test_ifCase_record() async {
89+
await assertNoDiagnostics(r'''
90+
void f() {
91+
if (('', '') case (String(), String())) {
92+
print('');
93+
}
94+
}
95+
''');
96+
}
97+
98+
test_switchExpression() async {
99+
await assertNoDiagnostics(r'''
100+
bool f(Object o) => switch(o) {
101+
[1] => true,
102+
{1:1} => false,
103+
(1, 1) => false,
104+
String(isEmpty: false) => false,
105+
_ => false,
106+
};
107+
''');
108+
}
109+
39110
test_whenClause() async {
40111
await assertDiagnostics(r'''
41112
void f() {

0 commit comments

Comments
 (0)