dart-decimate 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/Cargo.lock +572 -0
  2. package/Cargo.toml +41 -0
  3. package/LICENSE +21 -0
  4. package/README.md +617 -0
  5. package/assets/dart-decimate-banner.png +0 -0
  6. package/npm/bin/dart-decimate-mcp.js +48 -0
  7. package/npm/bin/dart-decimate.js +48 -0
  8. package/npm/scripts/postinstall.js +46 -0
  9. package/npm/scripts/test-npx-local.js +54 -0
  10. package/npm/scripts/test-npx-mcp-local.js +56 -0
  11. package/package.json +45 -0
  12. package/src/baseline.rs +643 -0
  13. package/src/bin/dart-decimate-mcp.rs +11 -0
  14. package/src/boundaries/tests.rs +60 -0
  15. package/src/boundaries.rs +317 -0
  16. package/src/changed_scope.rs +117 -0
  17. package/src/ci_template.rs +399 -0
  18. package/src/cli/analyze.rs +462 -0
  19. package/src/cli/analyzer_options.rs +82 -0
  20. package/src/cli/audit_run.rs +327 -0
  21. package/src/cli/boundary_args.rs +44 -0
  22. package/src/cli/ci_template_run.rs +196 -0
  23. package/src/cli/command_name.rs +20 -0
  24. package/src/cli/common_args.rs +167 -0
  25. package/src/cli/config_run.rs +78 -0
  26. package/src/cli/coverage_run.rs +393 -0
  27. package/src/cli/decision_surface_run.rs +99 -0
  28. package/src/cli/default_command.rs +69 -0
  29. package/src/cli/dupes_args.rs +150 -0
  30. package/src/cli/entry_points.rs +121 -0
  31. package/src/cli/error.rs +149 -0
  32. package/src/cli/error_output.rs +68 -0
  33. package/src/cli/explain_run.rs +72 -0
  34. package/src/cli/fix_run.rs +162 -0
  35. package/src/cli/flags_args.rs +23 -0
  36. package/src/cli/health_args.rs +200 -0
  37. package/src/cli/hooks_run.rs +191 -0
  38. package/src/cli/impact_run.rs +95 -0
  39. package/src/cli/init_run.rs +49 -0
  40. package/src/cli/inspect_args.rs +20 -0
  41. package/src/cli/inspect_run.rs +66 -0
  42. package/src/cli/issue_filter_args.rs +240 -0
  43. package/src/cli/list_run.rs +311 -0
  44. package/src/cli/mode_args.rs +72 -0
  45. package/src/cli/output_format.rs +62 -0
  46. package/src/cli/regression_args.rs +156 -0
  47. package/src/cli/request_args.rs +175 -0
  48. package/src/cli/schema_commands.rs +72 -0
  49. package/src/cli/scope_args.rs +174 -0
  50. package/src/cli/security_args.rs +175 -0
  51. package/src/cli/security_gate_run.rs +66 -0
  52. package/src/cli/security_summary_run.rs +43 -0
  53. package/src/cli/summary_args.rs +12 -0
  54. package/src/cli/tests.rs +516 -0
  55. package/src/cli/trace_args.rs +67 -0
  56. package/src/cli/trace_run.rs +131 -0
  57. package/src/cli/trace_tests.rs +235 -0
  58. package/src/cli/unsupported_run.rs +116 -0
  59. package/src/cli/watch_run.rs +153 -0
  60. package/src/cli.rs +603 -0
  61. package/src/config/boundary_config.rs +235 -0
  62. package/src/config/cache.rs +25 -0
  63. package/src/config/dependencies.rs +114 -0
  64. package/src/config/health.rs +237 -0
  65. package/src/config/jsonc.rs +66 -0
  66. package/src/config/policy.rs +91 -0
  67. package/src/config/rule_aliases.rs +487 -0
  68. package/src/config/rules.rs +339 -0
  69. package/src/config.rs +635 -0
  70. package/src/coverage.rs +469 -0
  71. package/src/dart_parser.rs +673 -0
  72. package/src/decision_surface.rs +405 -0
  73. package/src/dependencies/analyze.rs +218 -0
  74. package/src/dependencies/codegen.rs +118 -0
  75. package/src/dependencies/discovery.rs +60 -0
  76. package/src/dependencies/overrides.rs +76 -0
  77. package/src/dependencies/private_src_imports.rs +32 -0
  78. package/src/dependencies/pubspec_document.rs +86 -0
  79. package/src/dependencies/pubspec_entry.rs +96 -0
  80. package/src/dependencies/tests.rs +544 -0
  81. package/src/dependencies/usage.rs +33 -0
  82. package/src/dependencies.rs +553 -0
  83. package/src/dependency_scripts.rs +91 -0
  84. package/src/dupes/lex.rs +236 -0
  85. package/src/dupes/tests.rs +119 -0
  86. package/src/dupes.rs +625 -0
  87. package/src/explain.rs +692 -0
  88. package/src/extract/directives.rs +252 -0
  89. package/src/extract/error_tests.rs +25 -0
  90. package/src/extract/members.rs +210 -0
  91. package/src/extract/primary_constructors.rs +421 -0
  92. package/src/extract/references.rs +151 -0
  93. package/src/extract/routes.rs +691 -0
  94. package/src/extract/signatures.rs +266 -0
  95. package/src/extract/string_tests.rs +18 -0
  96. package/src/extract/strings.rs +107 -0
  97. package/src/extract/tests.rs +697 -0
  98. package/src/extract.rs +680 -0
  99. package/src/feature_flags/tests.rs +76 -0
  100. package/src/feature_flags.rs +453 -0
  101. package/src/finding_identity.rs +60 -0
  102. package/src/fix.rs +551 -0
  103. package/src/generated.rs +53 -0
  104. package/src/graph/augment_tests.rs +212 -0
  105. package/src/graph/conditionals.rs +74 -0
  106. package/src/graph/package_config_tests.rs +100 -0
  107. package/src/graph/parts.rs +248 -0
  108. package/src/graph/pubspec_tests.rs +119 -0
  109. package/src/graph/tests.rs +837 -0
  110. package/src/graph/uri_tests.rs +102 -0
  111. package/src/graph.rs +644 -0
  112. package/src/health/coverage.rs +309 -0
  113. package/src/health/ownership.rs +175 -0
  114. package/src/health/runtime_coverage.rs +616 -0
  115. package/src/health/runtime_intelligence.rs +511 -0
  116. package/src/health/scores.rs +296 -0
  117. package/src/health/tests.rs +240 -0
  118. package/src/health/threshold_types.rs +163 -0
  119. package/src/health/thresholds.rs +229 -0
  120. package/src/health/types.rs +636 -0
  121. package/src/health.rs +597 -0
  122. package/src/hooks/agent_settings.rs +175 -0
  123. package/src/hooks/templates.rs +51 -0
  124. package/src/hooks.rs +569 -0
  125. package/src/impact.rs +287 -0
  126. package/src/init.rs +237 -0
  127. package/src/inspect.rs +142 -0
  128. package/src/intelligence/tests.rs +232 -0
  129. package/src/intelligence.rs +305 -0
  130. package/src/lib.rs +198 -0
  131. package/src/main.rs +5 -0
  132. package/src/manifest/mcp.rs +565 -0
  133. package/src/manifest.rs +552 -0
  134. package/src/mcp/cli_args/value_args.rs +175 -0
  135. package/src/mcp/cli_args.rs +658 -0
  136. package/src/mcp/cli_args_tests.rs +522 -0
  137. package/src/mcp/code_execute.rs +671 -0
  138. package/src/mcp/tools.rs +660 -0
  139. package/src/mcp.rs +325 -0
  140. package/src/output/audit_risk.rs +135 -0
  141. package/src/output/dependency_findings.rs +327 -0
  142. package/src/output/duplication_findings.rs +114 -0
  143. package/src/output/feature_flag_findings.rs +122 -0
  144. package/src/output/format.rs +31 -0
  145. package/src/output/graph_findings.rs +461 -0
  146. package/src/output/health_findings.rs +612 -0
  147. package/src/output/human.rs +27 -0
  148. package/src/output/next_steps.rs +92 -0
  149. package/src/output/route_findings.rs +76 -0
  150. package/src/output/runtime_coverage.rs +515 -0
  151. package/src/output/scope.rs +183 -0
  152. package/src/output/security_findings.rs +390 -0
  153. package/src/output/security_sarif.rs +150 -0
  154. package/src/output/suppressions.rs +323 -0
  155. package/src/output/symbol_findings.rs +257 -0
  156. package/src/output/tests.rs +114 -0
  157. package/src/output/types.rs +604 -0
  158. package/src/output/widget_findings.rs +213 -0
  159. package/src/output.rs +682 -0
  160. package/src/package_map.rs +495 -0
  161. package/src/policy/packs.rs +232 -0
  162. package/src/policy/tests.rs +134 -0
  163. package/src/policy.rs +640 -0
  164. package/src/project_list.rs +376 -0
  165. package/src/report_schema/inventory.rs +418 -0
  166. package/src/report_schema.rs +488 -0
  167. package/src/routes.rs +354 -0
  168. package/src/scan/tests.rs +250 -0
  169. package/src/scan.rs +275 -0
  170. package/src/security/detect.rs +639 -0
  171. package/src/security/tests.rs +178 -0
  172. package/src/security.rs +373 -0
  173. package/src/security_gate.rs +555 -0
  174. package/src/symbols/path_filters.rs +27 -0
  175. package/src/symbols/private_type_leaks.rs +125 -0
  176. package/src/symbols/riverpod.rs +113 -0
  177. package/src/symbols/tests.rs +692 -0
  178. package/src/symbols.rs +693 -0
  179. package/src/trace/tests.rs +225 -0
  180. package/src/trace.rs +690 -0
  181. package/src/unsupported.rs +47 -0
  182. package/src/widgets/lifecycle.rs +484 -0
  183. package/src/widgets/params.rs +236 -0
  184. package/src/widgets/tests.rs +430 -0
  185. package/src/widgets/top_level.rs +110 -0
  186. package/src/widgets/unrendered.rs +374 -0
  187. package/src/widgets.rs +590 -0
  188. package/src/workspace_scope.rs +358 -0
