Skip to main content

calcit_cli/
type_coverage.rs

1//! Type coverage and weak-type analysis for `calcit analyze`.
2#![allow(dead_code)]
3
4use calcit_core::calcit::NullableOrigin;
5use std::borrow::Cow;
6use std::cell::RefCell;
7use std::collections::{BTreeMap, BTreeSet};
8use std::fmt::Write;
9use std::sync::Arc;
10
11use crate::cli_args::{CheckTypesCommand, WeakTypesCommand};
12use calcit_core::calcit::{
13  CalcitProc, CalcitSyntax, CalcitTypeAnnotation, MacroExpansionType, MacroSyntaxType, ParamShape, ParamShapeToken, ProcTypeSignature,
14  SchemaKind, SyntaxTypeSignature, resolve_type_slot, validate_definition_schema_shape,
15};
16use calcit_core::snapshot;
17use cirru_parser::Cirru;
18use md5::{Digest, Md5};
19
20use crate::cli_handlers::fix::schema_synthesis::{SchemaEvidenceCandidate, collect_schema_evidence_candidates};
21
22pub mod inferred_dynamic;
23pub mod legacy_migration;
24pub mod option_nil_roundtrip;
25
26/// Analyze compiler-proven absent contracts without changing source declarations.
27/// Failed proofs retain their original coverage; explicit Dynamic is never inferred.
28pub fn with_proven_helper_contracts<'a>(
29  snapshot: &'a snapshot::Snapshot,
30  namespace: Option<&str>,
31  namespace_prefix: Option<&str>,
32  include_dependencies: bool,
33) -> Result<Cow<'a, snapshot::Snapshot>, String> {
34  let targets = scoped_definition_entries(snapshot, namespace, namespace_prefix, include_dependencies)?
35    .into_iter()
36    .filter(|(_, _, entry)| {
37      snapshot::schema_annotation_is_missing(&entry.schema)
38        && matches!(&entry.code, Cirru::List(items) if matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "defn"))
39    })
40    .map(|(ns, def, _)| (ns.to_owned(), def.to_owned()))
41    .collect::<Vec<_>>();
42  let mut effective = Cow::Borrowed(snapshot);
43  if targets.is_empty() {
44    return Ok(effective);
45  }
46  struct StrictGuard(bool);
47  impl Drop for StrictGuard {
48    fn drop(&mut self) {
49      calcit_core::runner::preprocess::set_strict_types(self.0);
50      // A later analysis may compile with different strictness. Compiled
51      // definitions do not encode that mode or replay their diagnostics.
52      let _ = calcit_core::program::clear_runtime_caches_for_reload(Arc::from("query.type"), Arc::from("query.type"), true);
53    }
54  }
55  let _guard = StrictGuard(calcit_core::runner::preprocess::is_strict_types_enabled());
56  calcit_core::runner::preprocess::set_strict_types(true);
57  if crate::cli_handlers::prepare_program_for_type_query(snapshot).is_err() {
58    return Ok(effective);
59  }
60  for (namespace, definition) in targets {
61    let warnings = RefCell::new(vec![]);
62    let result = calcit_core::runner::preprocess::compile_source_def_for_snapshot(
63      &namespace,
64      &definition,
65      &warnings,
66      &calcit_core::call_stack::CallStackList::default(),
67    );
68    if result.is_err() || !warnings.borrow().is_empty() {
69      // Cached compiled definitions do not replay diagnostics. Discard a failed
70      // proof's cache before another target can reuse its dependencies as evidence.
71      if crate::cli_handlers::prepare_program_for_type_query(snapshot).is_err() {
72        break;
73      }
74      continue;
75    }
76    if let Some(schema) = calcit_core::program::lookup_compiled_def(&namespace, &definition)
77      .and_then(|compiled| calcit_core::runner::preprocess::infer_static_type_from_expr(&compiled.preprocessed_code))
78      .filter(|schema| matches!(schema.as_ref(), CalcitTypeAnnotation::Fn(_)))
79    {
80      effective
81        .to_mut()
82        .files
83        .get_mut(&namespace)
84        .expect("scoped namespace")
85        .defs
86        .get_mut(&definition)
87        .expect("scoped definition")
88        .schema = schema;
89    }
90  }
91  Ok(effective)
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
95#[serde(rename_all = "kebab-case")]
96pub enum DefKind {
97  Data,
98  Fn,
99  Macro,
100  Proc,
101  Syntax,
102  Other,
103}
104
105impl DefKind {
106  pub fn as_str(self) -> &'static str {
107    match self {
108      DefKind::Data => "data",
109      DefKind::Fn => "fn",
110      DefKind::Macro => "macro",
111      DefKind::Proc => "proc",
112      DefKind::Syntax => "syntax",
113      DefKind::Other => "other",
114    }
115  }
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
119#[serde(rename_all = "kebab-case")]
120pub enum CoverageLevel {
121  None,
122  Partial,
123  Full,
124}
125
126impl CoverageLevel {
127  pub fn as_str(self) -> &'static str {
128    match self {
129      CoverageLevel::None => "none",
130      CoverageLevel::Partial => "partial",
131      CoverageLevel::Full => "full",
132    }
133  }
134}
135
136#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
137pub struct TypeCoverageRow {
138  pub ns: String,
139  pub def: String,
140  pub kind: DefKind,
141  pub level: CoverageLevel,
142  pub params: Vec<String>,
143  pub param_annotations: BTreeMap<String, Vec<String>>,
144  pub return_type_hints: Vec<String>,
145  pub generics: Vec<String>,
146  pub where_bounds: Vec<String>,
147  pub data_type: Option<String>,
148  pub schema_issues: Vec<String>,
149}
150
151fn fn_polymorphism(fn_annot: &calcit_core::calcit::CalcitFnTypeAnnotation) -> (Vec<String>, Vec<String>) {
152  let generics = fn_annot.generics.iter().map(|name| format!("'{name}")).collect();
153  let where_bounds = fn_annot.where_bounds.iter().map(|bound| bound.to_brief_string()).collect();
154  (generics, where_bounds)
155}
156
157fn unwrap_singleton_group(mut node: &Cirru) -> &Cirru {
158  while let Cirru::List(items) = node
159    && items.len() == 1
160    && matches!(items.first(), Some(Cirru::List(_)))
161  {
162    node = &items[0];
163  }
164  node
165}
166
167fn is_cirru_list_head(node: &Cirru) -> bool {
168  matches!(node, Cirru::Leaf(head) if head.as_ref() == "[]")
169}
170
171/// `T` or `'T`: an uppercase name with at most one leading quote.
172fn is_type_variable_leaf(name: &str) -> bool {
173  let bare = name.strip_prefix('\'').unwrap_or(name);
174  bare.chars().next().is_some_and(|c| c.is_ascii_uppercase())
175}
176
177fn entry_polymorphism(entry: &snapshot::CodeEntry) -> (Vec<String>, Vec<String>) {
178  if let CalcitTypeAnnotation::Fn(fn_annot) = entry.schema.as_ref() {
179    return fn_polymorphism(fn_annot);
180  }
181  if let CalcitTypeAnnotation::Macro(signature) = entry.schema.as_ref() {
182    return (
183      signature.generics.iter().map(|name| format!("'{name}")).collect(),
184      signature.where_bounds.iter().map(|bound| bound.to_brief_string()).collect(),
185    );
186  }
187
188  let Cirru::List(items) = &entry.code else {
189    return (vec![], vec![]);
190  };
191  if !matches!(items.first(), Some(Cirru::Leaf(head)) if matches!(head.as_ref(), "defstruct" | "defenum")) {
192    return (vec![], vec![]);
193  }
194
195  // `(:generics T …)` and `(:where (T Debug) …)` clauses (#2700).
196  if let Some(Cirru::List(clause)) = items.get(2)
197    && matches!(clause.first(), Some(Cirru::Leaf(head)) if head.as_ref() == ":generics")
198  {
199    let generics = clause
200      .iter()
201      .skip(1)
202      .filter_map(|item| match item {
203        Cirru::Leaf(name) => Some(format!("'{}", name.trim_start_matches('\''))),
204        _ => None,
205      })
206      .collect();
207    let where_bounds = match items.get(3) {
208      Some(Cirru::List(clause)) if matches!(clause.first(), Some(Cirru::Leaf(head)) if head.as_ref() == ":where") => {
209        clause.iter().skip(1).map(render_cirru_inline).collect()
210      }
211      _ => vec![],
212    };
213    return (generics, where_bounds);
214  }
215  let generics = match items.get(2) {
216    // Generic parameters are written `[] T` or the older `[] 'T`.
217    Some(Cirru::List(vars))
218      if vars.iter().any(|item| !is_cirru_list_head(item))
219        && vars
220          .iter()
221          .all(|item| is_cirru_list_head(item) || matches!(item, Cirru::Leaf(name) if is_type_variable_leaf(name))) =>
222    {
223      vars
224        .iter()
225        .filter(|item| !is_cirru_list_head(item))
226        .filter_map(|item| match item {
227          Cirru::Leaf(name) => Some(format!("'{}", name.trim_start_matches('\''))),
228          _ => None,
229        })
230        .collect()
231    }
232    _ => vec![],
233  };
234  let where_bounds = items
235    .iter()
236    .skip(3)
237    .find_map(|item| match unwrap_singleton_group(item) {
238      Cirru::List(parts) if matches!(parts.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "{}") => {
239        Some(parts.iter().skip(1).map(render_cirru_inline).collect::<Vec<_>>())
240      }
241      _ => None,
242    })
243    .unwrap_or_default();
244  (generics, where_bounds)
245}
246
247#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
248#[serde(rename_all = "kebab-case")]
249pub enum WeakTypeKind {
250  SchemaDynamic,
251  /// `AnyFn` / `AnyStruct` / `AnyEnum` in a written schema (#2976).
252  SchemaOpen,
253  UnresolvedTypeSlot,
254  CodeDynamic,
255  CodeNil,
256  UnsafeCoerce,
257  /// `Dynamic` in a struct field, enum payload or union member. Reported only
258  /// when selected with `--only data-dynamic`, so default reports and existing
259  /// gates keep their counts.
260  DataDynamic,
261}
262
263impl WeakTypeKind {
264  pub fn as_str(&self) -> &'static str {
265    match self {
266      Self::SchemaDynamic => "schema-dynamic",
267      Self::SchemaOpen => "schema-open",
268      Self::UnresolvedTypeSlot => "unresolved-type-slot",
269      Self::CodeDynamic => "code-dynamic",
270      Self::CodeNil => "code-nil",
271      Self::UnsafeCoerce => "unsafe-coerce",
272      Self::DataDynamic => "data-dynamic",
273    }
274  }
275
276  /// Every kind the analysis records. `all()` is the default filter and leaves
277  /// out the opt-in `data-dynamic` kind.
278  pub fn collected() -> BTreeSet<Self> {
279    let mut kinds = Self::all();
280    kinds.insert(Self::DataDynamic);
281    kinds
282  }
283
284  pub fn all() -> BTreeSet<Self> {
285    BTreeSet::from([
286      Self::SchemaDynamic,
287      Self::SchemaOpen,
288      Self::UnresolvedTypeSlot,
289      Self::CodeDynamic,
290      Self::CodeNil,
291      Self::UnsafeCoerce,
292    ])
293  }
294}
295
296#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
297#[serde(rename_all = "kebab-case")]
298pub enum WeakTypeIntent {
299  Unresolved,
300  IntentionalJsFfi,
301  /// Dynamic in a `:js-ffi` function at a position that never reaches a host
302  /// operation, such as Calcit props, states or callbacks passed through.
303  JsFfiNonHost,
304  IntentionalMacroSyntax,
305  IntentionalTypeSlotDynamic,
306  /// Dynamic input of a function whose schema declares `:decode-boundary`:
307  /// a reviewed place that checks open data into a concrete type.
308  IntentionalDecode,
309  /// Dynamic inside a `Fn` schema that states why it stays open with
310  /// `(:open :reflect|:decode|:host)`, or a calcit.core signature marked
311  /// `(:open :intrinsic)` whose types the checker decides with a built-in rule.
312  IntentionalOpen,
313  ExplicitUnsafe,
314  DeclaredUnit,
315}
316
317impl WeakTypeIntent {
318  pub fn as_str(self) -> &'static str {
319    match self {
320      Self::Unresolved => "unresolved",
321      Self::IntentionalJsFfi => "intentional-js-ffi",
322      Self::JsFfiNonHost => "js-ffi-non-host",
323      Self::IntentionalMacroSyntax => "intentional-macro-syntax",
324      Self::IntentionalTypeSlotDynamic => "intentional-type-slot-dynamic",
325      Self::IntentionalDecode => "intentional-decode",
326      Self::IntentionalOpen => "intentional-open",
327      Self::ExplicitUnsafe => "explicit-unsafe",
328      Self::DeclaredUnit => "declared-unit",
329    }
330  }
331
332  pub fn all() -> BTreeSet<Self> {
333    BTreeSet::from([
334      Self::Unresolved,
335      Self::IntentionalJsFfi,
336      Self::JsFfiNonHost,
337      Self::IntentionalMacroSyntax,
338      Self::IntentionalTypeSlotDynamic,
339      Self::IntentionalDecode,
340      Self::IntentionalOpen,
341      Self::ExplicitUnsafe,
342      Self::DeclaredUnit,
343    ])
344  }
345}
346
347#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
348pub struct WeakTypeOccurrence {
349  pub kind: WeakTypeKind,
350  pub intent: WeakTypeIntent,
351  pub detail: String,
352  pub path: String,
353  pub unsafe_evidence: Option<UnsafeCoerceEvidence>,
354}
355
356/// Static evidence attached only to an explicit `unsafe-coerce` boundary.
357/// It intentionally describes source *form*, not an inferred host value type:
358/// `analyze weak-types` reads a Snapshot and never executes the program.
359#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
360pub struct UnsafeCoerceEvidence {
361  pub source_form: String,
362  pub target_schema: String,
363  pub js_ffi_feature: bool,
364  pub raw_adapter_namespace: bool,
365}
366
367#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
368pub struct WeakTypeRow {
369  pub ns: String,
370  pub def: String,
371  pub occurrences: Vec<WeakTypeOccurrence>,
372}
373
374#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
375pub(crate) struct MapShapeFieldCandidate {
376  name: String,
377  observed_types: Vec<String>,
378}
379
380#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
381pub(crate) struct MapShapeCandidate {
382  diagnostic_code: &'static str,
383  suggested_name: String,
384  confidence: &'static str,
385  fields: Vec<MapShapeFieldCandidate>,
386  evidence_paths: Vec<String>,
387  contract_status: &'static str,
388}
389
390#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
391pub(crate) struct DispatchCandidate {
392  diagnostic_code: &'static str,
393  suggested_name: String,
394  confidence: &'static str,
395  variants: Vec<String>,
396  evidence_paths: Vec<String>,
397  contract_status: &'static str,
398}
399
400#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
401pub(crate) struct StructuralCandidates {
402  pub map_shapes: Vec<MapShapeCandidate>,
403  pub dispatch: Vec<DispatchCandidate>,
404}
405
406#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
407pub struct FfiBoundaryOperation {
408  pub kind: String,
409  pub classification: String,
410  pub source: String,
411  pub member: Option<String>,
412  pub path: String,
413  pub nullable_evidence: String,
414}
415
416#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
417pub struct FfiHelperCandidate {
418  pub definition: String,
419  pub origin: String,
420  pub compatibility: String,
421  pub target: String,
422}
423
424#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
425pub struct FfiTraitCandidate {
426  pub receiver: String,
427  pub suggested_name: String,
428  pub fields: Vec<String>,
429  pub methods: Vec<String>,
430  pub contract_status: String,
431  /// Paste-ready `defexternal` starting point; payload types stay `Dynamic`
432  /// placeholders until a reviewer refines the contract.
433  pub defexternal_skeleton: String,
434}
435
436#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
437pub struct FfiAdapterCandidate {
438  pub source: String,
439  pub suggested_definition: String,
440  pub schema_cirru_edn: String,
441  pub contract_status: String,
442}
443
444#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
445pub struct FfiBoundaryEvidence {
446  pub diagnostic_code: String,
447  pub definition: String,
448  pub classification: String,
449  pub target: String,
450  pub js_ffi_feature: bool,
451  pub raw_adapter_namespace: bool,
452  pub operations: Vec<FfiBoundaryOperation>,
453  pub unsafe_paths: Vec<String>,
454  pub callers: Vec<String>,
455  pub helper_candidates: Vec<FfiHelperCandidate>,
456  pub trait_candidates: Vec<FfiTraitCandidate>,
457  pub adapter_candidates: Vec<FfiAdapterCandidate>,
458  pub provenance: Vec<String>,
459}
460
461#[derive(Debug, Clone, PartialEq, Eq)]
462struct FfiImportBinding {
463  source: String,
464  member: Option<String>,
465}
466
467fn schema_has_js_ffi(schema: &CalcitTypeAnnotation) -> bool {
468  match schema {
469    CalcitTypeAnnotation::Fn(annotation) => annotation.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
470    CalcitTypeAnnotation::Macro(annotation) => annotation.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
471    _ => false,
472  }
473}
474
475fn ffi_import_bindings(code: &Cirru, namespace: &str) -> Result<BTreeMap<String, FfiImportBinding>, String> {
476  use calcit_core::program::ImportRule;
477
478  Ok(
479    calcit_core::program::extract_import_map(code, namespace)?
480      .into_iter()
481      .filter_map(|(local, rule)| {
482        // Default imports are JS bindings; aliases/references need a string
483        // module origin, just as preprocessing and JS emission require.
484        let (source, member) = match rule.as_ref() {
485          ImportRule::NsDefault(source) => (source, Some("default".to_owned())),
486          ImportRule::NsAs(source) if source.starts_with(['|', '"']) => (source, None),
487          ImportRule::NsReferDef(source, member) if source.starts_with(['|', '"']) => (source, Some(member.to_string())),
488          _ => return None,
489        };
490        Some((
491          local.to_string(),
492          FfiImportBinding {
493            source: source.trim_start_matches(['|', '"']).to_owned(),
494            member,
495          },
496        ))
497      })
498      .collect(),
499  )
500}
501
502fn ffi_member_operation(head: &str) -> Option<(&'static str, &'static str, bool)> {
503  if head.starts_with(".?!") {
504    Some(("optional-method-call", ".?!", true))
505  } else if head.starts_with(".?-") {
506    Some(("optional-field-read", ".?-", true))
507  } else if head.starts_with(".!") {
508    Some(("method-call", ".!", false))
509  } else if head.starts_with(".-") {
510    Some(("field-read", ".-", false))
511  } else {
512    None
513  }
514}
515
516fn ffi_postfix_operation(head: &str) -> Option<(String, String, &'static str, bool)> {
517  for (marker, kind, optional) in [
518    (".?!", "optional-method-call", true),
519    (".?-", "optional-field-read", true),
520    (".!", "method-call", false),
521    (".-", "field-read", false),
522  ] {
523    if let Some((receiver, member)) = head.split_once(marker)
524      && !receiver.is_empty()
525      && !member.is_empty()
526    {
527      return Some((receiver.to_owned(), member.to_owned(), kind, optional));
528    }
529  }
530  None
531}
532
533fn ffi_classification(source: &str, import_source: Option<&str>, target: Option<snapshot::SnapshotTarget>) -> &'static str {
534  let lowered = format!("{} {}", source, import_source.unwrap_or_default()).to_ascii_lowercase();
535  if lowered.contains("webgpu")
536    || lowered.contains("navigator.gpu")
537    || lowered
538      .split(|character: char| !character.is_ascii_alphanumeric())
539      .any(|part| part == "gpu")
540  {
541    "webgpu"
542  } else if import_source.is_some() {
543    let package = import_source.unwrap_or_default().trim_start_matches("node:");
544    if matches!(
545      package,
546      "assert"
547        | "buffer"
548        | "child_process"
549        | "crypto"
550        | "events"
551        | "fs"
552        | "http"
553        | "https"
554        | "os"
555        | "path"
556        | "process"
557        | "stream"
558        | "url"
559        | "util"
560    ) {
561      "node"
562    } else {
563      "npm-import"
564    }
565  } else if [
566    "js/window",
567    "js/document",
568    "js/navigator",
569    "js/location",
570    "js/localstorage",
571    "js/sessionstorage",
572  ]
573  .iter()
574  .any(|prefix| lowered.contains(prefix))
575  {
576    "browser"
577  } else if ["js/process", "js/buffer", "js/global", "js/__dirname", "js/__filename"]
578    .iter()
579    .any(|prefix| lowered.contains(prefix))
580  {
581    "node"
582  } else {
583    match target {
584      Some(snapshot::SnapshotTarget::Browser) => "browser",
585      Some(snapshot::SnapshotTarget::Node) => "node",
586      _ => "unknown-host",
587    }
588  }
589}
590
591fn push_ffi_operation(
592  operations: &mut Vec<FfiBoundaryOperation>,
593  kind: &str,
594  source: String,
595  member: Option<String>,
596  path: &[usize],
597  optional: bool,
598) {
599  operations.push(FfiBoundaryOperation {
600    kind: kind.to_owned(),
601    classification: "unknown-host".to_owned(),
602    source,
603    member,
604    path: format_cirru_path("code", path),
605    nullable_evidence: if optional { "optional-access" } else { "not-proven" }.to_owned(),
606  });
607}
608
609fn scan_ffi_operations(
610  node: &Cirru,
611  path: &mut Vec<usize>,
612  quote_context: QuoteContext,
613  imports: &BTreeMap<String, FfiImportBinding>,
614  operations: &mut Vec<FfiBoundaryOperation>,
615) {
616  let Cirru::List(items) = node else {
617    return;
618  };
619  let head = items.first().and_then(|item| match item {
620    Cirru::Leaf(value) => Some(value.as_ref()),
621    _ => None,
622  });
623  if !quote_context.is_quoted()
624    && let Some(head) = head
625  {
626    if head.starts_with("js/") {
627      push_ffi_operation(operations, "raw-js-call", head.to_owned(), None, path, false);
628    } else if head == "unsafe-coerce" {
629      let source = items
630        .get(1)
631        .map(render_cirru_inline)
632        .unwrap_or_else(|| "<missing-value>".to_owned());
633      push_ffi_operation(operations, "unsafe-coerce", source, None, path, false);
634    } else if let Some((kind, marker, optional)) = ffi_member_operation(head) {
635      let receiver = items
636        .get(1)
637        .map(render_cirru_inline)
638        .unwrap_or_else(|| "<missing-receiver>".to_owned());
639      push_ffi_operation(
640        operations,
641        kind,
642        receiver,
643        Some(head.trim_start_matches(marker).to_owned()),
644        path,
645        optional,
646      );
647    } else if let Some((receiver, member, kind, optional)) = ffi_postfix_operation(head) {
648      push_ffi_operation(operations, kind, receiver, Some(member), path, optional);
649    } else if matches!(head, "aget" | "aset" | "js-get" | "js-set") {
650      let receiver = items
651        .get(1)
652        .map(render_cirru_inline)
653        .unwrap_or_else(|| "<missing-receiver>".to_owned());
654      let member = items.get(2).map(render_cirru_inline);
655      push_ffi_operation(operations, head, receiver, member, path, false);
656    } else if let Some((binding, export)) = head.split_once('/')
657      && imports.contains_key(binding)
658    {
659      push_ffi_operation(
660        operations,
661        "module-call",
662        format!("{binding}/{export}"),
663        Some(export.to_owned()),
664        path,
665        false,
666      );
667    } else if let Some(member) = imports.get(head).and_then(|binding| binding.member.as_ref()) {
668      push_ffi_operation(operations, "module-call", head.to_owned(), Some(member.to_owned()), path, false);
669    }
670  }
671  for (index, child) in items.iter().enumerate() {
672    path.push(index);
673    scan_ffi_operations(child, path, quote_context.for_child(head, index), imports, operations);
674    path.pop();
675  }
676}
677
678fn code_calls_definition(code: &Cirru, caller_namespace: &str, namespace: &str, definition: &str) -> bool {
679  fn visit(node: &Cirru, caller_namespace: &str, namespace: &str, definition: &str, quote_context: QuoteContext) -> bool {
680    let Cirru::List(items) = node else {
681      return false;
682    };
683    let head = items.first().and_then(|item| match item {
684      Cirru::Leaf(value) => Some(value.as_ref()),
685      _ => None,
686    });
687    if !quote_context.is_quoted()
688      && head.is_some_and(|head| {
689        (caller_namespace == namespace && head == definition) || head == format!("{namespace}/{definition}").as_str()
690      })
691    {
692      return true;
693    }
694    items
695      .iter()
696      .enumerate()
697      .any(|(index, item)| visit(item, caller_namespace, namespace, definition, quote_context.for_child(head, index)))
698  }
699
700  visit(code, caller_namespace, namespace, definition, QuoteContext::default())
701}
702
703fn ffi_target_name(entry: &snapshot::CodeEntry, fallback: Option<snapshot::SnapshotTarget>) -> Result<String, String> {
704  let target = entry
705    .ffi
706    .as_ref()
707    .map(snapshot::parse_ffi_target)
708    .transpose()?
709    .flatten()
710    .or(fallback);
711  Ok(
712    target
713      .map(|target| target.as_str().to_owned())
714      .unwrap_or_else(|| "unspecified".to_owned()),
715  )
716}
717
718fn selected_js_implementation(
719  ns: &str,
720  entry: &snapshot::CodeEntry,
721) -> Result<Option<calcit_core::js_ffi_source::JsFfiImplementation>, String> {
722  entry
723    .ffi
724    .as_ref()
725    .map(|ffi| calcit_core::js_ffi_source::validate_js_source_in(ffi, &entry.schema, ns))
726    .transpose()
727    .map(Option::flatten)
728}
729
730fn schema_cirru_edn(schema: &CalcitTypeAnnotation) -> Result<String, String> {
731  cirru_edn::format(&snapshot::schema_annotation_to_edn(schema), true)
732    .map_err(|error| format!("Failed to render FFI adapter schema: {error}"))
733}
734
735fn suggested_trait_name(definition: &str) -> String {
736  let mut out = String::new();
737  let mut uppercase = true;
738  for character in definition.chars() {
739    if character.is_ascii_alphanumeric() {
740      if uppercase {
741        out.extend(character.to_uppercase());
742        uppercase = false;
743      } else {
744        out.push(character);
745      }
746    } else {
747      uppercase = true;
748    }
749  }
750  if out.is_empty() {
751    "HostBoundary".to_owned()
752  } else if out.ends_with("Host") {
753    out
754  } else {
755    format!("{out}Host")
756  }
757}
758
759/// Whether a detected host member can be written as a Calcit `defexternal`
760/// field tag or method symbol. Index/string keys from raw `aget`/`js-get`
761/// operations are not expressible as trait members.
762fn is_defexternal_member_name(name: &str) -> bool {
763  let mut chars = name.chars();
764  let Some(first) = chars.next() else {
765    return false;
766  };
767  if !(first.is_ascii_alphabetic() || first == '_') {
768    return false;
769  }
770  name
771    .chars()
772    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '?' | '!' | '*' | '<' | '>' | '=' | '+' | '-' | '/'))
773}
774
775/// Build a paste-ready `defexternal` starting point for a detected host boundary.
776/// Field and method payload types are unknown from member access alone, so the
777/// skeleton keeps `Dynamic` placeholders and stays review-required; callers must
778/// refine the contract before it can pass a strict quality gate. Returns an empty
779/// string when no detected member is expressible as a trait member.
780fn defexternal_skeleton(name: &str, target: &str, fields: &[String], methods: &[String]) -> String {
781  let fields: Vec<&String> = fields.iter().filter(|field| is_defexternal_member_name(field)).collect();
782  let methods: Vec<&String> = methods.iter().filter(|method| is_defexternal_member_name(method)).collect();
783  if fields.is_empty() && methods.is_empty() {
784    return String::new();
785  }
786  let mut lines = vec![format!("defexternal {name}")];
787  if !target.is_empty() && target != "unspecified" && target != "invalid" {
788    lines.push(format!("  :target :{target}"));
789  }
790  for field in fields {
791    lines.push(format!("  :{field} 'Dynamic"));
792  }
793  for method in methods {
794    lines.push(format!("  .{method} $ :: 'Fn $ {{}} (:args $ [] '{name}) (:return 'Dynamic)"));
795  }
796  lines.join("\n")
797}
798
799pub fn parse_weak_type_kinds(raw: &str) -> Result<BTreeSet<WeakTypeKind>, String> {
800  let mut selected = BTreeSet::new();
801
802  for item in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
803    let kind = match item {
804      "schema-dynamic" => WeakTypeKind::SchemaDynamic,
805      "schema-open" => WeakTypeKind::SchemaOpen,
806      "unresolved-type-slot" => WeakTypeKind::UnresolvedTypeSlot,
807      "code-dynamic" => WeakTypeKind::CodeDynamic,
808      "code-nil" => WeakTypeKind::CodeNil,
809      "unsafe-coerce" => WeakTypeKind::UnsafeCoerce,
810      "data-dynamic" => WeakTypeKind::DataDynamic,
811      other => {
812        return Err(format!(
813          "Unknown weak-type filter `{other}`. Expected comma-separated values from: schema-dynamic, schema-open, unresolved-type-slot, code-dynamic, code-nil, unsafe-coerce, data-dynamic; or exactly one view: coverage, dynamic-method, deprecated-call, option-nil-roundtrip, inferred-dynamic"
814        ));
815      }
816    };
817    selected.insert(kind);
818  }
819
820  if selected.is_empty() {
821    return Err(
822      "Weak-type filter cannot be empty. Use comma-separated values from: schema-dynamic, schema-open, unresolved-type-slot, code-dynamic, code-nil, unsafe-coerce, data-dynamic"
823        .to_owned(),
824    );
825  }
826
827  Ok(selected)
828}
829
830pub fn parse_weak_type_intents(raw: &str) -> Result<BTreeSet<WeakTypeIntent>, String> {
831  let mut selected = BTreeSet::new();
832
833  for item in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
834    let intent = match item {
835      "unresolved" => WeakTypeIntent::Unresolved,
836      "intentional-js-ffi" => WeakTypeIntent::IntentionalJsFfi,
837      "js-ffi-non-host" => WeakTypeIntent::JsFfiNonHost,
838      "intentional-macro-syntax" => WeakTypeIntent::IntentionalMacroSyntax,
839      "intentional-type-slot-dynamic" => WeakTypeIntent::IntentionalTypeSlotDynamic,
840      "intentional-decode" => WeakTypeIntent::IntentionalDecode,
841      "intentional-open" => WeakTypeIntent::IntentionalOpen,
842      "explicit-unsafe" => WeakTypeIntent::ExplicitUnsafe,
843      "declared-unit" => WeakTypeIntent::DeclaredUnit,
844      "declared-optional" => {
845        return Err(
846          "Weak-type intent `declared-optional` was removed with legacy Optional<T> in 0.33.0; nil returns are now `unresolved` or `declared-unit`".to_owned(),
847        );
848      }
849      other => {
850        return Err(format!(
851          "Unknown weak-type intent `{other}`. Expected comma-separated values from: unresolved, intentional-js-ffi, js-ffi-non-host, intentional-macro-syntax, intentional-type-slot-dynamic, intentional-decode, intentional-open, explicit-unsafe, declared-unit"
852        ));
853      }
854    };
855    selected.insert(intent);
856  }
857
858  if selected.is_empty() {
859    return Err(
860      "Weak-type intent filter cannot be empty. Use comma-separated values from: unresolved, intentional-js-ffi, js-ffi-non-host, intentional-macro-syntax, intentional-type-slot-dynamic, intentional-decode, intentional-open, explicit-unsafe, declared-unit"
861        .to_owned(),
862    );
863  }
864
865  Ok(selected)
866}
867
868fn format_cirru_path(root: &str, path: &[usize]) -> String {
869  if path.is_empty() {
870    root.to_owned()
871  } else {
872    let mut rendered = format!("{root}@");
873    for (i, idx) in path.iter().enumerate() {
874      if i > 0 {
875        rendered.push('.');
876      }
877      rendered.push_str(&idx.to_string());
878    }
879    rendered
880  }
881}
882
883fn weak_type_detail(kind: WeakTypeKind, detail: &str) -> String {
884  format!("{}:{}", kind.as_str(), detail)
885}
886
887fn extend_schema_dynamic_detail(detail: &str, segment: &str) -> String {
888  format!("{detail}:{segment}")
889}
890
891fn push_weak_type_occurrence(
892  occurrences: &mut Vec<WeakTypeOccurrence>,
893  kind: WeakTypeKind,
894  detail: impl Into<String>,
895  path: impl Into<String>,
896) {
897  occurrences.push(WeakTypeOccurrence {
898    kind,
899    intent: WeakTypeIntent::Unresolved,
900    detail: detail.into(),
901    path: path.into(),
902    unsafe_evidence: None,
903  });
904}
905
906fn apply_fn_open_reason(occurrences: &mut [WeakTypeOccurrence], reason: Option<calcit_core::calcit::FnOpenReason>) {
907  let Some(reason) = reason else {
908    return;
909  };
910  for occurrence in occurrences {
911    if matches!(occurrence.kind, WeakTypeKind::SchemaDynamic | WeakTypeKind::SchemaOpen)
912      && occurrence.intent == WeakTypeIntent::Unresolved
913    {
914      occurrence.intent = WeakTypeIntent::IntentionalOpen;
915      if occurrence.kind == WeakTypeKind::SchemaOpen {
916        occurrence.detail = format!("{}:open={}", occurrence.detail, reason.as_str());
917      }
918    }
919  }
920}
921
922fn scan_intentional_macro_expr(annotation: &CalcitTypeAnnotation, path: &str, detail: &str, occurrences: &mut Vec<WeakTypeOccurrence>) {
923  let start = occurrences.len();
924  scan_schema_dynamic_annotation(annotation, path, detail, occurrences);
925  for occurrence in &mut occurrences[start..] {
926    if occurrence.kind == WeakTypeKind::SchemaDynamic && occurrence.intent == WeakTypeIntent::Unresolved {
927      occurrence.intent = WeakTypeIntent::IntentionalMacroSyntax;
928    }
929  }
930}
931
932fn scan_schema_dynamic_annotation(
933  annotation: &CalcitTypeAnnotation,
934  path: &str,
935  detail: &str,
936  occurrences: &mut Vec<WeakTypeOccurrence>,
937) {
938  match annotation {
939    CalcitTypeAnnotation::Dynamic => {
940      push_weak_type_occurrence(
941        occurrences,
942        WeakTypeKind::SchemaDynamic,
943        weak_type_detail(WeakTypeKind::SchemaDynamic, detail),
944        path.to_owned(),
945      );
946    }
947    CalcitTypeAnnotation::TypeSlot(name) => match resolve_type_slot(name) {
948      Some(resolved) => {
949        let start = occurrences.len();
950        scan_schema_dynamic_annotation(&resolved, path, detail, occurrences);
951        for occurrence in &mut occurrences[start..] {
952          if occurrence.intent == WeakTypeIntent::Unresolved && occurrence.kind != WeakTypeKind::UnresolvedTypeSlot {
953            occurrence.intent = WeakTypeIntent::IntentionalTypeSlotDynamic;
954          }
955        }
956      }
957      None => push_weak_type_occurrence(
958        occurrences,
959        WeakTypeKind::UnresolvedTypeSlot,
960        weak_type_detail(WeakTypeKind::UnresolvedTypeSlot, &format!("{detail}:{name}")),
961        path.to_owned(),
962      ),
963    },
964    CalcitTypeAnnotation::Ref(inner, open_reason) => {
965      let nested_detail = extend_schema_dynamic_detail(detail, "ref-item");
966      let occurrence_start = occurrences.len();
967      scan_schema_dynamic_annotation(inner, &format!("{path}.item"), &nested_detail, occurrences);
968      apply_fn_open_reason(&mut occurrences[occurrence_start..], open_reason.0);
969    }
970    CalcitTypeAnnotation::List(inner)
971    | CalcitTypeAnnotation::Set(inner)
972    | CalcitTypeAnnotation::Variadic(inner)
973    | CalcitTypeAnnotation::Nullable(inner, _) => {
974      let segment = match annotation {
975        CalcitTypeAnnotation::List(_) => "list-item",
976        CalcitTypeAnnotation::Set(_) => "set-item",
977        CalcitTypeAnnotation::Variadic(_) => "variadic-item",
978        CalcitTypeAnnotation::Nullable(_, NullableOrigin::Inferred) => "nil-join-item",
979        CalcitTypeAnnotation::Nullable(_, NullableOrigin::JsHost) => "js-nullish-item",
980        _ => unreachable!("composite item annotation should be covered by the match arm"),
981      };
982      let nested_detail = extend_schema_dynamic_detail(detail, segment);
983      let occurrence_start = occurrences.len();
984      scan_schema_dynamic_annotation(inner, &format!("{path}.item"), &nested_detail, occurrences);
985      if matches!(annotation, CalcitTypeAnnotation::Nullable(_, NullableOrigin::JsHost)) {
986        for occurrence in &mut occurrences[occurrence_start..] {
987          if occurrence.kind == WeakTypeKind::SchemaDynamic && occurrence.intent == WeakTypeIntent::Unresolved {
988            occurrence.intent = WeakTypeIntent::IntentionalJsFfi;
989          }
990        }
991      }
992    }
993    CalcitTypeAnnotation::Map(key, value) => {
994      let key_detail = extend_schema_dynamic_detail(detail, "map-key");
995      let value_detail = extend_schema_dynamic_detail(detail, "map-value");
996      scan_schema_dynamic_annotation(key, &format!("{path}.key"), &key_detail, occurrences);
997      scan_schema_dynamic_annotation(value, &format!("{path}.value"), &value_detail, occurrences);
998    }
999    CalcitTypeAnnotation::Fn(fn_annot) => {
1000      let occurrence_start = occurrences.len();
1001      for (idx, arg) in fn_annot.arg_types.iter().enumerate() {
1002        let arg_detail = extend_schema_dynamic_detail(detail, "fn-arg");
1003        scan_schema_dynamic_annotation(arg, &format!("{path}.args.{idx}"), &arg_detail, occurrences);
1004      }
1005      let return_detail = extend_schema_dynamic_detail(detail, "fn-return");
1006      scan_schema_dynamic_annotation(&fn_annot.return_type, &format!("{path}.return"), &return_detail, occurrences);
1007      if let Some(rest) = &fn_annot.rest_type {
1008        let rest_detail = extend_schema_dynamic_detail(detail, "fn-rest");
1009        scan_schema_dynamic_annotation(rest, &format!("{path}.rest"), &rest_detail, occurrences);
1010      }
1011      // A stated `(:open …)` reason covers every open position below it.
1012      apply_fn_open_reason(&mut occurrences[occurrence_start..], fn_annot.open_reason.0);
1013    }
1014    CalcitTypeAnnotation::Macro(signature) => {
1015      for (idx, contract) in signature.required_inputs.iter().chain(signature.optional_inputs.iter()).enumerate() {
1016        if let MacroSyntaxType::Expr(semantic) = contract {
1017          scan_intentional_macro_expr(semantic, &format!("{path}.inputs.{idx}.expr"), detail, occurrences);
1018        }
1019      }
1020      if let Some(MacroSyntaxType::Expr(semantic)) = &signature.rest_input {
1021        scan_intentional_macro_expr(semantic, &format!("{path}.rest.expr"), detail, occurrences);
1022      }
1023      match &signature.expansion {
1024        MacroExpansionType::Expr(semantic) => {
1025          scan_intentional_macro_expr(semantic, &format!("{path}.expansion"), detail, occurrences);
1026        }
1027        MacroExpansionType::Definition(semantic) => {
1028          scan_schema_dynamic_annotation(semantic, &format!("{path}.expansion"), detail, occurrences);
1029        }
1030        MacroExpansionType::Dynamic => {
1031          scan_schema_dynamic_annotation(&CalcitTypeAnnotation::Dynamic, &format!("{path}.expansion"), detail, occurrences)
1032        }
1033        MacroExpansionType::Declarations => {}
1034      }
1035    }
1036    CalcitTypeAnnotation::Struct(_, args) | CalcitTypeAnnotation::Enum(_, args) | CalcitTypeAnnotation::TypeRef(_, args) => {
1037      for (idx, arg) in args.iter().enumerate() {
1038        let type_arg_detail = extend_schema_dynamic_detail(detail, "type-arg");
1039        scan_schema_dynamic_annotation(arg, &format!("{path}.type-arg.{idx}"), &type_arg_detail, occurrences);
1040      }
1041    }
1042    CalcitTypeAnnotation::Tuple(items) => {
1043      for (idx, item) in items.iter().enumerate() {
1044        let item_detail = extend_schema_dynamic_detail(detail, "item");
1045        scan_schema_dynamic_annotation(item, &format!("{path}.item.{idx}"), &item_detail, occurrences);
1046      }
1047    }
1048    _ if annotation.open_family_name().is_some() => {
1049      let family = annotation.open_family_name().expect("open_family_name matched Some");
1050      push_weak_type_occurrence(
1051        occurrences,
1052        WeakTypeKind::SchemaOpen,
1053        weak_type_detail(WeakTypeKind::SchemaOpen, &format!("{family}:{detail}")),
1054        path.to_owned(),
1055      );
1056    }
1057    _ => {}
1058  }
1059}
1060
1061fn is_dynamic_type_leaf(text: &str) -> bool {
1062  matches!(text, "Dynamic" | "'Dynamic" | ":dynamic")
1063}
1064
1065fn collect_dynamic_leaves(node: &Cirru, path: &mut Vec<usize>, found: &mut Vec<Vec<usize>>) {
1066  match node {
1067    Cirru::Leaf(text) if is_dynamic_type_leaf(text) => found.push(path.clone()),
1068    Cirru::Leaf(_) => {}
1069    Cirru::List(items) => {
1070      for (idx, item) in items.iter().enumerate() {
1071        path.push(idx);
1072        collect_dynamic_leaves(item, path, found);
1073        path.pop();
1074      }
1075    }
1076  }
1077}
1078
1079/// `Dynamic` written in the member types of a `defstruct`, `defenum`,
1080/// `defunion` (#2553), or `deftype` alias. Generic parameter lists such as
1081/// `([] T)` and leading clause pairs such as `(:generics T)` are skipped.
1082fn scan_data_declaration_dynamic(code: &Cirru, occurrences: &mut Vec<WeakTypeOccurrence>) {
1083  let Cirru::List(items) = code else {
1084    return;
1085  };
1086  let Some(Cirru::Leaf(head)) = items.first() else {
1087    return;
1088  };
1089  let head = head.as_ref();
1090  if !matches!(head, "defstruct" | "defenum" | "defunion" | "deftype") {
1091    return;
1092  }
1093  let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
1094  let body_start = 2 + clauses;
1095  for (idx, item) in items.iter().enumerate().skip(body_start) {
1096    let mut found = vec![];
1097    let label = match (head, item) {
1098      ("defunion", _) => {
1099        let mut path = vec![idx];
1100        collect_dynamic_leaves(item, &mut path, &mut found);
1101        format!("union-member:{}", idx - body_start)
1102      }
1103      ("deftype", _) => {
1104        let mut path = vec![idx];
1105        collect_dynamic_leaves(item, &mut path, &mut found);
1106        format!("type-alias:{}", idx - body_start)
1107      }
1108      (_, Cirru::List(parts)) => {
1109        let Some(Cirru::Leaf(name)) = parts.first() else {
1110          continue;
1111        };
1112        if !name.starts_with(':') {
1113          continue;
1114        }
1115        for (part_idx, part) in parts.iter().enumerate().skip(1) {
1116          let mut path = vec![idx, part_idx];
1117          collect_dynamic_leaves(part, &mut path, &mut found);
1118        }
1119        let member = name.trim_start_matches(':');
1120        if head == "defstruct" {
1121          format!("struct-field:{member}")
1122        } else {
1123          format!("enum-payload:{member}")
1124        }
1125      }
1126      _ => continue,
1127    };
1128    for path in found {
1129      push_weak_type_occurrence(
1130        occurrences,
1131        WeakTypeKind::DataDynamic,
1132        weak_type_detail(WeakTypeKind::DataDynamic, &label),
1133        format_cirru_path("code", &path),
1134      );
1135    }
1136  }
1137}
1138
1139fn weak_type_suggestion(occurrence: &WeakTypeOccurrence) -> &'static str {
1140  if occurrence.kind == WeakTypeKind::DataDynamic {
1141    return "Give this field, payload or union member a concrete type; use a type parameter on the declaration when the content varies by use, or a union when it takes a few known shapes. Keep `Dynamic` only for data that is checked at a documented decode boundary.";
1142  }
1143  if occurrence.kind == WeakTypeKind::UnsafeCoerce {
1144    if occurrence.unsafe_evidence.as_ref().is_some_and(|evidence| !evidence.js_ffi_feature) {
1145      return "Declare `:features $ #{} :js-ffi` on this adapter first, then keep the assertion narrow, validate or normalize untrusted runtime data before application code consumes it, and add positive and negative runtime-contract tests.";
1146    }
1147    return "Keep this assertion at a small trusted boundary, validate or normalize untrusted runtime data into Option, Result, a struct, or an enum before it reaches application code, and add positive and negative runtime-contract tests.";
1148  }
1149  if occurrence.intent == WeakTypeIntent::IntentionalJsFfi {
1150    return "Keep the dynamic value isolated at the declared FFI boundary (JS or native) and validate or convert it before typed code consumes it.";
1151  }
1152  if occurrence.intent == WeakTypeIntent::JsFfiNonHost {
1153    return "This position is inside a `:js-ffi` function but does not reach a host operation. Give it a concrete Calcit type, or a named external-object type if it is passed to another adapter.";
1154  }
1155  if occurrence.intent == WeakTypeIntent::IntentionalMacroSyntax {
1156    return "This Dynamic is an explicit open expression boundary inside a strict MacroSignature. Narrow the Expr semantic type when the macro contract guarantees more, but do not replace the phase-aware signature with whole-Dynamic.";
1157  }
1158  if occurrence.intent == WeakTypeIntent::IntentionalDecode {
1159    return "This Dynamic is the input of a reviewed `:decode-boundary` function. Keep the function small: check the value and return a concrete type, and cover rejected inputs with tests.";
1160  }
1161  if occurrence.intent == WeakTypeIntent::IntentionalOpen {
1162    if occurrence.kind == WeakTypeKind::SchemaOpen {
1163      return "This open family type (`AnyFn` / `AnyStruct` / `AnyEnum`) sits in a signature that states why it stays open with `(:open …)`. Keep the reason accurate; replace it with a concrete type, `:generics` type parameter, or trait `:where` bound once callers need more than the open contract.";
1164    }
1165    return "This Dynamic sits in a signature that states why it stays open with `(:open …)`. Keep the reason accurate; replace it with a concrete type or type parameter once callers need more than the open contract.";
1166  }
1167  if occurrence.intent == WeakTypeIntent::IntentionalTypeSlotDynamic {
1168    return "This slot intentionally resolves to Dynamic for the selected entry. Keep that boundary documented and narrow or validate the value before typed code relies on it.";
1169  }
1170
1171  if occurrence.kind == WeakTypeKind::CodeNil {
1172    return match occurrence.intent {
1173      WeakTypeIntent::DeclaredUnit if occurrence.detail.contains("nil-macro") => {
1174        "The legacy `;nil` form returns Nil, not Unit. Replace it with `&unit`, or end the body with an effect that already returns Unit."
1175      }
1176      WeakTypeIntent::DeclaredUnit => {
1177        "The declared return is Unit, so replace this nil with `&unit`, or end the body with an effect that already returns Unit."
1178      }
1179      _ => {
1180        "Declare Unit for a no-value result and remove explicit nil/`;nil` when possible; use Option/Result for application absence or failure."
1181      }
1182    };
1183  }
1184  if occurrence.kind == WeakTypeKind::UnresolvedTypeSlot {
1185    return "Bind this slot in the selected entry with `calcit config set-type-slot <slot> <namespace/definition>`; a `Dynamic` binding does not count as bound.";
1186  }
1187  if occurrence.kind == WeakTypeKind::SchemaOpen {
1188    return "Replace `AnyFn` / `AnyStruct` / `AnyEnum` with a concrete type, a `:generics` type parameter, or a trait `:where` bound; if this signature is intentionally open, document why with `(:open :reflect)`, `(:open :decode)`, `(:open :host)`, or `(:open :cache)`.";
1189  }
1190  if occurrence.kind == WeakTypeKind::CodeDynamic {
1191    return "Replace this `Dynamic` with a concrete type; use a declared type variable when input and output types are related, or a trait plus `:where` when only a capability is required. Keep `Dynamic` only at a documented boundary.";
1192  }
1193  if occurrence.detail.contains("ref-item") {
1194    return "Replace a bare `Ref` with `quote $ Ref T`; use a declared type variable for a polymorphic ref, or a named enum for intentionally heterogeneous state.";
1195  }
1196  if occurrence.detail.contains("list-item") {
1197    return "Replace a bare `List` with `quote $ List T`; use a declared type variable for a homogeneous polymorphic list, or a named enum for heterogeneous items.";
1198  }
1199  if occurrence.detail.contains("set-item") {
1200    return "Replace a bare `Set` with `quote $ Set T` and choose a concrete type or a declared type variable.";
1201  }
1202  if occurrence.detail.contains("map-key") || occurrence.detail.contains("map-value") {
1203    return "Use `quote $ Map K V` and replace each unresolved slot with a concrete type or a declared type variable.";
1204  }
1205  "Replace `Dynamic` with a concrete type, a declared type variable, or a trait-bounded variable; add `(:features :js-ffi)` to the `Fn` schema only for an intentional JS or native FFI boundary."
1206}
1207
1208fn schema_has_feature(annotation: &CalcitTypeAnnotation, feature: &str) -> bool {
1209  matches!(annotation, CalcitTypeAnnotation::Fn(fn_annot) if fn_annot.features.iter().any(|tag| tag.ref_str() == feature))
1210}
1211
1212fn entry_schema_issues(ns: &str, def_name: &str, code: &Cirru, schema: &Arc<CalcitTypeAnnotation>) -> Vec<String> {
1213  let annotation = schema.as_ref();
1214  let mut issues = validate_def_vs_schema(ns, def_name, code, annotation);
1215  let has_js_ffi_feature = match annotation {
1216    CalcitTypeAnnotation::Fn(fn_annot) => fn_annot.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
1217    CalcitTypeAnnotation::Macro(signature) => signature.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
1218    _ => false,
1219  };
1220  if matches!(annotation, CalcitTypeAnnotation::Dynamic) {
1221    if matches!(code, Cirru::List(items) if matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "defmacro")) {
1222      let (warning, detail) = if snapshot::schema_annotation_is_missing(schema) {
1223        ("W_SCHEMA_MISSING", "has no declared macro schema")
1224      } else {
1225        (
1226          "W_MACRO_SCHEMA_DYNAMIC",
1227          "declares an intentionally untyped whole-Dynamic macro schema",
1228        )
1229      };
1230      issues.push(format!("[{warning}] {ns}/{def_name} {detail}"));
1231    }
1232    return issues;
1233  }
1234
1235  let has_decode_boundary = schema_has_feature(annotation, calcit_core::calcit::DECODE_BOUNDARY_FEATURE);
1236  let mut occurrences = vec![];
1237  scan_schema_dynamic_annotation(annotation, "schema", "root", &mut occurrences);
1238  for occurrence in occurrences {
1239    let decode_input = has_decode_boundary
1240      && occurrence.kind == WeakTypeKind::SchemaDynamic
1241      && (occurrence.path.starts_with("schema.args.") || occurrence.path.starts_with("schema.rest"));
1242    if decode_input
1243      || (has_js_ffi_feature && occurrence.kind == WeakTypeKind::SchemaDynamic)
1244      || occurrence.intent == WeakTypeIntent::IntentionalMacroSyntax
1245      || occurrence.intent == WeakTypeIntent::IntentionalOpen
1246    {
1247      continue;
1248    }
1249    let warning = match occurrence.kind {
1250      WeakTypeKind::UnresolvedTypeSlot => "W_UNRESOLVED_TYPE_SLOT",
1251      WeakTypeKind::SchemaOpen => "W_OPEN_FAMILY",
1252      _ => "W_SCHEMA_DYNAMIC",
1253    };
1254    issues.push(format!(
1255      "[{warning}] {} is unresolved ({}). Fix: {}",
1256      occurrence.path,
1257      occurrence.detail,
1258      weak_type_suggestion(&occurrence)
1259    ));
1260  }
1261  issues
1262}
1263
1264fn downgrade_coverage_for_dynamic_annotation(level: CoverageLevel, annotation: &CalcitTypeAnnotation) -> CoverageLevel {
1265  if level != CoverageLevel::Full {
1266    return level;
1267  }
1268  let mut occurrences = vec![];
1269  scan_schema_dynamic_annotation(annotation, "schema", "root", &mut occurrences);
1270  occurrences.retain(|occurrence| occurrence.intent != WeakTypeIntent::IntentionalOpen);
1271  if occurrences.is_empty() {
1272    CoverageLevel::Full
1273  } else {
1274    CoverageLevel::Partial
1275  }
1276}
1277
1278#[derive(Debug, Clone)]
1279struct WeakCodeParent {
1280  head: Option<String>,
1281  child_index: usize,
1282}
1283
1284fn classify_code_dynamic(parent: Option<&WeakCodeParent>) -> &'static str {
1285  match parent.and_then(|it| it.head.as_deref()) {
1286    Some("assert-type") => "assert-type",
1287    Some("hint-fn") => "hint-fn",
1288    Some("::") => "schema-tag",
1289    Some("defstruct") => "defstruct",
1290    Some("defenum") => "defenum",
1291    Some("deftrait") => "deftrait",
1292    Some("[]") => "list-item",
1293    _ => "literal",
1294  }
1295}
1296
1297fn classify_code_nil(parent: Option<&WeakCodeParent>) -> &'static str {
1298  match parent.and_then(|it| it.head.as_deref()) {
1299    Some("if") if parent.is_some_and(|it| it.child_index == 2) => "if-then",
1300    Some("if") if parent.is_some_and(|it| it.child_index == 3) => "if-else",
1301    Some("let") | Some("&let") => "let-binding",
1302    Some("do") => "do-step",
1303    Some("[]") => "list-item",
1304    Some("{}") | Some("&{}") | Some("#{}") => "collection-item",
1305    Some("cond") | Some("case") => "branch",
1306    _ => "literal",
1307  }
1308}
1309
1310fn nil_return_intent(annotation: &CalcitTypeAnnotation) -> WeakTypeIntent {
1311  let return_type = match annotation {
1312    CalcitTypeAnnotation::Fn(fn_annotation) => fn_annotation.return_type.as_ref(),
1313    CalcitTypeAnnotation::Macro(signature) => match &signature.expansion {
1314      MacroExpansionType::Expr(semantic) | MacroExpansionType::Definition(semantic) => semantic.as_ref(),
1315      MacroExpansionType::Dynamic | MacroExpansionType::Declarations => annotation,
1316    },
1317    other => other,
1318  };
1319  match return_type {
1320    CalcitTypeAnnotation::Unit => WeakTypeIntent::DeclaredUnit,
1321    CalcitTypeAnnotation::Nullable(_, NullableOrigin::JsHost) => WeakTypeIntent::IntentionalJsFfi,
1322    _ => WeakTypeIntent::Unresolved,
1323  }
1324}
1325
1326fn child_is_return_position(
1327  is_code_root: bool,
1328  parent_is_return_position: bool,
1329  head: Option<&str>,
1330  child_index: usize,
1331  child_count: usize,
1332) -> bool {
1333  if !parent_is_return_position {
1334    return false;
1335  }
1336  if is_code_root {
1337    return match head {
1338      Some("defn" | "defmacro" | "defcomp") => child_index >= 3 && child_index + 1 == child_count,
1339      Some("fn" | "macro") => child_index >= 2 && child_index + 1 == child_count,
1340      Some("def") => child_index == 2,
1341      _ => false,
1342    };
1343  }
1344  match head {
1345    Some("if") => matches!(child_index, 2 | 3),
1346    Some("let" | "&let") => child_index >= 2 && child_index + 1 == child_count,
1347    Some("do") => child_index >= 1 && child_index + 1 == child_count,
1348    _ => false,
1349  }
1350}
1351
1352fn code_declares_embedded_type_schema(code: &Cirru) -> bool {
1353  let inner = match code {
1354    Cirru::List(items) if items.len() == 3 && matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "def") => &items[2],
1355    other => other,
1356  };
1357  if let Cirru::List(items) = inner
1358    && matches!(items.first(), Some(Cirru::Leaf(head)) if matches!(head.as_ref(), "defunion" | "deftype"))
1359  {
1360    let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
1361    let mut dynamic_leaves = vec![];
1362    for member in items.iter().skip(2 + clauses) {
1363      collect_dynamic_leaves(member, &mut vec![], &mut dynamic_leaves);
1364    }
1365    return dynamic_leaves.is_empty();
1366  }
1367  matches!(
1368    inner,
1369    Cirru::List(items)
1370      if matches!(
1371        items.first(),
1372        Some(Cirru::Leaf(head)) if matches!(head.as_ref(), "defstruct" | "defenum" | "deftrait" | "defimpl" | "defexternal")
1373      )
1374  )
1375}
1376
1377fn classify_unsafe_coerce_source(items: &[Cirru]) -> &'static str {
1378  let Some(source) = items.get(1) else {
1379    return "missing-value";
1380  };
1381  match source {
1382    Cirru::Leaf(name) if name.starts_with("js/") => "raw-js-value",
1383    Cirru::List(parts) => match parts.first() {
1384      Some(Cirru::Leaf(head)) if head.starts_with("js/") => "raw-js-operation",
1385      Some(Cirru::Leaf(head))
1386        if matches!(head.as_ref(), "aget" | "js-get")
1387          || head.starts_with(".-")
1388          || head.starts_with(".!")
1389          || head.starts_with(".?-")
1390          || head.starts_with(".?!") =>
1391      {
1392        "host-member-operation"
1393      }
1394      _ => "expression",
1395    },
1396    Cirru::Leaf(_) => "value",
1397  }
1398}
1399
1400fn is_raw_adapter_namespace(ns: &str) -> bool {
1401  ns == "js-ffi.raw" || ns.starts_with("js-ffi.raw.") || ns.contains(".js-ffi.raw.")
1402}
1403
1404#[derive(Debug, Clone, Copy, Default)]
1405struct QuoteContext {
1406  quoted_depth: usize,
1407  quasiquoted_depth: usize,
1408}
1409
1410impl QuoteContext {
1411  fn is_quoted(self) -> bool {
1412    self.quoted_depth > 0 || self.quasiquoted_depth > 0
1413  }
1414
1415  fn for_child(self, head: Option<&str>, child_index: usize) -> Self {
1416    if child_index == 0 {
1417      return self;
1418    }
1419    match head {
1420      Some("quote") => Self {
1421        quoted_depth: self.quoted_depth + 1,
1422        ..self
1423      },
1424      Some("quasiquote") => Self {
1425        quasiquoted_depth: self.quasiquoted_depth + 1,
1426        ..self
1427      },
1428      Some("~" | "~@") if self.quoted_depth == 0 => Self {
1429        quasiquoted_depth: self.quasiquoted_depth.saturating_sub(1),
1430        ..self
1431      },
1432      _ => self,
1433    }
1434  }
1435}
1436
1437// Tag spellings are type aliases only in annotation slots, not member names or
1438// ordinary data. Keep this source-only distinction shared by all weak-type views.
1439#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1440enum WeakTypeContext {
1441  #[default]
1442  Code,
1443  Type,
1444  DeclarationMember,
1445  SchemaEntry,
1446}
1447
1448impl WeakTypeContext {
1449  fn for_child(self, head: Option<&str>, index: usize, count: usize) -> Self {
1450    match self {
1451      Self::Type if head == Some("{}") => {
1452        if index > 0 {
1453          Self::SchemaEntry
1454        } else {
1455          Self::Code
1456        }
1457      }
1458      Self::Type => {
1459        if index > 0 {
1460          Self::Type
1461        } else {
1462          Self::Code
1463        }
1464      }
1465      Self::SchemaEntry => {
1466        if index > 0
1467          && matches!(
1468            head,
1469            Some(":args" | ":return" | ":rest" | ":inputs" | ":expansion" | ":required" | ":optional")
1470          )
1471        {
1472          Self::Type
1473        } else {
1474          Self::Code
1475        }
1476      }
1477      Self::DeclarationMember if count == 1 && head.is_none() => Self::DeclarationMember,
1478      Self::DeclarationMember if index > 0 && head.is_some_and(|name| name.starts_with([':', '.'])) => Self::Type,
1479      Self::Code | Self::DeclarationMember => match head {
1480        Some("assert-type" | "unsafe-coerce") if index == 2 => Self::Type,
1481        Some("hint-fn") if index > 0 && index + 1 == count => Self::Type,
1482        Some("defstruct" | "defenum" | "deftrait" | "defexternal") if index >= 2 => Self::DeclarationMember,
1483        _ => Self::Code,
1484      },
1485    }
1486  }
1487}
1488
1489#[derive(Debug, Clone, Copy, Default)]
1490struct WeakScanState {
1491  nil_return_intent: Option<WeakTypeIntent>,
1492  quote_context: QuoteContext,
1493  type_context: WeakTypeContext,
1494}
1495
1496fn scan_cirru_weak_types(
1497  node: &Cirru,
1498  root: &str,
1499  path: &mut Vec<usize>,
1500  parent: Option<&WeakCodeParent>,
1501  state: WeakScanState,
1502  selected: &BTreeSet<WeakTypeKind>,
1503  occurrences: &mut Vec<WeakTypeOccurrence>,
1504) {
1505  match node {
1506    Cirru::Leaf(text) => {
1507      let is_dynamic = text.as_ref() == ":dynamic";
1508      if is_dynamic && root == "schema" && selected.contains(&WeakTypeKind::SchemaDynamic) {
1509        push_weak_type_occurrence(
1510          occurrences,
1511          WeakTypeKind::SchemaDynamic,
1512          weak_type_detail(WeakTypeKind::SchemaDynamic, "raw-schema"),
1513          format_cirru_path(root, path),
1514        );
1515      } else if is_dynamic
1516        && root == "code"
1517        && state.type_context == WeakTypeContext::Type
1518        && selected.contains(&WeakTypeKind::CodeDynamic)
1519        && !state.quote_context.is_quoted()
1520      {
1521        let detail = classify_code_dynamic(parent).to_owned();
1522        push_weak_type_occurrence(
1523          occurrences,
1524          WeakTypeKind::CodeDynamic,
1525          weak_type_detail(WeakTypeKind::CodeDynamic, &detail),
1526          format_cirru_path(root, path),
1527        );
1528      } else if text.as_ref() == "nil"
1529        && root == "code"
1530        && selected.contains(&WeakTypeKind::CodeNil)
1531        && !state.quote_context.is_quoted()
1532      {
1533        push_weak_type_occurrence(
1534          occurrences,
1535          WeakTypeKind::CodeNil,
1536          weak_type_detail(WeakTypeKind::CodeNil, classify_code_nil(parent)),
1537          format_cirru_path(root, path),
1538        );
1539        if let (Some(intent), Some(occurrence)) = (state.nil_return_intent, occurrences.last_mut()) {
1540          occurrence.intent = intent;
1541        }
1542      }
1543    }
1544    Cirru::List(items) => {
1545      let head = items.first().and_then(|item| match item {
1546        Cirru::Leaf(text) => Some(text.to_string()),
1547        _ => None,
1548      });
1549      if root == "code"
1550        && selected.contains(&WeakTypeKind::CodeNil)
1551        && matches!(head.as_deref(), Some(";nil"))
1552        && !state.quote_context.is_quoted()
1553      {
1554        push_weak_type_occurrence(
1555          occurrences,
1556          WeakTypeKind::CodeNil,
1557          weak_type_detail(WeakTypeKind::CodeNil, &format!("nil-macro:{}", classify_code_nil(parent))),
1558          format_cirru_path(root, path),
1559        );
1560        if let (Some(intent), Some(occurrence)) = (state.nil_return_intent, occurrences.last_mut()) {
1561          // `;nil` is a legacy spelling of Nil. It inherits a declared return
1562          // intent only when structural analysis proves that it is returned.
1563          occurrence.intent = intent;
1564        }
1565      }
1566      if root == "code"
1567        && selected.contains(&WeakTypeKind::UnsafeCoerce)
1568        && matches!(head.as_deref(), Some("unsafe-coerce"))
1569        && !state.quote_context.is_quoted()
1570      {
1571        let target = items
1572          .get(2)
1573          .map(render_cirru_inline)
1574          .unwrap_or_else(|| "<missing-target>".to_owned());
1575        occurrences.push(WeakTypeOccurrence {
1576          kind: WeakTypeKind::UnsafeCoerce,
1577          intent: WeakTypeIntent::ExplicitUnsafe,
1578          detail: format!("unsafe-coerce:target={target}"),
1579          path: format_cirru_path(root, path),
1580          unsafe_evidence: Some(UnsafeCoerceEvidence {
1581            source_form: classify_unsafe_coerce_source(items).to_owned(),
1582            target_schema: target,
1583            js_ffi_feature: false,
1584            raw_adapter_namespace: false,
1585          }),
1586        });
1587      }
1588      for (idx, item) in items.iter().enumerate() {
1589        path.push(idx);
1590        let next_parent = WeakCodeParent {
1591          head: head.clone(),
1592          child_index: idx,
1593        };
1594        let child_return_position = child_is_return_position(
1595          root == "code" && path.len() == 1,
1596          state.nil_return_intent.is_some(),
1597          head.as_deref(),
1598          idx,
1599          items.len(),
1600        );
1601        let child_state = WeakScanState {
1602          nil_return_intent: state.nil_return_intent.filter(|_| child_return_position),
1603          quote_context: state.quote_context.for_child(head.as_deref(), idx),
1604          type_context: state.type_context.for_child(head.as_deref(), idx, items.len()),
1605        };
1606        scan_cirru_weak_types(item, root, path, Some(&next_parent), child_state, selected, occurrences);
1607        path.pop();
1608      }
1609    }
1610  }
1611}
1612
1613/// Which schema positions of a `:js-ffi` function touch host operations.
1614///
1615/// This reads source only. A parameter reaches the host when it appears inside
1616/// a host operation, directly or through `let` bindings; the return reaches the
1617/// host when a tail expression contains a host operation or a binding derived
1618/// from one. Calls into other adapters, imported JS module functions and
1619/// external-object methods written as `.method` are not followed, so those
1620/// positions count as non-host.
1621struct JsFfiHostReach {
1622  params: Vec<bool>,
1623  rest: Option<bool>,
1624  ret: bool,
1625}
1626
1627impl JsFfiHostReach {
1628  fn schema_path_reaches_host(&self, path: &str) -> bool {
1629    let position = |prefix: &str| {
1630      path
1631        .strip_prefix(prefix)
1632        .is_some_and(|tail| tail.is_empty() || tail.starts_with('.'))
1633    };
1634    if let Some(tail) = path.strip_prefix("schema.args.") {
1635      let index = tail.split('.').next().and_then(|idx| idx.parse::<usize>().ok());
1636      return index.and_then(|idx| self.params.get(idx).copied()).unwrap_or(true);
1637    }
1638    if position("schema.rest") {
1639      return self.rest.unwrap_or(true);
1640    }
1641    if position("schema.return") {
1642      return self.ret;
1643    }
1644    true
1645  }
1646}
1647
1648fn is_js_host_head(head: &str) -> bool {
1649  head.starts_with(".-")
1650    || head.starts_with(".!")
1651    || head.starts_with(".?-")
1652    || head.starts_with(".?!")
1653    || head.starts_with("js/")
1654    || ffi_postfix_operation(head).is_some()
1655    || matches!(
1656      head,
1657      "aget"
1658        | "aset"
1659        | "js-get"
1660        | "js-set"
1661        | "js-delete"
1662        | "exists?"
1663        | "instance?"
1664        | "&js-object"
1665        | "js-array"
1666        | "js-await"
1667        | "js-for-await"
1668        | "new"
1669        | "set!"
1670        | "to-calcit-data"
1671        | "to-js-data"
1672        | "&raw-code"
1673        | "js-cast"
1674        | "unsafe-coerce"
1675    )
1676}
1677
1678fn collect_cirru_leaves<'a>(code: &'a Cirru, leaves: &mut BTreeSet<&'a str>) {
1679  match code {
1680    Cirru::Leaf(leaf) => {
1681      leaves.insert(leaf.as_ref());
1682    }
1683    Cirru::List(items) => items.iter().for_each(|item| collect_cirru_leaves(item, leaves)),
1684  }
1685}
1686
1687/// Collects leaves used by host operations and `let` bindings as `(name, value)`.
1688fn collect_js_host_uses<'a>(code: &'a Cirru, host_leaves: &mut BTreeSet<&'a str>, bindings: &mut Vec<(&'a str, &'a Cirru)>) {
1689  let Cirru::List(items) = code else {
1690    // A postfix access such as `node.!focus` names its receiver inside the leaf.
1691    if let Cirru::Leaf(leaf) = code
1692      && let Some((receiver, ..)) = ffi_postfix_operation(leaf)
1693    {
1694      host_leaves.insert(&leaf[..receiver.len()]);
1695    }
1696    return;
1697  };
1698  match items.first() {
1699    Some(Cirru::Leaf(head)) if is_js_host_head(head) => collect_cirru_leaves(code, host_leaves),
1700    Some(Cirru::Leaf(head)) if head.as_ref() == "let" => {
1701      if let Some(Cirru::List(pairs)) = items.get(1) {
1702        for pair in pairs {
1703          if let Cirru::List(pair) = pair
1704            && let [Cirru::Leaf(name), value] = pair.as_slice()
1705          {
1706            bindings.push((name.as_ref(), value));
1707          }
1708        }
1709      }
1710    }
1711    Some(Cirru::Leaf(head)) if head.as_ref() == "&let" => {
1712      if let Some(Cirru::List(pair)) = items.get(1)
1713        && let [Cirru::Leaf(name), value] = pair.as_slice()
1714      {
1715        bindings.push((name.as_ref(), value));
1716      }
1717    }
1718    _ => {}
1719  }
1720  items.iter().for_each(|item| collect_js_host_uses(item, host_leaves, bindings));
1721}
1722
1723fn cirru_contains_host_value(code: &Cirru, host_values: &BTreeSet<&str>) -> bool {
1724  match code {
1725    Cirru::Leaf(leaf) => leaf.starts_with("js/") || ffi_postfix_operation(leaf).is_some() || host_values.contains(leaf.as_ref()),
1726    Cirru::List(items) => {
1727      matches!(items.first(), Some(Cirru::Leaf(head)) if is_js_host_head(head))
1728        || items.iter().any(|item| cirru_contains_host_value(item, host_values))
1729    }
1730  }
1731}
1732
1733fn collect_tail_expressions<'a>(code: &'a Cirru, is_code_root: bool, tails: &mut Vec<&'a Cirru>) {
1734  let Cirru::List(items) = code else {
1735    if !is_code_root {
1736      tails.push(code);
1737    }
1738    return;
1739  };
1740  let head = match items.first() {
1741    Some(Cirru::Leaf(head)) => Some(head.as_ref()),
1742    _ => None,
1743  };
1744  let mut descended = false;
1745  for (idx, item) in items.iter().enumerate() {
1746    if child_is_return_position(is_code_root, true, head, idx, items.len()) {
1747      descended = true;
1748      collect_tail_expressions(item, false, tails);
1749    }
1750  }
1751  if !descended && !is_code_root {
1752    tails.push(code);
1753  }
1754}
1755
1756fn js_ffi_host_reach(code: &Cirru) -> Option<JsFfiHostReach> {
1757  let Cirru::List(items) = code else {
1758    return None;
1759  };
1760  if !matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "defn" || head.as_ref() == "defcomp") {
1761    return None;
1762  }
1763  let Some(Cirru::List(raw_params)) = items.get(2) else {
1764    return None;
1765  };
1766  let body = &items[3..];
1767  let mut host_leaves = BTreeSet::new();
1768  let mut bindings = vec![];
1769  body
1770    .iter()
1771    .for_each(|form| collect_js_host_uses(form, &mut host_leaves, &mut bindings));
1772
1773  // A binding that feeds a host operation makes its inputs host-facing too.
1774  loop {
1775    let before = host_leaves.len();
1776    for (name, value) in &bindings {
1777      if host_leaves.contains(name) {
1778        collect_cirru_leaves(value, &mut host_leaves);
1779      }
1780    }
1781    if host_leaves.len() == before {
1782      break;
1783    }
1784  }
1785  // A binding computed from a host operation carries a host value forward.
1786  let mut host_values = BTreeSet::new();
1787  loop {
1788    let before = host_values.len();
1789    for (name, value) in &bindings {
1790      if cirru_contains_host_value(value, &host_values) {
1791        host_values.insert(*name);
1792      }
1793    }
1794    if host_values.len() == before {
1795      break;
1796    }
1797  }
1798
1799  let mut params = vec![];
1800  let mut rest = None;
1801  let mut after_rest_marker = false;
1802  for param in raw_params {
1803    let Cirru::Leaf(name) = param else {
1804      return None;
1805    };
1806    match name.as_ref() {
1807      "&" => after_rest_marker = true,
1808      "?" | "[]" | "," => {}
1809      name if after_rest_marker => rest = Some(host_leaves.contains(name)),
1810      name => params.push(host_leaves.contains(name)),
1811    }
1812  }
1813  let mut tails = vec![];
1814  collect_tail_expressions(code, true, &mut tails);
1815  let ret = tails.iter().any(|tail| cirru_contains_host_value(tail, &host_values));
1816  Some(JsFfiHostReach { params, rest, ret })
1817}
1818
1819pub fn analyze_weak_types_entry(
1820  ns: &str,
1821  def_name: &str,
1822  entry: &snapshot::CodeEntry,
1823  selected: &BTreeSet<WeakTypeKind>,
1824) -> Option<WeakTypeRow> {
1825  let mut occurrences: Vec<WeakTypeOccurrence> = vec![];
1826
1827  let selected_schema_annotations = selected.contains(&WeakTypeKind::SchemaDynamic)
1828    || selected.contains(&WeakTypeKind::SchemaOpen)
1829    || selected.contains(&WeakTypeKind::UnresolvedTypeSlot);
1830  if matches!(entry.schema.as_ref(), CalcitTypeAnnotation::Dynamic) {
1831    if selected.contains(&WeakTypeKind::SchemaDynamic) && !code_declares_embedded_type_schema(&entry.code) {
1832      let intent = if ns == calcit_core::calcit::CORE_NS && entry.tags.iter().any(|tag| tag.ref_str() == "syntax") {
1833        WeakTypeIntent::IntentionalMacroSyntax
1834      } else {
1835        WeakTypeIntent::Unresolved
1836      };
1837      occurrences.push(WeakTypeOccurrence {
1838        kind: WeakTypeKind::SchemaDynamic,
1839        intent,
1840        detail: weak_type_detail(WeakTypeKind::SchemaDynamic, "root"),
1841        path: "schema".to_owned(),
1842        unsafe_evidence: None,
1843      });
1844    }
1845  } else if let CalcitTypeAnnotation::Fn(fn_annot) = entry.schema.as_ref() {
1846    if selected_schema_annotations {
1847      for (idx, arg) in fn_annot.arg_types.iter().enumerate() {
1848        scan_schema_dynamic_annotation(arg, &format!("schema.args.{idx}"), "arg", &mut occurrences);
1849      }
1850      scan_schema_dynamic_annotation(&fn_annot.return_type, "schema.return", "return", &mut occurrences);
1851      if let Some(rest) = &fn_annot.rest_type {
1852        scan_schema_dynamic_annotation(rest, "schema.rest", "rest", &mut occurrences);
1853      }
1854      // The root signature's `(:open …)` reason covers its positions too.
1855      apply_fn_open_reason(&mut occurrences, fn_annot.open_reason.0);
1856    }
1857  } else if selected_schema_annotations {
1858    let before = occurrences.len();
1859    scan_schema_dynamic_annotation(entry.schema.as_ref(), "schema", "root", &mut occurrences);
1860
1861    if occurrences.len() == before
1862      && selected.contains(&WeakTypeKind::SchemaDynamic)
1863      && let Ok(schema_cirru) = snapshot::schema_edn_to_cirru(&entry.schema.to_type_edn())
1864    {
1865      let mut path = vec![];
1866      scan_cirru_weak_types(
1867        &schema_cirru,
1868        "schema",
1869        &mut path,
1870        None,
1871        WeakScanState::default(),
1872        selected,
1873        &mut occurrences,
1874      );
1875    }
1876  }
1877
1878  let mut code_path = vec![];
1879  scan_cirru_weak_types(
1880    &entry.code,
1881    "code",
1882    &mut code_path,
1883    None,
1884    WeakScanState {
1885      nil_return_intent: Some(nil_return_intent(entry.schema.as_ref())),
1886      quote_context: QuoteContext::default(),
1887      type_context: WeakTypeContext::Code,
1888    },
1889    selected,
1890    &mut occurrences,
1891  );
1892
1893  if selected.contains(&WeakTypeKind::DataDynamic) {
1894    scan_data_declaration_dynamic(&entry.code, &mut occurrences);
1895  }
1896
1897  occurrences.retain(|occurrence| selected.contains(&occurrence.kind));
1898
1899  let has_js_ffi_feature = match entry.schema.as_ref() {
1900    CalcitTypeAnnotation::Fn(fn_annot) => fn_annot.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
1901    CalcitTypeAnnotation::Macro(signature) => signature.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
1902    _ => false,
1903  };
1904  if has_js_ffi_feature {
1905    let reach = js_ffi_host_reach(&entry.code);
1906    for occurrence in &mut occurrences {
1907      if matches!(occurrence.kind, WeakTypeKind::SchemaDynamic | WeakTypeKind::CodeDynamic) {
1908        let reaches_host = occurrence.kind != WeakTypeKind::SchemaDynamic
1909          || reach.as_ref().is_none_or(|reach| reach.schema_path_reaches_host(&occurrence.path));
1910        occurrence.intent = if reaches_host {
1911          WeakTypeIntent::IntentionalJsFfi
1912        } else {
1913          WeakTypeIntent::JsFfiNonHost
1914        };
1915      }
1916    }
1917  }
1918  // A reviewed decode boundary keeps its Dynamic input and the open values its
1919  // body checks; they are reported apart from unresolved Dynamic.
1920  if schema_has_feature(entry.schema.as_ref(), calcit_core::calcit::DECODE_BOUNDARY_FEATURE) {
1921    for occurrence in &mut occurrences {
1922      let decode_position = match occurrence.kind {
1923        WeakTypeKind::SchemaDynamic => occurrence.path.starts_with("schema.args.") || occurrence.path.starts_with("schema.rest"),
1924        WeakTypeKind::CodeDynamic => true,
1925        _ => false,
1926      };
1927      if decode_position && occurrence.intent == WeakTypeIntent::Unresolved {
1928        occurrence.intent = WeakTypeIntent::IntentionalDecode;
1929      }
1930    }
1931  }
1932  for occurrence in &mut occurrences {
1933    if let Some(evidence) = &mut occurrence.unsafe_evidence {
1934      evidence.js_ffi_feature = has_js_ffi_feature;
1935      evidence.raw_adapter_namespace = is_raw_adapter_namespace(ns);
1936    }
1937  }
1938
1939  if occurrences.is_empty() {
1940    None
1941  } else {
1942    Some(WeakTypeRow {
1943      ns: ns.to_owned(),
1944      def: def_name.to_owned(),
1945      occurrences,
1946    })
1947  }
1948}
1949
1950#[derive(Debug, Clone, Copy)]
1951struct AnalysisScope<'a> {
1952  namespace: Option<&'a str>,
1953  namespace_prefix: Option<&'a str>,
1954  include_dependencies: bool,
1955}
1956
1957fn visit_scoped_definitions<F>(snapshot: &snapshot::Snapshot, scope: AnalysisScope<'_>, mut visit: F) -> Result<(), String>
1958where
1959  F: FnMut(&str, &str, &snapshot::CodeEntry),
1960{
1961  if let Some(namespace) = scope.namespace
1962    && !snapshot.files.contains_key(namespace)
1963  {
1964    return Err(format!("Namespace not found: {namespace}"));
1965  }
1966
1967  let package = snapshot.package.as_str();
1968  let package_prefix = format!("{package}.");
1969  let explicit_scope = scope.namespace.is_some() || scope.namespace_prefix.is_some();
1970  for (namespace, file) in &snapshot.files {
1971    if !explicit_scope && namespace.ends_with(".$meta") {
1972      continue;
1973    }
1974    if scope.namespace.is_some_and(|exact| namespace != exact) {
1975      continue;
1976    }
1977    if scope.namespace_prefix.is_some_and(|prefix| !namespace.starts_with(prefix)) {
1978      continue;
1979    }
1980    if !(scope.include_dependencies || explicit_scope || namespace == package || namespace.starts_with(&package_prefix)) {
1981      continue;
1982    }
1983    for (definition, entry) in &file.defs {
1984      visit(namespace, definition, entry);
1985    }
1986  }
1987  Ok(())
1988}
1989
1990pub(crate) fn scoped_definition_entries<'a>(
1991  snapshot: &'a snapshot::Snapshot,
1992  namespace: Option<&str>,
1993  namespace_prefix: Option<&str>,
1994  include_dependencies: bool,
1995) -> Result<Vec<(&'a str, &'a str, &'a snapshot::CodeEntry)>, String> {
1996  if let Some(namespace) = namespace
1997    && !snapshot.files.contains_key(namespace)
1998  {
1999    return Err(format!("Namespace not found: {namespace}"));
2000  }
2001  let mut entries = Vec::new();
2002  let package = snapshot.package.as_str();
2003  let package_prefix = format!("{package}.");
2004  let explicit_scope = namespace.is_some() || namespace_prefix.is_some();
2005  for (current_namespace, file) in &snapshot.files {
2006    if !explicit_scope && current_namespace.ends_with(".$meta") {
2007      continue;
2008    }
2009    if namespace.is_some_and(|exact| current_namespace != exact) {
2010      continue;
2011    }
2012    if namespace_prefix.is_some_and(|prefix| !current_namespace.starts_with(prefix)) {
2013      continue;
2014    }
2015    if !(include_dependencies || explicit_scope || current_namespace == package || current_namespace.starts_with(&package_prefix)) {
2016      continue;
2017    }
2018    for (definition, entry) in &file.defs {
2019      entries.push((current_namespace.as_str(), definition.as_str(), entry));
2020    }
2021  }
2022  entries.sort_by(|left, right| left.0.cmp(right.0).then(left.1.cmp(right.1)));
2023  Ok(entries)
2024}
2025
2026pub(crate) fn filter_weak_type_rows(options: &WeakTypesCommand, rows: &mut Vec<WeakTypeRow>) -> Result<(), String> {
2027  let selected = options
2028    .only
2029    .as_deref()
2030    .map(parse_weak_type_kinds)
2031    .transpose()?
2032    .unwrap_or_else(WeakTypeKind::all);
2033  let selected_intents = options
2034    .intent
2035    .as_deref()
2036    .map(parse_weak_type_intents)
2037    .transpose()?
2038    .unwrap_or_else(WeakTypeIntent::all);
2039  for row in rows.iter_mut() {
2040    row
2041      .occurrences
2042      .retain(|occurrence| selected.contains(&occurrence.kind) && selected_intents.contains(&occurrence.intent));
2043  }
2044  rows.retain(|row| !row.occurrences.is_empty());
2045  rows.sort_by(|a, b| a.ns.cmp(&b.ns).then(a.def.cmp(&b.def)));
2046  Ok(())
2047}
2048
2049pub fn collect_weak_type_rows(options: &WeakTypesCommand, snapshot: &snapshot::Snapshot) -> Result<Vec<WeakTypeRow>, String> {
2050  let mut rows: Vec<WeakTypeRow> = vec![];
2051
2052  visit_scoped_definitions(
2053    snapshot,
2054    AnalysisScope {
2055      namespace: options.ns.as_deref(),
2056      namespace_prefix: options.ns_prefix.as_deref(),
2057      include_dependencies: options.deps,
2058    },
2059    |namespace, definition, entry| {
2060      if let Some(row) = analyze_weak_types_entry(namespace, definition, entry, &WeakTypeKind::collected()) {
2061        rows.push(row);
2062      }
2063    },
2064  )?;
2065  filter_weak_type_rows(options, &mut rows)?;
2066  Ok(rows)
2067}
2068
2069pub(crate) fn collect_schema_candidates(
2070  options: &WeakTypesCommand,
2071  snapshot: &snapshot::Snapshot,
2072) -> Result<Vec<SchemaEvidenceCandidate>, String> {
2073  if !options.schema_evidence {
2074    return Ok(Vec::new());
2075  }
2076  let rows = collect_weak_type_rows(options, snapshot)?;
2077  let package_prefix = format!("{}.", snapshot.package);
2078  let mut targets = rows
2079    .iter()
2080    .filter(|row| options.deps || row.ns == snapshot.package || row.ns.starts_with(&package_prefix))
2081    .filter(|row| {
2082      row
2083        .occurrences
2084        .iter()
2085        .any(|occurrence| occurrence.kind == WeakTypeKind::SchemaDynamic)
2086    })
2087    .map(|row| (row.ns.clone(), row.def.clone()))
2088    .collect::<Vec<_>>();
2089  targets.sort();
2090  targets.dedup();
2091
2092  let mut project_definitions = snapshot
2093    .files
2094    .iter()
2095    .filter(|(namespace, _)| options.deps || namespace.as_str() == snapshot.package || namespace.starts_with(&package_prefix))
2096    .filter(|(namespace, _)| !namespace.ends_with(".$meta"))
2097    .flat_map(|(namespace, file)| file.defs.keys().map(|definition| (namespace.clone(), definition.clone())))
2098    .collect::<Vec<_>>();
2099  project_definitions.sort();
2100  collect_schema_evidence_candidates(snapshot, &project_definitions, &targets)
2101}
2102
2103fn syntactic_value_type(node: &Cirru) -> String {
2104  match node {
2105    Cirru::Leaf(value) if value.as_ref() == "true" || value.as_ref() == "false" => "Bool".to_owned(),
2106    Cirru::Leaf(value) if value.starts_with('|') => "String".to_owned(),
2107    Cirru::Leaf(value) if value.starts_with(':') => "Tag".to_owned(),
2108    Cirru::Leaf(value) if value.parse::<f64>().is_ok() => "Number".to_owned(),
2109    Cirru::List(items) => match items.first() {
2110      Some(Cirru::Leaf(head)) if head.as_ref() == "[]" => "List".to_owned(),
2111      Some(Cirru::Leaf(head)) if head.as_ref() == "{}" || head.as_ref() == "&{}" => "Map".to_owned(),
2112      Some(Cirru::Leaf(head)) if head.as_ref() == "#{}" => "Set".to_owned(),
2113      Some(Cirru::Leaf(head)) if head.as_ref() == "::" => "TupleOrEnum".to_owned(),
2114      Some(Cirru::Leaf(head)) if head.as_ref() == "fn" => "Fn".to_owned(),
2115      _ => "Unknown".to_owned(),
2116    },
2117    Cirru::Leaf(_) => "Unknown".to_owned(),
2118  }
2119}
2120
2121#[derive(Default)]
2122struct MapShapeAggregate {
2123  fields: BTreeMap<String, BTreeSet<String>>,
2124  paths: Vec<String>,
2125}
2126
2127fn scan_structural_candidates(
2128  node: &Cirru,
2129  definition: &str,
2130  path: &mut Vec<usize>,
2131  map_shapes: &mut BTreeMap<Vec<String>, MapShapeAggregate>,
2132  dispatch: &mut Vec<DispatchCandidate>,
2133) {
2134  let Cirru::List(items) = node else {
2135    return;
2136  };
2137  let head = items.first().and_then(|item| match item {
2138    Cirru::Leaf(value) => Some(value.as_ref()),
2139    Cirru::List(_) => None,
2140  });
2141  if matches!(head, Some("quote" | "quasiquote")) {
2142    return;
2143  }
2144  if head == Some("{}") {
2145    let mut fields = BTreeMap::<String, String>::new();
2146    let mut valid = true;
2147    for pair in items.iter().skip(1) {
2148      let Cirru::List(pair_items) = pair else {
2149        valid = false;
2150        break;
2151      };
2152      let (Some(Cirru::Leaf(key)), Some(value)) = (pair_items.first(), pair_items.get(1)) else {
2153        valid = false;
2154        break;
2155      };
2156      if pair_items.len() != 2 || !key.starts_with(':') {
2157        valid = false;
2158        break;
2159      }
2160      fields.insert(key.to_string(), syntactic_value_type(value));
2161    }
2162    if valid && fields.len() >= 2 {
2163      let key = fields.keys().cloned().collect::<Vec<_>>();
2164      let aggregate = map_shapes.entry(key).or_default();
2165      for (field, observed) in fields {
2166        aggregate.fields.entry(field).or_default().insert(observed);
2167      }
2168      aggregate.paths.push(format!("{definition}:{}", format_cirru_path("code", path)));
2169    }
2170  }
2171  if head == Some("match") && items.len() >= 4 {
2172    let mut variants = Vec::new();
2173    for branch in items.iter().skip(2) {
2174      let Cirru::List(branch_items) = branch else {
2175        continue;
2176      };
2177      let pattern = match branch_items.first() {
2178        Some(Cirru::List(pattern)) => pattern,
2179        Some(Cirru::Leaf(tag)) if tag.starts_with(':') => branch_items,
2180        _ => continue,
2181      };
2182      if let Some(Cirru::Leaf(tag)) = pattern.first()
2183        && tag.starts_with(':')
2184      {
2185        variants.push(tag.to_string());
2186      }
2187    }
2188    variants.sort();
2189    variants.dedup();
2190    if variants.len() >= 2 {
2191      dispatch.push(DispatchCandidate {
2192        diagnostic_code: "I_DISPATCH_CANDIDATE_EVIDENCE",
2193        suggested_name: format!("{}-dispatch", definition.rsplit('/').next().unwrap_or(definition)),
2194        confidence: "usage-derived",
2195        variants,
2196        evidence_paths: vec![format!("{definition}:{}", format_cirru_path("code", path))],
2197        contract_status: "review-required",
2198      });
2199    }
2200  }
2201  for (index, child) in items.iter().enumerate() {
2202    path.push(index);
2203    scan_structural_candidates(child, definition, path, map_shapes, dispatch);
2204    path.pop();
2205  }
2206}
2207
2208pub(crate) fn collect_structural_candidates(
2209  options: &WeakTypesCommand,
2210  snapshot: &snapshot::Snapshot,
2211) -> Result<StructuralCandidates, String> {
2212  if !options.schema_evidence {
2213    return Ok(StructuralCandidates::default());
2214  }
2215  let mut shapes = BTreeMap::<Vec<String>, MapShapeAggregate>::new();
2216  let mut dispatch = Vec::new();
2217  visit_scoped_definitions(
2218    snapshot,
2219    AnalysisScope {
2220      namespace: options.ns.as_deref(),
2221      namespace_prefix: options.ns_prefix.as_deref(),
2222      include_dependencies: options.deps,
2223    },
2224    |namespace, definition, entry| {
2225      let id = format!("{namespace}/{definition}");
2226      if let Cirru::List(items) = &entry.code
2227        && matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "quote")
2228        && let Some(body) = items.get(1)
2229      {
2230        scan_structural_candidates(body, &id, &mut vec![1], &mut shapes, &mut dispatch);
2231      } else {
2232        scan_structural_candidates(&entry.code, &id, &mut Vec::new(), &mut shapes, &mut dispatch);
2233      }
2234    },
2235  )?;
2236  let mut map_shapes = shapes
2237    .into_iter()
2238    .filter(|(_, aggregate)| aggregate.paths.len() >= 2)
2239    .map(|(field_names, mut aggregate)| {
2240      aggregate.paths.sort();
2241      aggregate.paths.dedup();
2242      let fields = field_names
2243        .into_iter()
2244        .map(|name| MapShapeFieldCandidate {
2245          observed_types: aggregate.fields.remove(&name).unwrap_or_default().into_iter().collect(),
2246          name,
2247        })
2248        .collect::<Vec<_>>();
2249      let has_conflict = fields.iter().any(|field| field.observed_types.len() > 1);
2250      let has_unknown = fields
2251        .iter()
2252        .any(|field| field.observed_types.iter().any(|observed| observed == "Unknown"));
2253      MapShapeCandidate {
2254        diagnostic_code: "I_MAP_SHAPE_CANDIDATE_EVIDENCE",
2255        suggested_name: format!(
2256          "record-{}",
2257          fields
2258            .iter()
2259            .map(|field| field.name.trim_start_matches(':'))
2260            .collect::<Vec<_>>()
2261            .join("-")
2262        ),
2263        confidence: if has_conflict {
2264          "conflict"
2265        } else if has_unknown {
2266          "boundary-unknown"
2267        } else {
2268          "usage-derived"
2269        },
2270        fields,
2271        evidence_paths: aggregate.paths,
2272        contract_status: "review-required",
2273      }
2274    })
2275    .collect::<Vec<_>>();
2276  map_shapes.sort_by(|left, right| left.suggested_name.cmp(&right.suggested_name));
2277  dispatch.sort_by(|left, right| left.evidence_paths.cmp(&right.evidence_paths));
2278  Ok(StructuralCandidates { map_shapes, dispatch })
2279}
2280
2281pub fn collect_ffi_boundary_evidence(
2282  options: &WeakTypesCommand,
2283  snapshot: &snapshot::Snapshot,
2284) -> Result<Vec<FfiBoundaryEvidence>, String> {
2285  let active_target = snapshot.active_entry().ok().and_then(|entry| entry.target);
2286  let package_prefix = format!("{}.", snapshot.package);
2287  let mut boundaries = Vec::new();
2288  let mut target_error = None;
2289  let mut import_namespace = None;
2290  let mut imports = BTreeMap::new();
2291
2292  visit_scoped_definitions(
2293    snapshot,
2294    AnalysisScope {
2295      namespace: options.ns.as_deref(),
2296      namespace_prefix: options.ns_prefix.as_deref(),
2297      include_dependencies: options.deps,
2298    },
2299    |namespace, definition, entry| {
2300      if target_error.is_some() {
2301        return;
2302      }
2303      // The visitor groups definitions by namespace; resolve imports and emit its advice only once.
2304      if import_namespace.as_deref() != Some(namespace) {
2305        imports = match snapshot
2306          .files
2307          .get(namespace)
2308          .map(|file| ffi_import_bindings(&file.ns.code, namespace))
2309          .transpose()
2310        {
2311          Ok(imports) => imports.unwrap_or_default(),
2312          Err(error) => {
2313            target_error = Some(error);
2314            return;
2315          }
2316        };
2317        import_namespace = Some(namespace.to_owned());
2318      }
2319      let js_implementation = match selected_js_implementation(namespace, entry) {
2320        Ok(implementation) => implementation,
2321        Err(error) => {
2322          target_error = Some(format!("Invalid FFI metadata for {namespace}/{definition}: {error}"));
2323          return;
2324        }
2325      };
2326      let mut operations = Vec::new();
2327      // Opaque JS has declaration evidence, not operations inferred from a
2328      // shadow Cirru body which is neither emitted nor executed.
2329      if js_implementation.is_none() {
2330        scan_ffi_operations(&entry.code, &mut Vec::new(), QuoteContext::default(), &imports, &mut operations);
2331      }
2332      operations.sort_by(|left, right| left.path.cmp(&right.path).then(left.kind.cmp(&right.kind)));
2333      operations.dedup();
2334
2335      let js_ffi_feature = schema_has_js_ffi(entry.schema.as_ref());
2336      if operations.is_empty() && !js_ffi_feature && entry.ffi.is_none() {
2337        return;
2338      }
2339
2340      let target = match ffi_target_name(entry, active_target) {
2341        Ok(target) => target,
2342        Err(error) => {
2343          target_error = Some(format!("Invalid FFI metadata for {namespace}/{definition}: {error}"));
2344          return;
2345        }
2346      };
2347
2348      let mut classifications = BTreeSet::new();
2349      for operation in &mut operations {
2350        let import_source = operation
2351          .source
2352          .split_once('/')
2353          .and_then(|(binding, _)| imports.get(binding))
2354          .or_else(|| imports.get(&operation.source))
2355          .map(|binding| binding.source.as_str());
2356        let classification = ffi_classification(&operation.source, import_source, active_target);
2357        operation.classification = classification.to_owned();
2358        classifications.insert(classification);
2359      }
2360      if classifications.is_empty() {
2361        let target = entry
2362          .ffi
2363          .as_ref()
2364          .and_then(|ffi| snapshot::parse_ffi_target(ffi).ok().flatten())
2365          .or(active_target);
2366        classifications.insert(ffi_classification("", None, target));
2367      }
2368      let classification = if classifications.len() == 1 {
2369        classifications.iter().next().copied().unwrap_or("unknown-host").to_owned()
2370      } else {
2371        "mixed".to_owned()
2372      };
2373
2374      let unsafe_paths = operations
2375        .iter()
2376        .filter(|operation| operation.kind == "unsafe-coerce")
2377        .map(|operation| operation.path.clone())
2378        .collect::<Vec<_>>();
2379
2380      let mut callers = Vec::new();
2381      for (caller_ns, file) in &snapshot.files {
2382        for (caller_def, caller_entry) in &file.defs {
2383          if caller_ns == namespace && caller_def == definition {
2384            continue;
2385          }
2386          match selected_js_implementation(caller_ns, caller_entry) {
2387            Ok(Some(_)) => continue,
2388            Ok(None) => {}
2389            Err(error) => {
2390              target_error = Some(format!("Invalid FFI metadata for {caller_ns}/{caller_def}: {error}"));
2391              return;
2392            }
2393          }
2394          if code_calls_definition(&caller_entry.code, caller_ns, namespace, definition) {
2395            callers.push(format!("{caller_ns}/{caller_def}"));
2396          }
2397        }
2398      }
2399      callers.sort();
2400      callers.dedup();
2401
2402      let schema_is_concrete = {
2403        let mut findings = Vec::new();
2404        scan_schema_dynamic_annotation(entry.schema.as_ref(), "schema", "root", &mut findings);
2405        findings.is_empty() && !matches!(entry.schema.as_ref(), CalcitTypeAnnotation::Dynamic)
2406      };
2407      let mut helper_candidates = Vec::new();
2408      if schema_is_concrete && js_implementation.is_none() {
2409        for (candidate_ns, file) in &snapshot.files {
2410          for (candidate_def, candidate) in &file.defs {
2411            if candidate_ns == namespace && candidate_def == definition {
2412              continue;
2413            }
2414            if candidate.schema != entry.schema || !schema_has_js_ffi(candidate.schema.as_ref()) {
2415              continue;
2416            }
2417            let candidate_target = ffi_target_name(candidate, active_target).unwrap_or_else(|_| "invalid".to_owned());
2418            if target != "unspecified" && candidate_target != "unspecified" && candidate_target != target {
2419              continue;
2420            }
2421            let project_candidate = candidate_ns == &snapshot.package || candidate_ns.starts_with(&package_prefix);
2422            helper_candidates.push(FfiHelperCandidate {
2423              definition: format!("{candidate_ns}/{candidate_def}"),
2424              origin: if project_candidate { "project" } else { "dependency" }.to_owned(),
2425              compatibility: "exact-schema".to_owned(),
2426              target: candidate_target,
2427            });
2428          }
2429        }
2430      }
2431      helper_candidates.sort_by(|left, right| {
2432        let left_rank = if left.origin == "dependency" { 0 } else { 1 };
2433        let right_rank = if right.origin == "dependency" { 0 } else { 1 };
2434        left_rank.cmp(&right_rank).then(left.definition.cmp(&right.definition))
2435      });
2436
2437      let mut member_groups = BTreeMap::<String, (BTreeSet<String>, BTreeSet<String>)>::new();
2438      for operation in &operations {
2439        if operation.kind == "module-call" {
2440          continue;
2441        }
2442        let Some(member) = &operation.member else {
2443          continue;
2444        };
2445        let group = member_groups.entry(operation.source.clone()).or_default();
2446        if operation.kind.contains("method") {
2447          group.1.insert(member.clone());
2448        } else if matches!(
2449          operation.kind.as_str(),
2450          "field-read" | "optional-field-read" | "aget" | "aset" | "js-get" | "js-set"
2451        ) {
2452          group.0.insert(member.clone());
2453        }
2454      }
2455      let trait_candidates = member_groups
2456        .into_iter()
2457        .filter(|(_, (fields, methods))| !fields.is_empty() || !methods.is_empty())
2458        .map(|(receiver, (fields, methods))| {
2459          let suggested_name = suggested_trait_name(definition);
2460          let fields: Vec<String> = fields.into_iter().collect();
2461          let methods: Vec<String> = methods.into_iter().collect();
2462          FfiTraitCandidate {
2463            receiver,
2464            defexternal_skeleton: defexternal_skeleton(&suggested_name, &target, &fields, &methods),
2465            suggested_name,
2466            fields,
2467            methods,
2468            contract_status: "review-required".to_owned(),
2469          }
2470        })
2471        .collect::<Vec<_>>();
2472
2473      let schema = schema_cirru_edn(entry.schema.as_ref()).unwrap_or_else(|error| format!("<unavailable: {error}>"));
2474      let mut adapter_sources = BTreeSet::new();
2475      for operation in &operations {
2476        if operation.kind != "module-call" {
2477          continue;
2478        }
2479        if let Some((binding, export)) = operation.source.split_once('/')
2480          && let Some(import) = imports.get(binding)
2481        {
2482          adapter_sources.insert(format!("{}/{}", import.source, export));
2483        } else if let Some(import) = imports.get(&operation.source)
2484          && let Some(member) = &operation.member
2485        {
2486          adapter_sources.insert(format!("{}/{member}", import.source));
2487        }
2488      }
2489      let adapter_candidates = adapter_sources
2490        .into_iter()
2491        .map(|source| FfiAdapterCandidate {
2492          source,
2493          suggested_definition: format!("{definition}-adapter"),
2494          schema_cirru_edn: schema.clone(),
2495          contract_status: "review-required".to_owned(),
2496        })
2497        .collect();
2498
2499      boundaries.push(FfiBoundaryEvidence {
2500        diagnostic_code: "I_FFI_BOUNDARY_EVIDENCE".to_owned(),
2501        definition: format!("{namespace}/{definition}"),
2502        classification,
2503        target,
2504        js_ffi_feature,
2505        raw_adapter_namespace: is_raw_adapter_namespace(namespace),
2506        operations,
2507        unsafe_paths,
2508        callers,
2509        helper_candidates,
2510        trait_candidates,
2511        adapter_candidates,
2512        provenance: match js_implementation {
2513          Some(implementation) => vec![
2514            match implementation.source {
2515              calcit_core::js_ffi_source::JsFfiSource::Inline(_) => "js-inline".to_owned(),
2516              calcit_core::js_ffi_source::JsFfiSource::File { path } => format!("js-file:{path}"),
2517            },
2518            "declared-schema".to_owned(),
2519            "no-runtime-trust-inference".to_owned(),
2520          ],
2521          None => vec![
2522            "snapshot-source".to_owned(),
2523            "declared-schema".to_owned(),
2524            "namespace-imports".to_owned(),
2525            "no-runtime-trust-inference".to_owned(),
2526          ],
2527        },
2528      });
2529    },
2530  )?;
2531
2532  if let Some(error) = target_error {
2533    return Err(error);
2534  }
2535
2536  boundaries.sort_by(|left, right| left.definition.cmp(&right.definition));
2537  Ok(boundaries)
2538}
2539
2540pub fn run_weak_types_report(options: &WeakTypesCommand, snapshot: &snapshot::Snapshot, out: &mut String) -> Result<(), String> {
2541  let rows = collect_weak_type_rows(options, snapshot)?;
2542  run_weak_types_report_with_rows(options, snapshot, &rows, out)
2543}
2544
2545pub(crate) fn run_weak_types_report_with_rows(
2546  options: &WeakTypesCommand,
2547  snapshot: &snapshot::Snapshot,
2548  rows: &[WeakTypeRow],
2549  out: &mut String,
2550) -> Result<(), String> {
2551  let ffi_boundaries = if options.ffi_evidence {
2552    collect_ffi_boundary_evidence(options, snapshot)?
2553  } else {
2554    Vec::new()
2555  };
2556  let schema_candidates = collect_schema_candidates(options, snapshot)?;
2557  let structural_candidates = collect_structural_candidates(options, snapshot)?;
2558
2559  if rows.is_empty()
2560    && ffi_boundaries.is_empty()
2561    && schema_candidates.is_empty()
2562    && structural_candidates.map_shapes.is_empty()
2563    && structural_candidates.dispatch.is_empty()
2564  {
2565    let _ = writeln!(out, "No weak type usage found in selected namespace scope.");
2566    return Ok(());
2567  }
2568
2569  let mut kind_count: BTreeMap<&'static str, usize> = BTreeMap::new();
2570  let mut intent_count: BTreeMap<&'static str, usize> = BTreeMap::new();
2571  let mut detail_count: BTreeMap<&'static str, BTreeMap<String, usize>> = BTreeMap::new();
2572  let mut ns_set: BTreeSet<&str> = BTreeSet::new();
2573  let mut def_count = 0usize;
2574
2575  for row in rows {
2576    def_count += 1;
2577    ns_set.insert(row.ns.as_str());
2578    for occurrence in &row.occurrences {
2579      *kind_count.entry(occurrence.kind.as_str()).or_insert(0) += 1;
2580      *intent_count.entry(occurrence.intent.as_str()).or_insert(0) += 1;
2581      if options.summary_only {
2582        continue;
2583      }
2584      *detail_count
2585        .entry(occurrence.kind.as_str())
2586        .or_default()
2587        .entry(occurrence.detail.clone())
2588        .or_insert(0) += 1;
2589    }
2590  }
2591
2592  let _ = writeln!(out, "Weak type usage check");
2593  let _ = writeln!(out, "- namespaces: {}", ns_set.len());
2594  let _ = writeln!(out, "- defs with hits: {def_count}");
2595  if let Some(raw) = &options.only {
2596    let _ = writeln!(out, "- only: {raw}");
2597  }
2598  if let Some(raw) = &options.intent {
2599    let _ = writeln!(out, "- intent-filter: {raw}");
2600  }
2601  let _ = writeln!(
2602    out,
2603    "- hits: schema-dynamic={} schema-open={} unresolved-type-slot={} code-dynamic={} code-nil={} unsafe-coerce={}",
2604    kind_count.get("schema-dynamic").copied().unwrap_or(0),
2605    kind_count.get("schema-open").copied().unwrap_or(0),
2606    kind_count.get("unresolved-type-slot").copied().unwrap_or(0),
2607    kind_count.get("code-dynamic").copied().unwrap_or(0),
2608    kind_count.get("code-nil").copied().unwrap_or(0),
2609    kind_count.get("unsafe-coerce").copied().unwrap_or(0)
2610  );
2611  // Opt-in kind: printed only when it has hits, so the default line is unchanged.
2612  if let Some(count) = kind_count.get("data-dynamic") {
2613    let _ = writeln!(out, "- data-dynamic hits: {count}");
2614  }
2615  let _ = writeln!(
2616    out,
2617    "- intents: unresolved={} intentional-js-ffi={} js-ffi-non-host={} intentional-macro-syntax={} intentional-type-slot-dynamic={} intentional-decode={} intentional-open={} explicit-unsafe={} declared-unit={}",
2618    intent_count.get("unresolved").copied().unwrap_or(0),
2619    intent_count.get("intentional-js-ffi").copied().unwrap_or(0),
2620    intent_count.get("js-ffi-non-host").copied().unwrap_or(0),
2621    intent_count.get("intentional-macro-syntax").copied().unwrap_or(0),
2622    intent_count.get("intentional-type-slot-dynamic").copied().unwrap_or(0),
2623    intent_count.get("intentional-decode").copied().unwrap_or(0),
2624    intent_count.get("intentional-open").copied().unwrap_or(0),
2625    intent_count.get("explicit-unsafe").copied().unwrap_or(0),
2626    intent_count.get("declared-unit").copied().unwrap_or(0)
2627  );
2628  if options.ffi_evidence {
2629    let mut classifications = BTreeMap::<&str, usize>::new();
2630    for boundary in &ffi_boundaries {
2631      *classifications.entry(boundary.classification.as_str()).or_insert(0) += 1;
2632    }
2633    let _ = writeln!(out, "- FFI boundaries: {}", ffi_boundaries.len());
2634    let _ = writeln!(
2635      out,
2636      "- FFI classifications: {}",
2637      classifications
2638        .iter()
2639        .map(|(name, count)| format!("{name}={count}"))
2640        .collect::<Vec<_>>()
2641        .join(" ")
2642    );
2643  }
2644  if options.schema_evidence {
2645    let _ = writeln!(out, "- schema candidates: {}", schema_candidates.len());
2646    let _ = writeln!(out, "- repeated map-shape candidates: {}", structural_candidates.map_shapes.len());
2647    let _ = writeln!(out, "- dispatch candidates: {}", structural_candidates.dispatch.len());
2648  }
2649  let unresolved_dynamic = rows
2650    .iter()
2651    .flat_map(|row| row.occurrences.iter())
2652    .filter(|occurrence| {
2653      occurrence.intent == WeakTypeIntent::Unresolved
2654        && matches!(occurrence.kind, WeakTypeKind::SchemaDynamic | WeakTypeKind::CodeDynamic)
2655    })
2656    .count();
2657  if unresolved_dynamic > 0 {
2658    let _ = writeln!(
2659      out,
2660      "- agent-note: {unresolved_dynamic} unresolved dynamic slot(s) can erase generic relations, callback checks, and compile-time method specialization."
2661    );
2662    let _ = writeln!(
2663      out,
2664      "- next: rerun without `--summary-only`; prefer concrete types, `:generics` type variables, or trait `:where` bounds before retaining a documented dynamic boundary."
2665    );
2666  }
2667  let unresolved_type_slots = rows
2668    .iter()
2669    .flat_map(|row| row.occurrences.iter())
2670    .filter(|occurrence| occurrence.intent == WeakTypeIntent::Unresolved && occurrence.kind == WeakTypeKind::UnresolvedTypeSlot)
2671    .count();
2672  if unresolved_type_slots > 0 {
2673    let _ = writeln!(
2674      out,
2675      "- agent-note: {unresolved_type_slots} type slot(s) are not bound for the selected entry and currently behave like Dynamic."
2676    );
2677    let _ = writeln!(
2678      out,
2679      "- next: bind each slot with `calcit config set-type-slot` to a named type; a `Dynamic` binding does not count as bound."
2680    );
2681  }
2682  let nil_debt = rows
2683    .iter()
2684    .flat_map(|row| row.occurrences.iter())
2685    .filter(|occurrence| {
2686      occurrence.kind == WeakTypeKind::CodeNil && matches!(occurrence.intent, WeakTypeIntent::Unresolved | WeakTypeIntent::DeclaredUnit)
2687    })
2688    .count();
2689  if nil_debt > 0 {
2690    let _ = writeln!(
2691      out,
2692      "- agent-note: {nil_debt} nil occurrence(s) are unresolved, or violate Unit returns."
2693    );
2694    let _ = writeln!(
2695      out,
2696      "- next: filter `--only code-nil --intent unresolved,declared-unit`; use `&unit` for no-value returns, then prefer Option/Result for application absence or failure."
2697    );
2698  }
2699  let unsafe_coercions = rows
2700    .iter()
2701    .flat_map(|row| row.occurrences.iter())
2702    .filter(|occurrence| occurrence.kind == WeakTypeKind::UnsafeCoerce)
2703    .count();
2704  if unsafe_coercions > 0 {
2705    let _ = writeln!(
2706      out,
2707      "- agent-note: {unsafe_coercions} explicit unsafe coercion(s) bypass static compatibility and need a documented runtime contract."
2708    );
2709    let _ = writeln!(
2710      out,
2711      "- next: rerun with `--only unsafe-coerce`; keep each assertion in a minimal adapter and add positive and negative boundary-contract tests."
2712    );
2713  }
2714  if options.summary_only {
2715    return Ok(());
2716  }
2717  if options.schema_evidence && !schema_candidates.is_empty() {
2718    let _ = writeln!(out, "\n## Schema candidate evidence");
2719    let _ = writeln!(
2720      out,
2721      "\nCompiler and usage evidence only: every candidate remains review-required until explicitly selected."
2722    );
2723    for candidate in &schema_candidates {
2724      let _ = writeln!(out, "\n### `{}`", candidate.definition);
2725      let _ = writeln!(out, "\n- diagnostic code: `{}`", candidate.diagnostic_code);
2726      let _ = writeln!(out, "- confidence: `{}`", candidate.confidence);
2727      let _ = writeln!(out, "- unresolved slots: `{}`", candidate.unresolved_slots.join(", "));
2728      let _ = writeln!(out, "- affected usages: `{}`", candidate.affected_usages.join(", "));
2729      let _ = writeln!(out, "- contract status: `{}`", candidate.contract_status);
2730    }
2731  }
2732  if options.schema_evidence && (!structural_candidates.map_shapes.is_empty() || !structural_candidates.dispatch.is_empty()) {
2733    let _ = writeln!(out, "\n## Structural candidate evidence");
2734    for candidate in &structural_candidates.map_shapes {
2735      let _ = writeln!(
2736        out,
2737        "\n- map shape `{}` confidence=`{}` fields=`{}` evidence=`{}`",
2738        candidate.suggested_name,
2739        candidate.confidence,
2740        candidate
2741          .fields
2742          .iter()
2743          .map(|field| field.name.as_str())
2744          .collect::<Vec<_>>()
2745          .join(","),
2746        candidate.evidence_paths.join(", ")
2747      );
2748    }
2749    for candidate in &structural_candidates.dispatch {
2750      let _ = writeln!(
2751        out,
2752        "\n- dispatch `{}` confidence=`{}` variants=`{}` evidence=`{}`",
2753        candidate.suggested_name,
2754        candidate.confidence,
2755        candidate.variants.join(","),
2756        candidate.evidence_paths.join(", ")
2757      );
2758    }
2759  }
2760  if options.ffi_evidence && !ffi_boundaries.is_empty() {
2761    let _ = writeln!(out, "\n## FFI boundary evidence");
2762    let _ = writeln!(
2763      out,
2764      "\nStatic migration evidence only: every candidate remains review-required and does not assert runtime trust."
2765    );
2766    for boundary in &ffi_boundaries {
2767      let _ = writeln!(out, "\n### `{}`", boundary.definition);
2768      let _ = writeln!(out, "\n- diagnostic code: `{}`", boundary.diagnostic_code);
2769      let _ = writeln!(out, "- classification: `{}`", boundary.classification);
2770      let _ = writeln!(out, "- target: `{}`", boundary.target);
2771      let _ = writeln!(out, "- js-ffi feature: `{}`", boundary.js_ffi_feature);
2772      let _ = writeln!(out, "- callers: `{}`", boundary.callers.join(", "));
2773      for operation in &boundary.operations {
2774        let _ = writeln!(
2775          out,
2776          "  - `{}` classification=`{}` source=`{}` member=`{}` path=`{}` nullable=`{}`",
2777          operation.kind,
2778          operation.classification,
2779          operation.source,
2780          operation.member.as_deref().unwrap_or("-"),
2781          operation.path,
2782          operation.nullable_evidence
2783        );
2784      }
2785      for helper in &boundary.helper_candidates {
2786        let _ = writeln!(
2787          out,
2788          "  - helper candidate: `{}` origin=`{}` compatibility=`{}`",
2789          helper.definition, helper.origin, helper.compatibility
2790        );
2791      }
2792      for candidate in &boundary.trait_candidates {
2793        let _ = writeln!(
2794          out,
2795          "  - trait manifest: `{}` receiver=`{}` fields=`{}` methods=`{}` status=`{}`",
2796          candidate.suggested_name,
2797          candidate.receiver,
2798          candidate.fields.join(","),
2799          candidate.methods.join(","),
2800          candidate.contract_status
2801        );
2802        if !candidate.defexternal_skeleton.is_empty() {
2803          let _ = writeln!(out, "    defexternal skeleton:");
2804          for line in candidate.defexternal_skeleton.lines() {
2805            let _ = writeln!(out, "      {line}");
2806          }
2807        }
2808      }
2809      for candidate in &boundary.adapter_candidates {
2810        let _ = writeln!(
2811          out,
2812          "  - adapter manifest: `{}` source=`{}` status=`{}`",
2813          candidate.suggested_definition, candidate.source, candidate.contract_status
2814        );
2815      }
2816    }
2817  }
2818  let _ = writeln!(out, "\n## Weak type details\n");
2819  let _ = writeln!(out, "- detail:");
2820  for kind in [
2821    "schema-dynamic",
2822    "schema-open",
2823    "unresolved-type-slot",
2824    "code-dynamic",
2825    "code-nil",
2826    "unsafe-coerce",
2827    "data-dynamic",
2828  ] {
2829    if matches!(kind, "data-dynamic" | "schema-open") && !detail_count.contains_key(kind) {
2830      continue;
2831    }
2832    let _ = writeln!(out, "  - {kind}");
2833    if let Some(items) = detail_count.get(kind) {
2834      for (detail, count) in items {
2835        let _ = writeln!(out, "    - {detail}={count}");
2836      }
2837    }
2838  }
2839  let _ = writeln!(out,);
2840
2841  if !rows.is_empty() {
2842    let _ = writeln!(out, "## Weak type occurrences\n");
2843  }
2844  let mut current_ns: Option<&str> = None;
2845  for row in rows {
2846    if current_ns != Some(row.ns.as_str()) {
2847      let _ = writeln!(out, "namespace: {}", row.ns);
2848      current_ns = Some(row.ns.as_str());
2849    }
2850
2851    let _ = writeln!(out, "- def: {}", row.def);
2852    for occurrence in &row.occurrences {
2853      let _ = writeln!(
2854        out,
2855        "  - {} [{}] ({}) @ {}",
2856        occurrence.kind.as_str(),
2857        occurrence.intent.as_str(),
2858        occurrence.detail,
2859        occurrence.path
2860      );
2861      if let Some(evidence) = &occurrence.unsafe_evidence {
2862        let _ = writeln!(
2863          out,
2864          "    evidence: source-form={} target={} js-ffi-feature={} raw-adapter-namespace={}",
2865          evidence.source_form, evidence.target_schema, evidence.js_ffi_feature, evidence.raw_adapter_namespace
2866        );
2867      }
2868      let _ = writeln!(out, "    fix: {}", weak_type_suggestion(occurrence));
2869    }
2870    let _ = writeln!(out,);
2871  }
2872
2873  Ok(())
2874}
2875
2876pub fn collect_type_coverage_rows(options: &CheckTypesCommand, snapshot: &snapshot::Snapshot) -> Result<Vec<TypeCoverageRow>, String> {
2877  let mut rows: Vec<TypeCoverageRow> = Vec::new();
2878  visit_scoped_definitions(
2879    snapshot,
2880    AnalysisScope {
2881      namespace: options.ns.as_deref(),
2882      namespace_prefix: options.ns_prefix.as_deref(),
2883      include_dependencies: options.deps,
2884    },
2885    |namespace, definition, entry| rows.push(analyze_code_entry(namespace, definition, entry)),
2886  )?;
2887
2888  filter_type_coverage_rows(options, &mut rows)?;
2889  Ok(rows)
2890}
2891
2892pub(crate) fn filter_type_coverage_rows(options: &CheckTypesCommand, rows: &mut Vec<TypeCoverageRow>) -> Result<(), String> {
2893  if let Some(raw) = &options.only {
2894    let selected = parse_coverage_levels(raw)?;
2895    rows.retain(|row| selected.contains(&row.level));
2896  }
2897  rows.sort_by(|a, b| {
2898    a.ns
2899      .cmp(&b.ns)
2900      .then(a.level.cmp(&b.level))
2901      .then(a.kind.as_str().cmp(b.kind.as_str()))
2902      .then(a.def.cmp(&b.def))
2903  });
2904  Ok(())
2905}
2906
2907pub fn run_check_types_report(options: &CheckTypesCommand, snapshot: &snapshot::Snapshot, out: &mut String) -> Result<(), String> {
2908  let rows = collect_type_coverage_rows(options, snapshot)?;
2909  run_check_types_report_with_rows(options, &rows, out)
2910}
2911
2912pub(crate) fn run_check_types_report_with_rows(
2913  options: &CheckTypesCommand,
2914  rows: &[TypeCoverageRow],
2915  out: &mut String,
2916) -> Result<(), String> {
2917  if rows.is_empty() {
2918    let _ = writeln!(out, "No definitions found in selected namespace scope.");
2919    return Ok(());
2920  }
2921
2922  let mut level_count: BTreeMap<&'static str, usize> = BTreeMap::new();
2923  let mut kind_count: BTreeMap<&'static str, usize> = BTreeMap::new();
2924  let mut ns_set: BTreeSet<String> = BTreeSet::new();
2925  let mut polymorphic_defs = 0usize;
2926  let mut bounded_polymorphic_defs = 0usize;
2927
2928  for row in rows {
2929    *level_count.entry(row.level.as_str()).or_insert(0) += 1;
2930    *kind_count.entry(row.kind.as_str()).or_insert(0) += 1;
2931    ns_set.insert(row.ns.clone());
2932    if !row.generics.is_empty() {
2933      polymorphic_defs += 1;
2934      if !row.where_bounds.is_empty() {
2935        bounded_polymorphic_defs += 1;
2936      }
2937    }
2938  }
2939
2940  let _ = writeln!(out, "Type coverage check");
2941  let _ = writeln!(out, "- namespaces: {}", ns_set.len());
2942  let _ = writeln!(out, "- defs: {}", rows.len());
2943  if let Some(raw) = &options.only {
2944    let _ = writeln!(out, "- only: {raw}");
2945  }
2946  let _ = writeln!(
2947    out,
2948    "- levels: full={} partial={} none={}",
2949    level_count.get("full").copied().unwrap_or(0),
2950    level_count.get("partial").copied().unwrap_or(0),
2951    level_count.get("none").copied().unwrap_or(0)
2952  );
2953  let _ = writeln!(
2954    out,
2955    "- kinds: fn={} macro={} proc={} syntax={} data={} other={}",
2956    kind_count.get("fn").copied().unwrap_or(0),
2957    kind_count.get("macro").copied().unwrap_or(0),
2958    kind_count.get("proc").copied().unwrap_or(0),
2959    kind_count.get("syntax").copied().unwrap_or(0),
2960    kind_count.get("data").copied().unwrap_or(0),
2961    kind_count.get("other").copied().unwrap_or(0)
2962  );
2963  let _ = writeln!(
2964    out,
2965    "- polymorphism: generic={polymorphic_defs} trait-bounded={bounded_polymorphic_defs}"
2966  );
2967  let coverage_gaps = level_count.get("partial").copied().unwrap_or(0) + level_count.get("none").copied().unwrap_or(0);
2968  if coverage_gaps > 0 {
2969    let _ = writeln!(
2970      out,
2971      "- agent-note: {coverage_gaps} definition(s) lack full static coverage; unresolved dynamic slots can hide parametric relationships and force runtime method dispatch."
2972    );
2973    let _ = writeln!(
2974      out,
2975      "- next: `calcit analyze weak-types --only schema-dynamic,unresolved-type-slot,code-dynamic --intent unresolved --summary-only`, then scope the reported namespaces and rerun without `--summary-only`."
2976    );
2977  }
2978  if options.summary_only {
2979    return Ok(());
2980  }
2981  let _ = writeln!(out,);
2982
2983  let mut current_ns: Option<&str> = None;
2984
2985  for row in rows {
2986    let typed_params = count_typed_params(&row.params, &row.param_annotations);
2987    let total_params = row.params.len();
2988
2989    if current_ns != Some(row.ns.as_str()) {
2990      let _ = writeln!(out, "namespace: {}", row.ns);
2991      current_ns = Some(row.ns.as_str());
2992    }
2993
2994    let _ = writeln!(out, "- def: {}", row.def);
2995    let _ = writeln!(out, "  kind: {}", row.kind.as_str());
2996    let _ = writeln!(out, "  coverage: {}", row.level.as_str());
2997    if !row.generics.is_empty() {
2998      let _ = writeln!(out, "  generics: {}", row.generics.join(", "));
2999    }
3000    if !row.where_bounds.is_empty() {
3001      let _ = writeln!(out, "  where:");
3002      for bound in &row.where_bounds {
3003        let _ = writeln!(out, "    - {bound}");
3004      }
3005    }
3006
3007    match row.kind {
3008      DefKind::Data => {
3009        let _ = writeln!(
3010          out,
3011          "  data-type: {}",
3012          row.data_type.clone().unwrap_or_else(|| "unknown".to_string())
3013        );
3014      }
3015      DefKind::Fn => {
3016        if row.return_type_hints.is_empty() {
3017          let _ = writeln!(out, "  return: (no hint)");
3018        } else {
3019          let _ = writeln!(out, "  return:");
3020          for item in &row.return_type_hints {
3021            let _ = writeln!(out, "    - {item}");
3022          }
3023        }
3024
3025        let _ = writeln!(out, "  params ({typed_params}/{total_params}):");
3026        if total_params == 0 {
3027          let _ = writeln!(out, "    - (no params)");
3028        } else {
3029          for name in &row.params {
3030            match row.param_annotations.get(name) {
3031              Some(types) if !types.is_empty() => {
3032                let _ = writeln!(out, "    - {} => {}", name, types.join(" | "));
3033              }
3034              _ => {
3035                let _ = writeln!(out, "    - {name} => (no assert-type)");
3036              }
3037            }
3038          }
3039        }
3040      }
3041      DefKind::Macro => {
3042        let _ = writeln!(out, "  params ({typed_params}/{total_params}):");
3043        if total_params == 0 {
3044          let _ = writeln!(out, "    - (no params)");
3045        } else {
3046          for name in &row.params {
3047            match row.param_annotations.get(name) {
3048              Some(types) if !types.is_empty() => {
3049                let _ = writeln!(out, "    - {} => {}", name, types.join(" | "));
3050              }
3051              _ => {
3052                let _ = writeln!(out, "    - {name} => (no assert-type)");
3053              }
3054            }
3055          }
3056        }
3057      }
3058      DefKind::Proc => {
3059        if row.return_type_hints.is_empty() {
3060          let _ = writeln!(out, "  return: (no hint)");
3061        } else {
3062          let _ = writeln!(out, "  return:");
3063          for item in &row.return_type_hints {
3064            let _ = writeln!(out, "    - {item}");
3065          }
3066        }
3067
3068        let _ = writeln!(out, "  params ({typed_params}/{total_params}):");
3069        if total_params == 0 {
3070          let _ = writeln!(out, "    - (no params)");
3071        } else {
3072          for name in &row.params {
3073            match row.param_annotations.get(name) {
3074              Some(types) if !types.is_empty() => {
3075                let _ = writeln!(out, "    - {} => {}", name, types.join(" | "));
3076              }
3077              _ => {
3078                let _ = writeln!(out, "    - {name} => (no assert-type)");
3079              }
3080            }
3081          }
3082        }
3083      }
3084      DefKind::Syntax => {
3085        if row.return_type_hints.is_empty() {
3086          let _ = writeln!(out, "  return: (no hint)");
3087        } else {
3088          let _ = writeln!(out, "  return:");
3089          for item in &row.return_type_hints {
3090            let _ = writeln!(out, "    - {item}");
3091          }
3092        }
3093
3094        let _ = writeln!(out, "  params ({typed_params}/{total_params}):");
3095        if total_params == 0 {
3096          let _ = writeln!(out, "    - (no params)");
3097        } else {
3098          for name in &row.params {
3099            match row.param_annotations.get(name) {
3100              Some(types) if !types.is_empty() => {
3101                let _ = writeln!(out, "    - {} => {}", name, types.join(" | "));
3102              }
3103              _ => {
3104                let _ = writeln!(out, "    - {name} => (no assert-type)");
3105              }
3106            }
3107          }
3108        }
3109      }
3110      DefKind::Other => {
3111        let _ = writeln!(out, "  details: no type pattern recognized");
3112      }
3113    }
3114
3115    if !row.schema_issues.is_empty() {
3116      let _ = writeln!(out, "  schema-issues:");
3117      for issue in &row.schema_issues {
3118        let _ = writeln!(out, "    - {issue}");
3119      }
3120    }
3121
3122    let _ = writeln!(out,);
3123  }
3124
3125  Ok(())
3126}
3127
3128fn analyze_builtin_syntax(def_name: &str, sig: &SyntaxTypeSignature) -> TypeCoverageRow {
3129  let params: Vec<String> = sig.param_names.iter().map(|s| s.to_string()).collect();
3130
3131  let param_annotations: BTreeMap<String, Vec<String>> = sig
3132    .param_types
3133    .iter()
3134    .zip(sig.param_names.iter())
3135    .map(|(t, name)| {
3136      let type_str = t.describe();
3137      (name.to_string(), vec![type_str])
3138    })
3139    .collect();
3140
3141  let return_type_hints = vec![sig.return_type.describe()];
3142
3143  let typed_count = param_annotations.values().filter(|v| !v.is_empty()).count();
3144  let level = if params.is_empty() || typed_count == params.len() {
3145    CoverageLevel::Full
3146  } else if typed_count > 0 {
3147    CoverageLevel::Partial
3148  } else {
3149    CoverageLevel::None
3150  };
3151
3152  TypeCoverageRow {
3153    ns: calcit_core::calcit::CORE_NS.to_owned(),
3154    def: def_name.to_owned(),
3155    kind: DefKind::Syntax,
3156    level,
3157    params,
3158    param_annotations,
3159    return_type_hints,
3160    generics: vec![],
3161    where_bounds: vec![],
3162    data_type: None,
3163    schema_issues: vec![],
3164  }
3165}
3166
3167fn analyze_builtin_proc(def_name: &str, sig: &ProcTypeSignature) -> TypeCoverageRow {
3168  let params: Vec<String> = sig.arg_types.iter().enumerate().map(|(i, _)| format!("arg{i}")).collect();
3169
3170  let param_annotations: BTreeMap<String, Vec<String>> = sig
3171    .arg_types
3172    .iter()
3173    .enumerate()
3174    .map(|(i, t)| {
3175      let name = format!("arg{i}");
3176      let type_str = t.describe();
3177      (name, vec![type_str])
3178    })
3179    .collect();
3180
3181  let return_type_hints = vec![sig.return_type.describe()];
3182
3183  let typed_count = param_annotations.values().filter(|v| !v.is_empty()).count();
3184  let level = if params.is_empty() || typed_count == params.len() {
3185    CoverageLevel::Full
3186  } else if typed_count > 0 {
3187    CoverageLevel::Partial
3188  } else {
3189    CoverageLevel::None
3190  };
3191
3192  TypeCoverageRow {
3193    ns: calcit_core::calcit::CORE_NS.to_owned(),
3194    def: def_name.to_owned(),
3195    kind: DefKind::Proc,
3196    level,
3197    params,
3198    param_annotations,
3199    return_type_hints,
3200    generics: vec![],
3201    where_bounds: vec![],
3202    data_type: None,
3203    schema_issues: vec![],
3204  }
3205}
3206
3207/// Inventory the same definition/schema contract used by preprocessing.
3208/// Source Cirru owns only the code-kind and parameter-shape decoding here.
3209pub fn validate_def_vs_schema(ns: &str, def_name: &str, code: &Cirru, schema: &CalcitTypeAnnotation) -> Vec<String> {
3210  if matches!(code, Cirru::Leaf(s) if s.as_ref() == "&runtime-implementation") {
3211    return vec![];
3212  }
3213  if !matches!(schema, CalcitTypeAnnotation::Fn(_) | CalcitTypeAnnotation::Macro(_)) {
3214    return vec![];
3215  }
3216  let Cirru::List(xs) = code else { return vec![] };
3217  let code_kind = xs
3218    .first()
3219    .and_then(|head| match head {
3220      Cirru::Leaf(head) => Some(head.as_ref()),
3221      _ => None,
3222    })
3223    .unwrap_or("non-macro definition");
3224  if matches!(schema, CalcitTypeAnnotation::Fn(_)) && !matches!(code_kind, "defn" | "defmacro") {
3225    return vec![];
3226  }
3227  let code_shape = analyze_param_shape(xs.get(2));
3228  validate_definition_schema_shape(&format!("{ns}/{def_name}"), code_kind, &code_shape, schema)
3229}
3230
3231/// Count required params and detect rest param from a defn/defmacro args form.
3232pub fn analyze_param_arity(args: Option<&Cirru>) -> (usize, bool) {
3233  let shape = analyze_param_shape(args);
3234  (shape.required, shape.has_rest)
3235}
3236
3237fn analyze_param_shape(args: Option<&Cirru>) -> ParamShape {
3238  let Some(Cirru::List(xs)) = args else {
3239    return ParamShape::from_tokens([]);
3240  };
3241  ParamShape::from_tokens(xs.iter().filter_map(|item| match item {
3242    Cirru::Leaf(s) if matches!(s.as_ref(), "[]" | ",") => None,
3243    Cirru::Leaf(s) if s.as_ref() == "?" => Some(ParamShapeToken::LegacyOptionalMark),
3244    Cirru::Leaf(s) if s.as_ref() == "&" => Some(ParamShapeToken::RestMark),
3245    _ => Some(ParamShapeToken::Binding),
3246  }))
3247}
3248
3249pub fn analyze_code_entry(ns: &str, def_name: &str, entry: &snapshot::CodeEntry) -> TypeCoverageRow {
3250  // First check if this is a builtin proc in calcit.core
3251  if ns == calcit_core::calcit::CORE_NS {
3252    if let Ok(proc) = (*def_name).parse::<CalcitProc>()
3253      && let Some(sig) = proc.get_type_signature()
3254    {
3255      return analyze_builtin_proc(def_name, sig);
3256    }
3257    // Then check if this is a builtin syntax
3258    if let Ok(syntax) = (*def_name).parse::<CalcitSyntax>()
3259      && let Some(sig) = syntax.get_type_signature()
3260    {
3261      return analyze_builtin_syntax(def_name, &sig);
3262    }
3263  }
3264
3265  if let CalcitTypeAnnotation::Macro(signature) = entry.schema.as_ref() {
3266    let contract_label = |contract: &MacroSyntaxType| match contract {
3267      MacroSyntaxType::Syntax => "Syntax".to_owned(),
3268      MacroSyntaxType::SyntaxSymbol => "SyntaxSymbol".to_owned(),
3269      MacroSyntaxType::SyntaxList => "SyntaxList".to_owned(),
3270      MacroSyntaxType::Expr(semantic) => format!("Expr<{}>", semantic.to_brief_string()),
3271    };
3272    let mut params = vec![];
3273    let mut param_annotations = BTreeMap::new();
3274    for (idx, contract) in signature.required_inputs.iter().enumerate() {
3275      let name = format!("arg-{}", idx + 1);
3276      params.push(name.clone());
3277      param_annotations.insert(name, vec![contract_label(contract)]);
3278    }
3279    for (idx, contract) in signature.optional_inputs.iter().enumerate() {
3280      let name = format!("optional-{}", idx + 1);
3281      params.push(name.clone());
3282      param_annotations.insert(name, vec![contract_label(contract)]);
3283    }
3284    if let Some(contract) = &signature.rest_input {
3285      params.push("rest".to_owned());
3286      param_annotations.insert("rest".to_owned(), vec![contract_label(contract)]);
3287    }
3288    let expansion = match &signature.expansion {
3289      MacroExpansionType::Dynamic => "Dynamic".to_owned(),
3290      MacroExpansionType::Expr(semantic) => format!("Expr<{}>", semantic.to_brief_string()),
3291      MacroExpansionType::Definition(semantic) => format!("Definition<{}>", semantic.to_brief_string()),
3292      MacroExpansionType::Declarations => "Declarations".to_owned(),
3293    };
3294    let level = if !matches!(signature.expansion, MacroExpansionType::Dynamic) {
3295      CoverageLevel::Full
3296    } else {
3297      CoverageLevel::Partial
3298    };
3299    return TypeCoverageRow {
3300      ns: ns.to_owned(),
3301      def: def_name.to_owned(),
3302      kind: DefKind::Macro,
3303      level: downgrade_coverage_for_dynamic_annotation(level, entry.schema.as_ref()),
3304      params,
3305      param_annotations,
3306      return_type_hints: vec![expansion],
3307      generics: signature.generics.iter().map(|name| format!("'{name}")).collect(),
3308      where_bounds: signature.where_bounds.iter().map(|bound| bound.to_brief_string()).collect(),
3309      data_type: None,
3310      schema_issues: entry_schema_issues(ns, def_name, &entry.code, &entry.schema),
3311    };
3312  }
3313
3314  // Function schemas are the canonical source for top-level callable coverage.
3315  // Definition payloads may use `fn` values instead of `defn`, so relying on
3316  // the source head alone incorrectly classifies typed functions as `other`.
3317  if let CalcitTypeAnnotation::Fn(fn_annot) = entry.schema.as_ref()
3318    && let Ok(schema) = snapshot::schema_edn_to_cirru(&fn_annot.to_schema_edn())
3319    && let Some((params, param_annotations, return_type_hints, level)) = extract_fn_schema_hints(&schema)
3320  {
3321    let level = downgrade_coverage_for_dynamic_annotation(level, entry.schema.as_ref());
3322    let (generics, where_bounds) = fn_polymorphism(fn_annot);
3323    return TypeCoverageRow {
3324      ns: ns.to_owned(),
3325      def: def_name.to_owned(),
3326      kind: match fn_annot.fn_kind {
3327        SchemaKind::Fn => DefKind::Fn,
3328        SchemaKind::Macro => DefKind::Macro,
3329      },
3330      level,
3331      params,
3332      param_annotations,
3333      return_type_hints,
3334      generics,
3335      where_bounds,
3336      data_type: None,
3337      schema_issues: entry_schema_issues(ns, def_name, &entry.code, &entry.schema),
3338    };
3339  }
3340
3341  fn type_form_contains_dynamic(form: &Cirru) -> bool {
3342    match form {
3343      Cirru::Leaf(value) => value.as_ref() == ":dynamic",
3344      Cirru::List(items) => items.iter().any(type_form_contains_dynamic),
3345    }
3346  }
3347
3348  fn embedded_type_declaration_coverage(head: &str, items: &[Cirru]) -> CoverageLevel {
3349    let mut typed_slots = 0usize;
3350    let mut dynamic_slots = 0usize;
3351
3352    fn entry_parts(node: &Cirru, prefix: char) -> Option<&[Cirru]> {
3353      match unwrap_singleton_group(node) {
3354        Cirru::List(parts) if matches!(parts.first(), Some(Cirru::Leaf(name)) if name.starts_with(prefix)) => Some(parts.as_slice()),
3355        _ => None,
3356      }
3357    }
3358
3359    match head {
3360      "defstruct" => {
3361        let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
3362        for field in items.iter().skip(2 + clauses) {
3363          let Some(parts) = entry_parts(field, ':') else {
3364            continue;
3365          };
3366          let field_type = parts.get(1);
3367          match field_type {
3368            Some(form) if !type_form_contains_dynamic(form) => typed_slots += 1,
3369            _ => dynamic_slots += 1,
3370          }
3371        }
3372      }
3373      "defenum" => {
3374        let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
3375        for variant in items.iter().skip(2 + clauses) {
3376          let Some(parts) = entry_parts(variant, ':') else {
3377            continue;
3378          };
3379          for payload_type in parts.iter().skip(1) {
3380            if type_form_contains_dynamic(payload_type) {
3381              dynamic_slots += 1;
3382            } else {
3383              typed_slots += 1;
3384            }
3385          }
3386        }
3387      }
3388      "defunion" | "deftype" => {
3389        let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
3390        for member in items.iter().skip(2 + clauses) {
3391          let mut dynamic_leaves = vec![];
3392          collect_dynamic_leaves(member, &mut vec![], &mut dynamic_leaves);
3393          if dynamic_leaves.is_empty() {
3394            typed_slots += 1;
3395          } else {
3396            dynamic_slots += 1;
3397          }
3398        }
3399      }
3400      "deftrait" => {
3401        for method in items.iter().skip(2) {
3402          if entry_parts(method, '.').is_none() {
3403            continue;
3404          }
3405          if type_form_contains_dynamic(method) {
3406            dynamic_slots += 1;
3407          } else {
3408            typed_slots += 1;
3409          }
3410        }
3411      }
3412      "defexternal" => {
3413        let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
3414        for member in items.iter().skip(2 + clauses) {
3415          if entry_parts(member, '.').is_none() && entry_parts(member, ':').is_none() {
3416            continue;
3417          }
3418          if type_form_contains_dynamic(member) {
3419            dynamic_slots += 1;
3420          } else {
3421            typed_slots += 1;
3422          }
3423        }
3424      }
3425      "defimpl" => {
3426        for method in items.iter().skip(3) {
3427          if entry_parts(method, '.').is_none() {
3428            continue;
3429          }
3430          if type_form_contains_dynamic(method) {
3431            dynamic_slots += 1;
3432          } else {
3433            typed_slots += 1;
3434          }
3435        }
3436      }
3437      _ => {}
3438    }
3439
3440    if dynamic_slots == 0 {
3441      CoverageLevel::Full
3442    } else if typed_slots > 0 || matches!(head, "defstruct" | "defenum") {
3443      CoverageLevel::Partial
3444    } else {
3445      CoverageLevel::None
3446    }
3447  }
3448
3449  fn explicit_data_schema(annotation: &CalcitTypeAnnotation) -> Option<(String, CoverageLevel)> {
3450    if matches!(annotation, CalcitTypeAnnotation::Dynamic) {
3451      return None;
3452    }
3453    let description = annotation.describe();
3454    if matches!(description.as_str(), "dynamic" | "unknown") {
3455      return None;
3456    }
3457    let mut dynamic_parts = vec![];
3458    scan_schema_dynamic_annotation(annotation, "schema", "root", &mut dynamic_parts);
3459    dynamic_parts.retain(|occurrence| occurrence.intent != WeakTypeIntent::IntentionalOpen);
3460    let level = if dynamic_parts.is_empty() {
3461      CoverageLevel::Full
3462    } else {
3463      CoverageLevel::Partial
3464    };
3465    Some((description, level))
3466  }
3467
3468  let (kind, params, param_annotations, return_type_hints, data_type, level) = match &entry.code {
3469    Cirru::List(xs) => match xs.first() {
3470      Some(Cirru::Leaf(head))
3471        if matches!(
3472          head.as_ref(),
3473          "defstruct" | "defenum" | "defunion" | "deftype" | "deftrait" | "defimpl" | "defexternal"
3474        ) =>
3475      {
3476        (
3477          DefKind::Data,
3478          Vec::new(),
3479          BTreeMap::new(),
3480          Vec::new(),
3481          Some(head.trim_start_matches("def").to_owned()),
3482          embedded_type_declaration_coverage(head, xs),
3483        )
3484      }
3485      Some(Cirru::Leaf(head)) if &**head == "defn" => {
3486        if let CalcitTypeAnnotation::Fn(fn_annot) = entry.schema.as_ref()
3487          && let Ok(schema) = snapshot::schema_edn_to_cirru(&fn_annot.to_schema_edn())
3488          && let Some((params, param_annotations, return_type_hints, level)) = extract_fn_schema_hints(&schema)
3489        {
3490          let level = downgrade_coverage_for_dynamic_annotation(level, entry.schema.as_ref());
3491          let (generics, where_bounds) = fn_polymorphism(fn_annot);
3492          return TypeCoverageRow {
3493            ns: ns.to_owned(),
3494            def: def_name.to_owned(),
3495            kind: DefKind::Fn,
3496            level,
3497            params,
3498            param_annotations,
3499            return_type_hints,
3500            generics,
3501            where_bounds,
3502            data_type: None,
3503            schema_issues: entry_schema_issues(ns, def_name, &entry.code, &entry.schema),
3504          };
3505        }
3506        if std::env::var("CR_DEBUG_SCHEMA").is_ok() {
3507          let schema_kind = match entry.schema.as_ref() {
3508            CalcitTypeAnnotation::Fn(fn_annot) => match snapshot::schema_edn_to_cirru(&fn_annot.to_schema_edn()) {
3509              Ok(schema) => match extract_fn_schema_hints(&schema) {
3510                Some(_) => "Fn/schema-hints-ok".to_owned(),
3511                None => "Fn/schema-hints-none".to_owned(),
3512              },
3513              Err(e) => format!("Fn/edn-to-cirru-err:{e}"),
3514            },
3515            other => format!("non-fn:{other:?}"),
3516          };
3517          eprintln!("[debug] {ns}/{def_name}: schema={schema_kind}");
3518        }
3519
3520        let args = xs.get(2);
3521        let body = &xs[3..];
3522        let params = extract_param_symbols(args);
3523        let param_annotations = extract_assert_type_annotations(body);
3524        let return_type_hints = extract_return_type_hints(body);
3525        let typed_count = count_typed_params(&params, &param_annotations);
3526        let ret_typed = !return_type_hints.is_empty();
3527        let level = if ret_typed && (params.is_empty() || typed_count == params.len()) {
3528          CoverageLevel::Full
3529        } else if ret_typed || typed_count > 0 {
3530          CoverageLevel::Partial
3531        } else {
3532          CoverageLevel::None
3533        };
3534        (DefKind::Fn, params, param_annotations, return_type_hints, None, level)
3535      }
3536      Some(Cirru::Leaf(head)) if &**head == "defmacro" => {
3537        let args = xs.get(2);
3538        let body = &xs[3..];
3539        let params = extract_param_symbols(args);
3540        let param_annotations = extract_assert_type_annotations(body);
3541        let typed_count = count_typed_params(&params, &param_annotations);
3542        let level = if typed_count > 0 {
3543          CoverageLevel::Partial
3544        } else {
3545          CoverageLevel::None
3546        };
3547        (DefKind::Macro, params, param_annotations, Vec::new(), None, level)
3548      }
3549      Some(Cirru::Leaf(head)) if &**head == "def" => {
3550        let inferred = xs.get(2).and_then(infer_data_type);
3551        let explicit = explicit_data_schema(entry.schema.as_ref());
3552        let data_type = inferred.or_else(|| explicit.as_ref().map(|(data_type, _)| data_type.clone()));
3553        let level = explicit.map(|(_, level)| level).unwrap_or_else(|| {
3554          if data_type.is_some() {
3555            CoverageLevel::Full
3556          } else {
3557            CoverageLevel::None
3558          }
3559        });
3560        (DefKind::Data, Vec::new(), BTreeMap::new(), Vec::new(), data_type, level)
3561      }
3562      Some(Cirru::Leaf(head)) if head.as_ref() == "defref" => {
3563        let explicit = explicit_data_schema(entry.schema.as_ref());
3564        let (data_type, level) = explicit.unwrap_or_else(|| ("ref<dynamic>".to_owned(), CoverageLevel::Partial));
3565        (DefKind::Data, Vec::new(), BTreeMap::new(), Vec::new(), Some(data_type), level)
3566      }
3567      _ => match explicit_data_schema(entry.schema.as_ref()) {
3568        Some((data_type, level)) => (DefKind::Data, Vec::new(), BTreeMap::new(), Vec::new(), Some(data_type), level),
3569        None => (DefKind::Other, Vec::new(), BTreeMap::new(), Vec::new(), None, CoverageLevel::None),
3570      },
3571    },
3572    _ => match explicit_data_schema(entry.schema.as_ref()) {
3573      Some((data_type, level)) => (DefKind::Data, Vec::new(), BTreeMap::new(), Vec::new(), Some(data_type), level),
3574      None => (DefKind::Other, Vec::new(), BTreeMap::new(), Vec::new(), None, CoverageLevel::None),
3575    },
3576  };
3577  let (generics, where_bounds) = entry_polymorphism(entry);
3578
3579  TypeCoverageRow {
3580    ns: ns.to_owned(),
3581    def: def_name.to_owned(),
3582    kind,
3583    level,
3584    params,
3585    param_annotations,
3586    return_type_hints,
3587    generics,
3588    where_bounds,
3589    data_type,
3590    schema_issues: entry_schema_issues(ns, def_name, &entry.code, &entry.schema),
3591  }
3592}
3593
3594fn schema_to_map(schema: &Cirru) -> Option<BTreeMap<&str, &Cirru>> {
3595  let Cirru::List(items) = schema else {
3596    return None;
3597  };
3598  let Some(Cirru::Leaf(head)) = items.first() else {
3599    return None;
3600  };
3601
3602  let mut data = BTreeMap::new();
3603  match &**head {
3604    "&{}" => {
3605      if (items.len() - 1) % 2 != 0 {
3606        return None;
3607      }
3608      for idx in (1..items.len()).step_by(2) {
3609        let key = match &items[idx] {
3610          Cirru::Leaf(s) if s.starts_with(':') => s.as_ref(),
3611          _ => return None,
3612        };
3613        data.insert(key, &items[idx + 1]);
3614      }
3615    }
3616    "{}" => {
3617      for pair in items.iter().skip(1) {
3618        let Cirru::List(xs) = pair else {
3619          return None;
3620        };
3621        if xs.len() != 2 {
3622          return None;
3623        }
3624        let key = match &xs[0] {
3625          Cirru::Leaf(s) if s.starts_with(':') => s.as_ref(),
3626          _ => return None,
3627        };
3628        data.insert(key, &xs[1]);
3629      }
3630    }
3631    _ => return None,
3632  }
3633  Some(data)
3634}
3635
3636fn is_schema_list_annotation(node: &Cirru) -> bool {
3637  match node {
3638    Cirru::Leaf(s) => s.as_ref() == ":list",
3639    Cirru::List(xs) => {
3640      matches!(xs.first(), Some(Cirru::Leaf(head)) if &**head == "::")
3641        && matches!(xs.get(1), Some(Cirru::Leaf(tag)) if &**tag == ":list")
3642    }
3643  }
3644}
3645
3646fn render_schema_param_type(ty_node: Option<&Cirru>, wrap_rest_as_list: bool) -> String {
3647  let Some(ty_node) = ty_node else {
3648    return ":dynamic".to_owned();
3649  };
3650
3651  let rendered = render_cirru_inline(ty_node);
3652  if !wrap_rest_as_list || rendered == ":dynamic" || is_schema_list_annotation(ty_node) {
3653    rendered
3654  } else {
3655    format!(":: :list {rendered}")
3656  }
3657}
3658
3659fn read_schema_param_wrapped(item: &Cirru, default_name: &str, wrap_rest_as_list: bool) -> Option<(String, String)> {
3660  match item {
3661    Cirru::Leaf(_) => Some((default_name.to_owned(), render_schema_param_type(Some(item), wrap_rest_as_list))),
3662    Cirru::List(xs) => {
3663      let Some(Cirru::Leaf(head)) = xs.first() else {
3664        return None;
3665      };
3666      if &**head != "[]" && &**head != "::" {
3667        return None;
3668      }
3669
3670      match xs.len() {
3671        2 => {
3672          let ty = render_schema_param_type(xs.get(1), wrap_rest_as_list);
3673          Some((default_name.to_owned(), ty))
3674        }
3675        3 => {
3676          let ty_node = match xs.get(1) {
3677            Some(Cirru::Leaf(name)) if name.starts_with('\'') => xs.get(2),
3678            _ => Some(item),
3679          };
3680          let ty = render_schema_param_type(ty_node, wrap_rest_as_list);
3681          Some((default_name.to_owned(), ty))
3682        }
3683        _ => None,
3684      }
3685    }
3686  }
3687}
3688
3689type FnSchemaHints = (Vec<String>, BTreeMap<String, Vec<String>>, Vec<String>, CoverageLevel);
3690
3691pub fn extract_fn_schema_hints(schema: &Cirru) -> Option<FnSchemaHints> {
3692  let schema = schema_to_map(schema)?;
3693
3694  let mut params: Vec<String> = Vec::new();
3695  let mut param_annotations: BTreeMap<String, Vec<String>> = BTreeMap::new();
3696
3697  if let Some(args_node) = schema.get(":args")
3698    && let Cirru::List(items) = args_node
3699    && matches!(items.first(), Some(Cirru::Leaf(head)) if &**head == "[]")
3700  {
3701    for (idx, item) in items.iter().skip(1).enumerate() {
3702      if let Some((name, ty)) = read_schema_param_wrapped(item, &format!("arg{idx}"), false) {
3703        params.push(name.clone());
3704        param_annotations.entry(name).or_default().push(ty);
3705      }
3706    }
3707  }
3708
3709  if let Some(rest_node) = schema.get(":rest")
3710    && let Some((name, ty)) = read_schema_param_wrapped(rest_node, "rest", true)
3711  {
3712    params.push(name.clone());
3713    param_annotations.entry(name).or_default().push(ty);
3714  }
3715
3716  let return_type_hints = vec![
3717    schema
3718      .get(":return")
3719      .map_or_else(|| ":dynamic".to_owned(), |v| render_cirru_inline(v)),
3720  ];
3721
3722  let typed_count = params
3723    .iter()
3724    .filter(|name| {
3725      param_annotations
3726        .get(*name)
3727        .is_some_and(|hints| hints.iter().any(|hint| hint != ":dynamic"))
3728    })
3729    .count();
3730
3731  let ret_typed = return_type_hints.iter().any(|hint| hint != ":dynamic");
3732  let level = if ret_typed && (params.is_empty() || typed_count == params.len()) {
3733    CoverageLevel::Full
3734  } else if ret_typed || typed_count > 0 {
3735    CoverageLevel::Partial
3736  } else {
3737    CoverageLevel::None
3738  };
3739
3740  Some((params, param_annotations, return_type_hints, level))
3741}
3742
3743fn extract_param_symbols(args: Option<&Cirru>) -> Vec<String> {
3744  let mut out: Vec<String> = vec![];
3745  if let Some(node) = args {
3746    collect_param_symbols(node, &mut out);
3747  }
3748  dedup_keep_order(out)
3749}
3750
3751fn collect_param_symbols(node: &Cirru, out: &mut Vec<String>) {
3752  match node {
3753    Cirru::Leaf(s) => {
3754      let name = s.as_ref();
3755      if name == "&" || name == "?" || name == "[]" || name == "," {
3756        return;
3757      }
3758      if name.starts_with('|') || name.starts_with(':') || name.chars().all(|c| c.is_ascii_digit()) {
3759        return;
3760      }
3761      out.push(name.to_string());
3762    }
3763    Cirru::List(xs) => {
3764      for x in xs {
3765        collect_param_symbols(x, out);
3766      }
3767    }
3768  }
3769}
3770
3771fn extract_assert_type_annotations(nodes: &[Cirru]) -> BTreeMap<String, Vec<String>> {
3772  let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
3773  for node in nodes {
3774    collect_assert_type_annotations(node, &mut out);
3775  }
3776
3777  for items in out.values_mut() {
3778    let mut seen: BTreeSet<String> = BTreeSet::new();
3779    items.retain(|v| seen.insert(v.to_owned()));
3780  }
3781
3782  out
3783}
3784
3785fn collect_assert_type_annotations(node: &Cirru, out: &mut BTreeMap<String, Vec<String>>) {
3786  match node {
3787    Cirru::Leaf(_) => {}
3788    Cirru::List(xs) => {
3789      if let Some(Cirru::Leaf(head)) = xs.first()
3790        && &**head == "assert-type"
3791        && let Some(Cirru::Leaf(symbol)) = xs.get(1)
3792        && let Some(ty_node) = xs.get(2)
3793      {
3794        out.entry(symbol.to_string()).or_default().push(render_cirru_inline(ty_node));
3795      }
3796
3797      for x in xs {
3798        collect_assert_type_annotations(x, out);
3799      }
3800    }
3801  }
3802}
3803
3804fn extract_return_type_hints(nodes: &[Cirru]) -> Vec<String> {
3805  let mut out: Vec<String> = Vec::new();
3806  for node in nodes {
3807    collect_return_type_hints(node, &mut out);
3808  }
3809
3810  let mut seen: BTreeSet<String> = BTreeSet::new();
3811  out.retain(|v| seen.insert(v.to_owned()));
3812  out
3813}
3814
3815fn collect_return_type_hints(node: &Cirru, out: &mut Vec<String>) {
3816  match node {
3817    Cirru::Leaf(_) => {}
3818    Cirru::List(xs) => {
3819      if let Some(Cirru::Leaf(head)) = xs.first()
3820        && &**head == "return-type"
3821        && let Some(ty_node) = xs.get(1)
3822      {
3823        out.push(render_cirru_inline(ty_node));
3824      }
3825
3826      for x in xs {
3827        collect_return_type_hints(x, out);
3828      }
3829    }
3830  }
3831}
3832
3833pub fn count_typed_params(params: &[String], annotations: &BTreeMap<String, Vec<String>>) -> usize {
3834  params
3835    .iter()
3836    .filter(|name| annotations.get(*name).is_some_and(|items| !items.is_empty()))
3837    .count()
3838}
3839
3840fn dedup_keep_order(items: Vec<String>) -> Vec<String> {
3841  let mut seen: BTreeSet<String> = BTreeSet::new();
3842  let mut out: Vec<String> = Vec::new();
3843  for item in items {
3844    if seen.insert(item.to_owned()) {
3845      out.push(item);
3846    }
3847  }
3848  out
3849}
3850
3851fn render_cirru_inline(node: &Cirru) -> String {
3852  match node {
3853    Cirru::Leaf(s) => s.to_string(),
3854    Cirru::List(xs) => {
3855      let parts = xs.iter().map(render_cirru_inline).collect::<Vec<_>>().join(" ");
3856      format!("({parts})")
3857    }
3858  }
3859}
3860
3861pub fn parse_coverage_levels(raw: &str) -> Result<BTreeSet<CoverageLevel>, String> {
3862  let mut selected: BTreeSet<CoverageLevel> = BTreeSet::new();
3863
3864  for part in raw.split(',') {
3865    let token = part.trim().to_ascii_lowercase();
3866    if token.is_empty() {
3867      continue;
3868    }
3869
3870    match token.as_str() {
3871      "none" => {
3872        selected.insert(CoverageLevel::None);
3873      }
3874      "partial" => {
3875        selected.insert(CoverageLevel::Partial);
3876      }
3877      "full" => {
3878        selected.insert(CoverageLevel::Full);
3879      }
3880      _ => {
3881        return Err(format!(
3882          "Unknown coverage level `{token}` in --only. Expected comma-separated values from: none,partial,full"
3883        ));
3884      }
3885    }
3886  }
3887
3888  if selected.is_empty() {
3889    return Err("`--only` is empty. Use one or more of: none,partial,full".to_string());
3890  }
3891
3892  Ok(selected)
3893}
3894
3895fn infer_data_type(node: &Cirru) -> Option<String> {
3896  match node {
3897    Cirru::Leaf(s) => {
3898      let raw = s.as_ref();
3899      if raw == "nil" {
3900        Some("nil".to_string())
3901      } else if raw == "true" || raw == "false" {
3902        Some("bool".to_string())
3903      } else if raw.starts_with('|') {
3904        Some("string".to_string())
3905      } else if raw.starts_with(':') {
3906        Some("tag".to_string())
3907      } else if raw.parse::<f64>().is_ok() {
3908        Some("number".to_string())
3909      } else {
3910        None
3911      }
3912    }
3913    Cirru::List(xs) => match xs.first() {
3914      Some(Cirru::Leaf(head)) if &**head == "[]" => Some("list".to_string()),
3915      Some(Cirru::Leaf(head)) if &**head == "{}" || &**head == "&{}" => Some("map".to_string()),
3916      Some(Cirru::Leaf(head)) if &**head == "#{}" => Some("set".to_string()),
3917      Some(Cirru::Leaf(head)) if &**head == "::" => Some("tuple".to_string()),
3918      Some(Cirru::Leaf(head)) if &**head == "defn" || &**head == "fn" => Some("fn".to_string()),
3919      Some(Cirru::Leaf(head)) if &**head == "defmacro" => Some("macro".to_string()),
3920      _ => None,
3921    },
3922  }
3923}
3924
3925pub fn analysis_revision(snapshot: &snapshot::Snapshot, definitions: &[(String, String)]) -> Result<String, String> {
3926  let mut ids = definitions.to_vec();
3927  ids.sort();
3928  ids.dedup();
3929  let mut hasher = Md5::new();
3930  for (namespace, definition) in ids {
3931    let entry = snapshot
3932      .files
3933      .get(&namespace)
3934      .and_then(|file| file.defs.get(&definition))
3935      .ok_or_else(|| format!("Definition disappeared while computing analysis revision: {namespace}/{definition}"))?;
3936    let revision = snapshot::definition_revision(entry)?;
3937    let id = format!("{namespace}/{definition}");
3938    hasher.update((id.len() as u64).to_le_bytes());
3939    hasher.update(id.as_bytes());
3940    hasher.update(revision.as_bytes());
3941  }
3942  Ok(format!("md5:{}", hex::encode(hasher.finalize())))
3943}
3944
3945pub fn format_check_types_json(options: &CheckTypesCommand, snapshot: &snapshot::Snapshot) -> Result<String, String> {
3946  let rows = collect_type_coverage_rows(options, snapshot)?;
3947  format_check_types_json_with_rows(options, snapshot, &rows)
3948}
3949
3950pub fn format_check_types_json_with_rows(
3951  options: &CheckTypesCommand,
3952  snapshot: &snapshot::Snapshot,
3953  rows: &[TypeCoverageRow],
3954) -> Result<String, String> {
3955  let mut levels = BTreeMap::<&str, usize>::new();
3956  let mut kinds = BTreeMap::<&str, usize>::new();
3957  let mut namespaces = BTreeSet::<&str>::new();
3958  let mut polymorphic_defs = 0usize;
3959  let mut bounded_polymorphic_defs = 0usize;
3960  for row in rows {
3961    *levels.entry(row.level.as_str()).or_insert(0) += 1;
3962    *kinds.entry(row.kind.as_str()).or_insert(0) += 1;
3963    namespaces.insert(row.ns.as_str());
3964    if !row.generics.is_empty() {
3965      polymorphic_defs += 1;
3966      if !row.where_bounds.is_empty() {
3967        bounded_polymorphic_defs += 1;
3968      }
3969    }
3970  }
3971  for level in ["none", "partial", "full"] {
3972    levels.entry(level).or_insert(0);
3973  }
3974  for kind in ["fn", "macro", "proc", "syntax", "data", "other"] {
3975    kinds.entry(kind).or_insert(0);
3976  }
3977
3978  let definitions = rows
3979    .iter()
3980    .filter(|_| !options.summary_only)
3981    .map(|row| {
3982      let parameters = row
3983        .params
3984        .iter()
3985        .map(|name| {
3986          serde_json::json!({
3987            "name": name,
3988            "types": row.param_annotations.get(name).cloned().unwrap_or_default(),
3989          })
3990        })
3991        .collect::<Vec<_>>();
3992      serde_json::json!({
3993        "id": format!("{}/{}", row.ns, row.def),
3994        "namespace": row.ns,
3995        "name": row.def,
3996        "kind": row.kind.as_str(),
3997        "coverage": row.level.as_str(),
3998        "parameters": parameters,
3999        "return_types": row.return_type_hints,
4000        "generics": row.generics,
4001        "where_bounds": row.where_bounds,
4002        "data_type": row.data_type,
4003        "schema_issues": row.schema_issues,
4004      })
4005    })
4006    .collect::<Vec<_>>();
4007  let coverage_gaps = levels.get("partial").copied().unwrap_or(0) + levels.get("none").copied().unwrap_or(0);
4008  let mut diagnostics = vec![];
4009  if coverage_gaps > 0 {
4010    diagnostics.push(serde_json::json!({
4011      "code": "W_TYPE_COVERAGE_GAPS",
4012      "phase": "analysis",
4013      "severity": "warning",
4014      "message": format!("{coverage_gaps} definition(s) lack full static coverage; unresolved dynamic slots can hide generic relations and force runtime method dispatch."),
4015      "suggestion": "Run `calcit analyze weak-types --only schema-dynamic,unresolved-type-slot,code-dynamic --intent unresolved --format json`; bind required type slots, then prefer concrete types, declared type variables, or trait `:where` bounds.",
4016    }));
4017  }
4018  let ids = rows.iter().map(|row| (row.ns.clone(), row.def.clone())).collect::<Vec<_>>();
4019  let envelope = serde_json::json!({
4020    "schema_version": 2,
4021    "command": "analyze.check-types",
4022    "revision": analysis_revision(snapshot, &ids)?,
4023    "data": {
4024      "filters": {
4025        "namespace": options.ns,
4026        "namespace_prefix": options.ns_prefix,
4027        "only": options.only,
4028        "include_dependencies": options.deps,
4029        "summary_only": options.summary_only,
4030        "incremental": options.incremental,
4031      },
4032      "summary": {
4033        "namespaces": namespaces.len(),
4034        "definitions": rows.len(),
4035        "levels": levels,
4036        "kinds": kinds,
4037        "polymorphism": {
4038          "generic_definitions": polymorphic_defs,
4039          "trait_bounded_definitions": bounded_polymorphic_defs,
4040        },
4041      },
4042      "definitions": definitions,
4043    },
4044    "diagnostics": diagnostics,
4045  });
4046  serde_json::to_string_pretty(&envelope).map_err(|error| format!("Failed to encode type coverage JSON: {error}"))
4047}
4048
4049pub fn format_weak_types_json(options: &WeakTypesCommand, snapshot: &snapshot::Snapshot) -> Result<String, String> {
4050  let rows = collect_weak_type_rows(options, snapshot)?;
4051  format_weak_types_json_with_rows(options, snapshot, &rows)
4052}
4053
4054pub fn format_weak_types_json_with_rows(
4055  options: &WeakTypesCommand,
4056  snapshot: &snapshot::Snapshot,
4057  rows: &[WeakTypeRow],
4058) -> Result<String, String> {
4059  let ffi_boundaries = if options.ffi_evidence {
4060    collect_ffi_boundary_evidence(options, snapshot)?
4061  } else {
4062    Vec::new()
4063  };
4064  let schema_candidates = collect_schema_candidates(options, snapshot)?;
4065  let structural_candidates = collect_structural_candidates(options, snapshot)?;
4066  let mut kinds = BTreeMap::<&str, usize>::new();
4067  let mut intents = BTreeMap::<&str, usize>::new();
4068  let mut namespaces = BTreeSet::<&str>::new();
4069  for row in rows {
4070    namespaces.insert(row.ns.as_str());
4071    for occurrence in &row.occurrences {
4072      *kinds.entry(occurrence.kind.as_str()).or_insert(0) += 1;
4073      *intents.entry(occurrence.intent.as_str()).or_insert(0) += 1;
4074    }
4075  }
4076  for kind in [
4077    "schema-dynamic",
4078    "schema-open",
4079    "unresolved-type-slot",
4080    "code-dynamic",
4081    "code-nil",
4082    "unsafe-coerce",
4083  ] {
4084    kinds.entry(kind).or_insert(0);
4085  }
4086  for intent in [
4087    "unresolved",
4088    "intentional-js-ffi",
4089    "js-ffi-non-host",
4090    "intentional-macro-syntax",
4091    "intentional-type-slot-dynamic",
4092    "intentional-decode",
4093    "intentional-open",
4094    "explicit-unsafe",
4095    "declared-unit",
4096  ] {
4097    intents.entry(intent).or_insert(0);
4098  }
4099
4100  let definitions = rows
4101    .iter()
4102    .filter(|_| !options.summary_only)
4103    .map(|row| {
4104      serde_json::json!({
4105        "id": format!("{}/{}", row.ns, row.def),
4106        "namespace": row.ns,
4107        "name": row.def,
4108        "occurrences": row.occurrences.iter().map(|occurrence| {
4109          let evidence = occurrence.unsafe_evidence.as_ref().map(|evidence| serde_json::json!({
4110            "source_form": evidence.source_form,
4111            "target_schema": evidence.target_schema,
4112            "js_ffi_feature": evidence.js_ffi_feature,
4113            "raw_adapter_namespace": evidence.raw_adapter_namespace,
4114          }));
4115          serde_json::json!({
4116            "kind": occurrence.kind.as_str(),
4117            "intent": occurrence.intent.as_str(),
4118            "detail": occurrence.detail,
4119            "path": occurrence.path,
4120            "evidence": evidence,
4121            "suggestion": weak_type_suggestion(occurrence),
4122          })
4123        }).collect::<Vec<_>>(),
4124      })
4125    })
4126    .collect::<Vec<_>>();
4127  let mut ids = rows.iter().map(|row| (row.ns.clone(), row.def.clone())).collect::<Vec<_>>();
4128  for boundary in &ffi_boundaries {
4129    if let Some((namespace, definition)) = boundary.definition.split_once('/') {
4130      ids.push((namespace.to_owned(), definition.to_owned()));
4131    }
4132  }
4133  ids.sort();
4134  ids.dedup();
4135  let hit_count = rows.iter().map(|row| row.occurrences.len()).sum::<usize>();
4136  let unresolved_dynamic = rows
4137    .iter()
4138    .flat_map(|row| row.occurrences.iter())
4139    .filter(|occurrence| {
4140      occurrence.intent == WeakTypeIntent::Unresolved
4141        && matches!(occurrence.kind, WeakTypeKind::SchemaDynamic | WeakTypeKind::CodeDynamic)
4142    })
4143    .count();
4144  let unresolved_type_slots = rows
4145    .iter()
4146    .flat_map(|row| row.occurrences.iter())
4147    .filter(|occurrence| occurrence.intent == WeakTypeIntent::Unresolved && occurrence.kind == WeakTypeKind::UnresolvedTypeSlot)
4148    .count();
4149  let nil_debt = rows
4150    .iter()
4151    .flat_map(|row| row.occurrences.iter())
4152    .filter(|occurrence| {
4153      occurrence.kind == WeakTypeKind::CodeNil && matches!(occurrence.intent, WeakTypeIntent::Unresolved | WeakTypeIntent::DeclaredUnit)
4154    })
4155    .count();
4156  let unsafe_coercions = rows
4157    .iter()
4158    .flat_map(|row| row.occurrences.iter())
4159    .filter(|occurrence| occurrence.kind == WeakTypeKind::UnsafeCoerce)
4160    .count();
4161  let mut diagnostics = vec![];
4162  if unresolved_dynamic > 0 {
4163    diagnostics.push(serde_json::json!({
4164      "code": "W_DYNAMIC_TYPE_DEBT",
4165      "phase": "analysis",
4166      "severity": "warning",
4167      "message": format!("{unresolved_dynamic} unresolved dynamic slot(s) erase static relationships used by generic binding, callback checking, and method specialization."),
4168      "suggestion": "Prefer concrete types; use `:generics` when positions share a type and trait `:where` bounds when only capabilities are required. Keep `:dynamic` only at documented boundaries.",
4169    }));
4170  }
4171  if unresolved_type_slots > 0 {
4172    diagnostics.push(serde_json::json!({
4173      "code": "W_UNRESOLVED_TYPE_SLOT",
4174      "phase": "analysis",
4175      "severity": "warning",
4176      "message": format!("{unresolved_type_slots} type slot(s) are unbound for the selected entry and therefore accept every value as though they were Dynamic."),
4177      "suggestion": "Bind each slot with `calcit config set-type-slot <slot> <namespace/definition>`; a `Dynamic` binding does not count as bound.",
4178    }));
4179  }
4180  if nil_debt > 0 {
4181    diagnostics.push(serde_json::json!({
4182      "code": "W_NIL_TYPE_DEBT",
4183      "phase": "analysis",
4184      "severity": "warning",
4185      "message": format!("{nil_debt} nil occurrence(s) are unresolved, or violate Unit returns."),
4186      "suggestion": "Use `&unit` for no-value returns. Prefer Option for application absence and Result when failure details matter; keep JsNullish only at JavaScript FFI boundaries.",
4187    }));
4188  }
4189  if unsafe_coercions > 0 {
4190    diagnostics.push(serde_json::json!({
4191      "code": "W_JS_FFI_UNCHECKED_COERCE",
4192      "phase": "analysis",
4193      "severity": "warning",
4194      "message": format!("{unsafe_coercions} explicit unsafe coercion(s) bypass static compatibility and need an audited runtime contract when they cross an untrusted boundary."),
4195      "suggestion": "Keep each assertion at a minimal trusted boundary, validate or normalize untrusted runtime data before application code consumes it, and add positive and negative runtime-contract tests.",
4196    }));
4197  }
4198  let ffi_boundary_count = ffi_boundaries.len();
4199  let schema_candidate_count = schema_candidates.len();
4200  let map_shape_candidate_count = structural_candidates.map_shapes.len();
4201  let dispatch_candidate_count = structural_candidates.dispatch.len();
4202  let ffi_boundary_rows = if options.summary_only { Vec::new() } else { ffi_boundaries };
4203  let schema_candidate_rows = if options.summary_only { Vec::new() } else { schema_candidates };
4204  let structural_candidate_rows = if options.summary_only {
4205    StructuralCandidates::default()
4206  } else {
4207    structural_candidates
4208  };
4209  let envelope = serde_json::json!({
4210    "schema_version": 9,
4211    "command": "analyze.weak-types",
4212    "revision": analysis_revision(snapshot, &ids)?,
4213    "data": {
4214      "filters": {
4215        "namespace": options.ns,
4216        "namespace_prefix": options.ns_prefix,
4217        "only": options.only,
4218        "intent": options.intent,
4219        "include_dependencies": options.deps,
4220        "ffi_evidence": options.ffi_evidence,
4221        "schema_evidence": options.schema_evidence,
4222        "summary_only": options.summary_only,
4223        "incremental": options.incremental,
4224      },
4225      "summary": {
4226        "namespaces": namespaces.len(),
4227        "definitions": rows.len(),
4228        "hits": hit_count,
4229        "ffi_boundaries": ffi_boundary_count,
4230        "schema_candidates": schema_candidate_count,
4231        "map_shape_candidates": map_shape_candidate_count,
4232        "dispatch_candidates": dispatch_candidate_count,
4233        "kinds": kinds,
4234        "intents": intents,
4235      },
4236      "definitions": definitions,
4237      "evidence": {
4238        "ffi_boundaries": ffi_boundary_rows,
4239        "schema_candidates": schema_candidate_rows,
4240        "map_shapes": structural_candidate_rows.map_shapes,
4241        "dispatch": structural_candidate_rows.dispatch,
4242        "contract_status": "review-required",
4243        "runtime_trust_inferred": false,
4244      },
4245    },
4246    "diagnostics": diagnostics,
4247  });
4248  serde_json::to_string_pretty(&envelope).map_err(|error| format!("Failed to encode weak type JSON: {error}"))
4249}
4250
4251pub fn format_check_types(options: &CheckTypesCommand, snapshot: &snapshot::Snapshot) -> Result<String, String> {
4252  let mut out = String::new();
4253  run_check_types_report(options, snapshot, &mut out)?;
4254  Ok(out)
4255}
4256
4257pub fn format_check_types_with_rows(options: &CheckTypesCommand, rows: &[TypeCoverageRow]) -> Result<String, String> {
4258  let mut out = String::new();
4259  run_check_types_report_with_rows(options, rows, &mut out)?;
4260  Ok(out)
4261}
4262
4263pub fn format_weak_types(options: &WeakTypesCommand, snapshot: &snapshot::Snapshot) -> Result<String, String> {
4264  let mut out = String::new();
4265  run_weak_types_report(options, snapshot, &mut out)?;
4266  Ok(out)
4267}
4268
4269pub fn format_weak_types_with_rows(
4270  options: &WeakTypesCommand,
4271  snapshot: &snapshot::Snapshot,
4272  rows: &[WeakTypeRow],
4273) -> Result<String, String> {
4274  let mut out = String::new();
4275  run_weak_types_report_with_rows(options, snapshot, rows, &mut out)?;
4276  Ok(out)
4277}
4278
4279#[cfg(test)]
4280mod tests {
4281  use std::collections::HashSet;
4282  use std::sync::Arc;
4283
4284  use calcit_core::calcit::{
4285    CalcitTypeAnnotation, MacroExpansionType, MacroSignature, MacroSyntaxType, clear_type_slots, push_type_slot_override,
4286  };
4287  use cirru_parser::Cirru;
4288
4289  use super::{
4290    WeakTypeIntent, WeakTypeKind, classify_unsafe_coerce_source, defexternal_skeleton, entry_schema_issues, is_defexternal_member_name,
4291    is_raw_adapter_namespace, scan_schema_dynamic_annotation,
4292  };
4293
4294  fn leaf(value: &str) -> Cirru {
4295    Cirru::Leaf(Arc::from(value))
4296  }
4297
4298  fn list(items: Vec<Cirru>) -> Cirru {
4299    Cirru::List(items)
4300  }
4301
4302  #[test]
4303  fn ffi_import_origins_reuse_resolver_rules() {
4304    let rule = |source, kind, local| list(vec![leaf(source), leaf(kind), local]);
4305    let code = list(vec![
4306      leaf("ns"),
4307      leaf("app.main"),
4308      list(vec![
4309        leaf(":require"),
4310        rule("app.lib", ":as", leaf("lib")),
4311        rule("app.lib", ":refer", list(vec![leaf("increment")])),
4312        rule("|package", ":as", leaf("npm")),
4313        rule("\"node:fs", ":as", leaf("fs")),
4314        rule("|node:fs", ":refer", list(vec![leaf("existsSync")])),
4315        rule("package-default", ":default", leaf("default-package")),
4316      ]),
4317    ]);
4318    let imports = super::ffi_import_bindings(&code, "app.main").expect("resolver imports should parse");
4319    assert_eq!(imports.len(), 4);
4320    assert_eq!(imports["npm"].source, "package");
4321    assert_eq!(imports["fs"].source, "node:fs");
4322    assert_eq!(imports["default-package"].member.as_deref(), Some("default"));
4323    assert_eq!(imports["existsSync"].member.as_deref(), Some("existsSync"));
4324    assert!(super::ffi_import_bindings(&leaf("invalid-ns"), "app.main").is_err());
4325  }
4326
4327  fn scan(annotation: CalcitTypeAnnotation) -> Vec<super::WeakTypeOccurrence> {
4328    let mut occurrences = vec![];
4329    scan_schema_dynamic_annotation(&annotation, "schema", "root", &mut occurrences);
4330    occurrences
4331  }
4332
4333  fn macro_schema(
4334    required_inputs: Vec<MacroSyntaxType>,
4335    rest_input: Option<MacroSyntaxType>,
4336    expansion: MacroExpansionType,
4337  ) -> CalcitTypeAnnotation {
4338    CalcitTypeAnnotation::Macro(Arc::new(MacroSignature {
4339      generics: Arc::new(vec![]),
4340      where_bounds: Arc::new(vec![]),
4341      required_inputs: Arc::new(required_inputs),
4342      optional_inputs: Arc::new(vec![]),
4343      rest_input,
4344      expansion,
4345      capabilities: Arc::new(HashSet::new()),
4346      features: Arc::new(HashSet::new()),
4347    }))
4348  }
4349
4350  #[test]
4351  fn defexternal_skeleton_filters_unexpressible_members() {
4352    assert!(is_defexternal_member_name("textContent"));
4353    assert!(is_defexternal_member_name("focus!"));
4354    assert!(!is_defexternal_member_name("0"));
4355    assert!(!is_defexternal_member_name("|b"));
4356    assert!(!is_defexternal_member_name(""));
4357
4358    let skeleton = defexternal_skeleton(
4359      "QueryHost",
4360      "browser",
4361      &["length".to_owned(), "0".to_owned()],
4362      &["query".to_owned(), "|b".to_owned()],
4363    );
4364    assert_eq!(
4365      skeleton,
4366      "defexternal QueryHost\n  :target :browser\n  :length 'Dynamic\n  .query $ :: 'Fn $ {} (:args $ [] 'QueryHost) (:return 'Dynamic)"
4367    );
4368    // The multi-line skeleton must itself be a valid `defexternal` body.
4369    let parsed = cirru_parser::parse(&skeleton)
4370      .expect("skeleton should parse as Cirru")
4371      .into_iter()
4372      .next()
4373      .expect("skeleton should contain one expression");
4374    calcit_core::snapshot::validate_defexternal_shorthand(&parsed, "demo/QueryHost")
4375      .expect("generated skeleton should validate as defexternal");
4376
4377    // No expressible member means no paste-ready skeleton.
4378    assert_eq!(defexternal_skeleton("QueryHost", "browser", &["0".to_owned()], &[]), "");
4379    // Unknown targets are omitted rather than guessed.
4380    assert!(!defexternal_skeleton("QueryHost", "unspecified", &["length".to_owned()], &[]).contains(":target"));
4381  }
4382
4383  #[test]
4384  fn open_expr_positions_in_strict_macros_have_intentional_syntax_intent() {
4385    let annotation = macro_schema(
4386      vec![MacroSyntaxType::Expr(Arc::new(CalcitTypeAnnotation::Dynamic))],
4387      Some(MacroSyntaxType::Expr(Arc::new(CalcitTypeAnnotation::Dynamic))),
4388      MacroExpansionType::Expr(Arc::new(CalcitTypeAnnotation::Dynamic)),
4389    );
4390
4391    let occurrences = scan(annotation.clone());
4392
4393    assert_eq!(occurrences.len(), 3);
4394    assert!(
4395      occurrences
4396        .iter()
4397        .all(|occurrence| occurrence.intent == WeakTypeIntent::IntentionalMacroSyntax)
4398    );
4399    let issues = entry_schema_issues(
4400      "app.main",
4401      "open-macro",
4402      &list(vec![
4403        leaf("defmacro"),
4404        leaf("open-macro"),
4405        list(vec![leaf("x"), leaf("&"), leaf("xs")]),
4406        leaf("body"),
4407      ]),
4408      &Arc::new(annotation),
4409    );
4410    assert!(
4411      issues.is_empty(),
4412      "reviewed Expr<Dynamic> boundaries should not be unresolved: {issues:?}"
4413    );
4414  }
4415
4416  #[test]
4417  fn reasoned_open_signatures_have_intentional_open_intent() {
4418    let schema = |text: &str| {
4419      let form = cirru_parser::parse(text).expect("parse schema").remove(0);
4420      calcit_core::snapshot::parse_schema_annotation_for_write(&form).expect("schema parses")
4421    };
4422    // A reason covers the signature it is written on and everything below it.
4423    let marked = schema("Fn Dynamic (Fn Dynamic (-> Dynamic)) (-> Dynamic) (:open :intrinsic)");
4424    let occurrences = scan(marked.as_ref().clone());
4425    assert_eq!(occurrences.len(), 4);
4426    assert!(occurrences.iter().all(|it| it.intent == WeakTypeIntent::IntentionalOpen));
4427    assert_eq!(
4428      super::downgrade_coverage_for_dynamic_annotation(super::CoverageLevel::Full, marked.as_ref()),
4429      super::CoverageLevel::Full
4430    );
4431    // A reason on the inner callback leaves the outer positions unresolved.
4432    let inner = schema("Fn Dynamic (Fn Dynamic (-> Dynamic) (:open :reflect)) (-> Number)");
4433    let intents: Vec<WeakTypeIntent> = scan(inner.as_ref().clone()).iter().map(|it| it.intent).collect();
4434    assert_eq!(
4435      intents,
4436      vec![
4437        WeakTypeIntent::Unresolved,
4438        WeakTypeIntent::IntentionalOpen,
4439        WeakTypeIntent::IntentionalOpen
4440      ]
4441    );
4442    assert_eq!(
4443      super::downgrade_coverage_for_dynamic_annotation(super::CoverageLevel::Full, inner.as_ref()),
4444      super::CoverageLevel::Partial
4445    );
4446  }
4447
4448  #[test]
4449  fn weak_type_rows_apply_the_root_open_reason() {
4450    let schema = |text: &str| {
4451      let form = cirru_parser::parse(text).expect("parse schema").remove(0);
4452      calcit_core::snapshot::parse_schema_annotation_for_write(&form).expect("schema parses")
4453    };
4454    let row_intents = |text: &str| {
4455      let mut entry = calcit_core::snapshot::CodeEntry::from_code(cirru_parser::parse("defn f (x) x").expect("parse code").remove(0));
4456      entry.schema = schema(text);
4457      super::analyze_weak_types_entry("app.main", "f", &entry, &WeakTypeKind::collected())
4458        .map(|row| {
4459          row
4460            .occurrences
4461            .iter()
4462            .filter(|it| it.kind == WeakTypeKind::SchemaDynamic)
4463            .map(|it| it.intent)
4464            .collect::<Vec<_>>()
4465        })
4466        .unwrap_or_default()
4467    };
4468    let reasoned = row_intents("Fn Dynamic (-> Dynamic) (:open :reflect)");
4469    assert_eq!(reasoned.len(), 2);
4470    assert!(reasoned.iter().all(|intent| *intent == WeakTypeIntent::IntentionalOpen));
4471    let plain = row_intents("Fn Dynamic (-> Dynamic)");
4472    assert_eq!(plain, vec![WeakTypeIntent::Unresolved, WeakTypeIntent::Unresolved]);
4473  }
4474
4475  #[test]
4476  fn schema_open_reports_open_family_types_with_reason_and_filter() {
4477    let schema = |text: &str| {
4478      let form = cirru_parser::parse(text).expect("parse schema").remove(0);
4479      calcit_core::snapshot::parse_schema_annotation_for_write(&form).expect("schema parses")
4480    };
4481    let mut reasoned_entry = calcit_core::snapshot::CodeEntry::from_code(
4482      cirru_parser::parse("defn client-option-callback (k) None")
4483        .expect("parse code")
4484        .remove(0),
4485    );
4486    reasoned_entry.schema = schema("Fn Number (-> (Option AnyFn)) (:open :decode)");
4487
4488    let reasoned_row = super::analyze_weak_types_entry("app.main", "client-option-callback", &reasoned_entry, &WeakTypeKind::all())
4489      .expect("Option AnyFn with (:open :decode) must appear in weak-types");
4490    assert_eq!(reasoned_row.occurrences.len(), 1);
4491    let occ = &reasoned_row.occurrences[0];
4492    assert_eq!(occ.kind, WeakTypeKind::SchemaOpen);
4493    assert_eq!(occ.intent, WeakTypeIntent::IntentionalOpen);
4494    assert_eq!(occ.path, "schema.return.type-arg.0");
4495    assert_eq!(occ.detail, "schema-open:AnyFn:return:type-arg:open=decode");
4496
4497    let dynamic_only = super::analyze_weak_types_entry(
4498      "app.main",
4499      "client-option-callback",
4500      &reasoned_entry,
4501      &super::parse_weak_type_kinds("schema-dynamic").expect("filter parses"),
4502    );
4503    assert!(
4504      dynamic_only.is_none(),
4505      "schema-dynamic filter must keep SchemaDynamic counts unchanged"
4506    );
4507
4508    let mut plain_entry =
4509      calcit_core::snapshot::CodeEntry::from_code(cirru_parser::parse("defn f (x) x").expect("parse code").remove(0));
4510    plain_entry.schema = schema("Fn AnyEnum (-> AnyStruct)");
4511    let plain_row = super::analyze_weak_types_entry("app.main", "f", &plain_entry, &WeakTypeKind::all())
4512      .expect("AnyEnum/AnyStruct must appear in weak-types");
4513    assert_eq!(plain_row.occurrences.len(), 2);
4514    assert!(plain_row.occurrences.iter().all(|it| it.kind == WeakTypeKind::SchemaOpen));
4515    assert!(plain_row.occurrences.iter().all(|it| it.intent == WeakTypeIntent::Unresolved));
4516    assert_eq!(plain_row.occurrences[0].detail, "schema-open:AnyEnum:arg");
4517    assert_eq!(plain_row.occurrences[1].detail, "schema-open:AnyStruct:return");
4518
4519    // Inner (:open ...) keeps its own reason while outer (:open ...) covers outer open families.
4520    let mut nested_entry =
4521      calcit_core::snapshot::CodeEntry::from_code(cirru_parser::parse("defn wrap (cb) cb").expect("parse code").remove(0));
4522    nested_entry.schema = schema("Fn (Fn AnyFn (-> Unit) (:open :reflect)) (-> AnyStruct) (:open :host)");
4523    let nested_row = super::analyze_weak_types_entry("app.main", "wrap", &nested_entry, &WeakTypeKind::all())
4524      .expect("nested schema-open should be recorded");
4525    assert_eq!(nested_row.occurrences.len(), 2);
4526    assert_eq!(nested_row.occurrences[0].detail, "schema-open:AnyFn:arg:fn-arg:open=reflect");
4527    assert_eq!(nested_row.occurrences[1].detail, "schema-open:AnyStruct:return:open=host");
4528  }
4529
4530  #[test]
4531  fn whole_dynamic_macro_expansions_and_definitions_remain_unresolved() {
4532    let dynamic_expansion = scan(macro_schema(vec![], None, MacroExpansionType::Dynamic));
4533    let dynamic_definition = scan(macro_schema(
4534      vec![],
4535      None,
4536      MacroExpansionType::Definition(Arc::new(CalcitTypeAnnotation::Dynamic)),
4537    ));
4538
4539    assert_eq!(dynamic_expansion.len(), 1);
4540    assert_eq!(dynamic_expansion[0].intent, WeakTypeIntent::Unresolved);
4541    assert_eq!(dynamic_definition.len(), 1);
4542    assert_eq!(dynamic_definition[0].intent, WeakTypeIntent::Unresolved);
4543  }
4544
4545  #[test]
4546  fn nested_unresolved_slots_keep_unresolved_intent() {
4547    clear_type_slots();
4548    push_type_slot_override(
4549      Arc::from("outer"),
4550      Arc::new(CalcitTypeAnnotation::Nullable(
4551        Arc::new(CalcitTypeAnnotation::TypeSlot(Arc::from("inner"))),
4552        calcit_core::calcit::NullableOrigin::JsHost,
4553      )),
4554    );
4555
4556    let occurrences = scan(CalcitTypeAnnotation::TypeSlot(Arc::from("outer")));
4557
4558    assert_eq!(occurrences.len(), 1);
4559    assert_eq!(occurrences[0].kind, WeakTypeKind::UnresolvedTypeSlot);
4560    assert_eq!(occurrences[0].intent, WeakTypeIntent::Unresolved);
4561    clear_type_slots();
4562  }
4563
4564  #[test]
4565  fn js_ffi_host_reach_follows_let_bindings_and_tail_positions() {
4566    let code = cirru_parser::parse(
4567      "defn adapter (node props ? extra & items)\n  let\n      el $ .-el node\n      label $ get props :label\n    if (some? extra) (.!append el label) (to-calcit-data el)",
4568    )
4569    .expect("parse adapter")
4570    .remove(0);
4571    let reach = super::js_ffi_host_reach(&code).expect("defn reach");
4572
4573    // `label` feeds `.!append`, so `props` reaches the host through it.
4574    assert_eq!(reach.params, vec![true, true, false]);
4575    assert_eq!(reach.rest, Some(false));
4576    assert!(reach.ret);
4577    assert!(reach.schema_path_reaches_host("schema.args.1.value"));
4578    assert!(!reach.schema_path_reaches_host("schema.args.2"));
4579    assert!(!reach.schema_path_reaches_host("schema.rest.item"));
4580
4581    // Postfix access names the receiver inside one leaf; `[]` is a legacy list marker.
4582    let postfix = cirru_parser::parse("defn adapter ([] node label) (node.!focus) (println label) node.-value")
4583      .expect("parse adapter")
4584      .remove(0);
4585    let postfix_reach = super::js_ffi_host_reach(&postfix).expect("defn reach");
4586    assert_eq!(postfix_reach.params, vec![true, false]);
4587    assert!(postfix_reach.ret);
4588
4589    let plain = cirru_parser::parse("defn adapter (node) (.!focus node) nil")
4590      .expect("parse adapter")
4591      .remove(0);
4592    assert!(!super::js_ffi_host_reach(&plain).expect("defn reach").ret);
4593
4594    let comp = cirru_parser::parse("defcomp comp-codearea (states props) (div ({}))")
4595      .expect("parse comp")
4596      .remove(0);
4597    let comp_reach = super::js_ffi_host_reach(&comp).expect("defcomp reach");
4598    assert_eq!(comp_reach.params, vec![false, false]);
4599    assert!(!comp_reach.ret);
4600
4601    let comp_host = cirru_parser::parse("defcomp comp-preview (states props) (println states) props.-hostNode")
4602      .expect("parse comp")
4603      .remove(0);
4604    let comp_host_reach = super::js_ffi_host_reach(&comp_host).expect("defcomp host reach");
4605    assert_eq!(comp_host_reach.params, vec![false, true]);
4606    assert!(comp_host_reach.ret);
4607  }
4608
4609  #[test]
4610  fn nested_js_nullish_dynamic_keeps_ffi_intent() {
4611    clear_type_slots();
4612    push_type_slot_override(
4613      Arc::from("outer"),
4614      Arc::new(CalcitTypeAnnotation::Nullable(
4615        Arc::new(CalcitTypeAnnotation::Dynamic),
4616        calcit_core::calcit::NullableOrigin::JsHost,
4617      )),
4618    );
4619
4620    let occurrences = scan(CalcitTypeAnnotation::TypeSlot(Arc::from("outer")));
4621
4622    assert_eq!(occurrences.len(), 1);
4623    assert_eq!(occurrences[0].kind, WeakTypeKind::SchemaDynamic);
4624    assert_eq!(occurrences[0].intent, WeakTypeIntent::IntentionalJsFfi);
4625    // The shared `:js-ffi` feature also marks native FFI boundaries (#581), so the
4626    // suggestion must not send native modules looking for a JS adapter (#2434).
4627    let suggestion = super::weak_type_suggestion(&occurrences[0]);
4628    assert!(suggestion.contains("FFI boundary (JS or native)"), "{suggestion}");
4629    assert!(!suggestion.contains("declared JS FFI"), "{suggestion}");
4630    clear_type_slots();
4631  }
4632
4633  #[test]
4634  fn resolved_dynamic_slots_receive_slot_intent() {
4635    clear_type_slots();
4636    push_type_slot_override(Arc::from("slot"), Arc::new(CalcitTypeAnnotation::Dynamic));
4637
4638    let occurrences = scan(CalcitTypeAnnotation::TypeSlot(Arc::from("slot")));
4639
4640    assert_eq!(occurrences.len(), 1);
4641    assert_eq!(occurrences[0].kind, WeakTypeKind::SchemaDynamic);
4642    assert_eq!(occurrences[0].intent, WeakTypeIntent::IntentionalTypeSlotDynamic);
4643    clear_type_slots();
4644  }
4645
4646  #[test]
4647  fn unsafe_coerce_source_forms_and_adapter_names_are_static_and_distinct() {
4648    assert_eq!(
4649      classify_unsafe_coerce_source(&[Cirru::leaf("unsafe-coerce"), Cirru::leaf("js/window"), Cirru::leaf("Number")]),
4650      "raw-js-value"
4651    );
4652    assert_eq!(
4653      classify_unsafe_coerce_source(&[
4654        Cirru::leaf("unsafe-coerce"),
4655        Cirru::List(vec![Cirru::leaf("js/fetch"), Cirru::leaf("url")]),
4656        Cirru::leaf("Response"),
4657      ]),
4658      "raw-js-operation"
4659    );
4660    assert_eq!(
4661      classify_unsafe_coerce_source(&[
4662        Cirru::leaf("unsafe-coerce"),
4663        Cirru::List(vec![Cirru::leaf("aget"), Cirru::leaf("host"), Cirru::leaf("key")]),
4664        Cirru::leaf("String"),
4665      ]),
4666      "host-member-operation"
4667    );
4668    assert_eq!(
4669      classify_unsafe_coerce_source(&[Cirru::leaf("unsafe-coerce"), Cirru::leaf("value"), Cirru::leaf("String")]),
4670      "value"
4671    );
4672    assert!(is_raw_adapter_namespace("js-ffi.raw.node"));
4673    assert!(is_raw_adapter_namespace("app.js-ffi.raw.browser"));
4674    assert!(!is_raw_adapter_namespace("app.js-ffi.host.browser"));
4675  }
4676
4677  #[test]
4678  fn wrapped_def_nominal_types_and_core_syntax_forms_are_not_counted_as_unresolved() {
4679    let mut enum_entry = calcit_core::snapshot::CodeEntry::from_code(
4680      cirru_parser::parse("def Wrapped\n  defenum Wrapped (:a) (:b Number)")
4681        .expect("parse wrapped defenum")
4682        .remove(0),
4683    );
4684    enum_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
4685    assert!(
4686      super::analyze_weak_types_entry("calcit.core", "Wrapped", &enum_entry, &WeakTypeKind::all()).is_none(),
4687      "wrapped (def Name (defenum ...)) without internal Dynamic must not report schema-dynamic"
4688    );
4689
4690    let mut syntax_entry = calcit_core::snapshot::CodeEntry::from_code(Cirru::leaf("&runtime-implementation"));
4691    syntax_entry.tags.insert(cirru_edn::EdnTag::from("syntax"));
4692    syntax_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
4693    let syntax_row = super::analyze_weak_types_entry("calcit.core", "recur", &syntax_entry, &WeakTypeKind::all())
4694      .expect("syntax-tagged core form retains SchemaDynamic record");
4695    assert_eq!(syntax_row.occurrences.len(), 1);
4696    assert_eq!(syntax_row.occurrences[0].intent, WeakTypeIntent::IntentionalMacroSyntax);
4697
4698    let mut plain_core_entry = calcit_core::snapshot::CodeEntry::from_code(Cirru::leaf("&runtime-implementation"));
4699    plain_core_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
4700    let plain_row = super::analyze_weak_types_entry("calcit.core", "untyped-core-op", &plain_core_entry, &WeakTypeKind::all())
4701      .expect("untagged Dynamic core entry should still report");
4702    assert_eq!(plain_row.occurrences[0].intent, WeakTypeIntent::Unresolved);
4703
4704    let mut deftype_entry = calcit_core::snapshot::CodeEntry::from_code(
4705      cirru_parser::parse("deftype Pair (:generics A B) (Tuple A B)")
4706        .expect("parse deftype")
4707        .remove(0),
4708    );
4709    deftype_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
4710    assert!(
4711      super::analyze_weak_types_entry("app.main", "Pair", &deftype_entry, &WeakTypeKind::all()).is_none(),
4712      "clean deftype without internal Dynamic must not report unresolved schema-dynamic"
4713    );
4714    let deftype_cov = super::analyze_code_entry("app.main", "Pair", &deftype_entry);
4715    assert_eq!(deftype_cov.level, super::CoverageLevel::Full);
4716
4717    let mut open_deftype_entry = calcit_core::snapshot::CodeEntry::from_code(
4718      cirru_parser::parse("deftype OpenMap (Map Tag Dynamic)")
4719        .expect("parse open deftype")
4720        .remove(0),
4721    );
4722    open_deftype_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
4723    let open_deftype_row = super::analyze_weak_types_entry("app.main", "OpenMap", &open_deftype_entry, &WeakTypeKind::all())
4724      .expect("deftype containing Dynamic must still report schema-dynamic");
4725    assert!(
4726      open_deftype_row
4727        .occurrences
4728        .iter()
4729        .any(|occ| occ.kind == WeakTypeKind::SchemaDynamic && occ.path == "schema"),
4730      "got: {:?}",
4731      open_deftype_row.occurrences
4732    );
4733    let data_dynamic_row = super::analyze_weak_types_entry(
4734      "app.main",
4735      "OpenMap",
4736      &open_deftype_entry,
4737      &std::collections::BTreeSet::from([super::WeakTypeKind::DataDynamic]),
4738    )
4739    .expect("deftype containing Dynamic must report data-dynamic when selected");
4740    assert!(
4741      data_dynamic_row
4742        .occurrences
4743        .iter()
4744        .any(|occ| occ.kind == super::WeakTypeKind::DataDynamic && occ.detail == "data-dynamic:type-alias:0"),
4745      "got: {:?}",
4746      data_dynamic_row.occurrences
4747    );
4748
4749    let mut external_entry = calcit_core::snapshot::CodeEntry::from_code(
4750      cirru_parser::parse("defexternal DomHost (:target :browser) (:label String)")
4751        .expect("parse defexternal")
4752        .remove(0),
4753    );
4754    external_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
4755    assert!(
4756      super::analyze_weak_types_entry("app.main", "DomHost", &external_entry, &WeakTypeKind::all()).is_none(),
4757      "clean defexternal without Dynamic must not report unresolved schema-dynamic"
4758    );
4759    let external_cov = super::analyze_code_entry("app.main", "DomHost", &external_entry);
4760    assert_eq!(external_cov.level, super::CoverageLevel::Full);
4761  }
4762
4763  #[test]
4764  fn ref_open_cache_boundary_has_intentional_open_intent_and_full_coverage() {
4765    let schema = |text: &str| {
4766      let form = cirru_parser::parse(text).expect("parse schema").remove(0);
4767      calcit_core::snapshot::parse_schema_annotation_for_write(&form).expect("schema parses")
4768    };
4769    let mut cached_entry =
4770      calcit_core::snapshot::CodeEntry::from_code(cirru_parser::parse("defref *cache $ {}").expect("parse defref").remove(0));
4771    cached_entry.schema = schema("Ref Dynamic (:open :cache)");
4772
4773    let cached_cov = super::analyze_code_entry("app.main", "*cache", &cached_entry);
4774    assert_eq!(cached_cov.level, super::CoverageLevel::Full);
4775    assert!(
4776      cached_cov.schema_issues.is_empty(),
4777      "reviewed Ref cache must not fail schema audit: {:?}",
4778      cached_cov.schema_issues
4779    );
4780
4781    let cached_row = super::analyze_weak_types_entry("app.main", "*cache", &cached_entry, &WeakTypeKind::all())
4782      .expect("open ref still surfaces under explicit weak-types query");
4783    assert!(
4784      cached_row
4785        .occurrences
4786        .iter()
4787        .all(|occ| occ.intent == WeakTypeIntent::IntentionalOpen),
4788      "got: {:?}",
4789      cached_row.occurrences
4790    );
4791
4792    let mut plain_entry =
4793      calcit_core::snapshot::CodeEntry::from_code(cirru_parser::parse("defref *plain $ {}").expect("parse defref").remove(0));
4794    plain_entry.schema = schema("Ref Dynamic");
4795    let plain_cov = super::analyze_code_entry("app.main", "*plain", &plain_entry);
4796    assert_eq!(plain_cov.level, super::CoverageLevel::Partial);
4797    let plain_row =
4798      super::analyze_weak_types_entry("app.main", "*plain", &plain_entry, &WeakTypeKind::all()).expect("unmarked Ref Dynamic");
4799    assert!(
4800      plain_row.occurrences.iter().all(|occ| occ.intent == WeakTypeIntent::Unresolved),
4801      "got: {:?}",
4802      plain_row.occurrences
4803    );
4804  }
4805}