calcit-cli 0.59.1

CLI command handlers, static analysis, diffing, and native FFI host injection for Calcit
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
//! Deprecated API usage analysis for `calcit analyze weak-types --only deprecated-call`.

use std::cell::RefCell;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::fmt::Write;
use std::sync::Arc;

use crate::cli_args::DeprecatedCommand;
use calcit_core::calcit::{Calcit, CalcitSyntax};
use calcit_core::data::cirru::{reader_path_to_source_path, source_path_to_reader_path};
use calcit_core::{program, snapshot};
use cirru_parser::Cirru;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeprecatedApiUse {
  pub path: String,
  pub target_namespace: String,
  pub target_name: String,
  pub target_doc: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeprecatedApiRow {
  pub namespace: String,
  pub definition: String,
  pub uses: Vec<DeprecatedApiUse>,
}

#[derive(Debug, Clone)]
struct DeprecatedTarget {
  doc: String,
}

fn is_selected_namespace(options: &DeprecatedCommand, snapshot: &snapshot::Snapshot, namespace: &str) -> Result<bool, String> {
  if let Some(expected) = &options.ns
    && !snapshot.files.contains_key(expected)
  {
    return Err(format!("Namespace not found: {expected}"));
  }

  if options.ns.as_deref().is_some_and(|expected| namespace != expected) {
    return Ok(false);
  }
  if options.ns_prefix.as_deref().is_some_and(|prefix| !namespace.starts_with(prefix)) {
    return Ok(false);
  }

  let explicit_scope = options.ns.is_some() || options.ns_prefix.is_some();
  if !explicit_scope && namespace.ends_with(".$meta") {
    return Ok(false);
  }
  if options.deps || explicit_scope {
    return Ok(true);
  }

  let package_prefix = format!("{}.", snapshot.package);
  Ok(namespace == snapshot.package || namespace.starts_with(&package_prefix))
}

fn deprecated_targets(snapshot: &snapshot::Snapshot) -> HashMap<(String, String), DeprecatedTarget> {
  let mut targets = HashMap::new();
  for (namespace, file) in &snapshot.files {
    for (definition, entry) in &file.defs {
      if entry.tags.iter().any(|tag| tag.ref_str() == "deprecated") {
        targets.insert((namespace.clone(), definition.clone()), DeprecatedTarget { doc: entry.doc.clone() });
      }
    }
  }
  targets
}

fn push_use(
  uses: &mut Vec<DeprecatedApiUse>,
  targets: &HashMap<(String, String), DeprecatedTarget>,
  namespace: &str,
  definition: &str,
  path: &[usize],
) {
  if let Some(target) = targets.get(&(namespace.to_owned(), definition.to_owned())) {
    uses.push(DeprecatedApiUse {
      path: format_path(path),
      target_namespace: namespace.to_owned(),
      target_name: definition.to_owned(),
      target_doc: target.doc.clone(),
    });
  }
}

fn collect_uses(
  node: &Calcit,
  current_namespace: &str,
  imports: &HashMap<Arc<str>, Arc<program::ImportRule>>,
  targets: &HashMap<(String, String), DeprecatedTarget>,
  definitions: &HashSet<(String, String)>,
  path: &mut Vec<usize>,
  uses: &mut Vec<DeprecatedApiUse>,
) {
  let Calcit::List(items) = node else {
    return;
  };

  // Quoted source is data, not an API invocation or quality-budget debt.
  if matches!(items.first(), Some(Calcit::Syntax(CalcitSyntax::Quote, _)))
    || matches!(items.first(), Some(Calcit::Symbol { sym, .. }) if sym.as_ref() == "quote" || sym.as_ref() == "calcit.core/quote")
  {
    return;
  }

  if let Some(head) = items.first() {
    match head {
      // Reader-resolved builtins have no Symbol/Import node left to inspect.
      Calcit::Proc(proc) => push_use(uses, targets, calcit_core::calcit::CORE_NS, proc.as_ref(), path),
      Calcit::Import(import) => push_use(uses, targets, import.ns.as_ref(), import.def.as_ref(), path),
      Calcit::Symbol { sym, .. } => {
        if let Some((namespace, definition)) = sym.rsplit_once('/') {
          // Candidate discovery must not depend on whether a previous definition prepared the resolver.
          let resolved_namespace = match imports.get(namespace).map(AsRef::as_ref) {
            Some(program::ImportRule::NsAs(target)) => target.as_ref(),
            _ => namespace,
          };
          push_use(uses, targets, resolved_namespace, definition, path);
        } else {
          push_use(uses, targets, current_namespace, sym.as_ref(), path);
          if let Some(program::ImportRule::NsReferDef(imported_namespace, imported_definition)) =
            imports.get(sym.as_ref()).map(AsRef::as_ref)
          {
            push_use(uses, targets, imported_namespace.as_ref(), imported_definition.as_ref(), path);
          } else if !definitions.contains(&(current_namespace.to_owned(), sym.to_string())) {
            push_use(uses, targets, calcit_core::calcit::CORE_NS, sym.as_ref(), path);
          }
        }
      }
      _ => {}
    }
  }

  for (index, item) in items.iter().enumerate() {
    path.push(index);
    collect_uses(item, current_namespace, imports, targets, definitions, path, uses);
    path.pop();
  }
}

fn format_path(path: &[usize]) -> String {
  if path.is_empty() {
    "code".to_owned()
  } else {
    format!("code@{}", path.iter().map(usize::to_string).collect::<Vec<_>>().join("."))
  }
}

fn parse_path(path: &str) -> Option<Vec<usize>> {
  if path == "code" {
    return Some(vec![]);
  }
  path.strip_prefix("code@")?.split('.').map(|index| index.parse().ok()).collect()
}

fn source_node_at<'a>(mut node: &'a Calcit, path: &[usize]) -> Option<&'a Calcit> {
  for index in path {
    let Calcit::List(children) = node else { return None };
    node = children.get(*index)?;
  }
  Some(node)
}