@@ -0,0 +1,236 @@
1
+ use std::collections::BTreeMap;
2
+
3
+ use tree_sitter::Node;
4
+
5
+ use crate::Location;
6
+
7
+ #[derive(Debug, Clone, PartialEq, Eq)]
8
+ pub(super) struct WidgetParamCandidate {
9
+ pub(super) name: String,
10
+ pub(super) field_name: String,
11
+ pub(super) location: Location,
12
+ }
13
+
14
+ pub(super) fn constructor_params(
15
+ class: Node<'_>,
16
+ widget_class: &str,
17
+ source: &str,
18
+ ) -> Vec<WidgetParamCandidate> {
19
+ let mut declarations = Vec::new();
20
+ collect_nodes_in(class, &["declaration"], &mut declarations);
21
+ let mut params = BTreeMap::<String, WidgetParamCandidate>::new();
22
+ for declaration in declarations {
23
+ let Some(signature) = constructor_signature(declaration) else {
24
+ continue;
25
+ };
26
+ if constructor_owner(signature, source).as_deref() != Some(widget_class) {
27
+ continue;
28
+ }
29
+ let Some(parameters) = signature.child_by_field_name("parameters") else {
30
+ continue;
31
+ };
32
+ let mut constructor_params = Vec::new();
33
+ collect_nodes(parameters, "formal_parameter", &mut constructor_params);
34
+ for param in constructor_params {
35
+ if !is_named_parameter(param, signature, source) {
36
+ continue;
37
+ }
38
+ let Some(candidate) = field_formal_candidate(param, source)
39
+ .or_else(|| initializer_param_candidate(param, declaration, source))
40
+ else {
41
+ continue;
42
+ };
43
+ if candidate.name == "key" {
44
+ continue;
45
+ }
46
+ params.entry(candidate.name.clone()).or_insert(candidate);
47
+ }
48
+ }
49
+ params.into_values().collect()
50
+ }
51
+
52
+ const CONSTRUCTOR_SIGNATURES: &[&str] =
53
+ &["constructor_signature", "constant_constructor_signature"];
54
+
55
+ fn constructor_signature(declaration: Node<'_>) -> Option<Node<'_>> {
56
+ let mut cursor = declaration.walk();
57
+ declaration
58
+ .named_children(&mut cursor)
59
+ .find(|child| CONSTRUCTOR_SIGNATURES.contains(&child.kind()))
60
+ }
61
+
62
+ fn constructor_owner(signature: Node<'_>, source: &str) -> Option<String> {
63
+ field_text(signature, "name", source).and_then(|name| name.split('.').next().map(str::to_owned))
64
+ }
65
+
66
+ fn is_named_parameter(param: Node<'_>, signature: Node<'_>, source: &str) -> bool {
67
+ let mut parent = param.parent();
68
+ while let Some(node) = parent {
69
+ if same_node(node, signature) {
70
+ return false;
71
+ }
72
+ if node.kind() == "optional_formal_parameters" {
73
+ return node
74
+ .utf8_text(source.as_bytes())
75
+ .ok()
76
+ .is_some_and(|text| text.trim_start().starts_with('{'));
77
+ }
78
+ parent = node.parent();
79
+ }
80
+ false
81
+ }
82
+
83
+ fn field_formal_candidate(param: Node<'_>, source: &str) -> Option<WidgetParamCandidate> {
84
+ let text = param.utf8_text(source.as_bytes()).ok()?;
85
+ let offset = text.find("this.")? + "this.".len();
86
+ let name = text[offset..]
87
+ .chars()
88
+ .take_while(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '$'))
89
+ .collect::<String>();
90
+ if name.is_empty() {
91
+ return None;
92
+ }
93
+ let min_byte = param.start_byte() + offset;
94
+ let location = identifier_after(param, &name, min_byte, source).map_or_else(
95
+ || param.start_position().into(),
96
+ |node| node.start_position().into(),
97
+ );
98
+ Some(WidgetParamCandidate {
99
+ field_name: name.clone(),
100
+ name,
101
+ location,
102
+ })
103
+ }
104
+
105
+ fn initializer_param_candidate(
106
+ param: Node<'_>,
107
+ declaration: Node<'_>,
108
+ source: &str,
109
+ ) -> Option<WidgetParamCandidate> {
110
+ let text = param.utf8_text(source.as_bytes()).ok()?;
111
+ if text.contains("this.") || text.contains("super.") {
112
+ return None;
113
+ }
114
+ let name_node = explicit_param_name(param, source)?;
115
+ let name = name_node.utf8_text(source.as_bytes()).ok()?.to_owned();
116
+ let field_name = initialized_field_from_param(declaration, &name, source)?;
117
+ Some(WidgetParamCandidate {
118
+ name,
119
+ field_name,
120
+ location: name_node.start_position().into(),
121
+ })
122
+ }
123
+
124
+ fn explicit_param_name<'tree>(param: Node<'tree>, source: &str) -> Option<Node<'tree>> {
125
+ if matches!(param.kind(), "typed_identifier" | "initialized_identifier") {
126
+ return param.child_by_field_name("name");
127
+ }
128
+ if param.kind() == "formal_parameter" {
129
+ return param
130
+ .child_by_field_name("name")
131
+ .or_else(|| last_identifier_child(param, source));
132
+ }
133
+ let mut cursor = param.walk();
134
+ param
135
+ .named_children(&mut cursor)
136
+ .find_map(|child| explicit_param_name(child, source))
137
+ .filter(|node| node.utf8_text(source.as_bytes()).ok() != Some("key"))
138
+ }
139
+
140
+ fn last_identifier_child<'tree>(node: Node<'tree>, source: &str) -> Option<Node<'tree>> {
141
+ let mut cursor = node.walk();
142
+ node.named_children(&mut cursor)
143
+ .filter(|child| {
144
+ matches!(child.kind(), "identifier" | "identifier_dollar_escaped")
145
+ && child.utf8_text(source.as_bytes()).ok() != Some("key")
146
+ })
147
+ .last()
148
+ }
149
+
150
+ fn initialized_field_from_param(
151
+ declaration: Node<'_>,
152
+ param_name: &str,
153
+ source: &str,
154
+ ) -> Option<String> {
155
+ let mut initializers = Vec::new();
156
+ collect_nodes(declaration, "field_initializer", &mut initializers);
157
+ initializers.into_iter().find_map(|initializer| {
158
+ let field = field_text(initializer, "name", source)?;
159
+ let mut cursor = initializer.walk();
160
+ initializer
161
+ .children_by_field_name("value", &mut cursor)
162
+ .any(|value| initializer_value_uses_param(value, param_name, source))
163
+ .then_some(field)
164
+ })
165
+ }
166
+
167
+ fn initializer_value_uses_param(node: Node<'_>, name: &str, source: &str) -> bool {
168
+ if matches!(node.kind(), "identifier" | "identifier_dollar_escaped")
169
+ && node.utf8_text(source.as_bytes()).ok() == Some(name)
170
+ && node.parent().is_none_or(|parent| {
171
+ !field_contains_node(parent, "name", node)
172
+ && !field_contains_node(parent, "property", node)
173
+ })
174
+ {
175
+ return true;
176
+ }
177
+ let mut cursor = node.walk();
178
+ node.named_children(&mut cursor)
179
+ .any(|child| initializer_value_uses_param(child, name, source))
180
+ }
181
+
182
+ fn collect_nodes_in<'tree>(node: Node<'tree>, kinds: &[&str], nodes: &mut Vec<Node<'tree>>) {
183
+ if kinds.contains(&node.kind()) {
184
+ nodes.push(node);
185
+ }
186
+ let mut cursor = node.walk();
187
+ for child in node.named_children(&mut cursor) {
188
+ collect_nodes_in(child, kinds, nodes);
189
+ }
190
+ }
191
+
192
+ fn collect_nodes<'tree>(node: Node<'tree>, kind: &str, nodes: &mut Vec<Node<'tree>>) {
193
+ if node.kind() == kind {
194
+ nodes.push(node);
195
+ }
196
+ let mut cursor = node.walk();
197
+ for child in node.named_children(&mut cursor) {
198
+ collect_nodes(child, kind, nodes);
199
+ }
200
+ }
201
+
202
+ fn identifier_after<'tree>(
203
+ node: Node<'tree>,
204
+ name: &str,
205
+ min_byte: usize,
206
+ source: &str,
207
+ ) -> Option<Node<'tree>> {
208
+ if node.kind() == "identifier"
209
+ && node.start_byte() >= min_byte
210
+ && node.utf8_text(source.as_bytes()).ok() == Some(name)
211
+ {
212
+ return Some(node);
213
+ }
214
+ let mut cursor = node.walk();
215
+ node.named_children(&mut cursor)
216
+ .find_map(|child| identifier_after(child, name, min_byte, source))
217
+ }
218
+
219
+ fn field_text(node: Node<'_>, field_name: &str, source: &str) -> Option<String> {
220
+ node.child_by_field_name(field_name)
221
+ .and_then(|child| child.utf8_text(source.as_bytes()).ok())
222
+ .map(str::to_owned)
223
+ }
224
+
225
+ fn field_contains_node(parent: Node<'_>, field_name: &str, child: Node<'_>) -> bool {
226
+ let mut cursor = parent.walk();
227
+ parent
228
+ .children_by_field_name(field_name, &mut cursor)
229
+ .any(|field| same_node(field, child))
230
+ }
231
+
232
+ fn same_node(left: Node<'_>, right: Node<'_>) -> bool {
233
+ left.kind() == right.kind()
234
+ && left.start_byte() == right.start_byte()
235
+ && left.end_byte() == right.end_byte()
236
+ }
@@ -0,0 +1,430 @@
1
+ use std::path::Path;
2
+
3
+ use super::*;
4
+
5
+ #[test]
6
+ fn flags_unused_stateless_widget_field_formal() -> Result<(), Box<dyn std::error::Error>> {
7
+ let source = r"
8
+ class UserCard extends StatelessWidget {
9
+ const UserCard({super.key, required this.title, required this.subtitle});
10
+ final String title;
11
+ final String subtitle;
12
+ Widget build(BuildContext context) => Text(title);
13
+ }
14
+ ";
15
+ let unused = parse_findings(source)?.unused_params;
16
+
17
+ assert_eq!(unused.len(), 1);
18
+ assert_eq!(unused[0].widget_class, "UserCard");
19
+ assert_eq!(unused[0].param_name, "subtitle");
20
+ assert_eq!(unused[0].location.line, 3);
21
+ Ok(())
22
+ }
23
+
24
+ #[test]
25
+ fn flags_unused_explicit_widget_constructor_params() -> Result<(), Box<dyn std::error::Error>> {
26
+ let source = r"
27
+ class UserCard extends StatelessWidget {
28
+ const UserCard({super.key, required String unused, required String used})
29
+ : unused = unused,
30
+ used = used;
31
+ final String unused;
32
+ final String used;
33
+ Widget build(BuildContext context) => Text(used);
34
+ }
35
+ ";
36
+ let unused = parse_findings(source)?.unused_params;
37
+
38
+ assert_eq!(unused.len(), 1);
39
+ assert_eq!(unused[0].widget_class, "UserCard");
40
+ assert_eq!(unused[0].param_name, "unused");
41
+ assert_eq!(unused[0].location.line, 3);
42
+ Ok(())
43
+ }
44
+
45
+ #[test]
46
+ fn respects_explicit_params_used_through_backing_fields_and_state()
47
+ -> Result<(), Box<dyn std::error::Error>> {
48
+ let source = r"
49
+ class UserCard extends StatelessWidget {
50
+ const UserCard({super.key, required String label}) : _label = label;
51
+ final String _label;
52
+ Widget build(BuildContext context) => Text(_label);
53
+ }
54
+ class CounterCard extends StatefulWidget {
55
+ const CounterCard({super.key, required int count}) : _count = count;
56
+ final int _count;
57
+ State<CounterCard> createState() => _CounterCardState();
58
+ }
59
+ class _CounterCardState extends State<CounterCard> {
60
+ Widget build(BuildContext context) => Text('${widget._count}');
61
+ }
62
+ ";
63
+ let unused = parse_findings(source)?.unused_params;
64
+
65
+ assert!(unused.is_empty(), "{unused:?}");
66
+ Ok(())
67
+ }
68
+
69
+ #[test]
70
+ fn flags_explicit_params_when_backing_field_is_unused() -> Result<(), Box<dyn std::error::Error>> {
71
+ let source = r"
72
+ class UserCard extends StatelessWidget {
73
+ const UserCard({super.key, required String subtitle}) : _subtitle = subtitle;
74
+ final String _subtitle;
75
+ Widget build(BuildContext context) => const SizedBox();
76
+ }
77
+ ";
78
+ let unused = parse_findings(source)?.unused_params;
79
+
80
+ assert_eq!(unused.len(), 1);
81
+ assert_eq!(unused[0].param_name, "subtitle");
82
+ Ok(())
83
+ }
84
+
85
+ #[test]
86
+ fn respects_widget_and_state_usages() -> Result<(), Box<dyn std::error::Error>> {
87
+ let source = r"
88
+ class UsedInBuild extends StatelessWidget {
89
+ const UsedInBuild({super.key, required this.title});
90
+ final String title;
91
+ Widget build(BuildContext context) => Text('$title');
92
+ }
93
+ class UsedViaState extends StatefulWidget {
94
+ const UsedViaState({super.key, required this.count});
95
+ final int count;
96
+ State<UsedViaState> createState() => _UsedViaStateState();
97
+ }
98
+ class _UsedViaStateState extends State<UsedViaState> {
99
+ Widget build(BuildContext context) => Text('${widget.count}');
100
+ }
101
+ ";
102
+ let unused = parse_findings(source)?.unused_params;
103
+
104
+ assert!(unused.is_empty(), "{unused:?}");
105
+ Ok(())
106
+ }
107
+
108
+ #[test]
109
+ fn recognizes_consumer_and_hook_widget_bases() -> Result<(), Box<dyn std::error::Error>> {
110
+ let source = r"
111
+ class A extends ConsumerWidget {
112
+ const A({super.key, required this.value});
113
+ final String value;
114
+ Widget build(BuildContext context, WidgetRef ref) => const SizedBox();
115
+ }
116
+ class B extends HookConsumerWidget {
117
+ const B({super.key, required this.value});
118
+ final String value;
119
+ Widget build(BuildContext context, WidgetRef ref) => Text(value);
120
+ }
121
+ class C extends ConsumerStatefulWidget {
122
+ const C({super.key, required this.value});
123
+ final String value;
124
+ ConsumerState<C> createState() => _CState();
125
+ }
126
+ class _CState extends ConsumerState<C> {
127
+ Widget build(BuildContext context) => Text(oldWidget.value);
128
+ }
129
+ ";
130
+ let unused = parse_findings(source)?.unused_params;
131
+
132
+ assert_eq!(unused.len(), 1);
133
+ assert_eq!(unused[0].widget_class, "A");
134
+ assert_eq!(unused[0].widget_kind, WidgetClassKind::ConsumerWidget);
135
+ Ok(())
136
+ }
137
+
138
+ #[test]
139
+ fn flags_private_widget_classes_but_allows_private_states() -> Result<(), Box<dyn std::error::Error>>
140
+ {
141
+ let source = r"
142
+ class PublicCard extends StatefulWidget {
143
+ State<PublicCard> createState() => _PublicCardState();
144
+ }
145
+ class _PublicCardState extends State<PublicCard> {}
146
+ class PublicConsumer extends ConsumerStatefulWidget {
147
+ ConsumerState<PublicConsumer> createState() => _PublicConsumerState();
148
+ }
149
+ class _PublicConsumerState extends ConsumerState<PublicConsumer> {}
150
+ class _PrivateCard extends StatelessWidget {}
151
+ class _PrivateShell extends ConsumerWidget {}
152
+ class _PrivateHook extends HookConsumerWidget {}
153
+ ";
154
+ let private_widgets = parse_findings(source)?.private_widget_classes;
155
+
156
+ let classes = private_widgets
157
+ .iter()
158
+ .map(|widget| widget.widget_class.as_str())
159
+ .collect::<Vec<_>>();
160
+ assert_eq!(
161
+ classes,
162
+ vec!["_PrivateCard", "_PrivateShell", "_PrivateHook"]
163
+ );
164
+ Ok(())
165
+ }
166
+
167
+ #[test]
168
+ fn reports_all_private_widget_base_kinds() -> Result<(), Box<dyn std::error::Error>> {
169
+ let source = r"
170
+ class _A extends StatelessWidget {}
171
+ class _B extends StatefulWidget {}
172
+ class _C extends ConsumerWidget {}
173
+ class _D extends ConsumerStatefulWidget {}
174
+ class _E extends HookWidget {}
175
+ class _F extends HookConsumerWidget {}
176
+ ";
177
+ let kinds = parse_findings(source)?
178
+ .private_widget_classes
179
+ .into_iter()
180
+ .map(|widget| widget.widget_kind)
181
+ .collect::<Vec<_>>();
182
+
183
+ assert_eq!(
184
+ kinds,
185
+ vec![
186
+ WidgetClassKind::StatelessWidget,
187
+ WidgetClassKind::StatefulWidget,
188
+ WidgetClassKind::ConsumerWidget,
189
+ WidgetClassKind::ConsumerStatefulWidget,
190
+ WidgetClassKind::HookWidget,
191
+ WidgetClassKind::HookConsumerWidget,
192
+ ]
193
+ );
194
+ Ok(())
195
+ }
196
+
197
+ #[test]
198
+ fn ignores_public_widgets_and_non_widget_private_classes() -> Result<(), Box<dyn std::error::Error>>
199
+ {
200
+ let source = r"
201
+ class PublicCard extends StatelessWidget {}
202
+ class _Formatter {}
203
+ ";
204
+ let private_widgets = parse_findings(source)?.private_widget_classes;
205
+
206
+ assert!(private_widgets.is_empty(), "{private_widgets:?}");
207
+ Ok(())
208
+ }
209
+
210
+ #[test]
211
+ fn flags_top_level_widget_helper_functions_in_widget_files()
212
+ -> Result<(), Box<dyn std::error::Error>> {
213
+ let source = "\
214
+ class App extends StatelessWidget {}
215
+ Widget _buildHeader(BuildContext context) => const SizedBox();
216
+ List<Widget> buildItems() => const [];
217
+ ";
218
+ let helpers = parse_findings(source)?.top_level_functions;
219
+
220
+ assert_eq!(helpers.len(), 2);
221
+ assert_eq!(helpers[0].function_name, "_buildHeader");
222
+ assert_eq!(helpers[0].return_type.as_deref(), Some("Widget"));
223
+ assert_eq!(helpers[0].location.line, 2);
224
+ assert_eq!(helpers[1].function_name, "buildItems");
225
+ Ok(())
226
+ }
227
+
228
+ #[test]
229
+ fn flags_top_level_helpers_in_screen_files() -> Result<(), Box<dyn std::error::Error>> {
230
+ let source = "Widget header(BuildContext context) => const SizedBox();\n";
231
+ let helpers = parse_findings_at("lib/screens/home_screen.dart", source)?.top_level_functions;
232
+
233
+ assert_eq!(helpers.len(), 1);
234
+ assert_eq!(helpers[0].function_name, "header");
235
+ Ok(())
236
+ }
237
+
238
+ #[test]
239
+ fn does_not_flag_methods_local_functions_or_namespaces() -> Result<(), Box<dyn std::error::Error>> {
240
+ let source = r"
241
+ class App extends StatefulWidget {}
242
+ class _AppState extends State<App> {
243
+ Widget _buildHeader(BuildContext context) => const SizedBox();
244
+ }
245
+ abstract final class AppParts {
246
+ static Widget header(BuildContext context) => const SizedBox();
247
+ }
248
+ void container() {
249
+ Widget _buildLocal(BuildContext context) => const SizedBox();
250
+ }
251
+ ";
252
+ let helpers = parse_findings(source)?.top_level_functions;
253
+
254
+ assert!(helpers.is_empty(), "{helpers:?}");
255
+ Ok(())
256
+ }
257
+
258
+ #[test]
259
+ fn does_not_flag_main_providers_or_widget_named_configs() -> Result<(), Box<dyn std::error::Error>>
260
+ {
261
+ let source = r"
262
+ class App extends StatelessWidget {}
263
+ void main() {}
264
+ int count(Ref ref) => 1;
265
+ String title() => 'ok';
266
+ MyWidgetConfig _buildConfig() => MyWidgetConfig();
267
+ WidgetBuilder makeBuilder() => (context) => const SizedBox();
268
+ ";
269
+ let helpers = parse_findings(source)?.top_level_functions;
270
+
271
+ assert!(helpers.is_empty(), "{helpers:?}");
272
+ Ok(())
273
+ }
274
+
275
+ #[test]
276
+ fn flags_widget_awaits_without_context_mounted_guard() -> Result<(), Box<dyn std::error::Error>> {
277
+ let source = r"
278
+ class SaveButton extends StatefulWidget {
279
+ State<SaveButton> createState() => _SaveButtonState();
280
+ }
281
+
282
+ class _SaveButtonState extends State<SaveButton> {
283
+ Future<void> save() async {
284
+ await doWork();
285
+ Navigator.of(context).pop();
286
+ }
287
+
288
+ Future<void> guarded() async {
289
+ await doWork();
290
+ if (!context.mounted) return;
291
+ Navigator.of(context).pop();
292
+ }
293
+
294
+ Future<void> bareMountedIsNotEnough() async {
295
+ await doWork();
296
+ if (!mounted) return;
297
+ Navigator.of(context).pop();
298
+ }
299
+ }
300
+ ";
301
+ let findings = parse_findings(source)?.missing_context_mounted_after_await;
302
+
303
+ assert_eq!(findings.len(), 2);
304
+ assert_eq!(findings[0].owner, "_SaveButtonState.save");
305
+ assert_eq!(findings[0].location.line, 8);
306
+ assert_eq!(findings[1].owner, "_SaveButtonState.bareMountedIsNotEnough");
307
+ Ok(())
308
+ }
309
+
310
+ #[test]
311
+ fn flags_nested_widget_awaits_per_block() -> Result<(), Box<dyn std::error::Error>> {
312
+ let source = r"
313
+ class SaveButton extends StatelessWidget {
314
+ Future<void> save(BuildContext context, bool active) async {
315
+ if (active) {
316
+ await doWork();
317
+ if (!context.mounted) return;
318
+ Navigator.of(context).pop();
319
+ }
320
+ await doWork();
321
+ Navigator.of(context).pop();
322
+ }
323
+ }
324
+ ";
325
+ let findings = parse_findings(source)?.missing_context_mounted_after_await;
326
+
327
+ assert_eq!(findings.len(), 1);
328
+ assert_eq!(findings[0].owner, "SaveButton.save");
329
+ assert_eq!(findings[0].location.line, 9);
330
+ Ok(())
331
+ }
332
+
333
+ #[test]
334
+ fn does_not_flag_widget_awaits_without_lifecycle_use() -> Result<(), Box<dyn std::error::Error>> {
335
+ let source = r"
336
+ class SaveButton extends StatefulWidget {
337
+ State<SaveButton> createState() => _SaveButtonState();
338
+ }
339
+
340
+ class _SaveButtonState extends State<SaveButton> {
341
+ Future<void> refresh() async {
342
+ await doWork();
343
+ await logTap();
344
+ }
345
+ }
346
+ ";
347
+ let findings = parse_findings(source)?.missing_context_mounted_after_await;
348
+
349
+ assert!(findings.is_empty(), "{findings:?}");
350
+ Ok(())
351
+ }
352
+
353
+ #[test]
354
+ fn flags_widget_async_closure_awaits_and_accepts_return_guards()
355
+ -> Result<(), Box<dyn std::error::Error>> {
356
+ let source = r"
357
+ class SaveButton extends StatelessWidget {
358
+ Widget build(BuildContext context) {
359
+ return ElevatedButton(
360
+ onPressed: () async {
361
+ await doWork();
362
+ Navigator.of(context).pop();
363
+ },
364
+ onLongPress: () async {
365
+ await logTap();
366
+ },
367
+ child: const Text('Save'),
368
+ );
369
+ }
370
+
371
+ Future<bool> guardedFalse(BuildContext context) async {
372
+ await doWork();
373
+ if (!context.mounted) return false;
374
+ return true;
375
+ }
376
+
377
+ Future<String?> guardedNull(BuildContext context) async {
378
+ await doWork();
379
+ if (!context.mounted) return null;
380
+ return 'ok';
381
+ }
382
+
383
+ Future<void> guardedBraced(BuildContext context) async {
384
+ await doWork();
385
+ if (!context.mounted) {
386
+ return;
387
+ }
388
+ Navigator.of(context).pop();
389
+ }
390
+ }
391
+ ";
392
+ let findings = parse_findings(source)?.missing_context_mounted_after_await;
393
+
394
+ assert_eq!(findings.len(), 1);
395
+ assert_eq!(findings[0].owner, "SaveButton.build");
396
+ assert_eq!(findings[0].location.line, 6);
397
+ Ok(())
398
+ }
399
+
400
+ #[test]
401
+ fn flags_expression_bodied_lifecycle_awaits() -> Result<(), Box<dyn std::error::Error>> {
402
+ let source = r"
403
+ class SaveButton extends StatelessWidget {
404
+ Future<void> save(BuildContext context) async =>
405
+ Navigator.of(context).pop(await doWork());
406
+ }
407
+ ";
408
+ let findings = parse_findings(source)?;
409
+
410
+ assert_eq!(findings.missing_context_mounted_after_await.len(), 1);
411
+ assert_eq!(
412
+ findings.missing_context_mounted_after_await[0].owner,
413
+ "SaveButton.save"
414
+ );
415
+ Ok(())
416
+ }
417
+
418
+ fn parse_findings(source: &str) -> Result<FileWidgetFindings, WidgetAnalysisError> {
419
+ parse_findings_at("lib/widgets.dart", source)
420
+ }
421
+
422
+ fn parse_findings_at(path: &str, source: &str) -> Result<FileWidgetFindings, WidgetAnalysisError> {
423
+ let path = Path::new(path);
424
+ let parsed = parse_tree(path, source)?;
425
+ Ok(findings_in_source(
426
+ path,
427
+ parsed.tree().root_node(),
428
+ parsed.source(),
429
+ ))
430
+ }