dart-decimate 0.0.20 → 0.0.22

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.
@@ -0,0 +1,515 @@
1
+ use std::fs;
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use tree_sitter::Node;
5
+
6
+ use crate::{DartFile, Location, generated::is_generated_dart_path, scan::ScannedProject};
7
+
8
+ use super::navigation::{
9
+ go_router_symbol_import, has_go_router_import, local_type_declaration_named,
10
+ navigation_receiver_is_imported_go_router_api,
11
+ };
12
+ use super::{
13
+ argument_list, direct_named_child, field_text, find_first_named_descendant,
14
+ strip_method_type_arguments, strip_whitespace, visit_named,
15
+ };
16
+
17
+ #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
18
+ pub(in crate::output) enum MixedGoRouterUseKind {
19
+ RouteDefinition,
20
+ Navigation { method: String },
21
+ RedirectDestination,
22
+ }
23
+
24
+ #[derive(Debug, Clone, PartialEq, Eq)]
25
+ pub(in crate::output) struct MixedGoRouterUse {
26
+ pub path: PathBuf,
27
+ pub location: Location,
28
+ pub kind: MixedGoRouterUseKind,
29
+ }
30
+
31
+ pub(in crate::output) fn mixed_go_router_uses(project: &ScannedProject) -> Vec<MixedGoRouterUse> {
32
+ if !project.files.iter().any(is_typed_route_adoption) {
33
+ return Vec::new();
34
+ }
35
+
36
+ let mut uses = project
37
+ .files
38
+ .iter()
39
+ .filter(|file| is_production_path(&file.path))
40
+ .flat_map(mixed_go_router_uses_in_file)
41
+ .collect::<Vec<_>>();
42
+ uses.sort_by(|left, right| {
43
+ (
44
+ &left.path,
45
+ left.location.line,
46
+ left.location.column,
47
+ &left.kind,
48
+ )
49
+ .cmp(&(
50
+ &right.path,
51
+ right.location.line,
52
+ right.location.column,
53
+ &right.kind,
54
+ ))
55
+ });
56
+ uses
57
+ }
58
+
59
+ fn is_typed_route_adoption(file: &DartFile) -> bool {
60
+ if !is_production_path(&file.path) || !file_imports_go_router(file) {
61
+ return false;
62
+ }
63
+ let Ok(source) = fs::read_to_string(&file.path) else {
64
+ return false;
65
+ };
66
+ let Ok(parsed) = crate::dart_parser::parse_dart_source_lossy(&file.path, &source) else {
67
+ return false;
68
+ };
69
+ let root = parsed.tree().root_node();
70
+ let source = parsed.source();
71
+ let mut adopted = false;
72
+ visit_named(root, &mut |node| {
73
+ if adopted || node.kind() != "class_declaration" {
74
+ return;
75
+ }
76
+ adopted = typed_route_class_uses_imported_api(root, node, source);
77
+ });
78
+ adopted
79
+ }
80
+
81
+ fn typed_route_class_uses_imported_api(root: Node<'_>, class: Node<'_>, source: &str) -> bool {
82
+ let mut cursor = class.walk();
83
+ let imported_annotation = class
84
+ .named_children(&mut cursor)
85
+ .filter(|child| child.kind() == "annotation")
86
+ .any(|annotation| imported_typed_route_annotation(root, annotation, source));
87
+ imported_annotation
88
+ && class
89
+ .child_by_field_name("superclass")
90
+ .and_then(|superclass| superclass.utf8_text(source.as_bytes()).ok())
91
+ .is_some_and(|superclass| imported_route_data_superclass(root, superclass, source))
92
+ }
93
+
94
+ fn imported_typed_route_annotation(root: Node<'_>, annotation: Node<'_>, source: &str) -> bool {
95
+ let compact = annotation
96
+ .utf8_text(source.as_bytes())
97
+ .map(strip_whitespace)
98
+ .unwrap_or_default();
99
+ let reference = compact
100
+ .strip_prefix('@')
101
+ .unwrap_or(&compact)
102
+ .split('<')
103
+ .next()
104
+ .unwrap_or_default();
105
+ [
106
+ "TypedGoRoute",
107
+ "TypedRelativeGoRoute",
108
+ "TypedShellRoute",
109
+ "TypedStatefulShellRoute",
110
+ "TypedStatefulShellBranch",
111
+ ]
112
+ .iter()
113
+ .any(|type_name| imported_go_router_type_reference(root, reference, type_name, source))
114
+ }
115
+
116
+ fn imported_route_data_superclass(root: Node<'_>, superclass: &str, source: &str) -> bool {
117
+ let compact = strip_whitespace(superclass);
118
+ let reference = compact.strip_prefix("extends").unwrap_or(&compact);
119
+ [
120
+ "GoRouteData",
121
+ "RelativeGoRouteData",
122
+ "ShellRouteData",
123
+ "StatefulShellRouteData",
124
+ "StatefulShellBranchData",
125
+ ]
126
+ .iter()
127
+ .any(|type_name| imported_go_router_type_reference(root, reference, type_name, source))
128
+ }
129
+
130
+ fn mixed_go_router_uses_in_file(file: &DartFile) -> Vec<MixedGoRouterUse> {
131
+ if !file_imports_go_router(file) {
132
+ return Vec::new();
133
+ }
134
+ let Ok(source) = fs::read_to_string(&file.path) else {
135
+ return Vec::new();
136
+ };
137
+ let Ok(parsed) = crate::dart_parser::parse_dart_source_lossy(&file.path, &source) else {
138
+ return Vec::new();
139
+ };
140
+ let root = parsed.tree().root_node();
141
+ let source = parsed.source();
142
+ if !has_go_router_import(root, source) {
143
+ return Vec::new();
144
+ }
145
+
146
+ let mut uses = Vec::new();
147
+ collect_imported_raw_go_route_definitions(root, source, &file.path, &mut uses);
148
+ collect_raw_go_router_navigation(root, source, &file.path, &mut uses);
149
+ collect_raw_redirect_destinations(root, source, file, &mut uses);
150
+ uses
151
+ }
152
+
153
+ fn collect_imported_raw_go_route_definitions(
154
+ root: Node<'_>,
155
+ source: &str,
156
+ path: &Path,
157
+ uses: &mut Vec<MixedGoRouterUse>,
158
+ ) {
159
+ visit_named(root, &mut |node| {
160
+ if !matches!(
161
+ node.kind(),
162
+ "call_expression"
163
+ | "constructor_invocation"
164
+ | "const_object_expression"
165
+ | "new_expression"
166
+ ) {
167
+ return;
168
+ }
169
+ let Some(arguments) = argument_list(node) else {
170
+ return;
171
+ };
172
+ if !has_named_argument(arguments, "path", source) {
173
+ return;
174
+ }
175
+ let Some(prefix) = source.get(node.start_byte()..arguments.start_byte()) else {
176
+ return;
177
+ };
178
+ if imported_go_router_type_reference(root, prefix, "GoRoute", source) {
179
+ uses.push(MixedGoRouterUse {
180
+ path: path.to_path_buf(),
181
+ location: node.start_position().into(),
182
+ kind: MixedGoRouterUseKind::RouteDefinition,
183
+ });
184
+ }
185
+ });
186
+ }
187
+
188
+ fn collect_raw_go_router_navigation(
189
+ root: Node<'_>,
190
+ source: &str,
191
+ path: &Path,
192
+ uses: &mut Vec<MixedGoRouterUse>,
193
+ ) {
194
+ visit_named(root, &mut |node| {
195
+ if !matches!(
196
+ node.kind(),
197
+ "call_expression" | "function_expression_invocation"
198
+ ) {
199
+ return;
200
+ }
201
+ let Some(arguments) = argument_list(node) else {
202
+ return;
203
+ };
204
+ let Some(prefix) = source.get(node.start_byte()..arguments.start_byte()) else {
205
+ return;
206
+ };
207
+ let Some(method) = raw_go_router_navigation_name(prefix) else {
208
+ return;
209
+ };
210
+ let Some(receiver) = navigation_receiver(prefix, &method) else {
211
+ return;
212
+ };
213
+ if navigation_receiver_is_imported_go_router_api(root, node, &receiver, source) {
214
+ uses.push(MixedGoRouterUse {
215
+ path: path.to_path_buf(),
216
+ location: node.start_position().into(),
217
+ kind: MixedGoRouterUseKind::Navigation { method },
218
+ });
219
+ }
220
+ });
221
+ }
222
+
223
+ fn collect_raw_redirect_destinations(
224
+ root: Node<'_>,
225
+ source: &str,
226
+ file: &DartFile,
227
+ uses: &mut Vec<MixedGoRouterUse>,
228
+ ) {
229
+ visit_named(root, &mut |node| {
230
+ if node.kind() == "class_declaration"
231
+ && typed_route_class_uses_imported_api(root, node, source)
232
+ {
233
+ collect_typed_route_redirect_methods(node, source, &file.path, uses);
234
+ }
235
+ if is_imported_go_router_constructor(root, node, source) {
236
+ collect_go_router_redirect_argument(node, source, &file.path, uses);
237
+ }
238
+ });
239
+ }
240
+
241
+ fn collect_typed_route_redirect_methods(
242
+ class: Node<'_>,
243
+ source: &str,
244
+ path: &Path,
245
+ uses: &mut Vec<MixedGoRouterUse>,
246
+ ) {
247
+ let Some(body) = class.child_by_field_name("body") else {
248
+ return;
249
+ };
250
+ let mut cursor = body.walk();
251
+ for member in body.named_children(&mut cursor) {
252
+ let Some(method) = find_first_named_descendant(member, "method_declaration") else {
253
+ continue;
254
+ };
255
+ if method_name(method, source).as_deref() != Some("redirect") {
256
+ continue;
257
+ }
258
+ if method
259
+ .child_by_field_name("body")
260
+ .is_some_and(|body| redirect_body_has_raw_literal(body, source))
261
+ {
262
+ uses.push(MixedGoRouterUse {
263
+ path: path.to_path_buf(),
264
+ location: method.start_position().into(),
265
+ kind: MixedGoRouterUseKind::RedirectDestination,
266
+ });
267
+ }
268
+ }
269
+ }
270
+
271
+ fn collect_go_router_redirect_argument(
272
+ constructor: Node<'_>,
273
+ source: &str,
274
+ path: &Path,
275
+ uses: &mut Vec<MixedGoRouterUse>,
276
+ ) {
277
+ let Some(arguments) = argument_list(constructor) else {
278
+ return;
279
+ };
280
+ let mut cursor = arguments.walk();
281
+ for argument in arguments.named_children(&mut cursor) {
282
+ if argument.kind() != "named_argument"
283
+ || named_argument_label(argument, source).as_deref() != Some("redirect")
284
+ {
285
+ continue;
286
+ }
287
+ let Some(value) = named_argument_value(argument) else {
288
+ continue;
289
+ };
290
+ if redirect_callback_has_raw_literal(value, source) {
291
+ uses.push(MixedGoRouterUse {
292
+ path: path.to_path_buf(),
293
+ location: argument.start_position().into(),
294
+ kind: MixedGoRouterUseKind::RedirectDestination,
295
+ });
296
+ }
297
+ }
298
+ }
299
+
300
+ fn redirect_callback_has_raw_literal(value: Node<'_>, source: &str) -> bool {
301
+ let body = if value.kind() == "function_expression" {
302
+ value.child_by_field_name("body")
303
+ } else {
304
+ find_first_named_descendant(value, "function_expression_body")
305
+ };
306
+ let Some(body) = body else {
307
+ return false;
308
+ };
309
+ redirect_body_has_raw_literal(body, source)
310
+ }
311
+
312
+ fn redirect_body_has_raw_literal(body: Node<'_>, source: &str) -> bool {
313
+ let Some(expression_or_block) = first_non_label_named_child(body) else {
314
+ return false;
315
+ };
316
+ if expression_or_block.kind() != "block" {
317
+ return raw_redirect_expression(expression_or_block, source);
318
+ }
319
+
320
+ let mut found = false;
321
+ visit_returns_without_nested_callables(expression_or_block, &mut |return_statement| {
322
+ if first_non_label_named_child(return_statement)
323
+ .is_some_and(|expression| raw_redirect_expression(expression, source))
324
+ {
325
+ found = true;
326
+ }
327
+ });
328
+ found
329
+ }
330
+
331
+ fn raw_redirect_expression(node: Node<'_>, source: &str) -> bool {
332
+ let text = node.utf8_text(source.as_bytes()).unwrap_or_default().trim();
333
+ if is_dart_string_literal(text) {
334
+ return true;
335
+ }
336
+ if node.kind() == "conditional_expression" {
337
+ return ["consequence", "alternative"].into_iter().any(|field| {
338
+ node.child_by_field_name(field)
339
+ .is_some_and(|branch| raw_redirect_expression(branch, source))
340
+ });
341
+ }
342
+ if node.kind() == "if_null_expression" {
343
+ let mut cursor = node.walk();
344
+ return node
345
+ .named_children(&mut cursor)
346
+ .any(|branch| raw_redirect_expression(branch, source));
347
+ }
348
+ matches!(
349
+ node.kind(),
350
+ "parenthesized_expression" | "function_expression_body"
351
+ ) && first_non_label_named_child(node)
352
+ .is_some_and(|expression| raw_redirect_expression(expression, source))
353
+ }
354
+
355
+ fn is_dart_string_literal(text: &str) -> bool {
356
+ let text = text.trim_start_matches("const").trim();
357
+ let text = text.strip_prefix('r').unwrap_or(text);
358
+ text.starts_with('\'') || text.starts_with('"')
359
+ }
360
+
361
+ fn visit_returns_without_nested_callables(node: Node<'_>, visitor: &mut impl FnMut(Node<'_>)) {
362
+ if node.kind() == "return_statement" {
363
+ visitor(node);
364
+ return;
365
+ }
366
+ if matches!(
367
+ node.kind(),
368
+ "function_expression" | "method_declaration" | "function_declaration"
369
+ ) {
370
+ return;
371
+ }
372
+ let mut cursor = node.walk();
373
+ for child in node.named_children(&mut cursor) {
374
+ visit_returns_without_nested_callables(child, visitor);
375
+ }
376
+ }
377
+
378
+ fn is_imported_go_router_constructor(root: Node<'_>, node: Node<'_>, source: &str) -> bool {
379
+ if !matches!(
380
+ node.kind(),
381
+ "call_expression" | "constructor_invocation" | "const_object_expression" | "new_expression"
382
+ ) {
383
+ return false;
384
+ }
385
+ let Some(arguments) = argument_list(node) else {
386
+ return false;
387
+ };
388
+ let Some(prefix) = source.get(node.start_byte()..arguments.start_byte()) else {
389
+ return false;
390
+ };
391
+ imported_go_router_type_reference(root, prefix, "GoRouter", source)
392
+ }
393
+
394
+ fn imported_go_router_type_reference(
395
+ root: Node<'_>,
396
+ prefix: &str,
397
+ type_name: &str,
398
+ source: &str,
399
+ ) -> bool {
400
+ let compact = strip_whitespace(prefix);
401
+ let reference = compact
402
+ .strip_prefix("const")
403
+ .or_else(|| compact.strip_prefix("new"))
404
+ .unwrap_or(&compact)
405
+ .split('<')
406
+ .next()
407
+ .unwrap_or_default();
408
+ if reference == type_name {
409
+ return go_router_symbol_import(root, None, type_name, source)
410
+ && !local_type_declaration_named(root, type_name, source);
411
+ }
412
+ let Some(import_prefix) = reference.strip_suffix(&format!(".{type_name}")) else {
413
+ return false;
414
+ };
415
+ is_identifier(import_prefix)
416
+ && go_router_symbol_import(root, Some(import_prefix), type_name, source)
417
+ }
418
+
419
+ fn has_named_argument(arguments: Node<'_>, name: &str, source: &str) -> bool {
420
+ let mut cursor = arguments.walk();
421
+ arguments.named_children(&mut cursor).any(|argument| {
422
+ argument.kind() == "named_argument"
423
+ && named_argument_label(argument, source).as_deref() == Some(name)
424
+ })
425
+ }
426
+
427
+ fn named_argument_label(node: Node<'_>, source: &str) -> Option<String> {
428
+ direct_named_child(node, "label")
429
+ .and_then(|label| label.utf8_text(source.as_bytes()).ok())
430
+ .map(str::trim)
431
+ .and_then(|label| label.strip_suffix(':'))
432
+ .map(str::to_owned)
433
+ }
434
+
435
+ fn named_argument_value(node: Node<'_>) -> Option<Node<'_>> {
436
+ let mut cursor = node.walk();
437
+ node.named_children(&mut cursor)
438
+ .find(|child| child.kind() != "label")
439
+ }
440
+
441
+ fn first_non_label_named_child(node: Node<'_>) -> Option<Node<'_>> {
442
+ let mut cursor = node.walk();
443
+ node.named_children(&mut cursor)
444
+ .find(|child| child.kind() != "label")
445
+ }
446
+
447
+ fn method_name(node: Node<'_>, source: &str) -> Option<String> {
448
+ find_first_named_descendant(node, "function_signature")
449
+ .and_then(|signature| field_text(signature, "name", source))
450
+ }
451
+
452
+ fn raw_go_router_navigation_name(prefix: &str) -> Option<String> {
453
+ let compact = strip_whitespace(prefix);
454
+ let name = compact.rsplit('.').next().unwrap_or(compact.as_str());
455
+ let name = strip_method_type_arguments(name);
456
+ matches!(
457
+ name,
458
+ "go" | "push"
459
+ | "pushReplacement"
460
+ | "replace"
461
+ | "goNamed"
462
+ | "pushNamed"
463
+ | "pushReplacementNamed"
464
+ | "replaceNamed"
465
+ | "namedLocation"
466
+ )
467
+ .then(|| name.to_owned())
468
+ }
469
+
470
+ fn navigation_receiver(prefix: &str, method: &str) -> Option<String> {
471
+ let prefix = prefix.trim();
472
+ let without_keyword = super::strip_constructor_keyword_prefix(prefix).unwrap_or(prefix);
473
+ let compact = strip_whitespace(without_keyword);
474
+ let suffix = format!(".{method}");
475
+ compact
476
+ .strip_suffix(&suffix)
477
+ .or_else(|| {
478
+ compact
479
+ .strip_suffix('>')
480
+ .and_then(|without_end| without_end.rfind('<').map(|start| &compact[..start]))
481
+ .and_then(|without_type_arguments| without_type_arguments.strip_suffix(&suffix))
482
+ })
483
+ .map(str::to_owned)
484
+ }
485
+
486
+ fn is_identifier(text: &str) -> bool {
487
+ let mut chars = text.chars();
488
+ chars
489
+ .next()
490
+ .is_some_and(|first| first == '_' || first == '$' || first.is_ascii_alphabetic())
491
+ && chars.all(|character| {
492
+ character == '_' || character == '$' || character.is_ascii_alphanumeric()
493
+ })
494
+ }
495
+
496
+ fn is_production_path(path: &Path) -> bool {
497
+ !is_generated_dart_path(path) && !is_test_dart_path(path)
498
+ }
499
+
500
+ fn file_imports_go_router(file: &DartFile) -> bool {
501
+ file.imports
502
+ .iter()
503
+ .any(|import| import.uri == "package:go_router/go_router.dart")
504
+ }
505
+
506
+ fn is_test_dart_path(path: &Path) -> bool {
507
+ path.file_name()
508
+ .and_then(|name| name.to_str())
509
+ .is_some_and(|name| name.ends_with("_test.dart"))
510
+ || path.components().any(|component| {
511
+ component.as_os_str().to_str().is_some_and(|segment| {
512
+ matches!(segment, "test" | "integration_test" | "test_driver")
513
+ })
514
+ })
515
+ }