/// Retain reader-resolved proc calls and use the compiler resolver for symbol calls.
/// Failed source proofs keep the existing conservative static report.
fn resolved_function_uses(
  node: &Calcit,
  source: &Cirru,
  namespace: &str,
  definition: &str,
  targets: &HashMap<(String, String), DeprecatedTarget>,
  candidates: &[DeprecatedApiUse],
) -> Option<Vec<DeprecatedApiUse>> {
  let Calcit::List(items) = node else { return None };
  if !matches!(items.first(), Some(Calcit::Symbol { sym, .. }) if sym.as_ref() == "defn") {
    return None;
  }
  let warnings = RefCell::new(vec![]);
  let references = calcit_core::runner::preprocess::trace_source_usages(
    node,
    namespace,
    definition,
    &warnings,
    &calcit_core::call_stack::CallStackList::default(),
  )
  .ok()?;
  let mut uses = candidates
    .iter()
    .filter(|usage| {
      let Some(path) = parse_path(&usage.path) else {
        return false;
      };
      matches!(source_node_at(node, &path), Some(Calcit::List(children)) if matches!(children.first(), Some(Calcit::Proc(_))))
    })
    .cloned()
    .collect::<Vec<_>>();
  for reference in references {
    let Some(location) = reference.location else { continue };
    if location.ns.as_ref() != namespace || location.def.as_ref() != definition {
      continue;
    }
    // Resolver locations are Snapshot source coordinates; candidates use reader paths.
    let source_coord = location.coord.iter().map(|index| usize::from(*index)).collect::<Vec<_>>();
    let Some(mut path) = source_path_to_reader_path(source, &source_coord) else {
      continue;
    };
    // A preferred method may legitimately lower to a legacy internal helper.
    // Only explicit function calls represent legacy source spelling here.
    if !matches!(source_node_at(node, &path), Some(Calcit::Symbol { .. } | Calcit::Import(_))) {
      continue;
    }
    if path.pop() != Some(0) {
      continue;
    }
    push_use(
      &mut uses,
      targets,
      reference.target_ns.as_ref(),
      reference.target_def.as_ref(),
      &path,
    );
  }
  Some(uses)
}

