dart-decimate 0.0.12 → 0.0.14

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 (41) hide show
  1. package/Cargo.lock +75 -1
  2. package/Cargo.toml +2 -1
  3. package/README.md +31 -27
  4. package/npm/scripts/postinstall.js +33 -12
  5. package/npm/scripts/test-npx-local.js +7 -2
  6. package/npm/scripts/test-npx-mcp-local.js +3 -1
  7. package/npm/scripts/test-npx-prebuilt.js +33 -13
  8. package/npm/scripts/test-postinstall-prebuilt.js +33 -13
  9. package/package.json +11 -1
  10. package/src/changed_scope.rs +4 -7
  11. package/src/cli/audit_run.rs +1 -3
  12. package/src/cli/decision_surface_run.rs +1 -3
  13. package/src/cli/entry_points.rs +75 -13
  14. package/src/dart_parser.rs +1 -3
  15. package/src/dependencies/codegen.rs +26 -0
  16. package/src/dependencies.rs +1 -0
  17. package/src/dependency_scripts.rs +42 -8
  18. package/src/extract.rs +6 -0
  19. package/src/git_command.rs +58 -0
  20. package/src/graph.rs +5 -0
  21. package/src/lib.rs +1 -0
  22. package/src/manifest.rs +1 -1
  23. package/src/output/graph_findings.rs +117 -43
  24. package/src/output/route_cycle/classification.rs +862 -0
  25. package/src/output/route_cycle/navigation.rs +6 -1
  26. package/src/output/route_cycle/registry_api.rs +268 -0
  27. package/src/output/route_cycle.rs +28 -162
  28. package/src/output/types.rs +3 -3
  29. package/src/output.rs +2 -2
  30. package/src/scan/tests.rs +133 -0
  31. package/src/scan.rs +122 -47
  32. package/src/security/detect.rs +1275 -10
  33. package/src/security_gate.rs +3 -5
  34. package/src/trace.rs +22 -13
  35. package/src/widgets/inheritance.rs +250 -0
  36. package/src/widgets/params.rs +81 -1
  37. package/src/widgets/patterns.rs +32 -25
  38. package/src/widgets/reads.rs +61 -11
  39. package/src/widgets/resolution.rs +281 -0
  40. package/src/widgets/unrendered.rs +111 -47
  41. package/src/widgets.rs +69 -11
