1use std::cell::RefCell;
2use std::collections::{BTreeSet, HashSet};
3use std::time::Instant;
4
5use crate::cli_args::CheckPublicCommand;
6use calcit_core::calcit::{CalcitErr, LocatedWarning};
7use calcit_core::call_stack::CallStackList;
8use calcit_core::runner;
9use calcit_core::snapshot::{self, SnapshotTarget};
10use cirru_parser::Cirru;
11use serde_json::{Value, json};
12
13use crate::type_coverage;
14
15#[derive(Debug)]
16struct DefinitionResult {
17 id: String,
18 namespace: String,
19 definition: String,
20 kind: &'static str,
21 declared_target: Option<SnapshotTarget>,
22 status: &'static str,
23}
24
25struct PreparedDefinition {
26 id: String,
27 namespace: String,
28 definition: String,
29 kind: &'static str,
30 declared_target: Option<SnapshotTarget>,
31 rejected: bool,
32 runtime_intrinsic: bool,
33}
34
35pub(crate) fn is_core_runtime_intrinsic(namespace: &str, definition: &str, entry: &snapshot::CodeEntry) -> bool {
36 if namespace != calcit_core::calcit::CORE_NS || !entry.tags.iter().any(|tag| tag.ref_str() == "builtin") {
37 return false;
38 }
39
40 match &entry.code {
41 Cirru::Leaf(symbol) => symbol.as_ref() == "&runtime-implementation",
42 Cirru::List(items) if items.len() == 1 => matches!(&items[0], Cirru::Leaf(symbol) if symbol.as_ref() == "&runtime-implementation"),
43 Cirru::List(items) if items.len() == 3 => {
44 matches!(&items[0], Cirru::Leaf(head) if head.as_ref() == "def")
45 && matches!(&items[1], Cirru::Leaf(name) if name.as_ref() == definition)
46 && matches!(&items[2], Cirru::Leaf(symbol) if symbol.as_ref() == "&runtime-implementation")
47 }
48 _ => false,
49 }
50}
51
52fn definition_target(entry: &snapshot::CodeEntry) -> Result<Option<SnapshotTarget>, String> {
53 let Some(ffi) = &entry.ffi else {
54 return Ok(None);
55 };
56 snapshot::parse_ffi_target(ffi)
57}
58
59fn error_diagnostic(error: &CalcitErr, definition_id: &str) -> Value {
60 json!({
61 "code": error.code.as_deref().unwrap_or("E_PUBLIC_CHECK_PREPROCESS"),
62 "phase": "preprocess",
63 "severity": "error",
64 "definition": definition_id,
65 "kind": error.kind.to_string().to_lowercase(),
66 "message": error.headline(),
67 "location": error.location.as_ref().map(|location| json!({
68 "ns": location.ns.to_string(),
69 "def": location.def.to_string(),
70 "coord": location.coord.to_vec(),
71 })),
72 "hint": error.hint,
73 "provenance": error.provenance,
74 })
75}
76
77fn warning_diagnostic(warning: &LocatedWarning) -> Value {
78 let mut row = warning.as_json();
79 if let Value::Object(fields) = &mut row {
80 fields.insert("phase".to_owned(), json!("preprocess"));
81 fields.insert("severity".to_owned(), json!("warning"));
82 }
83 row
84}
85
86fn result_json(row: &DefinitionResult) -> Value {
87 json!({
88 "id": row.id,
89 "namespace": row.namespace,
90 "definition": row.definition,
91 "kind": row.kind,
92 "declared_target": row.declared_target.map(SnapshotTarget::as_str),
93 "status": row.status,
94 })
95}
96
97fn check_definition(
98 namespace: &str,
99 definition: &str,
100 id: &str,
101 warnings: &RefCell<Vec<LocatedWarning>>,
102 diagnostics: &mut Vec<Value>,
103) -> &'static str {
104 let warning_count = warnings.borrow().len();
105 let outcome = runner::preprocess::ensure_ns_def_compiled(namespace, definition, warnings, &CallStackList::default());
106 runner::preprocess::drop_macro_owned_proof_warnings(warnings, warning_count);
109 match outcome {
110 Ok(()) if warnings.borrow().len() == warning_count => "passed",
111 Ok(()) => "warning",
112 Err(error) => {
113 diagnostics.push(error_diagnostic(&error, id));
114 diagnostics.extend(error.warnings.iter().map(warning_diagnostic));
115 "failed"
116 }
117 }
118}
119
120pub fn run(options: &CheckPublicCommand, snapshot: &snapshot::Snapshot, project_namespaces: &HashSet<String>) -> Result<(), String> {
121 if !matches!(options.format.as_str(), "human" | "text" | "edn" | "json") {
122 return Err(format!(
123 "Unknown public check output format `{}`. Expected `human`, `edn`, or `json`.",
124 options.format
125 ));
126 }
127
128 let _static_core = options.static_core.then(runner::preprocess::StaticCoreModeGuard::enabled);
129 let started = Instant::now();
130 let requested_namespaces = options.ns.iter().cloned().collect::<BTreeSet<_>>();
131 let active_target = snapshot.active_entry()?.target;
132 let mut diagnostics = Vec::<Value>::new();
133 let mut selected = Vec::<(String, String, &snapshot::CodeEntry)>::new();
134
135 if requested_namespaces.is_empty() {
136 diagnostics.push(json!({
137 "code": "E_PUBLIC_CHECK_SCOPE_REQUIRED",
138 "phase": "selection",
139 "severity": "error",
140 "message": "check-public requires at least one --ns namespace.",
141 }));
142 }
143 if !options.static_core && active_target.is_none() {
144 diagnostics.push(json!({
145 "code": "E_PUBLIC_CHECK_TARGET_REQUIRED",
146 "phase": "selection",
147 "severity": "error",
148 "message": format!("Entry `{}` has no :target; public checks require an explicit browser, node, native, or wasm target.", snapshot.active_entry_name()),
149 }));
150 }
151
152 for namespace in &requested_namespaces {
153 let Some(file) = snapshot.files.get(namespace) else {
154 diagnostics.push(json!({
155 "code": "E_PUBLIC_CHECK_NAMESPACE_NOT_FOUND",
156 "phase": "selection",
157 "severity": "error",
158 "namespace": namespace,
159 "message": format!("Selected namespace `{namespace}` is not loaded by entry `{}`.", snapshot.active_entry_name()),
160 }));
161 continue;
162 };
163 if !options.deps && !project_namespaces.contains(namespace) {
164 diagnostics.push(json!({
165 "code": "E_PUBLIC_CHECK_DEPENDENCY_SCOPE",
166 "phase": "selection",
167 "severity": "error",
168 "namespace": namespace,
169 "message": format!("Selected namespace `{namespace}` belongs to a dependency; pass --deps to admit it explicitly."),
170 }));
171 continue;
172 }
173 if file.defs.is_empty() {
174 diagnostics.push(json!({
175 "code": "E_PUBLIC_CHECK_EMPTY_NAMESPACE",
176 "phase": "selection",
177 "severity": "error",
178 "namespace": namespace,
179 "message": format!("Selected namespace `{namespace}` contains no definitions; zero coverage is not a successful check."),
180 }));
181 continue;
182 }
183 let mut definitions = file.defs.iter().collect::<Vec<_>>();
184 definitions.sort_by_key(|(definition, _)| *definition);
185 selected.extend(
186 definitions
187 .into_iter()
188 .map(|(definition, entry)| (namespace.clone(), definition.clone(), entry)),
189 );
190 }
191
192 let revision_ids = selected
193 .iter()
194 .map(|(namespace, definition, _)| (namespace.clone(), definition.clone()))
195 .collect::<Vec<_>>();
196 let selected_count = revision_ids.len();
197 let selection_complete = diagnostics.is_empty();
198 let revision = type_coverage::analysis_revision(snapshot, &revision_ids)?;
199 let warnings = RefCell::new(Vec::<LocatedWarning>::new());
200 let mut results = Vec::<DefinitionResult>::new();
201 let mut checked_definition_ids = Vec::<String>::new();
202 let mut prepared = Vec::<PreparedDefinition>::new();
203
204 if options.static_core || active_target.is_some() {
205 for (namespace, definition, entry) in selected {
206 let id = format!("{namespace}/{definition}");
207 let kind = type_coverage::analyze_code_entry(&namespace, &definition, entry).kind.as_str();
208 let declared_target = match definition_target(entry) {
209 Ok(value) => value,
210 Err(message) => {
211 diagnostics.push(json!({
212 "code": "E_PUBLIC_CHECK_INVALID_TARGET",
213 "phase": "target",
214 "severity": "error",
215 "definition": id,
216 "message": message,
217 }));
218 prepared.push(PreparedDefinition {
219 id,
220 namespace,
221 definition,
222 kind,
223 declared_target: None,
224 rejected: true,
225 runtime_intrinsic: false,
226 });
227 continue;
228 }
229 };
230 if options.static_core
231 && let Some(expected) = declared_target
232 {
233 diagnostics.push(json!({
234 "code": runner::preprocess::STATIC_CORE_BOUNDARY_ERROR,
235 "phase": "target",
236 "severity": "error",
237 "definition": id,
238 "message": format!("Definition `{id}` declares host `:ffi :target :{}`, which is not allowed in portable Static Core.", expected.as_str()),
239 }));
240 prepared.push(PreparedDefinition {
241 id,
242 namespace,
243 definition,
244 kind,
245 declared_target,
246 rejected: true,
247 runtime_intrinsic: false,
248 });
249 continue;
250 }
251 if !options.static_core
252 && let Some(target) = active_target
253 && let Some(expected) = declared_target
254 && expected != target
255 {
256 diagnostics.push(json!({
257 "code": "E_JS_FFI_TARGET_MISMATCH",
258 "phase": "target",
259 "severity": "error",
260 "definition": id,
261 "message": format!("Definition `{id}` requires `{}` target, but entry `{}` targets `{}`.", expected.as_str(), snapshot.active_entry_name(), target.as_str()),
262 }));
263 prepared.push(PreparedDefinition {
264 id,
265 namespace,
266 definition,
267 kind,
268 declared_target,
269 rejected: true,
270 runtime_intrinsic: false,
271 });
272 continue;
273 }
274
275 let runtime_intrinsic = is_core_runtime_intrinsic(&namespace, &definition, entry);
276 prepared.push(PreparedDefinition {
277 id,
278 namespace,
279 definition,
280 kind,
281 declared_target,
282 rejected: false,
283 runtime_intrinsic,
284 });
285 }
286 }
287
288 let preflight_ready =
292 selection_complete && (options.static_core || active_target.is_some()) && prepared.iter().all(|row| !row.rejected);
293
294 for row in prepared {
295 if preflight_ready {
296 let PreparedDefinition {
297 id,
298 namespace,
299 definition,
300 kind,
301 declared_target,
302 runtime_intrinsic,
303 ..
304 } = row;
305 checked_definition_ids.push(id.clone());
306 let status = if runtime_intrinsic {
307 "intrinsic"
308 } else {
309 check_definition(&namespace, &definition, &id, &warnings, &mut diagnostics)
310 };
311 results.push(DefinitionResult {
312 id,
313 namespace,
314 definition,
315 kind,
316 declared_target,
317 status,
318 });
319 } else {
320 results.push(DefinitionResult {
321 id: row.id,
322 namespace: row.namespace,
323 definition: row.definition,
324 kind: row.kind,
325 declared_target: row.declared_target,
326 status: if row.rejected { "rejected" } else { "not_checked" },
327 });
328 }
329 }
330
331 if runner::preprocess::default_proof_enabled() && preflight_ready && results.iter().any(|row| row.status == "passed") {
338 let _silence = crate::ProgramOutputGuard::new(false, true);
341 let audit_warnings = RefCell::new(Vec::new());
342 let warned_definitions = warnings
345 .borrow()
346 .iter()
347 .map(LocatedWarning::as_json)
348 .filter_map(|row| {
349 Some((
350 row["location"]["ns"].as_str()?.to_owned(),
351 row["location"]["def"].as_str()?.to_owned(),
352 ))
353 })
354 .collect::<HashSet<_>>();
355 runner::preprocess::check_with_default_proof(&audit_warnings, || {
356 for row in results
357 .iter_mut()
358 .filter(|row| row.status == "passed" && !warned_definitions.contains(&(row.namespace.clone(), row.definition.clone())))
359 {
360 let mut row_diagnostics = Vec::new();
361 let warning_count = audit_warnings.borrow().len();
362 let status = check_definition(&row.namespace, &row.definition, &row.id, &audit_warnings, &mut row_diagnostics);
363 let inside_warned_dependency = |diagnostic: &Value| {
366 diagnostic["location"]["ns"]
367 .as_str()
368 .zip(diagnostic["location"]["def"].as_str())
369 .is_some_and(|(ns, def)| warned_definitions.contains(&(ns.to_owned(), def.to_owned())))
370 };
371 if status == "failed" && row_diagnostics.iter().all(inside_warned_dependency) {
372 continue;
373 }
374 if status == "warning"
376 && audit_warnings.borrow()[warning_count..]
377 .iter()
378 .all(|warning| inside_warned_dependency(&warning.as_json()))
379 {
380 continue;
381 }
382 row.status = status;
383 diagnostics.extend(row_diagnostics);
384 }
385 });
386 let mut warnings = warnings.borrow_mut();
388 for warning in audit_warnings.into_inner() {
389 let location = warning.as_json();
390 let in_warned = location["location"]["ns"]
391 .as_str()
392 .zip(location["location"]["def"].as_str())
393 .is_some_and(|(ns, def)| warned_definitions.contains(&(ns.to_owned(), def.to_owned())));
394 if !in_warned && !warnings.contains(&warning) {
395 warnings.push(warning);
396 }
397 }
398 }
399
400 let (blocking, advisories) = runner::preprocess::split_blocking_advisories(runner::preprocess::take_advisories());
407 for advisory in advisories {
408 runner::preprocess::push_advisory(advisory);
409 }
410 for advisory in &blocking {
411 let mut diagnostic = warning_diagnostic(advisory);
412 diagnostic["severity"] = json!("error");
413 let location = (
414 diagnostic["location"]["ns"].as_str().map(str::to_owned),
415 diagnostic["location"]["def"].as_str().map(str::to_owned),
416 );
417 let row = results
418 .iter_mut()
419 .find(|row| Some(&row.namespace) == location.0.as_ref() && Some(&row.definition) == location.1.as_ref());
420 let reached = matches!(
421 advisory.code(),
422 Some(
423 snapshot::UNBOUND_TYPE_SLOT_ERROR
424 | snapshot::OPTION_ERASED_ERROR
425 | snapshot::OPTION_NIL_CHECK_ERROR
426 | snapshot::LEGACY_NIL_USAGE_ERROR
427 | snapshot::LEGACY_DYNAMIC_STYLE_ERROR
428 | snapshot::RUNTIME_TYPE_PREDICATE_ERROR
429 | snapshot::RUNTIME_TYPE_PREDICATE_WARNING
430 )
431 );
432 match row {
433 Some(row) => row.status = "failed",
434 None if reached => {}
435 None => continue,
436 }
437 if !diagnostics.contains(&diagnostic) {
438 diagnostics.push(diagnostic);
439 }
440 }
441 diagnostics.extend(warnings.borrow().iter().map(warning_diagnostic));
442 let warned_definitions = diagnostics
445 .iter()
446 .filter(|diagnostic| diagnostic["severity"] == "warning")
447 .filter_map(|diagnostic| Some((diagnostic["location"]["ns"].as_str()?, diagnostic["location"]["def"].as_str()?)))
448 .collect::<HashSet<_>>();
449 for row in &mut results {
450 if row.status == "passed" && warned_definitions.contains(&(row.namespace.as_str(), row.definition.as_str())) {
451 row.status = "warning";
452 }
453 }
454 let checked_count = checked_definition_ids.len();
455 let passed_count = results.iter().filter(|row| row.status == "passed").count();
456 let intrinsic_count = results.iter().filter(|row| row.status == "intrinsic").count();
457 let complete = selection_complete && selected_count > 0 && checked_count == selected_count;
458 let passed = complete && passed_count + intrinsic_count == selected_count && diagnostics.is_empty();
459 if selected_count == 0 && diagnostics.is_empty() {
460 diagnostics.push(json!({
461 "code": "E_PUBLIC_CHECK_EMPTY_SCOPE",
462 "phase": "selection",
463 "severity": "error",
464 "message": "The selected public namespace scope contains no definitions; zero coverage is not a successful check.",
465 }));
466 }
467 let duration_ms = started.elapsed().as_secs_f64() * 1000.0;
468
469 let target_label = if options.static_core {
470 Some("static-core")
471 } else {
472 active_target.map(SnapshotTarget::as_str)
473 };
474 match options.format.as_str() {
475 format @ ("json" | "edn") => {
476 let envelope = json!({
477 "schema_version": 1,
478 "command": "analyze.check-public",
479 "revision": revision,
480 "data": {
481 "entry": snapshot.active_entry_name(),
482 "target": target_label,
483 "filters": {
484 "namespaces": requested_namespaces,
485 "include_dependencies": options.deps,
486 "summary_only": options.summary_only,
487 "static_core": options.static_core,
488 },
489 "summary": {
490 "definitions_selected": selected_count,
491 "definitions_checked": checked_count,
492 "definitions_passed": passed_count + intrinsic_count,
493 "definitions_source_passed": passed_count,
494 "definitions_intrinsic": intrinsic_count,
495 "complete": complete,
496 "passed": passed,
497 "duration_ms": duration_ms,
498 },
499 "checked_definition_ids": checked_definition_ids,
500 "definitions": if options.summary_only { Vec::new() } else { results.iter().map(result_json).collect::<Vec<_>>() },
501 },
502 "diagnostics": diagnostics,
503 });
504 if format == "edn" {
505 println!("{}", crate::cli_handlers::format_json_value_as_edn(&envelope)?);
506 } else {
507 println!("{envelope}");
508 }
509 }
510 "human" | "text" => {
511 println!("Public definition check");
512 println!("- entry: {}", snapshot.active_entry_name());
513 println!("- target: {}", target_label.unwrap_or("missing"));
514 println!(
515 "- namespaces: {}",
516 requested_namespaces.iter().cloned().collect::<Vec<_>>().join(", ")
517 );
518 println!("- revision: {revision}");
519 println!("- coverage: {checked_count}/{selected_count} definitions checked");
520 println!("- source definitions passed: {passed_count}; core runtime intrinsics: {intrinsic_count}");
521 println!("- result: {} ({duration_ms:.3}ms)", if passed { "PASS" } else { "FAIL" });
522 if !options.summary_only {
523 for row in &results {
524 println!("- [{}] {} ({})", row.status, row.id, row.kind);
525 }
526 }
527 for diagnostic in &diagnostics {
528 println!("- diagnostic: {}", diagnostic["message"].as_str().unwrap_or("unknown diagnostic"));
529 }
530 }
531 _ => unreachable!("check-public output format was validated before analysis"),
532 }
533
534 if passed {
535 Ok(())
536 } else {
537 Err(format!(
538 "Public definition check failed: {checked_count}/{selected_count} definitions checked, {passed_count} passed, {intrinsic_count} core runtime intrinsics, {} diagnostic(s).",
539 diagnostics.len()
540 ))
541 }
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547 use std::sync::Arc;
548
549 use calcit_core::calcit::{CalcitErrKind, CalcitErrProvenance, DYNAMIC_TYPE};
550 use cirru_edn::{Edn, EdnTag};
551 use cirru_parser::Cirru;
552
553 fn entry_with_ffi(ffi: Option<Edn>) -> snapshot::CodeEntry {
554 snapshot::CodeEntry {
555 doc: String::new(),
556 examples: vec![],
557 tests: vec![],
558 tags: HashSet::new(),
559 code: Cirru::Leaf(Arc::from("placeholder")),
560 schema: DYNAMIC_TYPE.clone(),
561 ffi,
562 }
563 }
564
565 #[test]
566 fn only_exact_builtin_core_placeholders_skip_source_preprocessing() {
567 let mut entry = entry_with_ffi(None);
568 entry.tags.insert(EdnTag::new("builtin"));
569 entry.code = Cirru::leaf("&runtime-implementation");
570 assert!(is_core_runtime_intrinsic("calcit.core", "example", &entry));
571 assert!(!is_core_runtime_intrinsic("app.main", "example", &entry));
572
573 entry.code = Cirru::List(vec![Cirru::leaf("&runtime-implementation")]);
574 assert!(is_core_runtime_intrinsic("calcit.core", "example", &entry));
575
576 entry.code = Cirru::List(vec![
577 Cirru::leaf("def"),
578 Cirru::leaf("example"),
579 Cirru::leaf("&runtime-implementation"),
580 ]);
581 assert!(is_core_runtime_intrinsic("calcit.core", "example", &entry));
582 assert!(!is_core_runtime_intrinsic("calcit.core", "other", &entry));
583
584 entry.code = Cirru::List(vec![
585 Cirru::leaf("def"),
586 Cirru::leaf("example"),
587 Cirru::leaf("&runtime-implementation"),
588 Cirru::leaf("unexpected"),
589 ]);
590 assert!(!is_core_runtime_intrinsic("calcit.core", "example", &entry));
591 entry.code = Cirru::leaf("&runtime-implementation");
592 entry.tags.clear();
593 assert!(!is_core_runtime_intrinsic("calcit.core", "example", &entry));
594 }
595
596 #[test]
597 fn parses_definition_targets_and_rejects_unknown_values() {
598 let ffi = Edn::map_from_iter([(Edn::tag("target"), Edn::tag("browser"))]);
599 assert_eq!(
600 definition_target(&entry_with_ffi(Some(ffi))).unwrap(),
601 Some(SnapshotTarget::Browser)
602 );
603
604 let ffi = Edn::map_from_iter([(Edn::tag("target"), Edn::tag("desktop"))]);
605 assert!(definition_target(&entry_with_ffi(Some(ffi))).is_err());
606 assert!(definition_target(&entry_with_ffi(Some(Edn::str("browser")))).is_err());
607
608 let malformed_key = Edn::map_from_iter([(Edn::str("target"), Edn::tag("browser"))]);
609 assert!(definition_target(&entry_with_ffi(Some(malformed_key))).is_err());
610 assert_eq!(definition_target(&entry_with_ffi(None)).unwrap(), None);
611 }
612
613 #[test]
614 fn serializes_bounded_dynamic_provenance() {
615 let mut error = CalcitErr::use_str(CalcitErrKind::Type, "erased relation");
616 error.code = Some("E_ERASED_GENERIC_RELATION".to_owned());
617 *error.provenance = vec![CalcitErrProvenance {
618 kind: "typed-operation".to_owned(),
619 operation: "calcit.core/get".to_owned(),
620 definition: Some("app.main/consume".to_owned()),
621 path: Some("code@3.2".to_owned()),
622 r#type: "Map<Tag,Dynamic>".to_owned(),
623 output_type: "Option<Dynamic>".to_owned(),
624 flow: "Map value -> get return Option<Dynamic> -> generic consumer argument".to_owned(),
625 migration: "Give the map value a concrete schema.".to_owned(),
626 }];
627
628 let diagnostic = error_diagnostic(&error, "app.main/consume");
629 let provenance = diagnostic["provenance"].as_array().expect("provenance array");
630 assert_eq!(provenance.len(), 1);
631 assert_eq!(provenance[0]["definition"], "app.main/consume");
632 assert_eq!(provenance[0]["path"], "code@3.2");
633 assert_eq!(provenance[0]["type"], "Map<Tag,Dynamic>");
634 }
635}