pub fn collect_deprecated_api_rows(
  options: &DeprecatedCommand,
  snapshot: &snapshot::Snapshot,
) -> Result<Vec<DeprecatedApiRow>, String> {
  let targets = deprecated_targets(snapshot);
  let program_data = program::extract_program_data(snapshot)?;
  struct ResolutionGuard(bool);
  impl Drop for ResolutionGuard {
    fn drop(&mut self) {
      calcit_core::runner::preprocess::set_strict_types(self.0);
      let _ = program::clear_runtime_caches_for_reload(Arc::from("analyze.deprecated"), Arc::from("analyze.deprecated"), true);
    }
  }
  let _guard = ResolutionGuard(calcit_core::runner::preprocess::is_strict_types_enabled());
  calcit_core::runner::preprocess::set_strict_types(false);
  // Prepared on first need so an unaffected project never compiles its call graph.
  let mut resolver_state: Option<bool> = None;
  let mut resolver_ready = |needed: bool| -> bool {
    needed && *resolver_state.get_or_insert_with(|| crate::cli_handlers::prepare_program_for_type_query(snapshot).is_ok())
  };
  let definitions = program_data
    .iter()
    .flat_map(|(namespace, file)| {
      file
        .defs
        .keys()
        .map(move |definition| (namespace.to_string(), definition.to_string()))
    })
    .collect::<HashSet<_>>();
  let mut rows = vec![];

  for (namespace, file) in &program_data {
    if !is_selected_namespace(options, snapshot, namespace)? {
      continue;
    }
    for (definition, entry) in &file.defs {
      let source_code = snapshot
        .files
        .get(namespace.as_ref())
        .and_then(|file| file.defs.get(definition.as_ref()))
        .map(|entry| &entry.code);
      let written_code = program::written_source_code_for_attached_def(namespace, definition, &entry.code);
      let inspected_code = written_code.as_ref().unwrap_or(&entry.code);
      let mut uses = vec![];
      collect_uses(
        inspected_code,
        namespace,
        &file.import_map,
        &targets,
        &definitions,
        &mut vec![],
        &mut uses,
      );
      // Do not compile unrelated call graphs merely to confirm an empty report.
      // Their macros may have compile-time effects that a metadata query must not trigger.
      if resolver_ready(!targets.is_empty() && !uses.is_empty())
        && let Some(resolved) =
          source_code.and_then(|source| resolved_function_uses(inspected_code, source, namespace, definition, &targets, &uses))
      {
        uses = resolved;
      }
      // Report Snapshot source paths so `query def` / `tree` address the same node.
      if let Some(source) = source_code {
        for usage in &mut uses {
          if let Some(reader_path) = parse_path(&usage.path)
            && let Some(source_path) = reader_path_to_source_path(source, &reader_path)
          {
            usage.path = format_path(&source_path);
          }
        }
      }
      uses.sort_by(|left, right| {
        left
          .path
          .cmp(&right.path)
          .then(left.target_namespace.cmp(&right.target_namespace))
          .then(left.target_name.cmp(&right.target_name))
      });
      uses.dedup_by(|left, right| {
        left.path == right.path && left.target_namespace == right.target_namespace && left.target_name == right.target_name
      });
      if !uses.is_empty() {
        rows.push(DeprecatedApiRow {
          namespace: namespace.to_string(),
          definition: definition.to_string(),
          uses,
        });
      }
    }
  }

  rows.sort_by(|left, right| left.namespace.cmp(&right.namespace).then(left.definition.cmp(&right.definition)));
  Ok(rows)
}

