@@ -15,8 +15,11 @@ const _desc = 'Unused top-level members in executable libraries.';
15
15
const _details = r'''
16
16
17
17
Top-level members in an executable library should be used directly inside this
18
- library. Executable library are usually never used as dependency and it's better
19
- to avoid defining unused members.
18
+ library. Executable libraries are usually never used as dependency and it's
19
+ better to avoid defining unused members.
20
+
21
+ This rule assumes that an executable library shouldn't be imported by other
22
+ files except to execute its `main` function.
20
23
21
24
**BAD:**
22
25
@@ -32,7 +35,7 @@ main() {
32
35
f();
33
36
}
34
37
void f() {}
35
- ``
38
+ ```
36
39
37
40
''' ;
38
41
@@ -66,8 +69,6 @@ class _Visitor extends SimpleAstVisitor<void> {
66
69
if (node.directives.whereType <PartOfDirective >().isNotEmpty) return ;
67
70
if (node.directives.whereType <PartDirective >().isNotEmpty) return ;
68
71
69
- if (! _isInsideExecutableLibrary (node)) return ;
70
-
71
72
var topDeclarations = node.declarations
72
73
.expand ((e) => [
73
74
if (e is TopLevelVariableDeclaration )
@@ -77,6 +78,8 @@ class _Visitor extends SimpleAstVisitor<void> {
77
78
])
78
79
.toSet ();
79
80
81
+ if (! topDeclarations.any (_isEntryPoint)) return ;
82
+
80
83
var declarationByElement = < Element , Declaration > {};
81
84
for (var declaration in topDeclarations) {
82
85
var element = declaration.declaredElement;
@@ -118,9 +121,8 @@ class _Visitor extends SimpleAstVisitor<void> {
118
121
while (toTraverse.isNotEmpty) {
119
122
var declaration = toTraverse.removeLast ();
120
123
for (var dep in dependencies[declaration]! ) {
121
- if (! usedMembers.contains (dep)) {
122
- usedMembers.add (dep);
123
- if (! toTraverse.contains (dep)) toTraverse.add (dep);
124
+ if (usedMembers.add (dep)) {
125
+ toTraverse.add (dep);
124
126
}
125
127
}
126
128
}
@@ -161,12 +163,4 @@ class _Visitor extends SimpleAstVisitor<void> {
161
163
}
162
164
return false ;
163
165
}
164
-
165
- bool _isInsideExecutableLibrary (AstNode node) {
166
- var root = node.root;
167
- if (root is ! CompilationUnit ) return false ;
168
- var library = root.declaredElement? .library;
169
- return library != null &&
170
- library.exportNamespace.definedNames.containsKey ('main' );
171
- }
172
166
}
0 commit comments