Skip to content

Commit 954ed42

Browse files
srawlinsCommit Queue
authored and
Commit Queue
committed
linter: unreachable_from_main: consider any 'toJson' as reachable
Fixes https://github.com/dart-lang/linter/issues/4495 Change-Id: Ic6ba67393f9c05d8fa1b327b8d2c87f654fc01d0 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/362561 Auto-Submit: Samuel Rawlins <[email protected]> Commit-Queue: Samuel Rawlins <[email protected]> Reviewed-by: Nate Bosch <[email protected]>
1 parent 4435145 commit 954ed42

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

pkg/linter/lib/src/rules/unreachable_from_main.dart

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,20 @@ class _ReferenceVisitor extends RecursiveAstVisitor {
280280
super.visitExtensionTypeDeclaration(node);
281281
}
282282

283+
@override
284+
void visitMethodDeclaration(MethodDeclaration node) {
285+
if (node.name.lexeme == 'toJson' && !node.isStatic) {
286+
// The 'dart:convert' library uses dynamic invocation to call `toJson` on
287+
// arbitrary objects. Any declaration of `toJson` is automatically
288+
// reachable.
289+
var element = node.declaredElement;
290+
if (element != null) {
291+
_addDeclaration(element);
292+
}
293+
}
294+
super.visitMethodDeclaration(node);
295+
}
296+
283297
@override
284298
void visitNamedType(NamedType node) {
285299
var element = node.element;

pkg/linter/test/rules/unreachable_from_main_test.dart

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1051,6 +1051,20 @@ extension E on int {
10511051
]);
10521052
}
10531053

1054+
test_instanceMethod_reachable_toJson() async {
1055+
await assertNoDiagnostics(r'''
1056+
import 'dart:convert';
1057+
1058+
void main() async {
1059+
jsonEncode([C()]);
1060+
}
1061+
1062+
class C {
1063+
List<Object> toJson() => ['c'];
1064+
}
1065+
''');
1066+
}
1067+
10541068
test_instanceMethod_unreachable_inExtensionType() async {
10551069
await assertDiagnostics(r'''
10561070
void main() {

0 commit comments

Comments
 (0)