pub fn format_deprecated_api_report(options: &DeprecatedCommand, snapshot: &snapshot::Snapshot) -> Result<String, String> {
  let rows = collect_deprecated_api_rows(options, snapshot)?;
  let hit_count = rows.iter().map(|row| row.uses.len()).sum::<usize>();
  if rows.is_empty() {
    return Ok("No deprecated API usage found in selected namespace scope.\n".to_owned());
  }

  let mut out = String::new();
  let _ = writeln!(out, "Deprecated API usage check");
  let _ = writeln!(out, "- definitions with hits: {}", rows.len());
  let _ = writeln!(out, "- calls: {hit_count}");
  if !options.summary_only {
    for row in &rows {
      let _ = writeln!(out, "\n{}/{}", row.namespace, row.definition);
      for usage in &row.uses {
        let _ = writeln!(
          out,
          "  - {}: {}/{} is deprecated{}",
          usage.path,
          usage.target_namespace,
          usage.target_name,
          if usage.target_doc.is_empty() {
            String::new()
          } else {
            format!("; {}", usage.target_doc.lines().next().unwrap_or_default())
          }
        );
      }
    }
  }
  let _ = writeln!(
    out,
    "\nMigration: replace deprecated calls with the API named in each target's documentation."
  );
  Ok(out)
}

pub fn format_deprecated_api_json(options: &DeprecatedCommand, snapshot: &snapshot::Snapshot) -> Result<String, String> {
  let rows = collect_deprecated_api_rows(options, snapshot)?;
  let hit_count = rows.iter().map(|row| row.uses.len()).sum::<usize>();
  let namespaces = rows.iter().map(|row| row.namespace.as_str()).collect::<BTreeSet<_>>();
  let targets = rows
    .iter()
    .flat_map(|row| row.uses.iter())
    .map(|usage| format!("{}/{}", usage.target_namespace, usage.target_name))
    .collect::<BTreeSet<_>>();
  let definitions = rows
    .iter()
    .filter(|_| !options.summary_only)
    .map(|row| {
      serde_json::json!({
        "id": format!("{}/{}", row.namespace, row.definition),
        "namespace": row.namespace,
        "name": row.definition,
        "uses": row.uses.iter().map(|usage| serde_json::json!({
          "path": usage.path,
          "target": format!("{}/{}", usage.target_namespace, usage.target_name),
          "documentation": usage.target_doc,
          "suggestion": "Replace this deprecated API using the target documentation.",
        })).collect::<Vec<_>>(),
      })
    })
    .collect::<Vec<_>>();
  let diagnostics = if hit_count == 0 {
    vec![]
  } else {
    vec![serde_json::json!({
      "code": "W_DEPRECATED_API",
      "phase": "analysis",
      "severity": "warning",
      "message": format!("{hit_count} deprecated API call(s) found in {} definition(s).", rows.len()),
      "suggestion": "Replace each call using the migration guidance in the deprecated API documentation.",
    })]
  };
  let envelope = serde_json::json!({
    "schema_version": 1,
    "command": "analyze.deprecated",
    "revision": crate::type_coverage::analysis_revision(
      snapshot,
      &rows.iter().map(|row| (row.namespace.clone(), row.definition.clone())).collect::<Vec<_>>(),
    )?,
    "data": {
      "filters": {
        "namespace": options.ns,
        "namespace_prefix": options.ns_prefix,
        "include_dependencies": options.deps,
        "summary_only": options.summary_only,
      },
      "summary": {
        "namespaces": namespaces.len(),
        "definitions": rows.len(),
        "calls": hit_count,
        "targets": targets.into_iter().collect::<Vec<_>>(),
      },
      "definitions": definitions,
    },
    "diagnostics": diagnostics,
  });
  serde_json::to_string_pretty(&envelope).map_err(|error| format!("Failed to encode deprecated API JSON: {error}"))
}

#[cfg(test)]
mod tests {
  use super::*;
  use calcit_core::data::cirru::code_to_calcit;

  #[test]
  fn finds_implicit_core_deprecated_call_at_body_path() {
    let expression = cirru_parser::parse("defn demo () $ record? nil")
      .expect("parse expression")
      .into_iter()
      .next()
      .expect("one expression");
    let code = code_to_calcit(&expression, "app.main", "demo", vec![]).expect("convert expression");
    let targets = HashMap::from([(
      (calcit_core::calcit::CORE_NS.to_owned(), "record?".to_owned()),
      DeprecatedTarget {
        doc: "Replace with struct?.".to_owned(),
      },
    )]);
    let mut uses = vec![];

    collect_uses(
      &code,
      "app.main",
      &HashMap::new(),
      &targets,
      &HashSet::new(),
      &mut vec![],
      &mut uses,
    );

    assert_eq!(uses.len(), 1);
    assert_eq!(uses[0].path, "code@3");
    assert_eq!(uses[0].target_namespace, calcit_core::calcit::CORE_NS);
    assert_eq!(uses[0].target_name, "record?");
  }

