dart-decimate 0.0.9 → 0.0.11

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 (48) hide show
  1. package/Cargo.lock +1 -1
  2. package/Cargo.toml +1 -1
  3. package/README.md +50 -58
  4. package/package.json +1 -1
  5. package/src/cli/analyze.rs +6 -3
  6. package/src/cli/entry_points.rs +18 -2
  7. package/src/cli/list_run.rs +1 -0
  8. package/src/cli/tests.rs +74 -0
  9. package/src/config/rules.rs +50 -13
  10. package/src/dependencies/analyze.rs +7 -1
  11. package/src/dependencies/tests.rs +29 -0
  12. package/src/dependencies.rs +19 -0
  13. package/src/dependency_scripts.rs +2 -0
  14. package/src/dupes/declarations.rs +512 -0
  15. package/src/dupes/packages.rs +213 -0
  16. package/src/dupes/tests.rs +197 -0
  17. package/src/dupes.rs +57 -19
  18. package/src/extract/reference_tests.rs +106 -0
  19. package/src/extract/references.rs +264 -2
  20. package/src/extract/tests.rs +25 -0
  21. package/src/extract.rs +6 -3
  22. package/src/generated.rs +96 -3
  23. package/src/graph/package_config_tests.rs +123 -0
  24. package/src/graph/tests.rs +125 -0
  25. package/src/graph.rs +6 -5
  26. package/src/output/feature_flag_findings.rs +63 -1
  27. package/src/output/graph_findings.rs +73 -37
  28. package/src/output/route_cycle/aliases.rs +875 -0
  29. package/src/output/route_cycle/navigation.rs +1005 -0
  30. package/src/output/route_cycle/receivers.rs +41 -0
  31. package/src/output/route_cycle/state_context.rs +209 -0
  32. package/src/output/route_cycle/tests.rs +175 -0
  33. package/src/output/route_cycle.rs +730 -0
  34. package/src/output/security_findings.rs +15 -2
  35. package/src/output/tests.rs +104 -1
  36. package/src/output.rs +2 -1
  37. package/src/package_map.rs +220 -28
  38. package/src/routes.rs +6 -1
  39. package/src/scan.rs +15 -5
  40. package/src/security/detect.rs +140 -6
  41. package/src/security/tests.rs +96 -0
  42. package/src/trace.rs +1 -1
  43. package/src/widgets/forwarding.rs +684 -0
  44. package/src/widgets/patterns.rs +2595 -0
  45. package/src/widgets/reads.rs +616 -0
  46. package/src/widgets/tests.rs +1837 -55
  47. package/src/widgets/unrendered.rs +150 -0
  48. package/src/widgets.rs +25 -93