@@ -0,0 +1,862 @@
1
+ use std::collections::{BTreeMap, BTreeSet, VecDeque};
2
+ use std::fs;
3
+ use std::path::{Path, PathBuf};
4
+
5
+ use petgraph::algo::tarjan_scc;
6
+ use petgraph::graph::{DiGraph, NodeIndex};
7
+ use petgraph::visit::EdgeRef;
8
+ use tree_sitter::Node;
9
+
10
+ use super::{
11
+ argument_list, helper_has_typed_route_navigation_call,
12
+ navigation::term_identifier_shadowed_at,
13
+ registry_api::{VisibleNonRouteRegistryApi, visible_non_route_registry_api},
14
+ route_extension_navigation_call, route_location_argument, route_location_expression_member,
15
+ typed_route_navigation_call, visit_named,
16
+ };
17
+ use crate::{
18
+ DartFile, DependencyCycle, DependencyKind, Location, ResolvedDependency, scan::ScannedProject,
19
+ };
20
+
21
+ #[derive(Debug, Clone, PartialEq, Eq)]
22
+ pub(in crate::output) struct TypedGoRouterCycle {
23
+ pub residual_cycles: Vec<ResidualCycle>,
24
+ pub typed_route_files: Vec<PathBuf>,
25
+ }
26
+
27
+ #[derive(Debug, Clone, PartialEq, Eq)]
28
+ pub(in crate::output) struct ResidualCycle {
29
+ pub files: Vec<PathBuf>,
30
+ pub edge: Option<ResolvedDependency>,
31
+ }
32
+
33
+ pub(in crate::output) fn decompose_typed_go_router_cycle(
34
+ project: &ScannedProject,
35
+ cycle: &DependencyCycle,
36
+ ) -> Option<TypedGoRouterCycle> {
37
+ let cycle_files = cycle.files.iter().cloned().collect::<BTreeSet<_>>();
38
+ let route_files = project
39
+ .files
40
+ .iter()
41
+ .filter(|file| cycle_files.contains(&file.path) && is_typed_go_router_registry(file))
42
+ .map(|file| file.path.clone())
43
+ .collect::<BTreeSet<_>>();
44
+ if route_files.is_empty() {
45
+ return None;
46
+ }
47
+
48
+ let files_by_path = project
49
+ .files
50
+ .iter()
51
+ .map(|file| (file.path.clone(), file))
52
+ .collect::<BTreeMap<_, _>>();
53
+ let dependencies = project.graph.dependencies();
54
+ let internal_dependencies = dependencies
55
+ .iter()
56
+ .filter(|dependency| {
57
+ cycle_files.contains(&dependency.from_path)
58
+ && cycle_files.contains(&dependency.to_path)
59
+ && dependency.from_path != dependency.to_path
60
+ })
61
+ .cloned()
62
+ .collect::<Vec<_>>();
63
+ let typed_back_edges = internal_dependencies
64
+ .iter()
65
+ .filter(|dependency| {
66
+ is_typed_go_router_navigation_back_edge(
67
+ dependency,
68
+ &route_files,
69
+ &files_by_path,
70
+ &dependencies,
71
+ )
72
+ })
73
+ .cloned()
74
+ .collect::<Vec<_>>();
75
+ if typed_back_edges.is_empty() {
76
+ return None;
77
+ }
78
+
79
+ let residual_dependencies = internal_dependencies
80
+ .iter()
81
+ .filter(|dependency| {
82
+ !typed_back_edges
83
+ .iter()
84
+ .any(|typed| same_dependency(typed, dependency))
85
+ })
86
+ .cloned()
87
+ .collect::<Vec<_>>();
88
+ let residual_reachability = ResidualReachability::new(&residual_dependencies);
89
+ let typed_route_files = typed_route_cycle_files(
90
+ &typed_back_edges,
91
+ &residual_dependencies,
92
+ &residual_reachability,
93
+ );
94
+ if typed_route_files.is_empty() {
95
+ return None;
96
+ }
97
+
98
+ let mut residual_cycles = residual_dependency_cycles(&cycle_files, &residual_dependencies);
99
+ append_typed_route_path_edge_errors(
100
+ &route_files,
101
+ &typed_back_edges,
102
+ &residual_dependencies,
103
+ &residual_reachability,
104
+ &mut residual_cycles,
105
+ );
106
+ append_route_registry_edge_errors(&route_files, &residual_dependencies, &mut residual_cycles);
107
+ residual_cycles.sort_by(|left, right| left.files.cmp(&right.files));
108
+
109
+ Some(TypedGoRouterCycle {
110
+ residual_cycles,
111
+ typed_route_files,
112
+ })
113
+ }
114
+
115
+ fn is_typed_go_router_navigation_back_edge(
116
+ dependency: &ResolvedDependency,
117
+ route_files: &BTreeSet<PathBuf>,
118
+ files_by_path: &BTreeMap<PathBuf, &DartFile>,
119
+ dependencies: &[ResolvedDependency],
120
+ ) -> bool {
121
+ if dependency.kind != DependencyKind::Import
122
+ || !route_files.contains(&dependency.to_path)
123
+ || route_files.contains(&dependency.from_path)
124
+ {
125
+ return false;
126
+ }
127
+ let Some(route_file) = files_by_path.get(&dependency.to_path) else {
128
+ return false;
129
+ };
130
+ let Some(helper_file) = files_by_path.get(&dependency.from_path) else {
131
+ return false;
132
+ };
133
+ is_typed_go_router_navigation_helper(
134
+ dependency,
135
+ helper_file,
136
+ route_file,
137
+ files_by_path,
138
+ dependencies,
139
+ )
140
+ }
141
+
142
+ fn is_typed_go_router_navigation_helper(
143
+ dependency: &ResolvedDependency,
144
+ helper_file: &DartFile,
145
+ route_file: &DartFile,
146
+ files_by_path: &BTreeMap<PathBuf, &DartFile>,
147
+ dependencies: &[ResolvedDependency],
148
+ ) -> bool {
149
+ let route_classes = route_file
150
+ .routes
151
+ .iter()
152
+ .map(|route| route.route_class.clone())
153
+ .collect::<BTreeSet<_>>();
154
+ if route_classes.is_empty() {
155
+ return false;
156
+ }
157
+ let Ok(source) = fs::read_to_string(&helper_file.path) else {
158
+ return false;
159
+ };
160
+ let Ok(parsed) = crate::dart_parser::parse_dart_source_lossy(&helper_file.path, &source) else {
161
+ return false;
162
+ };
163
+ let root = parsed.tree().root_node();
164
+ let source = parsed.source();
165
+ let non_route_api =
166
+ visible_non_route_registry_api(dependency, route_file, files_by_path, dependencies);
167
+ if !non_route_api.is_empty()
168
+ && helper_references_imported_api(
169
+ dependency,
170
+ helper_file,
171
+ root,
172
+ source,
173
+ &non_route_api,
174
+ &route_classes,
175
+ )
176
+ {
177
+ return false;
178
+ }
179
+ helper_has_typed_route_navigation_call(root, source, &route_classes)
180
+ }
181
+
182
+ fn helper_references_imported_api(
183
+ dependency: &ResolvedDependency,
184
+ helper_file: &DartFile,
185
+ root: Node<'_>,
186
+ source: &str,
187
+ imported_api: &VisibleNonRouteRegistryApi,
188
+ route_classes: &BTreeSet<String>,
189
+ ) -> bool {
190
+ let mut found = false;
191
+ let mut syntactic_references = BTreeSet::new();
192
+ visit_named(root, &mut |node| {
193
+ if found {
194
+ return;
195
+ }
196
+ let Some(name) = reference_identifier_text(node, source) else {
197
+ return;
198
+ };
199
+ syntactic_references.insert((
200
+ name.to_owned(),
201
+ node.start_position().row + 1,
202
+ node.start_position().column,
203
+ ));
204
+ if imported_api.top_level_names.contains(name)
205
+ && top_level_reference_uses_imported_api(
206
+ dependency,
207
+ helper_file,
208
+ root,
209
+ node,
210
+ source,
211
+ name,
212
+ )
213
+ {
214
+ found = true;
215
+ return;
216
+ }
217
+ if imported_api.member_names.contains(name)
218
+ && member_reference_uses_imported_api(dependency, root, node, source)
219
+ && !typed_route_navigation_member_reference(root, node, source, route_classes)
220
+ {
221
+ found = true;
222
+ }
223
+ });
224
+ found
225
+ || (dependency.visibility.prefix.is_none()
226
+ && helper_file.references.iter().any(|reference| {
227
+ imported_api
228
+ .top_level_names
229
+ .contains(reference.name.as_str())
230
+ && !syntactic_references.contains(&(
231
+ reference.name.clone(),
232
+ reference.location.line,
233
+ reference.location.column,
234
+ ))
235
+ && !helper_declares_or_aliases_name(helper_file, &reference.name)
236
+ && !reference_is_declaration_name(
237
+ root,
238
+ source,
239
+ &reference.name,
240
+ reference.location,
241
+ )
242
+ && !reference_shadowed_at(root, source, &reference.name, reference.location)
243
+ }))
244
+ }
245
+
246
+ fn top_level_reference_uses_imported_api(
247
+ dependency: &ResolvedDependency,
248
+ helper_file: &DartFile,
249
+ root: Node<'_>,
250
+ node: Node<'_>,
251
+ source: &str,
252
+ name: &str,
253
+ ) -> bool {
254
+ if let Some(prefix) = dependency.visibility.prefix.as_deref() {
255
+ return identifier_uses_prefix(source, node.start_byte(), prefix)
256
+ && !term_identifier_shadowed_at(root, node, prefix, source);
257
+ }
258
+ !identifier_has_prefix(source, node.start_byte())
259
+ && !helper_declares_or_aliases_name(helper_file, name)
260
+ && !term_identifier_shadowed_at(root, node, name, source)
261
+ }
262
+
263
+ fn member_reference_uses_imported_api(
264
+ dependency: &ResolvedDependency,
265
+ root: Node<'_>,
266
+ node: Node<'_>,
267
+ source: &str,
268
+ ) -> bool {
269
+ if let Some(prefix) = dependency.visibility.prefix.as_deref() {
270
+ return member_reference_receiver_uses_prefix(node, source, prefix)
271
+ && !term_identifier_shadowed_at(root, node, prefix, source);
272
+ }
273
+ identifier_has_prefix(source, node.start_byte())
274
+ }
275
+
276
+ fn typed_route_navigation_member_reference(
277
+ root: Node<'_>,
278
+ node: Node<'_>,
279
+ source: &str,
280
+ route_classes: &BTreeSet<String>,
281
+ ) -> bool {
282
+ let mut current = node.parent();
283
+ while let Some(parent) = current {
284
+ if matches!(
285
+ parent.kind(),
286
+ "call_expression" | "function_expression_invocation"
287
+ ) && typed_route_navigation_call(root, parent, source, route_classes)
288
+ && (route_extension_navigation_call_member_identifier(
289
+ root,
290
+ parent,
291
+ node,
292
+ source,
293
+ route_classes,
294
+ ) || route_location_argument_member_identifier(
295
+ parent,
296
+ node,
297
+ root,
298
+ source,
299
+ route_classes,
300
+ ))
301
+ {
302
+ return true;
303
+ }
304
+ if same_node(parent, root) {
305
+ break;
306
+ }
307
+ current = parent.parent();
308
+ }
309
+ false
310
+ }
311
+
312
+ fn route_extension_navigation_call_member_identifier(
313
+ root: Node<'_>,
314
+ call: Node<'_>,
315
+ node: Node<'_>,
316
+ source: &str,
317
+ route_classes: &BTreeSet<String>,
318
+ ) -> bool {
319
+ let Some(arguments) = argument_list(call) else {
320
+ return false;
321
+ };
322
+ if node.start_byte() >= arguments.start_byte() {
323
+ return false;
324
+ }
325
+ let Some(prefix) = source.get(call.start_byte()..arguments.start_byte()) else {
326
+ return false;
327
+ };
328
+ let Some(name) = super::navigation_call_name(prefix) else {
329
+ return false;
330
+ };
331
+ if !route_extension_navigation_call(root, call, prefix, &name, arguments, route_classes, source)
332
+ {
333
+ return false;
334
+ }
335
+ node.utf8_text(source.as_bytes()).ok() == Some(name.as_str())
336
+ }
337
+
338
+ fn route_location_argument_member_identifier(
339
+ call: Node<'_>,
340
+ node: Node<'_>,
341
+ root: Node<'_>,
342
+ source: &str,
343
+ route_classes: &BTreeSet<String>,
344
+ ) -> bool {
345
+ let Some(arguments) = argument_list(call) else {
346
+ return false;
347
+ };
348
+ let Some(argument) = route_location_argument(arguments) else {
349
+ return false;
350
+ };
351
+ route_location_expression_member(argument, root, call, route_classes, source)
352
+ .and_then(|member| member.child_by_field_name("property"))
353
+ .is_some_and(|property| same_node(property, node))
354
+ }
355
+
356
+ fn member_reference_receiver_uses_prefix(node: Node<'_>, source: &str, prefix: &str) -> bool {
357
+ let Some(receiver) = member_reference_receiver_text(node, source) else {
358
+ return false;
359
+ };
360
+ let compact = receiver
361
+ .chars()
362
+ .filter(|character| !character.is_whitespace())
363
+ .collect::<String>();
364
+ compact == prefix || compact.starts_with(&format!("{prefix}."))
365
+ }
366
+
367
+ fn member_reference_receiver_text<'source>(
368
+ node: Node<'_>,
369
+ source: &'source str,
370
+ ) -> Option<&'source str> {
371
+ let mut current = node.parent();
372
+ while let Some(parent) = current {
373
+ if matches!(
374
+ parent.kind(),
375
+ "member_expression" | "null_aware_member_expression" | "assignable_expression"
376
+ ) && parent
377
+ .child_by_field_name("property")
378
+ .is_some_and(|property| same_node(property, node))
379
+ {
380
+ return parent
381
+ .child_by_field_name("object")
382
+ .and_then(|object| object.utf8_text(source.as_bytes()).ok());
383
+ }
384
+ current = parent.parent();
385
+ }
386
+ None
387
+ }
388
+
389
+ fn reference_shadowed_at(root: Node<'_>, source: &str, name: &str, location: Location) -> bool {
390
+ let Some(site) = reference_node_at(root, source, name, location) else {
391
+ return false;
392
+ };
393
+ term_identifier_shadowed_at(root, site, name, source)
394
+ }
395
+
396
+ fn reference_is_declaration_name(
397
+ root: Node<'_>,
398
+ source: &str,
399
+ name: &str,
400
+ location: Location,
401
+ ) -> bool {
402
+ let Some(node) = reference_node_at(root, source, name, location) else {
403
+ return false;
404
+ };
405
+ node.utf8_text(source.as_bytes()).ok() == Some(name) && identifier_is_declaration_name(node)
406
+ }
407
+
408
+ fn reference_node_at<'tree>(
409
+ root: Node<'tree>,
410
+ source: &str,
411
+ name: &str,
412
+ location: Location,
413
+ ) -> Option<Node<'tree>> {
414
+ let byte = byte_offset_at_location(source, location)?;
415
+ root.descendant_for_byte_range(byte, byte + name.len())
416
+ }
417
+
418
+ fn byte_offset_at_location(source: &str, location: Location) -> Option<usize> {
419
+ if location.line == 0 {
420
+ return None;
421
+ }
422
+ let mut line = 1;
423
+ let mut line_start = 0;
424
+ loop {
425
+ if line == location.line {
426
+ let line_end = source
427
+ .get(line_start..)?
428
+ .find('\n')
429
+ .map_or(source.len(), |relative| line_start + relative);
430
+ let offset = line_start.checked_add(location.column)?;
431
+ return (offset <= line_end).then_some(offset);
432
+ }
433
+ let newline = source.get(line_start..)?.find('\n')?;
434
+ line_start += newline + 1;
435
+ line += 1;
436
+ }
437
+ }
438
+
439
+ fn reference_identifier_text<'source>(
440
+ node: Node<'_>,
441
+ source: &'source str,
442
+ ) -> Option<&'source str> {
443
+ if !matches!(node.kind(), "identifier" | "type_identifier") {
444
+ return None;
445
+ }
446
+ let name = node.utf8_text(source.as_bytes()).ok()?;
447
+ if name == "_" || has_ancestor_kind(node, &["import_or_export", "part_directive"]) {
448
+ return None;
449
+ }
450
+ if identifier_is_declaration_name(node) {
451
+ return None;
452
+ }
453
+ Some(name)
454
+ }
455
+
456
+ fn identifier_is_declaration_name(node: Node<'_>) -> bool {
457
+ let Some(parent) = node.parent() else {
458
+ return false;
459
+ };
460
+ if parent.kind() == "type_alias" && is_type_alias_name(parent, node) {
461
+ return true;
462
+ }
463
+ if parent.kind() == "identifier_list" {
464
+ return true;
465
+ }
466
+ DECLARATION_NAME_OWNER_KINDS.contains(&parent.kind()) && is_child_field(parent, node, "name")
467
+ }
468
+
469
+ fn identifier_uses_prefix(source: &str, identifier_start: usize, prefix: &str) -> bool {
470
+ let Some(dot) = previous_non_whitespace(source, identifier_start) else {
471
+ return false;
472
+ };
473
+ if source.as_bytes().get(dot) != Some(&b'.') {
474
+ return false;
475
+ }
476
+ let Some(prefix_end) = previous_non_whitespace(source, dot) else {
477
+ return false;
478
+ };
479
+ let Some(prefix_start) = (prefix_end + 1).checked_sub(prefix.len()) else {
480
+ return false;
481
+ };
482
+ source
483
+ .get(prefix_start..=prefix_end)
484
+ .is_some_and(|candidate| candidate == prefix)
485
+ && source
486
+ .get(..prefix_start)
487
+ .and_then(|before| before.chars().next_back())
488
+ .is_none_or(|character| !is_identifier_character(character) && character != '.')
489
+ }
490
+
491
+ fn identifier_has_prefix(source: &str, identifier_start: usize) -> bool {
492
+ previous_non_whitespace(source, identifier_start)
493
+ .is_some_and(|index| source.as_bytes().get(index) == Some(&b'.'))
494
+ }
495
+
496
+ fn previous_non_whitespace(source: &str, before: usize) -> Option<usize> {
497
+ source
498
+ .get(..before)?
499
+ .char_indices()
500
+ .rev()
501
+ .find_map(|(index, character)| (!character.is_whitespace()).then_some(index))
502
+ }
503
+
504
+ fn helper_declares_or_aliases_name(helper_file: &DartFile, name: &str) -> bool {
505
+ helper_file
506
+ .declarations
507
+ .iter()
508
+ .any(|declaration| declaration.name == name)
509
+ || helper_file
510
+ .imports
511
+ .iter()
512
+ .any(|import| import.prefix.as_deref() == Some(name))
513
+ }
514
+
515
+ const DECLARATION_NAME_OWNER_KINDS: &[&str] = &[
516
+ "class_declaration",
517
+ "constant_constructor_signature",
518
+ "constructor_signature",
519
+ "default_formal_parameter",
520
+ "enum_declaration",
521
+ "enum_constant",
522
+ "extension_declaration",
523
+ "extension_type_declaration",
524
+ "factory_constructor_signature",
525
+ "field_formal_parameter",
526
+ "formal_parameter",
527
+ "function_signature",
528
+ "getter_signature",
529
+ "initialized_identifier",
530
+ "initialized_variable_definition",
531
+ "mixin_declaration",
532
+ "normal_formal_parameter",
533
+ "operator_signature",
534
+ "redirecting_factory_constructor_signature",
535
+ "setter_signature",
536
+ "static_final_declaration",
537
+ "typed_identifier",
538
+ "type_alias",
539
+ "variable_pattern",
540
+ ];
541
+
542
+ fn has_ancestor_kind(node: Node<'_>, kinds: &[&str]) -> bool {
543
+ let mut parent = node.parent();
544
+ while let Some(ancestor) = parent {
545
+ if kinds.contains(&ancestor.kind()) {
546
+ return true;
547
+ }
548
+ parent = ancestor.parent();
549
+ }
550
+ false
551
+ }
552
+
553
+ fn is_child_field(parent: Node<'_>, child: Node<'_>, field_name: &str) -> bool {
554
+ let mut cursor = parent.walk();
555
+ parent
556
+ .children_by_field_name(field_name, &mut cursor)
557
+ .any(|field| same_node(field, child))
558
+ }
559
+
560
+ fn is_type_alias_name(parent: Node<'_>, child: Node<'_>) -> bool {
561
+ let mut cursor = parent.walk();
562
+ parent
563
+ .named_children(&mut cursor)
564
+ .find(|node| matches!(node.kind(), "identifier" | "type_identifier"))
565
+ .is_some_and(|name| same_node(name, child))
566
+ }
567
+
568
+ fn same_node(left: Node<'_>, right: Node<'_>) -> bool {
569
+ left.kind() == right.kind()
570
+ && left.start_byte() == right.start_byte()
571
+ && left.end_byte() == right.end_byte()
572
+ }
573
+
574
+ fn is_identifier_character(character: char) -> bool {
575
+ character == '_' || character == '$' || character.is_ascii_alphanumeric()
576
+ }
577
+
578
+ fn typed_route_cycle_files(
579
+ typed_back_edges: &[ResolvedDependency],
580
+ residual_dependencies: &[ResolvedDependency],
581
+ residual_reachability: &ResidualReachability,
582
+ ) -> Vec<PathBuf> {
583
+ let mut files = BTreeSet::new();
584
+ for edge in typed_back_edges {
585
+ if !residual_reachability.reaches(&edge.to_path, &edge.from_path) {
586
+ continue;
587
+ }
588
+ files.insert(edge.to_path.clone());
589
+ files.insert(edge.from_path.clone());
590
+ for dependency in residual_dependencies.iter().filter(|dependency| {
591
+ dependency_lies_on_typed_route_path(dependency, edge, residual_reachability)
592
+ }) {
593
+ files.insert(dependency.from_path.clone());
594
+ files.insert(dependency.to_path.clone());
595
+ }
596
+ }
597
+ files.into_iter().collect()
598
+ }
599
+
600
+ fn dependency_lies_on_typed_route_path(
601
+ dependency: &ResolvedDependency,
602
+ typed_back_edge: &ResolvedDependency,
603
+ residual_reachability: &ResidualReachability,
604
+ ) -> bool {
605
+ residual_reachability.reaches(&typed_back_edge.to_path, &dependency.from_path)
606
+ && residual_reachability.reaches(&dependency.to_path, &typed_back_edge.from_path)
607
+ }
608
+
609
+ #[derive(Debug, Clone, PartialEq, Eq)]
610
+ struct ResidualReachability {
611
+ reachable: BTreeMap<PathBuf, BTreeSet<PathBuf>>,
612
+ }
613
+
614
+ impl ResidualReachability {
615
+ fn new(dependencies: &[ResolvedDependency]) -> Self {
616
+ let mut adjacency = BTreeMap::<PathBuf, Vec<PathBuf>>::new();
617
+ for dependency in dependencies {
618
+ adjacency
619
+ .entry(dependency.from_path.clone())
620
+ .or_default()
621
+ .push(dependency.to_path.clone());
622
+ adjacency.entry(dependency.to_path.clone()).or_default();
623
+ }
624
+ for next_paths in adjacency.values_mut() {
625
+ next_paths.sort();
626
+ next_paths.dedup();
627
+ }
628
+ let reachable = adjacency
629
+ .keys()
630
+ .map(|path| (path.clone(), reachable_from(path, &adjacency)))
631
+ .collect();
632
+ Self { reachable }
633
+ }
634
+
635
+ fn reaches(&self, from: &Path, to: &Path) -> bool {
636
+ from == to
637
+ || self
638
+ .reachable
639
+ .get(from)
640
+ .is_some_and(|targets| targets.contains(to))
641
+ }
642
+ }
643
+
644
+ fn reachable_from(start: &Path, adjacency: &BTreeMap<PathBuf, Vec<PathBuf>>) -> BTreeSet<PathBuf> {
645
+ let mut reachable = BTreeSet::new();
646
+ let mut queue = VecDeque::new();
647
+ if let Some(next_paths) = adjacency.get(start) {
648
+ for next_path in next_paths {
649
+ if reachable.insert(next_path.clone()) {
650
+ queue.push_back(next_path.clone());
651
+ }
652
+ }
653
+ }
654
+ while let Some(path) = queue.pop_front() {
655
+ let Some(next_paths) = adjacency.get(&path) else {
656
+ continue;
657
+ };
658
+ for next_path in next_paths {
659
+ if reachable.insert(next_path.clone()) {
660
+ queue.push_back(next_path.clone());
661
+ }
662
+ }
663
+ }
664
+ reachable
665
+ }
666
+
667
+ fn residual_dependency_cycles(
668
+ cycle_files: &BTreeSet<PathBuf>,
669
+ dependencies: &[ResolvedDependency],
670
+ ) -> Vec<ResidualCycle> {
671
+ let mut graph = DiGraph::<PathBuf, ()>::new();
672
+ let nodes = cycle_files
673
+ .iter()
674
+ .map(|path| (path.clone(), graph.add_node(path.clone())))
675
+ .collect::<BTreeMap<_, _>>();
676
+ for dependency in dependencies {
677
+ let Some(from) = nodes.get(&dependency.from_path).copied() else {
678
+ continue;
679
+ };
680
+ let Some(to) = nodes.get(&dependency.to_path).copied() else {
681
+ continue;
682
+ };
683
+ graph.add_edge(from, to, ());
684
+ }
685
+
686
+ let mut cycles = tarjan_scc(&graph)
687
+ .into_iter()
688
+ .filter_map(|component| residual_cycle_from_component(&graph, component, dependencies))
689
+ .collect::<Vec<_>>();
690
+ cycles.sort_by(|left, right| left.files.cmp(&right.files));
691
+ cycles
692
+ }
693
+
694
+ fn residual_cycle_from_component(
695
+ graph: &DiGraph<PathBuf, ()>,
696
+ component: Vec<NodeIndex>,
697
+ dependencies: &[ResolvedDependency],
698
+ ) -> Option<ResidualCycle> {
699
+ let first = component.first().copied()?;
700
+ let is_cycle = component.len() > 1 || component_has_self_loop(graph, first);
701
+ if !is_cycle {
702
+ return None;
703
+ }
704
+ let mut files = component
705
+ .into_iter()
706
+ .map(|node| graph[node].clone())
707
+ .collect::<Vec<_>>();
708
+ files.sort();
709
+ let edge = first_dependency_in_cycle(&files, dependencies).cloned();
710
+ Some(ResidualCycle { files, edge })
711
+ }
712
+
713
+ fn component_has_self_loop(graph: &DiGraph<PathBuf, ()>, node: NodeIndex) -> bool {
714
+ graph.edges(node).any(|edge| edge.target() == node)
715
+ }
716
+
717
+ fn first_dependency_in_cycle<'dependencies>(
718
+ files: &[PathBuf],
719
+ dependencies: &'dependencies [ResolvedDependency],
720
+ ) -> Option<&'dependencies ResolvedDependency> {
721
+ dependencies
722
+ .iter()
723
+ .filter(|dependency| {
724
+ files.contains(&dependency.from_path) && files.contains(&dependency.to_path)
725
+ })
726
+ .min_by(|left, right| {
727
+ (
728
+ &left.from_path,
729
+ &left.to_path,
730
+ dependency_kind_order(left.kind),
731
+ &left.specifier,
732
+ )
733
+ .cmp(&(
734
+ &right.from_path,
735
+ &right.to_path,
736
+ dependency_kind_order(right.kind),
737
+ &right.specifier,
738
+ ))
739
+ })
740
+ }
741
+
742
+ fn append_route_registry_edge_errors(
743
+ route_files: &BTreeSet<PathBuf>,
744
+ dependencies: &[ResolvedDependency],
745
+ residual_cycles: &mut Vec<ResidualCycle>,
746
+ ) {
747
+ for dependency in dependencies.iter().filter(|dependency| {
748
+ route_files.contains(&dependency.from_path)
749
+ && !route_files.contains(&dependency.to_path)
750
+ && dependency.kind != DependencyKind::Import
751
+ }) {
752
+ if residual_cycles.iter().any(|cycle| {
753
+ cycle.files.contains(&dependency.from_path) && cycle.files.contains(&dependency.to_path)
754
+ }) {
755
+ continue;
756
+ }
757
+ let mut files = vec![dependency.from_path.clone(), dependency.to_path.clone()];
758
+ files.sort();
759
+ residual_cycles.push(ResidualCycle {
760
+ files,
761
+ edge: Some(dependency.clone()),
762
+ });
763
+ }
764
+ }
765
+
766
+ fn append_typed_route_path_edge_errors(
767
+ route_files: &BTreeSet<PathBuf>,
768
+ typed_back_edges: &[ResolvedDependency],
769
+ residual_dependencies: &[ResolvedDependency],
770
+ residual_reachability: &ResidualReachability,
771
+ residual_cycles: &mut Vec<ResidualCycle>,
772
+ ) {
773
+ let mut path_edges = residual_dependencies
774
+ .iter()
775
+ .filter(|dependency| {
776
+ dependency.kind != DependencyKind::Import
777
+ || route_registry_import_edge(route_files, dependency)
778
+ })
779
+ .filter(|dependency| {
780
+ typed_back_edges.iter().any(|typed_back_edge| {
781
+ dependency_lies_on_typed_route_path(
782
+ dependency,
783
+ typed_back_edge,
784
+ residual_reachability,
785
+ )
786
+ })
787
+ })
788
+ .cloned()
789
+ .collect::<Vec<_>>();
790
+ path_edges.sort_by(|left, right| {
791
+ (
792
+ &left.from_path,
793
+ &left.to_path,
794
+ dependency_kind_order(left.kind),
795
+ &left.specifier,
796
+ )
797
+ .cmp(&(
798
+ &right.from_path,
799
+ &right.to_path,
800
+ dependency_kind_order(right.kind),
801
+ &right.specifier,
802
+ ))
803
+ });
804
+ for dependency in path_edges {
805
+ if residual_cycles.iter().any(|cycle| {
806
+ cycle.files.contains(&dependency.from_path) && cycle.files.contains(&dependency.to_path)
807
+ }) {
808
+ continue;
809
+ }
810
+ let mut files = vec![dependency.from_path.clone(), dependency.to_path.clone()];
811
+ files.sort();
812
+ residual_cycles.push(ResidualCycle {
813
+ files,
814
+ edge: Some(dependency),
815
+ });
816
+ }
817
+ }
818
+
819
+ fn route_registry_import_edge(
820
+ route_files: &BTreeSet<PathBuf>,
821
+ dependency: &ResolvedDependency,
822
+ ) -> bool {
823
+ dependency.kind == DependencyKind::Import
824
+ && route_files.contains(&dependency.from_path)
825
+ && route_files.contains(&dependency.to_path)
826
+ }
827
+
828
+ fn same_dependency(left: &ResolvedDependency, right: &ResolvedDependency) -> bool {
829
+ left.from_path == right.from_path
830
+ && left.to_path == right.to_path
831
+ && left.kind == right.kind
832
+ && left.specifier == right.specifier
833
+ && left.location == right.location
834
+ }
835
+
836
+ fn dependency_kind_order(kind: DependencyKind) -> u8 {
837
+ match kind {
838
+ DependencyKind::Import => 0,
839
+ DependencyKind::Export => 1,
840
+ DependencyKind::Part => 2,
841
+ DependencyKind::Augment => 3,
842
+ }
843
+ }
844
+
845
+ fn is_typed_go_router_registry(file: &DartFile) -> bool {
846
+ if file.routes.is_empty()
847
+ && !file.references.iter().any(|reference| {
848
+ matches!(
849
+ reference.name.as_str(),
850
+ "TypedGoRoute"
851
+ | "TypedRelativeGoRoute"
852
+ | "TypedShellRoute"
853
+ | "TypedStatefulShellRoute"
854
+ | "TypedStatefulShellBranch"
855
+ )
856
+ })
857
+ {
858
+ return false;
859
+ }
860
+
861
+ file.parts.iter().any(|part| part.uri.ends_with(".g.dart"))
862
+ }