  #[test]
  fn ignores_core_deprecated_call_shadowed_by_local_definition() {
    let expression = cirru_parser::parse("defn demo () $ record? nil")
      .expect("parse expression")
      .into_iter()
      .next()
      .expect("one expression");
    let code = code_to_calcit(&expression, "app.main", "demo", vec![]).expect("convert expression");
    let targets = HashMap::from([(
      (calcit_core::calcit::CORE_NS.to_owned(), "record?".to_owned()),
      DeprecatedTarget {
        doc: "Replace with struct?.".to_owned(),
      },
    )]);
    let definitions = HashSet::from([("app.main".to_owned(), "record?".to_owned())]);
    let mut uses = vec![];

    collect_uses(&code, "app.main", &HashMap::new(), &targets, &definitions, &mut vec![], &mut uses);

    assert!(uses.is_empty());
  }

  #[test]
  fn finds_deprecated_call_inside_list_valued_callee() {
    let expression = cirru_parser::parse("defn demo () $ (record? nil)")
      .expect("parse expression")
      .into_iter()
      .next()
      .expect("one expression");
    let code = code_to_calcit(&expression, "app.main", "demo", vec![]).expect("convert expression");
    let targets = HashMap::from([(
      (calcit_core::calcit::CORE_NS.to_owned(), "record?".to_owned()),
      DeprecatedTarget {
        doc: "Replace with struct?.".to_owned(),
      },
    )]);
    let mut uses = vec![];

    collect_uses(
      &code,
      "app.main",
      &HashMap::new(),
      &targets,
      &HashSet::new(),
      &mut vec![],
      &mut uses,
    );

    assert_eq!(uses.len(), 1);
    assert_eq!(uses[0].target_name, "record?");
  }

  #[test]
  fn distinguishes_reader_resolved_builtin_calls_from_quoted_data() {
    let expression = cirru_parser::parse("defn demo () (remove-watch *r :k) (quote (remove-watch *r :k))")
      .expect("parse expression")
      .into_iter()
      .next()
      .expect("one expression");
    let code = code_to_calcit(&expression, "app.main", "demo", vec![]).expect("convert expression");
    let targets = HashMap::from([(
      (calcit_core::calcit::CORE_NS.to_owned(), "remove-watch".to_owned()),
      DeprecatedTarget {
        doc: "Prefer remove-watch!.".to_owned(),
      },
    )]);
    let mut uses = vec![];
    collect_uses(
      &code,
      "app.main",
      &HashMap::new(),
      &targets,
      &HashSet::new(),
      &mut vec![],
      &mut uses,
    );
    assert_eq!(uses.len(), 1);
    assert_eq!(uses[0].path, "code@3");
    assert_eq!(uses[0].target_name, "remove-watch");
  }

  #[test]
  fn finds_imported_candidates_without_preparing_global_program_data() {
    let expression = cirru_parser::parse("defn demo () (compat/old-api nil) (old-referred nil)")
      .expect("parse expression")
      .into_iter()
      .next()
      .expect("one expression");
    let code = code_to_calcit(&expression, "isolated.imports", "demo", vec![]).expect("convert expression");
    let imports = HashMap::from([
      (Arc::from("compat"), Arc::new(program::ImportRule::NsAs(Arc::from("legacy.api")))),
      (
        Arc::from("old-referred"),
        Arc::new(program::ImportRule::NsReferDef(Arc::from("legacy.api"), Arc::from("old-api"))),
      ),
    ]);
    let targets = HashMap::from([(
      ("legacy.api".to_owned(), "old-api".to_owned()),
      DeprecatedTarget { doc: String::new() },
    )]);
    let mut uses = vec![];

    collect_uses(
      &code,
      "isolated.imports",
      &imports,
      &targets,
      &HashSet::new(),
      &mut vec![],
      &mut uses,
    );

    assert_eq!(uses.len(), 2);
    assert_eq!(uses[0].path, "code@3");
    assert_eq!(uses[1].path, "code@4");
    assert!(
      uses
        .iter()
        .all(|usage| usage.target_namespace == "legacy.api" && usage.target_name == "old-api")
    );
  }