@@ -0,0 +1,512 @@
1
+ use std::collections::{BTreeMap, BTreeSet};
2
+ use std::fs;
3
+ use std::path::{Path, PathBuf};
4
+
5
+ use super::{CodeClone, CodeCloneInstance};
6
+
7
+ pub(super) struct DeclarationCloneFilter {
8
+ files: BTreeMap<PathBuf, Option<DeclarationFileContext>>,
9
+ }
10
+
11
+ impl DeclarationCloneFilter {
12
+ pub(super) fn new() -> Self {
13
+ Self {
14
+ files: BTreeMap::new(),
15
+ }
16
+ }
17
+
18
+ pub(super) fn is_declaration_only_clone(&mut self, group: &CodeClone) -> bool {
19
+ group
20
+ .instances
21
+ .iter()
22
+ .all(|instance| self.clone_instance_is_declaration_only(instance))
23
+ }
24
+
25
+ fn clone_instance_is_declaration_only(&mut self, instance: &CodeCloneInstance) -> bool {
26
+ let path = instance.path.clone();
27
+ let Some(file) = self
28
+ .files
29
+ .entry(path)
30
+ .or_insert_with(|| DeclarationFileContext::read(&instance.path))
31
+ .as_ref()
32
+ else {
33
+ return false;
34
+ };
35
+ let lines = file
36
+ .source
37
+ .lines()
38
+ .enumerate()
39
+ .filter_map(|(index, line)| {
40
+ let line_number = index + 1;
41
+ (line_number >= instance.start_line && line_number <= instance.end_line)
42
+ .then_some((line_number, strip_line_comment(line).trim()))
43
+ })
44
+ .filter(|(_, line)| !line.is_empty())
45
+ .collect::<Vec<_>>();
46
+ !lines.is_empty() && declaration_only_lines(&lines, &file.context.direct_type_body_lines)
47
+ }
48
+
49
+ #[cfg(test)]
50
+ fn cached_file_count(&self) -> usize {
51
+ self.files.len()
52
+ }
53
+ }
54
+
55
+ struct DeclarationFileContext {
56
+ source: String,
57
+ context: DeclarationContext,
58
+ }
59
+
60
+ impl DeclarationFileContext {
61
+ fn read(path: &Path) -> Option<Self> {
62
+ let source = fs::read_to_string(path).ok()?;
63
+ let context = DeclarationContext::from_source(&source);
64
+ Some(Self { source, context })
65
+ }
66
+ }
67
+
68
+ fn strip_line_comment(line: &str) -> &str {
69
+ line.split_once("//").map_or(line, |(code, _)| code)
70
+ }
71
+
72
+ fn declaration_only_line(line: &str, in_declaration_body: bool) -> bool {
73
+ abstract_type_header(line)
74
+ || line == "}"
75
+ || line == "};"
76
+ || (in_declaration_body && abstract_member_signature(line))
77
+ }
78
+
79
+ fn declaration_only_lines(
80
+ lines: &[(usize, &str)],
81
+ direct_type_body_lines: &BTreeSet<usize>,
82
+ ) -> bool {
83
+ let mut index = 0;
84
+ while index < lines.len() {
85
+ let (line_number, line) = lines[index];
86
+ let in_declaration_body = direct_type_body_lines.contains(&line_number);
87
+ if declaration_only_line(line, in_declaration_body) {
88
+ index += 1;
89
+ continue;
90
+ }
91
+ if in_declaration_body && let Some(end) = multiline_signature_end(lines, index) {
92
+ let signature = lines[index..=end]
93
+ .iter()
94
+ .map(|(_, line)| *line)
95
+ .collect::<Vec<_>>()
96
+ .join(" ");
97
+ if abstract_member_signature(&signature) {
98
+ index = end + 1;
99
+ continue;
100
+ }
101
+ }
102
+ return false;
103
+ }
104
+ true
105
+ }
106
+
107
+ fn multiline_signature_end(lines: &[(usize, &str)], start: usize) -> Option<usize> {
108
+ if lines[start].1.ends_with(';') {
109
+ return None;
110
+ }
111
+ lines
112
+ .iter()
113
+ .enumerate()
114
+ .skip(start + 1)
115
+ .find_map(|(index, (_, line))| line.ends_with(';').then_some(index))
116
+ }
117
+
118
+ fn abstract_type_header(line: &str) -> bool {
119
+ let Some(header) = line.strip_suffix('{').map(str::trim) else {
120
+ return false;
121
+ };
122
+ declaration_type_header(header)
123
+ }
124
+
125
+ fn declaration_type_header(header: &str) -> bool {
126
+ let tokens = header.split_whitespace().collect::<Vec<_>>();
127
+ if tokens.is_empty() {
128
+ return false;
129
+ }
130
+ for (index, token) in tokens.iter().enumerate() {
131
+ match *token {
132
+ "class" => {
133
+ if index > 0
134
+ && tokens.get(index.saturating_sub(1)) == Some(&"mixin")
135
+ && type_modifiers(&tokens[..index.saturating_sub(1)])
136
+ {
137
+ return true;
138
+ }
139
+ return index > 0 && type_modifiers(&tokens[..index]);
140
+ }
141
+ "mixin" => {
142
+ if tokens.get(index + 1) == Some(&"class") {
143
+ continue;
144
+ }
145
+ return type_modifiers(&tokens[..index]);
146
+ }
147
+ "enum" | "extension" => return type_modifiers(&tokens[..index]),
148
+ _ => {}
149
+ }
150
+ }
151
+ false
152
+ }
153
+
154
+ fn type_modifiers(tokens: &[&str]) -> bool {
155
+ tokens.iter().all(|token| {
156
+ matches!(
157
+ *token,
158
+ "abstract" | "base" | "final" | "interface" | "sealed"
159
+ )
160
+ })
161
+ }
162
+
163
+ fn abstract_member_signature(line: &str) -> bool {
164
+ let Some(signature) = line.strip_suffix(';').map(str::trim) else {
165
+ return false;
166
+ };
167
+ if signature_contains_non_operator_equals(signature)
168
+ || signature_contains_top_level_body_brace(signature)
169
+ || signature.starts_with("import ")
170
+ || signature.starts_with("export ")
171
+ || signature.starts_with("part ")
172
+ {
173
+ return false;
174
+ }
175
+ getter_signature(signature) || callable_member_signature(signature)
176
+ }
177
+
178
+ fn signature_contains_non_operator_equals(signature: &str) -> bool {
179
+ let Some(paren) = signature.find('(') else {
180
+ return signature.contains('=');
181
+ };
182
+ let before_parameters = signature[..paren].trim();
183
+ let tokens = before_parameters.split_whitespace().collect::<Vec<_>>();
184
+ if tokens.len() >= 2 && tokens.get(tokens.len() - 2) == Some(&"operator") {
185
+ let Some(operator_token) = tokens.last() else {
186
+ return signature.contains('=');
187
+ };
188
+ let Some(operator_start) = before_parameters.rfind(operator_token) else {
189
+ return signature.contains('=');
190
+ };
191
+ return before_parameters[..operator_start].contains('=')
192
+ || signature[paren..].contains('=');
193
+ }
194
+ signature.contains('=')
195
+ }
196
+
197
+ fn signature_contains_top_level_body_brace(signature: &str) -> bool {
198
+ let mut paren_depth = 0usize;
199
+ let mut bracket_depth = 0usize;
200
+ let mut quote = None::<char>;
201
+ let mut escaped = false;
202
+
203
+ for character in signature.chars() {
204
+ if let Some(delimiter) = quote {
205
+ if escaped {
206
+ escaped = false;
207
+ } else if character == '\\' {
208
+ escaped = true;
209
+ } else if character == delimiter {
210
+ quote = None;
211
+ }
212
+ continue;
213
+ }
214
+
215
+ match character {
216
+ '"' | '\'' => quote = Some(character),
217
+ '(' => paren_depth += 1,
218
+ ')' => paren_depth = paren_depth.saturating_sub(1),
219
+ '[' => bracket_depth += 1,
220
+ ']' => bracket_depth = bracket_depth.saturating_sub(1),
221
+ '{' | '}' if paren_depth == 0 && bracket_depth == 0 => return true,
222
+ _ => {}
223
+ }
224
+ }
225
+
226
+ false
227
+ }
228
+
229
+ fn getter_signature(signature: &str) -> bool {
230
+ let tokens = signature.split_whitespace().collect::<Vec<_>>();
231
+ let Some(get_index) = tokens.iter().position(|token| *token == "get") else {
232
+ return false;
233
+ };
234
+ get_index + 1 < tokens.len()
235
+ && tokens[..get_index]
236
+ .iter()
237
+ .all(|token| !EXPRESSION_STARTERS.contains(token))
238
+ && identifier_like(tokens[get_index + 1])
239
+ }
240
+
241
+ fn callable_member_signature(signature: &str) -> bool {
242
+ let Some(paren) = signature.find('(') else {
243
+ return false;
244
+ };
245
+ let before_parameters = signature[..paren].trim();
246
+ if before_parameters.contains('.') {
247
+ return false;
248
+ }
249
+ let tokens = before_parameters.split_whitespace().collect::<Vec<_>>();
250
+ if tokens.len() < 2
251
+ || tokens
252
+ .iter()
253
+ .any(|token| EXPRESSION_STARTERS.contains(token))
254
+ {
255
+ return false;
256
+ }
257
+ let Some(member_name) = tokens.last() else {
258
+ return false;
259
+ };
260
+ identifier_like(member_name) || tokens.get(tokens.len().saturating_sub(2)) == Some(&"operator")
261
+ }
262
+
263
+ fn identifier_like(value: &str) -> bool {
264
+ let mut chars = value.chars();
265
+ let Some(first) = chars.next() else {
266
+ return false;
267
+ };
268
+ (first == '_' || first == '$' || first.is_ascii_alphabetic())
269
+ && chars.all(|character| {
270
+ character == '_' || character == '$' || character.is_ascii_alphanumeric()
271
+ })
272
+ }
273
+
274
+ const EXPRESSION_STARTERS: &[&str] = &[
275
+ "assert", "await", "break", "continue", "do", "for", "if", "return", "switch", "throw",
276
+ "while", "yield",
277
+ ];
278
+
279
+ struct DeclarationContext {
280
+ direct_type_body_lines: BTreeSet<usize>,
281
+ }
282
+
283
+ impl DeclarationContext {
284
+ fn from_source(source: &str) -> Self {
285
+ let mut direct_type_body_lines = BTreeSet::new();
286
+ let mut type_body_depths = Vec::<usize>::new();
287
+ let mut brace_depth = 0usize;
288
+
289
+ for (index, raw_line) in source.lines().enumerate() {
290
+ let line_number = index + 1;
291
+ let line = strip_line_comment(raw_line).trim();
292
+ if type_body_depths
293
+ .last()
294
+ .is_some_and(|type_depth| brace_depth == *type_depth)
295
+ {
296
+ direct_type_body_lines.insert(line_number);
297
+ }
298
+
299
+ let opens_type = abstract_type_header(line);
300
+ let opens = line.chars().filter(|character| *character == '{').count();
301
+ let closes = line.chars().filter(|character| *character == '}').count();
302
+ if opens_type && opens > 0 {
303
+ type_body_depths.push(brace_depth + 1);
304
+ }
305
+ brace_depth = brace_depth.saturating_add(opens).saturating_sub(closes);
306
+ while type_body_depths
307
+ .last()
308
+ .is_some_and(|type_depth| brace_depth < *type_depth)
309
+ {
310
+ type_body_depths.pop();
311
+ }
312
+ }
313
+
314
+ Self {
315
+ direct_type_body_lines,
316
+ }
317
+ }
318
+ }
319
+
320
+ #[cfg(test)]
321
+ mod tests {
322
+ use super::*;
323
+
324
+ #[test]
325
+ fn declaration_filter_reuses_file_contexts_by_path() -> Result<(), Box<dyn std::error::Error>> {
326
+ let fixture = tempfile::tempdir()?;
327
+ let path = fixture.path().join("contract.dart");
328
+ fs::write(
329
+ &path,
330
+ "abstract class Contract {\n String get title;\n void save();\n}\n",
331
+ )?;
332
+ let group = CodeClone {
333
+ fingerprint: "contract".to_owned(),
334
+ instances: vec![
335
+ CodeCloneInstance {
336
+ path: path.clone(),
337
+ start_line: 1,
338
+ end_line: 4,
339
+ column: 0,
340
+ },
341
+ CodeCloneInstance {
342
+ path,
343
+ start_line: 1,
344
+ end_line: 4,
345
+ column: 0,
346
+ },
347
+ ],
348
+ line_count: 4,
349
+ token_count: 8,
350
+ };
351
+ let mut filter = DeclarationCloneFilter::new();
352
+
353
+ assert!(filter.is_declaration_only_clone(&group));
354
+ assert_eq!(filter.cached_file_count(), 1);
355
+ Ok(())
356
+ }
357
+
358
+ #[test]
359
+ fn declaration_filter_treats_operator_signatures_as_declarations()
360
+ -> Result<(), Box<dyn std::error::Error>> {
361
+ let fixture = tempfile::tempdir()?;
362
+ let path = fixture.path().join("contract.dart");
363
+ fs::write(
364
+ &path,
365
+ "abstract interface class Contract {\n bool operator ==(Object other);\n String operator [](int index);\n void operator []=(int index, String value);\n}\n",
366
+ )?;
367
+ let group = CodeClone {
368
+ fingerprint: "operators".to_owned(),
369
+ instances: vec![CodeCloneInstance {
370
+ path,
371
+ start_line: 1,
372
+ end_line: 5,
373
+ column: 0,
374
+ }],
375
+ line_count: 5,
376
+ token_count: 12,
377
+ };
378
+ let mut filter = DeclarationCloneFilter::new();
379
+
380
+ assert!(filter.is_declaration_only_clone(&group));
381
+ Ok(())
382
+ }
383
+
384
+ #[test]
385
+ fn declaration_filter_rejects_defaults_and_assignments()
386
+ -> Result<(), Box<dyn std::error::Error>> {
387
+ let fixture = tempfile::tempdir()?;
388
+ let path = fixture.path().join("contract.dart");
389
+ fs::write(
390
+ &path,
391
+ "abstract class Contract {\n void save({String label = 'x'});\n String title = 'x';\n}\n",
392
+ )?;
393
+ let group = CodeClone {
394
+ fingerprint: "defaults".to_owned(),
395
+ instances: vec![CodeCloneInstance {
396
+ path,
397
+ start_line: 1,
398
+ end_line: 4,
399
+ column: 0,
400
+ }],
401
+ line_count: 4,
402
+ token_count: 12,
403
+ };
404
+ let mut filter = DeclarationCloneFilter::new();
405
+
406
+ assert!(!filter.is_declaration_only_clone(&group));
407
+ Ok(())
408
+ }
409
+
410
+ #[test]
411
+ fn declaration_filter_accepts_modified_type_headers() -> Result<(), Box<dyn std::error::Error>>
412
+ {
413
+ let fixture = tempfile::tempdir()?;
414
+ let path = fixture.path().join("contract.dart");
415
+ fs::write(
416
+ &path,
417
+ "abstract final class UtilityContract {\n String get title;\n void save();\n}\nabstract base class BaseContract {\n String get label;\n void load();\n}\nbase mixin class BehaviorContract {\n String get name;\n void apply();\n}\nsealed class SealedContract {\n String get value;\n void seal();\n}\n",
418
+ )?;
419
+ let group = CodeClone {
420
+ fingerprint: "modified-contracts".to_owned(),
421
+ instances: vec![CodeCloneInstance {
422
+ path,
423
+ start_line: 1,
424
+ end_line: 16,
425
+ column: 0,
426
+ }],
427
+ line_count: 16,
428
+ token_count: 32,
429
+ };
430
+ let mut filter = DeclarationCloneFilter::new();
431
+
432
+ assert!(filter.is_declaration_only_clone(&group));
433
+ Ok(())
434
+ }
435
+
436
+ #[test]
437
+ fn declaration_filter_accepts_multiline_member_signatures()
438
+ -> Result<(), Box<dyn std::error::Error>> {
439
+ let fixture = tempfile::tempdir()?;
440
+ let path = fixture.path().join("contract.dart");
441
+ fs::write(
442
+ &path,
443
+ "abstract interface class Contract {\n Future<void> save({\n required String title,\n required int count,\n });\n Stream<List<Item>> watchItems({\n required String ownerId,\n });\n}\n",
444
+ )?;
445
+ let group = CodeClone {
446
+ fingerprint: "multiline-contract".to_owned(),
447
+ instances: vec![CodeCloneInstance {
448
+ path,
449
+ start_line: 1,
450
+ end_line: 9,
451
+ column: 0,
452
+ }],
453
+ line_count: 9,
454
+ token_count: 24,
455
+ };
456
+ let mut filter = DeclarationCloneFilter::new();
457
+
458
+ assert!(filter.is_declaration_only_clone(&group));
459
+ Ok(())
460
+ }
461
+
462
+ #[test]
463
+ fn declaration_filter_rejects_multiline_defaults() -> Result<(), Box<dyn std::error::Error>> {
464
+ let fixture = tempfile::tempdir()?;
465
+ let path = fixture.path().join("contract.dart");
466
+ fs::write(
467
+ &path,
468
+ "abstract class Contract {\n void save({\n String label = 'x',\n });\n}\n",
469
+ )?;
470
+ let group = CodeClone {
471
+ fingerprint: "multiline-default".to_owned(),
472
+ instances: vec![CodeCloneInstance {
473
+ path,
474
+ start_line: 1,
475
+ end_line: 5,
476
+ column: 0,
477
+ }],
478
+ line_count: 5,
479
+ token_count: 12,
480
+ };
481
+ let mut filter = DeclarationCloneFilter::new();
482
+
483
+ assert!(!filter.is_declaration_only_clone(&group));
484
+ Ok(())
485
+ }
486
+
487
+ #[test]
488
+ fn declaration_filter_rejects_concrete_method_bodies() -> Result<(), Box<dyn std::error::Error>>
489
+ {
490
+ let fixture = tempfile::tempdir()?;
491
+ let path = fixture.path().join("contract.dart");
492
+ fs::write(
493
+ &path,
494
+ "abstract class Contract {\n void save() {\n analytics.track();\n }\n}\n",
495
+ )?;
496
+ let group = CodeClone {
497
+ fingerprint: "concrete-method".to_owned(),
498
+ instances: vec![CodeCloneInstance {
499
+ path,
500
+ start_line: 1,
501
+ end_line: 5,
502
+ column: 0,
503
+ }],
504
+ line_count: 5,
505
+ token_count: 12,
506
+ };
507
+ let mut filter = DeclarationCloneFilter::new();
508
+
509
+ assert!(!filter.is_declaration_only_clone(&group));
510
+ Ok(())
511
+ }
512
+ }