dart-decimate 0.0.40 → 0.0.42

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.
@@ -20,9 +20,29 @@ pub(super) struct FileReachabilityFacts {
20
20
  pub(super) class_names: BTreeSet<String>,
21
21
  pub(super) widgets: Vec<UnrenderedWidgetClass>,
22
22
  pub(super) object_constructors: Vec<String>,
23
+ contextual_constructors: Vec<ContextualConstructor>,
24
+ typed_fields: Vec<TypedField>,
23
25
  pub(super) superclasses: BTreeMap<String, String>,
24
26
  }
25
27
 
28
+ #[derive(Debug, Clone, PartialEq, Eq)]
29
+ enum ContextualConstructor {
30
+ NamedArgument {
31
+ owner_constructor: String,
32
+ argument: String,
33
+ },
34
+ TypedInitializer {
35
+ target: String,
36
+ },
37
+ }
38
+
39
+ #[derive(Debug, Clone, PartialEq, Eq)]
40
+ struct TypedField {
41
+ owner: String,
42
+ field: String,
43
+ target: String,
44
+ }
45
+
26
46
  pub(super) fn unrendered_widgets(
27
47
  project: &ScannedProject,
28
48
  files: &[WidgetFileFacts],
@@ -94,6 +114,8 @@ pub(super) fn reachability_facts(
94
114
  .collect(),
95
115
  widgets: widget_classes(path, classes, source),
96
116
  object_constructors: object_constructor_names(root, source),
117
+ contextual_constructors: contextual_constructor_names(root, source),
118
+ typed_fields: typed_fields(classes, source),
97
119
  superclasses: class_superclasses(classes, source),
98
120
  }
99
121
  }
@@ -150,6 +172,237 @@ fn object_constructor_names(root: Node<'_>, source: &str) -> Vec<String> {
150
172
  constructors
151
173
  }
152
174
 