  #[test]
  fn skips_compiler_generated_impl_traits_while_reporting_handwritten_calls() {
    let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|err| err.into_inner());
    let mut snapshot = calcit_core::load_core_snapshot().expect("embedded core");
    snapshot.package = "tests".to_owned();
    let ns = "tests.deprecated-synthetic-impl-traits";

    let parse_one = |src: &str| {
      cirru_parser::parse(src)
        .expect("parse expression")
        .into_iter()
        .next()
        .expect("one expression")
    };
    let entry = |src: &str| snapshot::CodeEntry {
      doc: String::new(),
      examples: vec![],
      tests: vec![],
      code: parse_one(src),
      schema: Arc::new(calcit_core::calcit::CalcitTypeAnnotation::Dynamic),
      tags: Default::default(),
      ffi: None,
    };

    snapshot.files.insert(
      ns.to_owned(),
      snapshot::FileInSnapShot {
        ns: snapshot::NsEntry {
          doc: String::new(),
          code: parse_one(&format!("ns {ns}")),
        },
        defs: HashMap::from([
          ("ShowTrait".to_owned(), entry("deftrait ShowTrait\n  .show $ Fn Self (-> String)")),
          (
            "CanonicalBox".to_owned(),
            entry("defstruct CanonicalBox (:n Number) (:impls ShowTrait)"),
          ),
          (
            "CanonicalBoxImpl".to_owned(),
            entry("defimpl CanonicalBox ShowTrait\n  .show $ fn (self) |ok"),
          ),
          (
            "OldHelper".to_owned(),
            snapshot::CodeEntry {
              tags: HashSet::from([cirru_edn::EdnTag::new("deprecated")]),
              ..entry("defn old-helper () 1")
            },
          ),
          ("DeprecatedCaller".to_owned(), entry("def DeprecatedCaller $ OldHelper")),
        ]),
      },
    );

    let targets = deprecated_targets(&snapshot);
    let program_data = program::extract_program_data(&snapshot).expect("extract program data");
    let file = program_data.get(ns).expect("test namespace present");
    let definitions = program_data
      .iter()
      .flat_map(|(namespace, f)| f.defs.keys().map(move |def| (namespace.to_string(), def.to_string())))
      .collect::<HashSet<_>>();

    let canonical = file.defs.get("CanonicalBox").expect("CanonicalBox entry");
    let written = program::written_source_code_for_attached_def(ns, "CanonicalBox", &canonical.code)
      .expect("canonical (:impls ...) should recover pre-attachment code");
    let mut canonical_uses = vec![];
    collect_uses(
      &written,
      ns,
      &file.import_map,
      &targets,
      &definitions,
      &mut vec![],
      &mut canonical_uses,
    );
    assert!(
      canonical_uses.is_empty(),
      "expected 0 uses for CanonicalBox, got {canonical_uses:?}"
    );

    let caller = file.defs.get("DeprecatedCaller").expect("DeprecatedCaller entry");
    assert!(
      program::written_source_code_for_attached_def(ns, "DeprecatedCaller", &caller.code).is_none(),
      "ordinary def must not be masked by WRITTEN_CODE"
    );
    let mut legacy_uses = vec![];
    collect_uses(
      &caller.code,
      ns,
      &file.import_map,
      &targets,
      &definitions,
      &mut vec![],
      &mut legacy_uses,
    );
    assert_eq!(legacy_uses.len(), 1);
    assert_eq!(legacy_uses[0].target_name, "OldHelper");
  }
}