Skip to main content

calcit_cli/
strict_check.rs

1use std::cell::RefCell;
2use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet, VecDeque};
3use std::sync::Arc;
4
5use crate::call_tree::{CallTreeAnalyzer, CallTreeConfig, CallTreeNode};
6use calcit_core::ProgramEntries;
7use calcit_core::calcit::{CalcitErr, CalcitTypeAnnotation, LocatedWarning};
8use calcit_core::call_stack::CallStackList;
9use calcit_core::program;
10use calcit_core::runner;
11use calcit_core::snapshot::{self, FeaturePolicy, SnapshotTarget};
12use serde::Serialize;
13
14use crate::cli_handlers::{StructuredOutputFormat, format_json_value_as_edn};
15
16type DefinitionGraph = BTreeMap<String, BTreeSet<String>>;
17
18#[derive(Debug, Clone, Serialize)]
19struct CheckDiagnostic {
20  severity: &'static str,
21  code: Option<String>,
22  message: String,
23  definition: String,
24  path: Vec<u16>,
25  hint: Option<String>,
26  expected: Option<String>,
27  actual: Option<String>,
28  provenance: Vec<calcit_core::calcit::CalcitErrProvenance>,
29}
30
31#[derive(Debug, Clone, Serialize)]
32struct DefinitionResult {
33  definition: String,
34  status: &'static str,
35  blocked_by: Vec<String>,
36  diagnostics: Vec<CheckDiagnostic>,
37}
38
39#[derive(Debug, Clone, Serialize)]
40struct CheckSummary {
41  total: usize,
42  passed: usize,
43  failed: usize,
44  blocked: usize,
45  cascaded: usize,
46}
47
48#[derive(Debug, Clone, Serialize)]
49struct CheckData {
50  status: &'static str,
51  /// `reachable` (entry closure) or `all-defs` (entry closure plus all project definitions)
52  scope: &'static str,
53  entries: Vec<String>,
54  summary: CheckSummary,
55  definitions: Vec<DefinitionResult>,
56  /// Non-failing diagnostics such as `W_OPEN_FAMILY`; they never change `status`.
57  advisories: Vec<CheckDiagnostic>,
58}
59
60#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
61struct CompactCheckDiagnostic {
62  severity: &'static str,
63  code: Option<String>,
64  /// Present only when the offending expression belongs to another definition (or an advisory).
65  #[serde(skip_serializing_if = "Option::is_none")]
66  definition: Option<String>,
67  path: Vec<u16>,
68}
69
70#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
71struct CompactDefinitionResult {
72  definition: String,
73  status: &'static str,
74  #[serde(skip_serializing_if = "Vec::is_empty")]
75  blocked_by: Vec<String>,
76  #[serde(skip_serializing_if = "Vec::is_empty")]
77  diagnostics: Vec<CompactCheckDiagnostic>,
78}
79
80#[derive(Debug, Clone, Serialize)]
81struct CompactCheckData {
82  status: &'static str,
83  scope: &'static str,
84  summary_only: bool,
85  entries: Vec<String>,
86  summary: CheckSummary,
87  definitions: Vec<CompactDefinitionResult>,
88  advisories: Vec<CompactCheckDiagnostic>,
89}
90
91fn collect_graph(node: &CallTreeNode, graph: &mut DefinitionGraph) {
92  let dependencies = graph.entry(node.fqn.clone()).or_default();
93  for child in &node.calls {
94    dependencies.insert(child.fqn.clone());
95  }
96  for child in &node.calls {
97    collect_graph(child, graph);
98  }
99}
100
101fn finish_definition(definition: &str, graph: &DefinitionGraph, visited: &mut HashSet<String>, finished: &mut Vec<String>) {
102  if !visited.insert(definition.to_owned()) {
103    return;
104  }
105  if let Some(dependencies) = graph.get(definition) {
106    for dependency in dependencies {
107      finish_definition(dependency, graph, visited, finished);
108    }
109  }
110  finished.push(definition.to_owned());
111}
112
113fn collect_reverse_component(definition: &str, reverse: &DefinitionGraph, visited: &mut HashSet<String>, component: &mut Vec<String>) {
114  if !visited.insert(definition.to_owned()) {
115    return;
116  }
117  component.push(definition.to_owned());
118  if let Some(dependents) = reverse.get(definition) {
119    for dependent in dependents {
120      collect_reverse_component(dependent, reverse, visited, component);
121    }
122  }
123}
124
125fn visit_component(component: usize, dependencies: &[BTreeSet<usize>], visited: &mut HashSet<usize>, ordered: &mut Vec<usize>) {
126  if !visited.insert(component) {
127    return;
128  }
129  for dependency in &dependencies[component] {
130    visit_component(*dependency, dependencies, visited, ordered);
131  }
132  ordered.push(component);
133}
134
135fn strongly_connected_components(graph: &DefinitionGraph) -> Vec<Vec<String>> {
136  let mut nodes = BTreeSet::new();
137  for (definition, dependencies) in graph {
138    nodes.insert(definition.clone());
139    nodes.extend(dependencies.iter().cloned());
140  }
141
142  let mut finished = Vec::new();
143  let mut visited = HashSet::new();
144  for definition in &nodes {
145    finish_definition(definition, graph, &mut visited, &mut finished);
146  }
147
148  let mut reverse = DefinitionGraph::new();
149  for definition in &nodes {
150    reverse.entry(definition.clone()).or_default();
151  }
152  for (definition, dependencies) in graph {
153    for dependency in dependencies {
154      reverse.entry(dependency.clone()).or_default().insert(definition.clone());
155    }
156  }
157
158  let mut components = Vec::new();
159  visited.clear();
160  for definition in finished.iter().rev() {
161    if visited.contains(definition) {
162      continue;
163    }
164    let mut component = Vec::new();
165    collect_reverse_component(definition, &reverse, &mut visited, &mut component);
166    component.sort();
167    components.push(component);
168  }
169  components.sort_by(|a, b| a[0].cmp(&b[0]));
170
171  let component_by_definition = components
172    .iter()
173    .enumerate()
174    .flat_map(|(index, component)| component.iter().map(move |definition| (definition.clone(), index)))
175    .collect::<BTreeMap<_, _>>();
176  let mut dependencies = vec![BTreeSet::new(); components.len()];
177  for (definition, definition_dependencies) in graph {
178    let component = component_by_definition[definition];
179    for dependency in definition_dependencies {
180      let dependency_component = component_by_definition[dependency];
181      if component != dependency_component {
182        dependencies[component].insert(dependency_component);
183      }
184    }
185  }
186
187  let mut ordered = Vec::new();
188  let mut visited_components = HashSet::new();
189  for component in 0..components.len() {
190    visit_component(component, &dependencies, &mut visited_components, &mut ordered);
191  }
192  ordered.into_iter().map(|index| components[index].clone()).collect()
193}
194
195/// Per-entry runtime/checking context captured from the Snapshot.
196#[derive(Debug, Clone)]
197struct EntryCheckContext {
198  name: String,
199  init_fn: String,
200  reload_fn: String,
201  init_ns: String,
202  init_def: String,
203  reload_ns: String,
204  reload_def: String,
205  target: Option<SnapshotTarget>,
206  type_slots: HashMap<String, String>,
207  feature_policy: HashMap<String, FeaturePolicy>,
208}
209
210/// Extra roots for the all-definitions scope: every definition of the project namespaces.
211/// Dependencies and core are never roots; they are only checked when a root reaches them.
212pub struct AllDefsScope {
213  /// `(namespace, definition)` roots, sorted so the sequence never depends on Snapshot or HashSet order.
214  roots: Vec<(String, String)>,
215  /// Project namespaces owned by this snapshot (used for namespace-level entry ownership).
216  project_namespaces: HashSet<String>,
217  /// Core builtin placeholders have no Calcit body to preprocess; they are excluded like `--check-only --ns` does.
218  intrinsics: HashSet<String>,
219  /// All entries in the snapshot, starting with the selected entry, so multi-target
220  /// projects check each entry's closure and unwired definitions under their true target (#2917).
221  entry_contexts: Vec<EntryCheckContext>,
222  /// Declared `:ffi :target` metadata across all loaded definitions (project + dependencies).
223  declared_targets: HashMap<String, SnapshotTarget>,
224}
225
226impl AllDefsScope {
227  pub fn from_snapshot(
228    snapshot: &snapshot::Snapshot,
229    project_namespaces: &HashSet<String>,
230    selected_entries: &ProgramEntries,
231  ) -> Result<Self, String> {
232    let mut roots = Vec::new();
233    let mut intrinsics = HashSet::new();
234    for ns in project_namespaces {
235      let Some(file) = snapshot.files.get(ns) else {
236        continue;
237      };
238      for (def, entry) in &file.defs {
239        if crate::public_api_check::is_core_runtime_intrinsic(ns, def, entry) {
240          intrinsics.insert(format!("{ns}/{def}"));
241        } else {
242          roots.push((ns.clone(), def.clone()));
243        }
244      }
245    }
246    roots.sort();
247
248    let mut declared_targets = HashMap::new();
249    for (ns, file) in &snapshot.files {
250      for (def, entry) in &file.defs {
251        if let Some(ffi) = &entry.ffi
252          && let Ok(Some(target)) = snapshot::parse_ffi_target(ffi)
253        {
254          declared_targets.insert(format!("{ns}/{def}"), target);
255        }
256      }
257    }
258
259    let selected_name = snapshot.active_entry_name();
260    let mut entry_names = snapshot.entries.keys().cloned().collect::<Vec<_>>();
261    entry_names.sort_by_key(|name| (name != selected_name, name != snapshot::DEFAULT_ENTRY_NAME, name.clone()));
262
263    let mut entry_contexts = Vec::with_capacity(entry_names.len());
264    for name in entry_names {
265      let entry = &snapshot.entries[&name];
266      let mut feature_policy = entry.feature_policy.clone();
267      feature_policy.entry("js-ffi".to_owned()).or_insert(FeaturePolicy::Error);
268      let (init_fn, reload_fn, init_ns, init_def, reload_ns, reload_def) = if name == selected_name {
269        (
270          selected_entries.init_fn.to_string(),
271          selected_entries.reload_fn.to_string(),
272          selected_entries.init_ns.to_string(),
273          selected_entries.init_def.to_string(),
274          selected_entries.reload_ns.to_string(),
275          selected_entries.reload_def.to_string(),
276        )
277      } else {
278        let (init_ns, init_def) = calcit_core::util::string::extract_ns_def(&entry.init_fn)?;
279        let (reload_ns, reload_def) = calcit_core::util::string::extract_ns_def(&entry.reload_fn)?;
280        (
281          entry.init_fn.clone(),
282          entry.reload_fn.clone(),
283          init_ns,
284          init_def,
285          reload_ns,
286          reload_def,
287        )
288      };
289      entry_contexts.push(EntryCheckContext {
290        name,
291        init_fn,
292        reload_fn,
293        init_ns,
294        init_def,
295        reload_ns,
296        reload_def,
297        target: entry.target,
298        type_slots: entry.type_slots.clone(),
299        feature_policy,
300      });
301    }
302
303    Ok(AllDefsScope {
304      roots,
305      project_namespaces: project_namespaces.clone(),
306      intrinsics,
307      entry_contexts,
308      declared_targets,
309    })
310  }
311
312  fn has_multiple_targets(&self) -> bool {
313    let mut targets = Vec::new();
314    for ctx in &self.entry_contexts {
315      if let Some(target) = ctx.target {
316        push_unique_target(&mut targets, target);
317      }
318    }
319    targets.len() >= 2
320  }
321}
322
323/// Restores global entry target, feature policy, and type slots when leaving
324/// multi-entry checking.
325struct EntryContextGuard {
326  target: Option<SnapshotTarget>,
327  feature_policy: HashMap<String, FeaturePolicy>,
328  type_slots: HashMap<Arc<str>, Arc<CalcitTypeAnnotation>>,
329}
330
331impl EntryContextGuard {
332  fn capture(initial_feature_policy: &HashMap<String, FeaturePolicy>) -> Self {
333    Self {
334      target: program::active_entry_target(),
335      feature_policy: initial_feature_policy.clone(),
336      type_slots: calcit_core::calcit::entry_type_slots(),
337    }
338  }
339}
340
341impl Drop for EntryContextGuard {
342  fn drop(&mut self) {
343    program::configure_entry_target(self.target);
344    program::configure_entry_feature_policy(&self.feature_policy);
345    calcit_core::calcit::install_entry_type_slots(std::mem::take(&mut self.type_slots));
346  }
347}
348
349fn resolve_type_ref_fqn(current_ns: &str, raw_name: &str) -> String {
350  let trimmed = raw_name.trim_start_matches('\'').trim_start_matches(':');
351  if let Some((prefix, def)) = trimmed.rsplit_once('/') {
352    if let Some(resolved_ns) = program::lookup_ns_target_in_import(current_ns, prefix) {
353      format!("{resolved_ns}/{def}")
354    } else {
355      format!("{prefix}/{def}")
356    }
357  } else if let Some((target_ns, target_def)) = program::lookup_refer_target_in_import(current_ns, trimmed) {
358    format!("{target_ns}/{target_def}")
359  } else {
360    format!("{current_ns}/{trimmed}")
361  }
362}
363
364fn push_unique_target(targets: &mut Vec<SnapshotTarget>, target: SnapshotTarget) {
365  if !targets.contains(&target) {
366    targets.push(target);
367  }
368}
369
370fn collect_schema_declared_targets(
371  current_ns: &str,
372  annotation: &CalcitTypeAnnotation,
373  declared_targets: &HashMap<String, SnapshotTarget>,
374  out: &mut Vec<SnapshotTarget>,
375) {
376  match annotation {
377    CalcitTypeAnnotation::TypeRef(name, args) => {
378      let fqn = resolve_type_ref_fqn(current_ns, name);
379      if let Some(&target) = declared_targets.get(&fqn) {
380        push_unique_target(out, target);
381      }
382      for arg in args.iter() {
383        collect_schema_declared_targets(current_ns, arg, declared_targets, out);
384      }
385    }
386    CalcitTypeAnnotation::Trait(trait_def) | CalcitTypeAnnotation::DynTrait(trait_def) => {
387      if let Some(def_ref) = trait_def.definition_ref.as_deref()
388        && let Some(&target) = declared_targets.get(def_ref)
389      {
390        push_unique_target(out, target);
391      }
392    }
393    CalcitTypeAnnotation::TraitSet(traits) => {
394      for trait_def in traits.iter() {
395        if let Some(def_ref) = trait_def.definition_ref.as_deref()
396          && let Some(&target) = declared_targets.get(def_ref)
397        {
398          push_unique_target(out, target);
399        }
400      }
401    }
402    CalcitTypeAnnotation::Fn(fn_annot) => {
403      for arg in &fn_annot.arg_types {
404        collect_schema_declared_targets(current_ns, arg, declared_targets, out);
405      }
406      if let Some(rest) = &fn_annot.rest_type {
407        collect_schema_declared_targets(current_ns, rest, declared_targets, out);
408      }
409      collect_schema_declared_targets(current_ns, &fn_annot.return_type, declared_targets, out);
410    }
411    CalcitTypeAnnotation::List(inner)
412    | CalcitTypeAnnotation::Set(inner)
413    | CalcitTypeAnnotation::Ref(inner, _)
414    | CalcitTypeAnnotation::Variadic(inner)
415    | CalcitTypeAnnotation::Nullable(inner, _) => {
416      collect_schema_declared_targets(current_ns, inner, declared_targets, out);
417    }
418    CalcitTypeAnnotation::Map(k, v) => {
419      collect_schema_declared_targets(current_ns, k, declared_targets, out);
420      collect_schema_declared_targets(current_ns, v, declared_targets, out);
421    }
422    CalcitTypeAnnotation::Tuple(items) => {
423      for item in items.iter() {
424        collect_schema_declared_targets(current_ns, item, declared_targets, out);
425      }
426    }
427    CalcitTypeAnnotation::Struct(_, args) | CalcitTypeAnnotation::Enum(_, args) => {
428      for arg in args.iter() {
429        collect_schema_declared_targets(current_ns, arg, declared_targets, out);
430      }
431    }
432    _ => {}
433  }
434}
435
436fn status_rank(status: &str) -> u8 {
437  match status {
438    "failed" => 3,
439    "cascaded" => 2,
440    "blocked" => 1,
441    _ => 0,
442  }
443}
444
445fn merge_definition_result(existing: &mut DefinitionResult, incoming: DefinitionResult) {
446  let incoming_rank = status_rank(incoming.status);
447  let existing_rank = status_rank(existing.status);
448
449  for diagnostic in incoming.diagnostics {
450    push_unique_diagnostic(&mut existing.diagnostics, diagnostic);
451  }
452
453  if incoming_rank > existing_rank {
454    existing.status = incoming.status;
455    if incoming.status == "blocked" {
456      existing.blocked_by = incoming.blocked_by;
457    } else {
458      existing.blocked_by.clear();
459    }
460  } else if incoming_rank == existing_rank && existing.status == "blocked" {
461    let mut blockers = existing.blocked_by.iter().cloned().collect::<BTreeSet<_>>();
462    blockers.extend(incoming.blocked_by);
463    existing.blocked_by = blockers.into_iter().collect();
464  }
465}
466
467fn push_unique_warning(warnings: &mut Vec<LocatedWarning>, warning: LocatedWarning) {
468  let loc = warning.location();
469  let duplicate = warnings.iter().any(|existing| {
470    let existing_loc = existing.location();
471    existing.code() == warning.code()
472      && existing.message() == warning.message()
473      && existing_loc.ns == loc.ns
474      && existing_loc.def == loc.def
475      && existing_loc.coord == loc.coord
476  });
477  if !duplicate {
478    warnings.push(warning);
479  }
480}
481
482/// Build the dependency graph for a specific list of roots, excluding core runtime intrinsics.
483fn build_graph_for_roots(
484  roots: &[(String, String)],
485  include_core: bool,
486  intrinsics: Option<&HashSet<String>>,
487) -> Result<(DefinitionGraph, Vec<Vec<String>>), String> {
488  let mut graph = BTreeMap::new();
489  // One analyzer is shared across roots: expanded nodes keep every outgoing edge in
490  // `graph`, so later roots only add what is new and the final graph is root-order independent.
491  let mut analyzer = CallTreeAnalyzer::new(CallTreeConfig {
492    include_core,
493    ..CallTreeConfig::default()
494  });
495  for (ns, definition) in roots {
496    let result = analyzer.analyze(ns, definition)?;
497    collect_graph(&result.tree, &mut graph);
498  }
499
500  if let Some(intrinsics) = intrinsics {
501    graph.retain(|definition, _| !intrinsics.contains(definition));
502    for dependencies in graph.values_mut() {
503      dependencies.retain(|dependency| !intrinsics.contains(dependency));
504    }
505  }
506
507  let components = strongly_connected_components(&graph);
508  Ok((graph, components))
509}
510
511/// Collect the definition graph from the entry roots, plus every definition of the
512/// project namespaces when the all-definitions scope is requested.
513fn reachable_definitions(
514  entries: &ProgramEntries,
515  all_defs: Option<&AllDefsScope>,
516) -> Result<(DefinitionGraph, Vec<Vec<String>>), String> {
517  let mut roots = vec![
518    (entries.init_ns.to_string(), entries.init_def.to_string()),
519    (entries.reload_ns.to_string(), entries.reload_def.to_string()),
520  ];
521  // When the project itself is calcit.core, its definitions must stay in the graph as edges.
522  let mut include_core = false;
523  if let Some(scope) = all_defs {
524    include_core = scope.roots.iter().any(|(ns, _)| calcit_core::calcit::is_bundled_core_ns(ns));
525    roots.extend(scope.roots.iter().cloned());
526  }
527  build_graph_for_roots(&roots, include_core, all_defs.map(|scope| &scope.intrinsics))
528}
529
530fn warning_diagnostic(warning: &LocatedWarning) -> CheckDiagnostic {
531  let location = warning.location();
532  CheckDiagnostic {
533    severity: located_warning_severity(warning),
534    code: warning.code().map(str::to_owned),
535    message: warning.message().to_owned(),
536    definition: format!("{}/{}", location.ns, location.def),
537    path: location.coord.to_vec(),
538    hint: warning.hint().map(str::to_owned),
539    expected: warning.expected().map(str::to_owned),
540    actual: warning.actual().map(str::to_owned),
541    provenance: Vec::new(),
542  }
543}
544
545/// Collected preprocessing diagnostics with an `E_` code (or an uncoded
546/// `[Error]` message) block the check, so report them as errors; other
547/// collected diagnostics keep warning severity.
548fn located_warning_severity(warning: &LocatedWarning) -> &'static str {
549  if warning
550    .code()
551    .map_or_else(|| warning.message().starts_with("[Error]"), |code| code.starts_with("E_"))
552  {
553    "error"
554  } else {
555    "warning"
556  }
557}
558
559fn advisory_diagnostic(advisory: &LocatedWarning) -> CheckDiagnostic {
560  CheckDiagnostic {
561    severity: "note",
562    ..warning_diagnostic(advisory)
563  }
564}
565
566fn error_diagnostic(error: &CalcitErr, fallback: &str) -> CheckDiagnostic {
567  let definition = error
568    .location
569    .as_ref()
570    .map(|location| format!("{}/{}", location.ns, location.def))
571    .unwrap_or_else(|| fallback.to_owned());
572  let path = error.location.as_ref().map(|location| location.coord.to_vec()).unwrap_or_default();
573  CheckDiagnostic {
574    severity: "error",
575    code: error.code.clone(),
576    message: error.msg.clone(),
577    definition,
578    path,
579    hint: error.hint.as_deref().map(str::to_owned),
580    expected: error.provenance.first().map(|item| item.r#type.clone()),
581    actual: error.provenance.first().map(|item| item.output_type.clone()),
582    provenance: error.provenance.as_ref().clone(),
583  }
584}
585
586fn push_unique_diagnostic(diagnostics: &mut Vec<CheckDiagnostic>, diagnostic: CheckDiagnostic) {
587  if !diagnostics.iter().any(|item| {
588    item.severity == diagnostic.severity
589      && item.code == diagnostic.code
590      && item.message == diagnostic.message
591      && item.definition == diagnostic.definition
592      && item.path == diagnostic.path
593  }) {
594    diagnostics.push(diagnostic);
595  }
596}
597
598fn take_definition_outcome(
599  definition: &str,
600  confirmed: &mut BTreeMap<String, Vec<CheckDiagnostic>>,
601  cascaded: &mut BTreeMap<String, Vec<CheckDiagnostic>>,
602  blockers: &[String],
603) -> (&'static str, Vec<String>, Vec<CheckDiagnostic>) {
604  if let Some(mut diagnostics) = confirmed.remove(definition) {
605    if let Some(extra) = cascaded.remove(definition) {
606      for diagnostic in extra {
607        push_unique_diagnostic(&mut diagnostics, diagnostic);
608      }
609    }
610    ("failed", Vec::new(), diagnostics)
611  } else if let Some(diagnostics) = cascaded.remove(definition) {
612    ("cascaded", Vec::new(), diagnostics)
613  } else if blockers.is_empty() {
614    ("passed", Vec::new(), Vec::new())
615  } else {
616    ("blocked", blockers.to_vec(), Vec::new())
617  }
618}
619
620fn check_definitions(graph: &DefinitionGraph, components: &[Vec<String>]) -> Vec<DefinitionResult> {
621  let mut statuses = BTreeMap::new();
622  let mut results = Vec::new();
623
624  for component in components {
625    let component_set = component.iter().cloned().collect::<HashSet<_>>();
626    let external_blockers = component
627      .iter()
628      .flat_map(|definition| graph.get(definition).into_iter().flatten())
629      .filter(|dependency| !component_set.contains(*dependency))
630      .filter(|dependency| matches!(statuses.get(*dependency), Some(&"failed" | &"blocked" | &"cascaded")))
631      .cloned()
632      .collect::<BTreeSet<_>>()
633      .into_iter()
634      .collect::<Vec<_>>();
635    if !external_blockers.is_empty() {
636      for definition in component {
637        statuses.insert(definition.clone(), "blocked");
638        results.push(DefinitionResult {
639          definition: definition.clone(),
640          status: "blocked",
641          blocked_by: external_blockers.clone(),
642          diagnostics: Vec::new(),
643        });
644      }
645      continue;
646    }
647
648    let mut confirmed = BTreeMap::<String, Vec<CheckDiagnostic>>::new();
649    let mut cascaded = BTreeMap::<String, Vec<CheckDiagnostic>>::new();
650    for definition in component {
651      let Some((ns, def)) = definition.split_once('/') else {
652        cascaded.entry(definition.clone()).or_default().push(CheckDiagnostic {
653          severity: "error",
654          code: Some("E_INVALID_DEFINITION_ID".to_owned()),
655          message: format!("Invalid qualified definition `{definition}`"),
656          definition: definition.clone(),
657          path: Vec::new(),
658          hint: None,
659          expected: None,
660          actual: None,
661          provenance: Vec::new(),
662        });
663        continue;
664      };
665
666      let warnings = RefCell::new(Vec::new());
667      let outcome = runner::preprocess::ensure_ns_def_compiled(ns, def, &warnings, &CallStackList::default());
668      runner::preprocess::drop_macro_owned_proof_warnings(&warnings, 0);
669      for diagnostic in warnings.borrow().iter().map(warning_diagnostic) {
670        if component_set.contains(&diagnostic.definition) {
671          push_unique_diagnostic(confirmed.entry(diagnostic.definition.clone()).or_default(), diagnostic);
672        } else {
673          push_unique_diagnostic(cascaded.entry(definition.clone()).or_default(), diagnostic);
674        }
675      }
676      if let Err(error) = outcome {
677        for diagnostic in error.warnings.iter().map(warning_diagnostic) {
678          if component_set.contains(&diagnostic.definition) {
679            push_unique_diagnostic(confirmed.entry(diagnostic.definition.clone()).or_default(), diagnostic);
680          } else {
681            push_unique_diagnostic(cascaded.entry(definition.clone()).or_default(), diagnostic);
682          }
683        }
684        let owner = error.location.as_ref().map(|location| format!("{}/{}", location.ns, location.def));
685        let diagnostic = error_diagnostic(&error, definition);
686        if let Some(owner) = owner.filter(|owner| component_set.contains(owner)) {
687          push_unique_diagnostic(confirmed.entry(owner).or_default(), diagnostic);
688        } else {
689          push_unique_diagnostic(cascaded.entry(definition.clone()).or_default(), diagnostic);
690        }
691      }
692    }
693
694    let blockers = confirmed
695      .keys()
696      .chain(cascaded.keys())
697      .cloned()
698      .collect::<BTreeSet<_>>()
699      .into_iter()
700      .collect::<Vec<_>>();
701    for definition in component {
702      let (status, blocked_by, diagnostics) = take_definition_outcome(definition, &mut confirmed, &mut cascaded, &blockers);
703      statuses.insert(definition.clone(), status);
704      results.push(DefinitionResult {
705        definition: definition.clone(),
706        status,
707        blocked_by,
708        diagnostics,
709      });
710    }
711  }
712  results
713}
714
715/// Marks passed definitions blocked when a definition they depend on failed
716/// after the ordinary check, such as for a bare broad type (#2504).
717/// `components` are in dependency order, so blocks propagate in one pass.
718fn block_dependents_of_failed(graph: &DefinitionGraph, components: &[Vec<String>], results: &mut [DefinitionResult]) {
719  let mut statuses = results
720    .iter()
721    .map(|result| (result.definition.clone(), result.status))
722    .collect::<HashMap<_, _>>();
723  for component in components {
724    let component_set = component.iter().collect::<HashSet<_>>();
725    let blockers = component
726      .iter()
727      .flat_map(|definition| graph.get(definition).into_iter().flatten())
728      .filter(|dependency| !component_set.contains(dependency))
729      .chain(component.iter())
730      .filter(|dependency| matches!(statuses.get(*dependency), Some(&"failed" | &"blocked" | &"cascaded")))
731      .cloned()
732      .collect::<BTreeSet<_>>();
733    if blockers.is_empty() {
734      continue;
735    }
736    for definition in component {
737      let Some(result) = results
738        .iter_mut()
739        .find(|result| &result.definition == definition && result.status == "passed")
740      else {
741        continue;
742      };
743      result.status = "blocked";
744      result.blocked_by = blockers.iter().filter(|blocker| *blocker != definition).cloned().collect();
745      statuses.insert(definition.clone(), "blocked");
746    }
747  }
748}
749
750fn print_human(data: &CheckData) {
751  println!("# Strict check\n");
752  println!("- status: **{}**", data.status.to_uppercase());
753  println!("- scope: {}", data.scope);
754  println!(
755    "- entries: {}",
756    data.entries.iter().map(|entry| format!("`{entry}`")).collect::<Vec<_>>().join(", ")
757  );
758  println!("- definitions: {}", data.summary.total);
759  println!("- failed: {}", data.summary.failed);
760  println!("- blocked: {}", data.summary.blocked);
761  println!("- cascaded: {}", data.summary.cascaded);
762  for result in &data.definitions {
763    println!("\n## `{}`\n", result.definition);
764    println!("- status: **{}**", result.status.to_uppercase());
765    if !result.blocked_by.is_empty() {
766      println!(
767        "- blocked by: {}",
768        result
769          .blocked_by
770          .iter()
771          .map(|item| format!("`{item}`"))
772          .collect::<Vec<_>>()
773          .join(", ")
774      );
775    }
776    for diagnostic in &result.diagnostics {
777      let code = diagnostic.code.as_deref().unwrap_or("unclassified");
778      println!("- {} `{code}`", diagnostic.severity);
779      println!("\n```text\n{}\n```", diagnostic.message);
780      if let Some(expected) = &diagnostic.expected {
781        println!("\n- expected: `{expected}`");
782      }
783      if let Some(actual) = &diagnostic.actual {
784        println!("- actual: `{actual}`");
785      }
786      if let Some(hint) = &diagnostic.hint {
787        println!("\n> {hint}");
788      }
789    }
790  }
791}
792
793fn compact_check_data(data: &CheckData) -> CompactCheckData {
794  let definitions = data
795    .definitions
796    .iter()
797    .filter(|result| result.status != "passed")
798    .map(|result| CompactDefinitionResult {
799      definition: result.definition.clone(),
800      status: result.status,
801      blocked_by: result.blocked_by.clone(),
802      diagnostics: result
803        .diagnostics
804        .iter()
805        .map(|diag| CompactCheckDiagnostic {
806          severity: diag.severity,
807          code: diag.code.clone(),
808          definition: (diag.definition != result.definition).then(|| diag.definition.clone()),
809          path: diag.path.clone(),
810        })
811        .collect(),
812    })
813    .collect();
814
815  let advisories = data
816    .advisories
817    .iter()
818    .map(|advisory| CompactCheckDiagnostic {
819      severity: advisory.severity,
820      code: advisory.code.clone(),
821      definition: Some(advisory.definition.clone()),
822      path: advisory.path.clone(),
823    })
824    .collect();
825
826  CompactCheckData {
827    status: data.status,
828    scope: data.scope,
829    summary_only: true,
830    entries: data.entries.clone(),
831    summary: data.summary.clone(),
832    definitions,
833    advisories,
834  }
835}
836
837fn format_path(path: &[u16]) -> String {
838  path.iter().map(u16::to_string).collect::<Vec<_>>().join(".")
839}
840
841fn format_compact_diagnostic(diag: &CompactCheckDiagnostic) -> String {
842  let code = diag.code.as_deref().unwrap_or("unclassified");
843  let owner = diag.definition.as_ref().map(|name| format!(" in `{name}`")).unwrap_or_default();
844  let coord = if diag.path.is_empty() {
845    String::new()
846  } else {
847    format!(" @{}", format_path(&diag.path))
848  };
849  format!("{} `{code}`{owner}{coord}", diag.severity)
850}
851
852fn print_human_compact(data: &CompactCheckData) {
853  println!("# Strict check\n");
854  println!("- status: **{}**", data.status.to_uppercase());
855  println!("- scope: {}", data.scope);
856  println!("- summary-only: true");
857  println!(
858    "- entries: {}",
859    data.entries.iter().map(|entry| format!("`{entry}`")).collect::<Vec<_>>().join(", ")
860  );
861  println!("- definitions: {}", data.summary.total);
862  println!("- passed: {}", data.summary.passed);
863  println!("- failed: {}", data.summary.failed);
864  println!("- blocked: {}", data.summary.blocked);
865  println!("- cascaded: {}", data.summary.cascaded);
866
867  let failing: Vec<_> = data
868    .definitions
869    .iter()
870    .filter(|result| result.status == "failed" || result.status == "cascaded")
871    .collect();
872  if !failing.is_empty() {
873    println!("\n## Failed\n");
874    for result in failing {
875      if result.diagnostics.is_empty() {
876        println!("- `{}` (**{}**)", result.definition, result.status.to_uppercase());
877      } else {
878        let details = result
879          .diagnostics
880          .iter()
881          .map(format_compact_diagnostic)
882          .collect::<Vec<_>>()
883          .join("; ");
884        println!("- `{}` (**{}**): {details}", result.definition, result.status.to_uppercase());
885      }
886    }
887  }
888
889  let blocked: Vec<_> = data.definitions.iter().filter(|result| result.status == "blocked").collect();
890  if !blocked.is_empty() {
891    println!("\n## Blocked\n");
892    for result in blocked {
893      let blockers = result
894        .blocked_by
895        .iter()
896        .map(|item| format!("`{item}`"))
897        .collect::<Vec<_>>()
898        .join(", ");
899      println!("- `{}` — blocked by {blockers}", result.definition);
900    }
901  }
902
903  if !data.definitions.is_empty() {
904    println!("\n- next: rerun without `--summary-only` (or run `--check-only --ns <ns>`) for full diagnostic messages.");
905  }
906}
907
908fn apply_broad_type_errors(
909  graph: &DefinitionGraph,
910  definitions: &[Vec<String>],
911  results: &mut Vec<DefinitionResult>,
912  broad_type_errors: &[LocatedWarning],
913) {
914  // Bare broad types (#2504) and Options erased to nil (#2124) are errors
915  // since 0.36.0: they fail the definition that writes them, reachable or not.
916  for error in broad_type_errors {
917    let diagnostic = CheckDiagnostic {
918      severity: "error",
919      ..warning_diagnostic(error)
920    };
921    match results.iter_mut().find(|result| result.definition == diagnostic.definition) {
922      Some(result) => {
923        result.status = "failed";
924        result.blocked_by.clear();
925        push_unique_diagnostic(&mut result.diagnostics, diagnostic);
926      }
927      None => results.push(DefinitionResult {
928        definition: diagnostic.definition.clone(),
929        status: "failed",
930        blocked_by: vec![],
931        diagnostics: vec![diagnostic],
932      }),
933    }
934  }
935  if !broad_type_errors.is_empty() {
936    block_dependents_of_failed(graph, definitions, results);
937  }
938}
939
940/// Run the ordinary check + default proof audit on a single dependency graph
941/// under the currently active entry context.
942fn run_graph_pass(
943  graph: &DefinitionGraph,
944  definitions: &[Vec<String>],
945) -> (Vec<DefinitionResult>, Vec<LocatedWarning>, Vec<LocatedWarning>) {
946  let mut results = check_definitions(graph, definitions);
947  let (broad_type_errors, advisories) = runner::preprocess::split_blocking_advisories(runner::preprocess::take_advisories());
948  // The proof audit re-checks the components that passed the ordinary check,
949  // so ordinary rejections keep their own diagnostics (#2121). It runs even
950  // when another definition failed, so an unrelated warning cannot leave an
951  // unproven definition counted as passed (#2591). One audit covers the
952  // whole check, so shared dependencies are proved once.
953  if runner::preprocess::default_proof_enabled() {
954    let passed = results
955      .iter()
956      .filter(|result| result.status == "passed")
957      .map(|result| result.definition.clone())
958      .collect::<HashSet<_>>();
959    // A passed definition never depends on a failed one (it would be blocked),
960    // so these components are closed under their dependencies.
961    let passed_components = definitions
962      .iter()
963      .filter(|component| component.iter().all(|definition| passed.contains(definition)))
964      .cloned()
965      .collect::<Vec<_>>();
966    if !passed_components.is_empty() {
967      let mut audited = runner::preprocess::with_default_proof(|| check_definitions(graph, &passed_components))
968        .into_iter()
969        .map(|result| (result.definition.clone(), result))
970        .collect::<HashMap<_, _>>();
971      for result in &mut results {
972        if let Some(audited) = audited.remove(&result.definition) {
973          *result = audited;
974        }
975      }
976      // The audit re-preprocesses the same code; its advisories repeat the ordinary ones.
977      drop(runner::preprocess::take_advisories());
978    }
979  }
980  (results, broad_type_errors, advisories)
981}
982
983fn find_entry_with_target(entry_contexts: &[EntryCheckContext], target: SnapshotTarget) -> Option<usize> {
984  entry_contexts.iter().position(|ctx| ctx.target == Some(target))
985}
986
987fn transitive_nodes_from(start: &str, graph: &DefinitionGraph) -> BTreeSet<String> {
988  let mut visited = BTreeSet::new();
989  let mut queue = VecDeque::new();
990  visited.insert(start.to_owned());
991  queue.push_back(start.to_owned());
992  while let Some(node) = queue.pop_front() {
993    if let Some(deps) = graph.get(&node) {
994      for dep in deps {
995        if visited.insert(dep.clone()) {
996          queue.push_back(dep.clone());
997        }
998      }
999    }
1000  }
1001  visited
1002}
1003
1004fn assign_unwired_entry_owner(
1005  ns: &str,
1006  def: &str,
1007  scope: &AllDefsScope,
1008  ns_entry_targets: &HashMap<String, Vec<SnapshotTarget>>,
1009  ns_entry_indices: &HashMap<String, BTreeSet<usize>>,
1010  unwired_graph: &DefinitionGraph,
1011) -> usize {
1012  let fqn = format!("{ns}/{def}");
1013
1014  // 1. Own declared `:ffi :target` on the definition itself.
1015  if let Some(&target) = scope.declared_targets.get(&fqn)
1016    && let Some(idx) = find_entry_with_target(&scope.entry_contexts, target)
1017  {
1018    return idx;
1019  }
1020
1021  // 2. Exclusive namespace owner: all reached definitions in `ns` share one target.
1022  if let Some(targets) = ns_entry_targets.get(ns)
1023    && targets.len() == 1
1024    && let Some(&target) = targets.first()
1025  {
1026    if let Some(indices) = ns_entry_indices.get(ns)
1027      && let Some(&idx) = indices.iter().find(|&&idx| scope.entry_contexts[idx].target == Some(target))
1028    {
1029      return idx;
1030    }
1031    if let Some(idx) = find_entry_with_target(&scope.entry_contexts, target) {
1032      return idx;
1033    }
1034  }
1035
1036  // 3. Unambiguous `:ffi :target` referenced by the definition's transitive call
1037  // graph or schemas. Conflicting targets (len > 1) fall back to the selected entry
1038  // so `E_JS_FFI_TARGET_MISMATCH` is still reported.
1039  let mut referenced_targets = Vec::new();
1040  for node in transitive_nodes_from(&fqn, unwired_graph) {
1041    if let Some(&target) = scope.declared_targets.get(&node) {
1042      push_unique_target(&mut referenced_targets, target);
1043    }
1044    if let Some((node_ns, node_def)) = node.rsplit_once('/') {
1045      let schema = program::lookup_def_schema(node_ns, node_def);
1046      collect_schema_declared_targets(node_ns, schema.as_ref(), &scope.declared_targets, &mut referenced_targets);
1047    }
1048  }
1049  if referenced_targets.len() == 1
1050    && let Some(&target) = referenced_targets.first()
1051    && let Some(idx) = find_entry_with_target(&scope.entry_contexts, target)
1052  {
1053    return idx;
1054  }
1055
1056  // 4. Default fallback: selected entry.
1057  0
1058}
1059
1060struct MultiEntryCheckOutcome {
1061  entries: Vec<String>,
1062  results: Vec<DefinitionResult>,
1063  advisories: Vec<LocatedWarning>,
1064}
1065
1066fn run_multi_entry_all_defs(scope: &AllDefsScope) -> Result<MultiEntryCheckOutcome, String> {
1067  let include_core = scope.roots.iter().any(|(ns, _)| calcit_core::calcit::is_bundled_core_ns(ns));
1068  let entry_count = scope.entry_contexts.len();
1069
1070  // Collect each entry's reachable closure so every definition reached by an
1071  // entry is checked under that entry's own target, type slots, and policy.
1072  let mut entry_roots: Vec<Vec<(String, String)>> = vec![Vec::new(); entry_count];
1073  let mut reached_definitions = HashSet::<String>::new();
1074  let mut ns_entry_targets = HashMap::<String, Vec<SnapshotTarget>>::new();
1075  let mut ns_entry_indices = HashMap::<String, BTreeSet<usize>>::new();
1076
1077  for (idx, ctx) in scope.entry_contexts.iter().enumerate() {
1078    let mut roots = Vec::new();
1079    for (ns, def) in [(&ctx.init_ns, &ctx.init_def), (&ctx.reload_ns, &ctx.reload_def)] {
1080      let pair = (ns.clone(), def.clone());
1081      if !roots.contains(&pair) {
1082        roots.push(pair);
1083      }
1084    }
1085    if roots.is_empty() {
1086      continue;
1087    }
1088    let (graph, _) = build_graph_for_roots(&roots, include_core, Some(&scope.intrinsics))?;
1089    for fqn in graph.keys() {
1090      reached_definitions.insert(fqn.clone());
1091      if let Some((ns, _)) = fqn.rsplit_once('/')
1092        && scope.project_namespaces.contains(ns)
1093      {
1094        ns_entry_indices.entry(ns.to_owned()).or_default().insert(idx);
1095        if let Some(target) = ctx.target {
1096          push_unique_target(ns_entry_targets.entry(ns.to_owned()).or_default(), target);
1097        }
1098      }
1099    }
1100    entry_roots[idx] = roots;
1101  }
1102
1103  // Assign unwired project definitions to their true entry context using a
1104  // single full graph so transitive target discovery is order-independent.
1105  let unwired_roots = scope
1106    .roots
1107    .iter()
1108    .filter(|(ns, def)| !reached_definitions.contains(&format!("{ns}/{def}")))
1109    .cloned()
1110    .collect::<Vec<_>>();
1111  if !unwired_roots.is_empty() {
1112    let (unwired_graph, _) = build_graph_for_roots(&unwired_roots, include_core, Some(&scope.intrinsics))?;
1113    for (ns, def) in &unwired_roots {
1114      let owner = assign_unwired_entry_owner(ns, def, scope, &ns_entry_targets, &ns_entry_indices, &unwired_graph);
1115      let pair = (ns.clone(), def.clone());
1116      if !entry_roots[owner].contains(&pair) {
1117        entry_roots[owner].push(pair);
1118      }
1119    }
1120  }
1121
1122  // Drain snapshot-level advisories (e.g. bare broad types) before per-entry passes.
1123  let (snapshot_broad_errors, initial_advisories) =
1124    runner::preprocess::split_blocking_advisories(runner::preprocess::take_advisories());
1125  let mut all_advisories = Vec::new();
1126  for advisory in initial_advisories {
1127    push_unique_warning(&mut all_advisories, advisory);
1128  }
1129
1130  let _context_guard = EntryContextGuard::capture(&scope.entry_contexts[0].feature_policy);
1131  let mut merged_results = BTreeMap::<String, DefinitionResult>::new();
1132  let mut union_graph = DefinitionGraph::new();
1133  let mut checked_entries = Vec::<String>::new();
1134
1135  for (idx, ctx) in scope.entry_contexts.iter().enumerate() {
1136    if entry_roots[idx].is_empty() {
1137      continue;
1138    }
1139    for entry_fn in [&ctx.init_fn, &ctx.reload_fn] {
1140      if !checked_entries.contains(entry_fn) {
1141        checked_entries.push(entry_fn.clone());
1142      }
1143    }
1144    let (entry_graph, entry_components) = build_graph_for_roots(&entry_roots[idx], include_core, Some(&scope.intrinsics))?;
1145    for (node, deps) in &entry_graph {
1146      union_graph.entry(node.clone()).or_default().extend(deps.iter().cloned());
1147    }
1148
1149    program::configure_entry_target(ctx.target);
1150    program::configure_entry_feature_policy(&ctx.feature_policy);
1151    calcit_core::calcit::configure_entry_type_slots(&ctx.type_slots)
1152      .map_err(|message| format!("entries.{}.type-slots: {message}", ctx.name))?;
1153
1154    let (mut entry_results, entry_broad_errors, entry_advisories) =
1155      runner::preprocess::with_restored_compiled_program(|| run_graph_pass(&entry_graph, &entry_components));
1156    apply_broad_type_errors(&entry_graph, &entry_components, &mut entry_results, &entry_broad_errors);
1157    for advisory in entry_advisories {
1158      push_unique_warning(&mut all_advisories, advisory);
1159    }
1160    for result in entry_results {
1161      match merged_results.get_mut(&result.definition) {
1162        Some(existing) => merge_definition_result(existing, result),
1163        None => {
1164          merged_results.insert(result.definition.clone(), result);
1165        }
1166      }
1167    }
1168  }
1169
1170  let union_components = strongly_connected_components(&union_graph);
1171  let mut results = Vec::with_capacity(merged_results.len());
1172  for component in &union_components {
1173    for definition in component {
1174      if let Some(result) = merged_results.remove(definition) {
1175        results.push(result);
1176      }
1177    }
1178  }
1179  results.extend(merged_results.into_values());
1180
1181  apply_broad_type_errors(&union_graph, &union_components, &mut results, &snapshot_broad_errors);
1182
1183  Ok(MultiEntryCheckOutcome {
1184    entries: checked_entries,
1185    results,
1186    advisories: all_advisories,
1187  })
1188}
1189
1190pub fn run(entries: &ProgramEntries, raw_format: &str, all_defs: Option<&AllDefsScope>, summary_only: bool) -> Result<(), String> {
1191  let format = StructuredOutputFormat::parse(raw_format, "check-only")?;
1192  let _output_guard = crate::ProgramOutputGuard::new(format != StructuredOutputFormat::Human, false);
1193  let (checked_entries, results, advisories) = match all_defs {
1194    Some(scope) if scope.has_multiple_targets() => {
1195      let outcome = run_multi_entry_all_defs(scope)?;
1196      (outcome.entries, outcome.results, outcome.advisories)
1197    }
1198    _ => {
1199      let (graph, definitions) = reachable_definitions(entries, all_defs)?;
1200      let (mut results, broad_type_errors, advisories) = run_graph_pass(&graph, &definitions);
1201      apply_broad_type_errors(&graph, &definitions, &mut results, &broad_type_errors);
1202      (
1203        vec![entries.init_fn.to_string(), entries.reload_fn.to_string()],
1204        results,
1205        advisories,
1206      )
1207    }
1208  };
1209  let summary = CheckSummary {
1210    total: results.len(),
1211    passed: results.iter().filter(|result| result.status == "passed").count(),
1212    failed: results.iter().filter(|result| result.status == "failed").count(),
1213    blocked: results.iter().filter(|result| result.status == "blocked").count(),
1214    cascaded: results.iter().filter(|result| result.status == "cascaded").count(),
1215  };
1216  let passed = summary.failed == 0 && summary.blocked == 0 && summary.cascaded == 0;
1217  let data = CheckData {
1218    status: if passed { "passed" } else { "failed" },
1219    scope: if all_defs.is_some() { "all-defs" } else { "reachable" },
1220    entries: checked_entries,
1221    summary,
1222    definitions: results,
1223    advisories: advisories.iter().map(advisory_diagnostic).collect(),
1224  };
1225
1226  if summary_only {
1227    let compact = compact_check_data(&data);
1228    let envelope = serde_json::json!({
1229      "schema_version": 1,
1230      "command": "check-only",
1231      "data": compact,
1232      "diagnostics": [],
1233    });
1234    match format {
1235      StructuredOutputFormat::Human => {
1236        print_human_compact(&compact);
1237        if !advisories.is_empty() {
1238          eprintln!(
1239            "\nNotes: ({} notes, the check still passes; rerun without --summary-only for details)",
1240            advisories.len()
1241          );
1242        }
1243      }
1244      StructuredOutputFormat::Edn => println!("{}", format_json_value_as_edn(&envelope)?),
1245      StructuredOutputFormat::Json => println!("{envelope}"),
1246    }
1247  } else {
1248    let envelope = serde_json::json!({
1249      "schema_version": 1,
1250      "command": "check-only",
1251      "data": data,
1252      "diagnostics": [],
1253    });
1254    match format {
1255      StructuredOutputFormat::Human => {
1256        print_human(&data);
1257        // Advisories never fail the check; stderr matches the plain check-only Notes.
1258        if !advisories.is_empty() {
1259          eprintln!("\nNotes: ({} notes, the check still passes)", advisories.len());
1260          LocatedWarning::print_list(&advisories);
1261        }
1262      }
1263      StructuredOutputFormat::Edn => println!("{}", format_json_value_as_edn(&envelope)?),
1264      StructuredOutputFormat::Json => println!("{envelope}"),
1265    }
1266  }
1267
1268  if passed {
1269    Ok(())
1270  } else {
1271    Err(format!(
1272      "Strict check found {} failed, {} blocked, and {} cascaded definition(s)",
1273      data.summary.failed, data.summary.blocked, data.summary.cascaded
1274    ))
1275  }
1276}
1277
1278#[cfg(test)]
1279mod tests {
1280  use super::{
1281    CheckData, CheckDiagnostic, CheckSummary, DefinitionResult, compact_check_data, merge_definition_result, take_definition_outcome,
1282  };
1283  use std::collections::BTreeMap;
1284
1285  fn diagnostic(message: &str, definition: &str) -> CheckDiagnostic {
1286    CheckDiagnostic {
1287      severity: "error",
1288      code: None,
1289      message: message.to_owned(),
1290      definition: definition.to_owned(),
1291      path: Vec::new(),
1292      hint: None,
1293      expected: None,
1294      actual: None,
1295      provenance: Vec::new(),
1296    }
1297  }
1298
1299  #[test]
1300  fn failed_definition_retains_its_cascaded_diagnostics() {
1301    let definition = "app.main/failing".to_owned();
1302    let mut confirmed = BTreeMap::from([(definition.clone(), vec![diagnostic("own error", &definition)])]);
1303    let mut cascaded = BTreeMap::from([(definition.clone(), vec![diagnostic("dependency error", "app.main/dependency")])]);
1304
1305    let (status, blocked_by, diagnostics) =
1306      take_definition_outcome(&definition, &mut confirmed, &mut cascaded, &["app.main/dependency".to_owned()]);
1307
1308    assert_eq!(status, "failed");
1309    assert!(blocked_by.is_empty());
1310    assert_eq!(diagnostics.len(), 2);
1311    assert!(confirmed.is_empty());
1312    assert!(cascaded.is_empty());
1313  }
1314
1315  #[test]
1316  fn merging_definition_results_prefers_failure_over_pass_or_blocked() {
1317    let mut shared = DefinitionResult {
1318      definition: "app.shared/helper".to_owned(),
1319      status: "passed",
1320      blocked_by: vec![],
1321      diagnostics: vec![],
1322    };
1323    merge_definition_result(
1324      &mut shared,
1325      DefinitionResult {
1326        definition: "app.shared/helper".to_owned(),
1327        status: "blocked",
1328        blocked_by: vec!["app.shared/dep".to_owned()],
1329        diagnostics: vec![],
1330      },
1331    );
1332    assert_eq!(shared.status, "blocked");
1333    assert_eq!(shared.blocked_by, vec!["app.shared/dep".to_owned()]);
1334
1335    merge_definition_result(
1336      &mut shared,
1337      DefinitionResult {
1338        definition: "app.shared/helper".to_owned(),
1339        status: "failed",
1340        blocked_by: vec![],
1341        diagnostics: vec![diagnostic("target mismatch", "app.shared/helper")],
1342      },
1343    );
1344    assert_eq!(shared.status, "failed");
1345    assert!(shared.blocked_by.is_empty());
1346    assert_eq!(shared.diagnostics.len(), 1);
1347  }
1348
1349  #[test]
1350  fn compact_check_data_omits_passed_and_keeps_failure_paths_and_blockers() {
1351    let mut own_diag = diagnostic("type mismatch details", "app.main/failing");
1352    own_diag.code = Some("E_TYPE_MISMATCH".to_owned());
1353    own_diag.path = vec![1, 2];
1354    let mut foreign_diag = diagnostic("dependency mismatch", "app.main/dependency");
1355    foreign_diag.code = Some("E_FN_RETURN_UNPROVEN".to_owned());
1356    foreign_diag.path = vec![0];
1357    let mut advisory = diagnostic("open family note", "app.main/ok");
1358    advisory.severity = "note";
1359    advisory.code = Some("W_OPEN_FAMILY".to_owned());
1360    advisory.path = vec![3];
1361
1362    let data = CheckData {
1363      status: "failed",
1364      scope: "all-defs",
1365      entries: vec!["app.main/main!".to_owned()],
1366      summary: CheckSummary {
1367        total: 3,
1368        passed: 1,
1369        failed: 1,
1370        blocked: 1,
1371        cascaded: 0,
1372      },
1373      definitions: vec![
1374        DefinitionResult {
1375          definition: "app.main/ok".to_owned(),
1376          status: "passed",
1377          blocked_by: vec![],
1378          diagnostics: vec![],
1379        },
1380        DefinitionResult {
1381          definition: "app.main/failing".to_owned(),
1382          status: "failed",
1383          blocked_by: vec![],
1384          diagnostics: vec![own_diag, foreign_diag],
1385        },
1386        DefinitionResult {
1387          definition: "app.main/caller".to_owned(),
1388          status: "blocked",
1389          blocked_by: vec!["app.main/failing".to_owned()],
1390          diagnostics: vec![],
1391        },
1392      ],
1393      advisories: vec![advisory],
1394    };
1395
1396    let compact = compact_check_data(&data);
1397    assert!(compact.summary_only);
1398    assert_eq!(compact.summary.total, 3);
1399    assert_eq!(compact.summary.passed, 1);
1400    assert_eq!(compact.definitions.len(), 2);
1401    assert_eq!(compact.definitions[0].definition, "app.main/failing");
1402    assert_eq!(compact.definitions[0].diagnostics.len(), 2);
1403    assert_eq!(compact.definitions[0].diagnostics[0].code.as_deref(), Some("E_TYPE_MISMATCH"));
1404    assert_eq!(compact.definitions[0].diagnostics[0].definition, None);
1405    assert_eq!(compact.definitions[0].diagnostics[0].path, vec![1, 2]);
1406    assert_eq!(
1407      compact.definitions[0].diagnostics[1].definition.as_deref(),
1408      Some("app.main/dependency")
1409    );
1410    assert_eq!(compact.definitions[1].definition, "app.main/caller");
1411    assert_eq!(compact.definitions[1].blocked_by, vec!["app.main/failing".to_owned()]);
1412    assert_eq!(compact.advisories.len(), 1);
1413    assert_eq!(compact.advisories[0].definition.as_deref(), Some("app.main/ok"));
1414  }
1415}