175
+ fn contextual_constructor_names(root: Node<'_>, source: &str) -> Vec<ContextualConstructor> {
176
+ let mut constructors = Vec::new();
177
+ visit_named(root, &mut |node| {
178
+ if node.kind() == "named_argument" && contains_dot_new(node, source) {
179
+ let Some(argument) = node.named_child(0).and_then(|label| {
180
+ label
181
+ .utf8_text(source.as_bytes())
182
+ .ok()
183
+ .map(|name| name.trim_end_matches(':').to_owned())
184
+ }) else {
185
+ return;
186
+ };
187
+ let Some(call) = node.parent().and_then(|arguments| arguments.parent()) else {
188
+ return;
189
+ };
190
+ if let Some(owner_constructor) = constructor_type_name(call, source) {
191
+ constructors.push(ContextualConstructor::NamedArgument {
192
+ owner_constructor,
193
+ argument,
194
+ });
195
+ }
196
+ return;
197
+ }
198
+
199
+ if node.kind() == "local_variable_declaration" {
200
+ let mut cursor = node.walk();
201
+ for definition in node
202
+ .named_children(&mut cursor)
203
+ .filter(|child| child.kind() == "initialized_variable_definition")
204
+ {
205
+ if let Some(target) = contextual_initialized_variable_target(definition, source) {
206
+ constructors.push(ContextualConstructor::TypedInitializer { target });
207
+ }
208
+ }
209
+ return;
210
+ }
211
+
212
+ if node.kind() == "declaration" {
213
+ constructors.extend(
214
+ contextual_declaration_targets(node, source)
215
+ .map(|target| ContextualConstructor::TypedInitializer { target }),
216
+ );
217
+ }
218
+ });
219
+ constructors
220
+ }
221
+
222
+ fn contextual_initialized_variable_target(definition: Node<'_>, source: &str) -> Option<String> {
223
+ let type_node = direct_named_child(definition, "type")?;
224
+ let value = definition.child_by_field_name("value")?;
225
+ contextual_initializer_target(type_node, value, source)
226
+ }
227
+
228
+ fn contextual_declaration_targets<'tree>(
229
+ declaration: Node<'tree>,
230
+ source: &'tree str,
231
+ ) -> impl Iterator<Item = String> + 'tree {
232
+ let Some(type_node) = direct_named_child(declaration, "type") else {
233
+ return Vec::new().into_iter();
234
+ };
235
+ let Some(target) = type_node
236
+ .utf8_text(source.as_bytes())
237
+ .ok()
238
+ .and_then(contextual_target_type)
239
+ else {
240
+ return Vec::new().into_iter();
241
+ };
242
+ let mut cursor = declaration.walk();
243
+ declaration
244
+ .named_children(&mut cursor)
245
+ .filter(|child| {
246
+ matches!(
247
+ child.kind(),
248
+ "identifier_list" | "initialized_identifier_list"
249
+ )
250
+ })
251
+ .flat_map(|list| initialized_identifiers(list))
252
+ .filter(move |identifier| {
253
+ identifier
254
+ .child_by_field_name("value")
255
+ .is_some_and(|value| is_contextual_initializer(value, source))
256
+ })
257
+ .map(move |_| target.clone())
258
+ .collect::<Vec<_>>()
259
+ .into_iter()
260
+ }
261
+
262
+ fn contextual_initializer_target(
263
+ type_node: Node<'_>,
264
+ value: Node<'_>,
265
+ source: &str,
266
+ ) -> Option<String> {
267
+ is_contextual_initializer(value, source).then_some(())?;
268
+ type_node
269
+ .utf8_text(source.as_bytes())
270
+ .ok()
271
+ .and_then(contextual_target_type)
272
+ }
273
+
274
+ fn is_contextual_initializer(value: Node<'_>, source: &str) -> bool {
275
+ let Ok(value_text) = value.utf8_text(source.as_bytes()) else {
276
+ return false;
277
+ };
278
+ let value_text = value_text.trim_start();
279
+ let is_direct_constructor =
280
+ value_text.starts_with(".new") || value_text.starts_with("const .new");
281
+ let is_collection_literal = value_text.starts_with('[')
282
+ || value_text.starts_with('{')
283
+ || value_text.starts_with("const [")
284
+ || value_text.starts_with("const {")
285
+ || value_text.starts_with("List.unmodifiable(")
286
+ || value_text.starts_with("List.of(")
287
+ || value_text.starts_with("Set.of(");
288
+ (is_direct_constructor || is_collection_literal) && contains_dot_new(value, source)
289
+ }
290
+
291
+ fn contains_dot_new(node: Node<'_>, source: &str) -> bool {
292
+ if node.kind() == "static_member_shorthand"
293
+ && node.utf8_text(source.as_bytes()).ok() == Some(".new")
294
+ {
295
+ return true;
296
+ }
297
+ if is_object_constructor(node) && constructor_type_name(node, source).as_deref() == Some("New_")
298
+ {
299
+ return true;
300
+ }
301
+ let mut cursor = node.walk();
302
+ node.named_children(&mut cursor)
303
+ .any(|child| contains_dot_new(child, source))
304
+ }
305
+
306
+ fn typed_fields(classes: &[Node<'_>], source: &str) -> Vec<TypedField> {
307
+ let mut fields = Vec::new();
308
+ for class in classes {
309
+ let Some(owner) = class
310
+ .child_by_field_name("name")
311
+ .and_then(|name| name.utf8_text(source.as_bytes()).ok())
312
+ else {
313
+ continue;
314
+ };
315
+ let Some(body) = class.child_by_field_name("body") else {
316
+ continue;
317
+ };
318
+ let mut cursor = body.walk();
319
+ for member in body.named_children(&mut cursor) {
320
+ let Some(declaration) = direct_named_child(member, "declaration") else {
321
+ continue;
322
+ };
323
+ for (field, target) in typed_fields_in_declaration(declaration, source) {
324
+ fields.push(TypedField {
325
+ owner: owner.to_owned(),
326
+ field,
327
+ target,
328
+ });
329
+ }
330
+ }
331
+ }
332
+ fields
333
+ }
334
+
335
+ fn typed_fields_in_declaration(declaration: Node<'_>, source: &str) -> Vec<(String, String)> {
336
+ let Some(type_node) = direct_named_child(declaration, "type") else {
337
+ return Vec::new();
338
+ };
339
+ let Some(type_text) = type_node.utf8_text(source.as_bytes()).ok() else {
340
+ return Vec::new();
341
+ };
342
+ let Some(target) = contextual_target_type(type_text) else {
343
+ return Vec::new();
344
+ };
345
+ let mut cursor = declaration.walk();
346
+ declaration
347
+ .named_children(&mut cursor)
348
+ .filter(|child| {
349
+ matches!(
350
+ child.kind(),
351
+ "identifier_list" | "initialized_identifier_list"
352
+ )
353
+ })
354
+ .flat_map(initialized_identifiers)
355
+ .filter_map(|identifier| {
356
+ identifier
357
+ .child_by_field_name("name")
358
+ .or_else(|| (identifier.kind() == "identifier").then_some(identifier))
359
+ .and_then(|name| name.utf8_text(source.as_bytes()).ok())
360
+ .map(|name| (name.to_owned(), target.clone()))
361
+ })
362
+ .collect()
363
+ }
364
+
365
+ fn direct_named_child<'tree>(node: Node<'tree>, kind: &str) -> Option<Node<'tree>> {
366
+ let mut cursor = node.walk();
367
+ node.named_children(&mut cursor)
368
+ .find(|child| child.kind() == kind)
369
+ }
370
+
371
+ fn initialized_identifiers(list: Node<'_>) -> Vec<Node<'_>> {
372
+ let mut cursor = list.walk();
373
+ list.named_children(&mut cursor).collect()
374
+ }
375
+
376
+ fn contextual_target_type(type_text: &str) -> Option<String> {
377
+ let mut target = type_text.trim().trim_end_matches('?').trim();
378
+ while let Some(open) = target.find('<') {
379
+ let close = target.rfind('>')?;
380
+ let inner = target.get(open + 1..close)?.trim();
381
+ if has_top_level_comma(inner) {
382
+ return None;
383
+ }
384
+ target = inner.trim_end_matches('?').trim();
385
+ }
386
+ (!target.is_empty()
387
+ && target
388
+ .bytes()
389
+ .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'$' | b'.')))
390
+ .then(|| target.to_owned())
391
+ }
392
+
393
+ fn has_top_level_comma(text: &str) -> bool {
394
+ let mut depth = 0usize;
395
+ for byte in text.bytes() {
396
+ match byte {
397
+ b'<' => depth += 1,
398
+ b'>' => depth = depth.saturating_sub(1),
399
+ b',' if depth == 0 => return true,
400
+ _ => {}
401
+ }
402
+ }
403
+ false
404
+ }
405
+
153
406
  fn is_object_constructor(node: Node<'_>) -> bool {
154
407
  matches!(
155
408
  node.kind(),
@@ -300,32 +553,87 @@ fn render_counts(
300
553
  ) -> BTreeMap<ClassKey, usize> {
301
554
  let superclasses = resolved_superclasses(files, resolver);
302
555
  let mut counts = BTreeMap::<ClassKey, usize>::new();
556
+ let typed_fields = files
557
+ .iter()
558
+ .flat_map(|file| {
559
+ file.typed_fields.iter().map(|field| {
560
+ (
561
+ (
562
+ ClassKey {
563
+ path: file.path.clone(),
564
+ name: field.owner.clone(),
565
+ },
566
+ field.field.clone(),
567
+ ),
568
+ field.target.clone(),
569
+ )
570
+ })
571
+ })
572
+ .collect::<BTreeMap<_, _>>();
303
573
  for file in files {
304
574
  for constructed in &file.object_constructors {
305
- let mut pending = resolver
306
- .resolve(&file.path, constructed)
307
- .into_iter()
308
- .collect::<Vec<_>>();
309
- let mut visited = BTreeSet::new();
310
- while let Some(class) = pending.pop() {
311
- if !visited.insert(class.clone()) {
312
- continue;
313
- }
314
- if candidate_keys.contains(&class) {
315
- *counts.entry(class.clone()).or_default() += 1;
575
+ increment_render_counts(
576
+ resolver.resolve(&file.path, constructed),
577
+ candidate_keys,
578
+ &superclasses,
579
+ &mut counts,
580
+ );
581
+ }
582
+ for contextual in &file.contextual_constructors {
583
+ match contextual {
584
+ ContextualConstructor::NamedArgument {
585
+ owner_constructor,
586
+ argument,
587
+ } => {
588
+ for owner in resolver.resolve(&file.path, owner_constructor) {
589
+ let Some(target) = typed_fields.get(&(owner.clone(), argument.clone()))
590
+ else {
591
+ continue;
592
+ };
593
+ increment_render_counts(
594
+ resolver.resolve(&owner.path, target),
595
+ candidate_keys,
596
+ &superclasses,
597
+ &mut counts,
598
+ );
599
+ }
316
600
  }
317
- pending.extend(
318
- superclasses
319
- .get(&class)
320
- .into_iter()
321
- .flat_map(|parents| parents.iter().cloned()),
322
- );
601
+ ContextualConstructor::TypedInitializer { target } => increment_render_counts(
602
+ resolver.resolve(&file.path, target),
603
+ candidate_keys,
604
+ &superclasses,
605
+ &mut counts,
606
+ ),
323
607
  }
324
608
  }
325
609
  }
326
610
  counts
327
611
  }
328
612
 
613
+ fn increment_render_counts(
614
+ classes: BTreeSet<ClassKey>,
615
+ candidate_keys: &BTreeSet<ClassKey>,
616
+ superclasses: &BTreeMap<ClassKey, BTreeSet<ClassKey>>,
617
+ counts: &mut BTreeMap<ClassKey, usize>,
618
+ ) {
619
+ let mut pending = classes.into_iter().collect::<Vec<_>>();
620
+ let mut visited = BTreeSet::new();
621
+ while let Some(class) = pending.pop() {
622
+ if !visited.insert(class.clone()) {
623
+ continue;
624
+ }
625
+ if candidate_keys.contains(&class) {
626
+ *counts.entry(class.clone()).or_default() += 1;
627
+ }
628
+ pending.extend(
629
+ superclasses
630
+ .get(&class)
631
+ .into_iter()
632
+ .flat_map(|parents| parents.iter().cloned()),
633
+ );
634
+ }
635
+ }
636
+
329
637
  fn resolved_superclasses(
330
638
  files: &[&FileReachabilityFacts],
331
639
  resolver: &DeclarationResolver,