#![allow(dead_code)]
use calcit_core::calcit::NullableOrigin;
use std::borrow::Cow;
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write;
use std::sync::Arc;
use crate::cli_args::{CheckTypesCommand, WeakTypesCommand};
use calcit_core::calcit::{
CalcitProc, CalcitSyntax, CalcitTypeAnnotation, MacroExpansionType, MacroSyntaxType, ParamShape, ParamShapeToken, ProcTypeSignature,
SchemaKind, SyntaxTypeSignature, resolve_type_slot, validate_definition_schema_shape,
};
use calcit_core::snapshot;
use cirru_parser::Cirru;
use md5::{Digest, Md5};
use crate::cli_handlers::fix::schema_synthesis::{SchemaEvidenceCandidate, collect_schema_evidence_candidates};
pub mod inferred_dynamic;
pub mod legacy_migration;
pub mod option_nil_roundtrip;
pub fn with_proven_helper_contracts<'a>(
snapshot: &'a snapshot::Snapshot,
namespace: Option<&str>,
namespace_prefix: Option<&str>,
include_dependencies: bool,
) -> Result<Cow<'a, snapshot::Snapshot>, String> {
let targets = scoped_definition_entries(snapshot, namespace, namespace_prefix, include_dependencies)?
.into_iter()
.filter(|(_, _, entry)| {
snapshot::schema_annotation_is_missing(&entry.schema)
&& matches!(&entry.code, Cirru::List(items) if matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "defn"))
})
.map(|(ns, def, _)| (ns.to_owned(), def.to_owned()))
.collect::<Vec<_>>();
let mut effective = Cow::Borrowed(snapshot);
if targets.is_empty() {
return Ok(effective);
}
struct StrictGuard(bool);
impl Drop for StrictGuard {
fn drop(&mut self) {
calcit_core::runner::preprocess::set_strict_types(self.0);
let _ = calcit_core::program::clear_runtime_caches_for_reload(Arc::from("query.type"), Arc::from("query.type"), true);
}
}
let _guard = StrictGuard(calcit_core::runner::preprocess::is_strict_types_enabled());
calcit_core::runner::preprocess::set_strict_types(true);
if crate::cli_handlers::prepare_program_for_type_query(snapshot).is_err() {
return Ok(effective);
}
for (namespace, definition) in targets {
let warnings = RefCell::new(vec![]);
let result = calcit_core::runner::preprocess::compile_source_def_for_snapshot(
&namespace,
&definition,
&warnings,
&calcit_core::call_stack::CallStackList::default(),
);
if result.is_err() || !warnings.borrow().is_empty() {
if crate::cli_handlers::prepare_program_for_type_query(snapshot).is_err() {
break;
}
continue;
}
if let Some(schema) = calcit_core::program::lookup_compiled_def(&namespace, &definition)
.and_then(|compiled| calcit_core::runner::preprocess::infer_static_type_from_expr(&compiled.preprocessed_code))
.filter(|schema| matches!(schema.as_ref(), CalcitTypeAnnotation::Fn(_)))
{
effective
.to_mut()
.files
.get_mut(&namespace)
.expect("scoped namespace")
.defs
.get_mut(&definition)
.expect("scoped definition")
.schema = schema;
}
}
Ok(effective)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum DefKind {
Data,
Fn,
Macro,
Proc,
Syntax,
Other,
}
impl DefKind {
pub fn as_str(self) -> &'static str {
match self {
DefKind::Data => "data",
DefKind::Fn => "fn",
DefKind::Macro => "macro",
DefKind::Proc => "proc",
DefKind::Syntax => "syntax",
DefKind::Other => "other",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CoverageLevel {
None,
Partial,
Full,
}
impl CoverageLevel {
pub fn as_str(self) -> &'static str {
match self {
CoverageLevel::None => "none",
CoverageLevel::Partial => "partial",
CoverageLevel::Full => "full",
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TypeCoverageRow {
pub ns: String,
pub def: String,
pub kind: DefKind,
pub level: CoverageLevel,
pub params: Vec<String>,
pub param_annotations: BTreeMap<String, Vec<String>>,
pub return_type_hints: Vec<String>,
pub generics: Vec<String>,
pub where_bounds: Vec<String>,
pub data_type: Option<String>,
pub schema_issues: Vec<String>,
}
fn fn_polymorphism(fn_annot: &calcit_core::calcit::CalcitFnTypeAnnotation) -> (Vec<String>, Vec<String>) {
let generics = fn_annot.generics.iter().map(|name| format!("'{name}")).collect();
let where_bounds = fn_annot.where_bounds.iter().map(|bound| bound.to_brief_string()).collect();
(generics, where_bounds)
}
fn unwrap_singleton_group(mut node: &Cirru) -> &Cirru {
while let Cirru::List(items) = node
&& items.len() == 1
&& matches!(items.first(), Some(Cirru::List(_)))
{
node = &items[0];
}
node
}
fn is_cirru_list_head(node: &Cirru) -> bool {
matches!(node, Cirru::Leaf(head) if head.as_ref() == "[]")
}
fn is_type_variable_leaf(name: &str) -> bool {
let bare = name.strip_prefix('\'').unwrap_or(name);
bare.chars().next().is_some_and(|c| c.is_ascii_uppercase())
}
fn entry_polymorphism(entry: &snapshot::CodeEntry) -> (Vec<String>, Vec<String>) {
if let CalcitTypeAnnotation::Fn(fn_annot) = entry.schema.as_ref() {
return fn_polymorphism(fn_annot);
}
if let CalcitTypeAnnotation::Macro(signature) = entry.schema.as_ref() {
return (
signature.generics.iter().map(|name| format!("'{name}")).collect(),
signature.where_bounds.iter().map(|bound| bound.to_brief_string()).collect(),
);
}
let Cirru::List(items) = &entry.code else {
return (vec![], vec![]);
};
if !matches!(items.first(), Some(Cirru::Leaf(head)) if matches!(head.as_ref(), "defstruct" | "defenum")) {
return (vec![], vec![]);
}
if let Some(Cirru::List(clause)) = items.get(2)
&& matches!(clause.first(), Some(Cirru::Leaf(head)) if head.as_ref() == ":generics")
{
let generics = clause
.iter()
.skip(1)
.filter_map(|item| match item {
Cirru::Leaf(name) => Some(format!("'{}", name.trim_start_matches('\''))),
_ => None,
})
.collect();
let where_bounds = match items.get(3) {
Some(Cirru::List(clause)) if matches!(clause.first(), Some(Cirru::Leaf(head)) if head.as_ref() == ":where") => {
clause.iter().skip(1).map(render_cirru_inline).collect()
}
_ => vec![],
};
return (generics, where_bounds);
}
let generics = match items.get(2) {
Some(Cirru::List(vars))
if vars.iter().any(|item| !is_cirru_list_head(item))
&& vars
.iter()
.all(|item| is_cirru_list_head(item) || matches!(item, Cirru::Leaf(name) if is_type_variable_leaf(name))) =>
{
vars
.iter()
.filter(|item| !is_cirru_list_head(item))
.filter_map(|item| match item {
Cirru::Leaf(name) => Some(format!("'{}", name.trim_start_matches('\''))),
_ => None,
})
.collect()
}
_ => vec![],
};
let where_bounds = items
.iter()
.skip(3)
.find_map(|item| match unwrap_singleton_group(item) {
Cirru::List(parts) if matches!(parts.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "{}") => {
Some(parts.iter().skip(1).map(render_cirru_inline).collect::<Vec<_>>())
}
_ => None,
})
.unwrap_or_default();
(generics, where_bounds)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum WeakTypeKind {
SchemaDynamic,
SchemaOpen,
UnresolvedTypeSlot,
CodeDynamic,
CodeNil,
UnsafeCoerce,
DataDynamic,
}
impl WeakTypeKind {
pub fn as_str(&self) -> &'static str {
match self {
Self::SchemaDynamic => "schema-dynamic",
Self::SchemaOpen => "schema-open",
Self::UnresolvedTypeSlot => "unresolved-type-slot",
Self::CodeDynamic => "code-dynamic",
Self::CodeNil => "code-nil",
Self::UnsafeCoerce => "unsafe-coerce",
Self::DataDynamic => "data-dynamic",
}
}
pub fn collected() -> BTreeSet<Self> {
let mut kinds = Self::all();
kinds.insert(Self::DataDynamic);
kinds
}
pub fn all() -> BTreeSet<Self> {
BTreeSet::from([
Self::SchemaDynamic,
Self::SchemaOpen,
Self::UnresolvedTypeSlot,
Self::CodeDynamic,
Self::CodeNil,
Self::UnsafeCoerce,
])
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum WeakTypeIntent {
Unresolved,
IntentionalJsFfi,
JsFfiNonHost,
IntentionalMacroSyntax,
IntentionalTypeSlotDynamic,
IntentionalDecode,
IntentionalOpen,
ExplicitUnsafe,
DeclaredUnit,
}
impl WeakTypeIntent {
pub fn as_str(self) -> &'static str {
match self {
Self::Unresolved => "unresolved",
Self::IntentionalJsFfi => "intentional-js-ffi",
Self::JsFfiNonHost => "js-ffi-non-host",
Self::IntentionalMacroSyntax => "intentional-macro-syntax",
Self::IntentionalTypeSlotDynamic => "intentional-type-slot-dynamic",
Self::IntentionalDecode => "intentional-decode",
Self::IntentionalOpen => "intentional-open",
Self::ExplicitUnsafe => "explicit-unsafe",
Self::DeclaredUnit => "declared-unit",
}
}
pub fn all() -> BTreeSet<Self> {
BTreeSet::from([
Self::Unresolved,
Self::IntentionalJsFfi,
Self::JsFfiNonHost,
Self::IntentionalMacroSyntax,
Self::IntentionalTypeSlotDynamic,
Self::IntentionalDecode,
Self::IntentionalOpen,
Self::ExplicitUnsafe,
Self::DeclaredUnit,
])
}
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct WeakTypeOccurrence {
pub kind: WeakTypeKind,
pub intent: WeakTypeIntent,
pub detail: String,
pub path: String,
pub unsafe_evidence: Option<UnsafeCoerceEvidence>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct UnsafeCoerceEvidence {
pub source_form: String,
pub target_schema: String,
pub js_ffi_feature: bool,
pub raw_adapter_namespace: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct WeakTypeRow {
pub ns: String,
pub def: String,
pub occurrences: Vec<WeakTypeOccurrence>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub(crate) struct MapShapeFieldCandidate {
name: String,
observed_types: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub(crate) struct MapShapeCandidate {
diagnostic_code: &'static str,
suggested_name: String,
confidence: &'static str,
fields: Vec<MapShapeFieldCandidate>,
evidence_paths: Vec<String>,
contract_status: &'static str,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub(crate) struct DispatchCandidate {
diagnostic_code: &'static str,
suggested_name: String,
confidence: &'static str,
variants: Vec<String>,
evidence_paths: Vec<String>,
contract_status: &'static str,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
pub(crate) struct StructuralCandidates {
pub map_shapes: Vec<MapShapeCandidate>,
pub dispatch: Vec<DispatchCandidate>,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct FfiBoundaryOperation {
pub kind: String,
pub classification: String,
pub source: String,
pub member: Option<String>,
pub path: String,
pub nullable_evidence: String,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct FfiHelperCandidate {
pub definition: String,
pub origin: String,
pub compatibility: String,
pub target: String,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct FfiTraitCandidate {
pub receiver: String,
pub suggested_name: String,
pub fields: Vec<String>,
pub methods: Vec<String>,
pub contract_status: String,
pub defexternal_skeleton: String,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct FfiAdapterCandidate {
pub source: String,
pub suggested_definition: String,
pub schema_cirru_edn: String,
pub contract_status: String,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct FfiBoundaryEvidence {
pub diagnostic_code: String,
pub definition: String,
pub classification: String,
pub target: String,
pub js_ffi_feature: bool,
pub raw_adapter_namespace: bool,
pub operations: Vec<FfiBoundaryOperation>,
pub unsafe_paths: Vec<String>,
pub callers: Vec<String>,
pub helper_candidates: Vec<FfiHelperCandidate>,
pub trait_candidates: Vec<FfiTraitCandidate>,
pub adapter_candidates: Vec<FfiAdapterCandidate>,
pub provenance: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct FfiImportBinding {
source: String,
member: Option<String>,
}
fn schema_has_js_ffi(schema: &CalcitTypeAnnotation) -> bool {
match schema {
CalcitTypeAnnotation::Fn(annotation) => annotation.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
CalcitTypeAnnotation::Macro(annotation) => annotation.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
_ => false,
}
}
fn ffi_import_bindings(code: &Cirru, namespace: &str) -> Result<BTreeMap<String, FfiImportBinding>, String> {
use calcit_core::program::ImportRule;
Ok(
calcit_core::program::extract_import_map(code, namespace)?
.into_iter()
.filter_map(|(local, rule)| {
let (source, member) = match rule.as_ref() {
ImportRule::NsDefault(source) => (source, Some("default".to_owned())),
ImportRule::NsAs(source) if source.starts_with(['|', '"']) => (source, None),
ImportRule::NsReferDef(source, member) if source.starts_with(['|', '"']) => (source, Some(member.to_string())),
_ => return None,
};
Some((
local.to_string(),
FfiImportBinding {
source: source.trim_start_matches(['|', '"']).to_owned(),
member,
},
))
})
.collect(),
)
}
fn ffi_member_operation(head: &str) -> Option<(&'static str, &'static str, bool)> {
if head.starts_with(".?!") {
Some(("optional-method-call", ".?!", true))
} else if head.starts_with(".?-") {
Some(("optional-field-read", ".?-", true))
} else if head.starts_with(".!") {
Some(("method-call", ".!", false))
} else if head.starts_with(".-") {
Some(("field-read", ".-", false))
} else {
None
}
}
fn ffi_postfix_operation(head: &str) -> Option<(String, String, &'static str, bool)> {
for (marker, kind, optional) in [
(".?!", "optional-method-call", true),
(".?-", "optional-field-read", true),
(".!", "method-call", false),
(".-", "field-read", false),
] {
if let Some((receiver, member)) = head.split_once(marker)
&& !receiver.is_empty()
&& !member.is_empty()
{
return Some((receiver.to_owned(), member.to_owned(), kind, optional));
}
}
None
}
fn ffi_classification(source: &str, import_source: Option<&str>, target: Option<snapshot::SnapshotTarget>) -> &'static str {
let lowered = format!("{} {}", source, import_source.unwrap_or_default()).to_ascii_lowercase();
if lowered.contains("webgpu")
|| lowered.contains("navigator.gpu")
|| lowered
.split(|character: char| !character.is_ascii_alphanumeric())
.any(|part| part == "gpu")
{
"webgpu"
} else if import_source.is_some() {
let package = import_source.unwrap_or_default().trim_start_matches("node:");
if matches!(
package,
"assert"
| "buffer"
| "child_process"
| "crypto"
| "events"
| "fs"
| "http"
| "https"
| "os"
| "path"
| "process"
| "stream"
| "url"
| "util"
) {
"node"
} else {
"npm-import"
}
} else if [
"js/window",
"js/document",
"js/navigator",
"js/location",
"js/localstorage",
"js/sessionstorage",
]
.iter()
.any(|prefix| lowered.contains(prefix))
{
"browser"
} else if ["js/process", "js/buffer", "js/global", "js/__dirname", "js/__filename"]
.iter()
.any(|prefix| lowered.contains(prefix))
{
"node"
} else {
match target {
Some(snapshot::SnapshotTarget::Browser) => "browser",
Some(snapshot::SnapshotTarget::Node) => "node",
_ => "unknown-host",
}
}
}
fn push_ffi_operation(
operations: &mut Vec<FfiBoundaryOperation>,
kind: &str,
source: String,
member: Option<String>,
path: &[usize],
optional: bool,
) {
operations.push(FfiBoundaryOperation {
kind: kind.to_owned(),
classification: "unknown-host".to_owned(),
source,
member,
path: format_cirru_path("code", path),
nullable_evidence: if optional { "optional-access" } else { "not-proven" }.to_owned(),
});
}
fn scan_ffi_operations(
node: &Cirru,
path: &mut Vec<usize>,
quote_context: QuoteContext,
imports: &BTreeMap<String, FfiImportBinding>,
operations: &mut Vec<FfiBoundaryOperation>,
) {
let Cirru::List(items) = node else {
return;
};
let head = items.first().and_then(|item| match item {
Cirru::Leaf(value) => Some(value.as_ref()),
_ => None,
});
if !quote_context.is_quoted()
&& let Some(head) = head
{
if head.starts_with("js/") {
push_ffi_operation(operations, "raw-js-call", head.to_owned(), None, path, false);
} else if head == "unsafe-coerce" {
let source = items
.get(1)
.map(render_cirru_inline)
.unwrap_or_else(|| "<missing-value>".to_owned());
push_ffi_operation(operations, "unsafe-coerce", source, None, path, false);
} else if let Some((kind, marker, optional)) = ffi_member_operation(head) {
let receiver = items
.get(1)
.map(render_cirru_inline)
.unwrap_or_else(|| "<missing-receiver>".to_owned());
push_ffi_operation(
operations,
kind,
receiver,
Some(head.trim_start_matches(marker).to_owned()),
path,
optional,
);
} else if let Some((receiver, member, kind, optional)) = ffi_postfix_operation(head) {
push_ffi_operation(operations, kind, receiver, Some(member), path, optional);
} else if matches!(head, "aget" | "aset" | "js-get" | "js-set") {
let receiver = items
.get(1)
.map(render_cirru_inline)
.unwrap_or_else(|| "<missing-receiver>".to_owned());
let member = items.get(2).map(render_cirru_inline);
push_ffi_operation(operations, head, receiver, member, path, false);
} else if let Some((binding, export)) = head.split_once('/')
&& imports.contains_key(binding)
{
push_ffi_operation(
operations,
"module-call",
format!("{binding}/{export}"),
Some(export.to_owned()),
path,
false,
);
} else if let Some(member) = imports.get(head).and_then(|binding| binding.member.as_ref()) {
push_ffi_operation(operations, "module-call", head.to_owned(), Some(member.to_owned()), path, false);
}
}
for (index, child) in items.iter().enumerate() {
path.push(index);
scan_ffi_operations(child, path, quote_context.for_child(head, index), imports, operations);
path.pop();
}
}
fn code_calls_definition(code: &Cirru, caller_namespace: &str, namespace: &str, definition: &str) -> bool {
fn visit(node: &Cirru, caller_namespace: &str, namespace: &str, definition: &str, quote_context: QuoteContext) -> bool {
let Cirru::List(items) = node else {
return false;
};
let head = items.first().and_then(|item| match item {
Cirru::Leaf(value) => Some(value.as_ref()),
_ => None,
});
if !quote_context.is_quoted()
&& head.is_some_and(|head| {
(caller_namespace == namespace && head == definition) || head == format!("{namespace}/{definition}").as_str()
})
{
return true;
}
items
.iter()
.enumerate()
.any(|(index, item)| visit(item, caller_namespace, namespace, definition, quote_context.for_child(head, index)))
}
visit(code, caller_namespace, namespace, definition, QuoteContext::default())
}
fn ffi_target_name(entry: &snapshot::CodeEntry, fallback: Option<snapshot::SnapshotTarget>) -> Result<String, String> {
let target = entry
.ffi
.as_ref()
.map(snapshot::parse_ffi_target)
.transpose()?
.flatten()
.or(fallback);
Ok(
target
.map(|target| target.as_str().to_owned())
.unwrap_or_else(|| "unspecified".to_owned()),
)
}
fn selected_js_implementation(
ns: &str,
entry: &snapshot::CodeEntry,
) -> Result<Option<calcit_core::js_ffi_source::JsFfiImplementation>, String> {
entry
.ffi
.as_ref()
.map(|ffi| calcit_core::js_ffi_source::validate_js_source_in(ffi, &entry.schema, ns))
.transpose()
.map(Option::flatten)
}
fn schema_cirru_edn(schema: &CalcitTypeAnnotation) -> Result<String, String> {
cirru_edn::format(&snapshot::schema_annotation_to_edn(schema), true)
.map_err(|error| format!("Failed to render FFI adapter schema: {error}"))
}
fn suggested_trait_name(definition: &str) -> String {
let mut out = String::new();
let mut uppercase = true;
for character in definition.chars() {
if character.is_ascii_alphanumeric() {
if uppercase {
out.extend(character.to_uppercase());
uppercase = false;
} else {
out.push(character);
}
} else {
uppercase = true;
}
}
if out.is_empty() {
"HostBoundary".to_owned()
} else if out.ends_with("Host") {
out
} else {
format!("{out}Host")
}
}
fn is_defexternal_member_name(name: &str) -> bool {
let mut chars = name.chars();
let Some(first) = chars.next() else {
return false;
};
if !(first.is_ascii_alphabetic() || first == '_') {
return false;
}
name
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '?' | '!' | '*' | '<' | '>' | '=' | '+' | '-' | '/'))
}
fn defexternal_skeleton(name: &str, target: &str, fields: &[String], methods: &[String]) -> String {
let fields: Vec<&String> = fields.iter().filter(|field| is_defexternal_member_name(field)).collect();
let methods: Vec<&String> = methods.iter().filter(|method| is_defexternal_member_name(method)).collect();
if fields.is_empty() && methods.is_empty() {
return String::new();
}
let mut lines = vec![format!("defexternal {name}")];
if !target.is_empty() && target != "unspecified" && target != "invalid" {
lines.push(format!(" :target :{target}"));
}
for field in fields {
lines.push(format!(" :{field} 'Dynamic"));
}
for method in methods {
lines.push(format!(" .{method} $ :: 'Fn $ {{}} (:args $ [] '{name}) (:return 'Dynamic)"));
}
lines.join("\n")
}
pub fn parse_weak_type_kinds(raw: &str) -> Result<BTreeSet<WeakTypeKind>, String> {
let mut selected = BTreeSet::new();
for item in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
let kind = match item {
"schema-dynamic" => WeakTypeKind::SchemaDynamic,
"schema-open" => WeakTypeKind::SchemaOpen,
"unresolved-type-slot" => WeakTypeKind::UnresolvedTypeSlot,
"code-dynamic" => WeakTypeKind::CodeDynamic,
"code-nil" => WeakTypeKind::CodeNil,
"unsafe-coerce" => WeakTypeKind::UnsafeCoerce,
"data-dynamic" => WeakTypeKind::DataDynamic,
other => {
return Err(format!(
"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"
));
}
};
selected.insert(kind);
}
if selected.is_empty() {
return Err(
"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"
.to_owned(),
);
}
Ok(selected)
}
pub fn parse_weak_type_intents(raw: &str) -> Result<BTreeSet<WeakTypeIntent>, String> {
let mut selected = BTreeSet::new();
for item in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
let intent = match item {
"unresolved" => WeakTypeIntent::Unresolved,
"intentional-js-ffi" => WeakTypeIntent::IntentionalJsFfi,
"js-ffi-non-host" => WeakTypeIntent::JsFfiNonHost,
"intentional-macro-syntax" => WeakTypeIntent::IntentionalMacroSyntax,
"intentional-type-slot-dynamic" => WeakTypeIntent::IntentionalTypeSlotDynamic,
"intentional-decode" => WeakTypeIntent::IntentionalDecode,
"intentional-open" => WeakTypeIntent::IntentionalOpen,
"explicit-unsafe" => WeakTypeIntent::ExplicitUnsafe,
"declared-unit" => WeakTypeIntent::DeclaredUnit,
"declared-optional" => {
return Err(
"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(),
);
}
other => {
return Err(format!(
"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"
));
}
};
selected.insert(intent);
}
if selected.is_empty() {
return Err(
"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"
.to_owned(),
);
}
Ok(selected)
}
fn format_cirru_path(root: &str, path: &[usize]) -> String {
if path.is_empty() {
root.to_owned()
} else {
let mut rendered = format!("{root}@");
for (i, idx) in path.iter().enumerate() {
if i > 0 {
rendered.push('.');
}
rendered.push_str(&idx.to_string());
}
rendered
}
}
fn weak_type_detail(kind: WeakTypeKind, detail: &str) -> String {
format!("{}:{}", kind.as_str(), detail)
}
fn extend_schema_dynamic_detail(detail: &str, segment: &str) -> String {
format!("{detail}:{segment}")
}
fn push_weak_type_occurrence(
occurrences: &mut Vec<WeakTypeOccurrence>,
kind: WeakTypeKind,
detail: impl Into<String>,
path: impl Into<String>,
) {
occurrences.push(WeakTypeOccurrence {
kind,
intent: WeakTypeIntent::Unresolved,
detail: detail.into(),
path: path.into(),
unsafe_evidence: None,
});
}
fn apply_fn_open_reason(occurrences: &mut [WeakTypeOccurrence], reason: Option<calcit_core::calcit::FnOpenReason>) {
let Some(reason) = reason else {
return;
};
for occurrence in occurrences {
if matches!(occurrence.kind, WeakTypeKind::SchemaDynamic | WeakTypeKind::SchemaOpen)
&& occurrence.intent == WeakTypeIntent::Unresolved
{
occurrence.intent = WeakTypeIntent::IntentionalOpen;
if occurrence.kind == WeakTypeKind::SchemaOpen {
occurrence.detail = format!("{}:open={}", occurrence.detail, reason.as_str());
}
}
}
}
fn scan_intentional_macro_expr(annotation: &CalcitTypeAnnotation, path: &str, detail: &str, occurrences: &mut Vec<WeakTypeOccurrence>) {
let start = occurrences.len();
scan_schema_dynamic_annotation(annotation, path, detail, occurrences);
for occurrence in &mut occurrences[start..] {
if occurrence.kind == WeakTypeKind::SchemaDynamic && occurrence.intent == WeakTypeIntent::Unresolved {
occurrence.intent = WeakTypeIntent::IntentionalMacroSyntax;
}
}
}
fn scan_schema_dynamic_annotation(
annotation: &CalcitTypeAnnotation,
path: &str,
detail: &str,
occurrences: &mut Vec<WeakTypeOccurrence>,
) {
match annotation {
CalcitTypeAnnotation::Dynamic => {
push_weak_type_occurrence(
occurrences,
WeakTypeKind::SchemaDynamic,
weak_type_detail(WeakTypeKind::SchemaDynamic, detail),
path.to_owned(),
);
}
CalcitTypeAnnotation::TypeSlot(name) => match resolve_type_slot(name) {
Some(resolved) => {
let start = occurrences.len();
scan_schema_dynamic_annotation(&resolved, path, detail, occurrences);
for occurrence in &mut occurrences[start..] {
if occurrence.intent == WeakTypeIntent::Unresolved && occurrence.kind != WeakTypeKind::UnresolvedTypeSlot {
occurrence.intent = WeakTypeIntent::IntentionalTypeSlotDynamic;
}
}
}
None => push_weak_type_occurrence(
occurrences,
WeakTypeKind::UnresolvedTypeSlot,
weak_type_detail(WeakTypeKind::UnresolvedTypeSlot, &format!("{detail}:{name}")),
path.to_owned(),
),
},
CalcitTypeAnnotation::Ref(inner, open_reason) => {
let nested_detail = extend_schema_dynamic_detail(detail, "ref-item");
let occurrence_start = occurrences.len();
scan_schema_dynamic_annotation(inner, &format!("{path}.item"), &nested_detail, occurrences);
apply_fn_open_reason(&mut occurrences[occurrence_start..], open_reason.0);
}
CalcitTypeAnnotation::List(inner)
| CalcitTypeAnnotation::Set(inner)
| CalcitTypeAnnotation::Variadic(inner)
| CalcitTypeAnnotation::Nullable(inner, _) => {
let segment = match annotation {
CalcitTypeAnnotation::List(_) => "list-item",
CalcitTypeAnnotation::Set(_) => "set-item",
CalcitTypeAnnotation::Variadic(_) => "variadic-item",
CalcitTypeAnnotation::Nullable(_, NullableOrigin::Inferred) => "nil-join-item",
CalcitTypeAnnotation::Nullable(_, NullableOrigin::JsHost) => "js-nullish-item",
_ => unreachable!("composite item annotation should be covered by the match arm"),
};
let nested_detail = extend_schema_dynamic_detail(detail, segment);
let occurrence_start = occurrences.len();
scan_schema_dynamic_annotation(inner, &format!("{path}.item"), &nested_detail, occurrences);
if matches!(annotation, CalcitTypeAnnotation::Nullable(_, NullableOrigin::JsHost)) {
for occurrence in &mut occurrences[occurrence_start..] {
if occurrence.kind == WeakTypeKind::SchemaDynamic && occurrence.intent == WeakTypeIntent::Unresolved {
occurrence.intent = WeakTypeIntent::IntentionalJsFfi;
}
}
}
}
CalcitTypeAnnotation::Map(key, value) => {
let key_detail = extend_schema_dynamic_detail(detail, "map-key");
let value_detail = extend_schema_dynamic_detail(detail, "map-value");
scan_schema_dynamic_annotation(key, &format!("{path}.key"), &key_detail, occurrences);
scan_schema_dynamic_annotation(value, &format!("{path}.value"), &value_detail, occurrences);
}
CalcitTypeAnnotation::Fn(fn_annot) => {
let occurrence_start = occurrences.len();
for (idx, arg) in fn_annot.arg_types.iter().enumerate() {
let arg_detail = extend_schema_dynamic_detail(detail, "fn-arg");
scan_schema_dynamic_annotation(arg, &format!("{path}.args.{idx}"), &arg_detail, occurrences);
}
let return_detail = extend_schema_dynamic_detail(detail, "fn-return");
scan_schema_dynamic_annotation(&fn_annot.return_type, &format!("{path}.return"), &return_detail, occurrences);
if let Some(rest) = &fn_annot.rest_type {
let rest_detail = extend_schema_dynamic_detail(detail, "fn-rest");
scan_schema_dynamic_annotation(rest, &format!("{path}.rest"), &rest_detail, occurrences);
}
apply_fn_open_reason(&mut occurrences[occurrence_start..], fn_annot.open_reason.0);
}
CalcitTypeAnnotation::Macro(signature) => {
for (idx, contract) in signature.required_inputs.iter().chain(signature.optional_inputs.iter()).enumerate() {
if let MacroSyntaxType::Expr(semantic) = contract {
scan_intentional_macro_expr(semantic, &format!("{path}.inputs.{idx}.expr"), detail, occurrences);
}
}
if let Some(MacroSyntaxType::Expr(semantic)) = &signature.rest_input {
scan_intentional_macro_expr(semantic, &format!("{path}.rest.expr"), detail, occurrences);
}
match &signature.expansion {
MacroExpansionType::Expr(semantic) => {
scan_intentional_macro_expr(semantic, &format!("{path}.expansion"), detail, occurrences);
}
MacroExpansionType::Definition(semantic) => {
scan_schema_dynamic_annotation(semantic, &format!("{path}.expansion"), detail, occurrences);
}
MacroExpansionType::Dynamic => {
scan_schema_dynamic_annotation(&CalcitTypeAnnotation::Dynamic, &format!("{path}.expansion"), detail, occurrences)
}
MacroExpansionType::Declarations => {}
}
}
CalcitTypeAnnotation::Struct(_, args) | CalcitTypeAnnotation::Enum(_, args) | CalcitTypeAnnotation::TypeRef(_, args) => {
for (idx, arg) in args.iter().enumerate() {
let type_arg_detail = extend_schema_dynamic_detail(detail, "type-arg");
scan_schema_dynamic_annotation(arg, &format!("{path}.type-arg.{idx}"), &type_arg_detail, occurrences);
}
}
CalcitTypeAnnotation::Tuple(items) => {
for (idx, item) in items.iter().enumerate() {
let item_detail = extend_schema_dynamic_detail(detail, "item");
scan_schema_dynamic_annotation(item, &format!("{path}.item.{idx}"), &item_detail, occurrences);
}
}
_ if annotation.open_family_name().is_some() => {
let family = annotation.open_family_name().expect("open_family_name matched Some");
push_weak_type_occurrence(
occurrences,
WeakTypeKind::SchemaOpen,
weak_type_detail(WeakTypeKind::SchemaOpen, &format!("{family}:{detail}")),
path.to_owned(),
);
}
_ => {}
}
}
fn is_dynamic_type_leaf(text: &str) -> bool {
matches!(text, "Dynamic" | "'Dynamic" | ":dynamic")
}
fn collect_dynamic_leaves(node: &Cirru, path: &mut Vec<usize>, found: &mut Vec<Vec<usize>>) {
match node {
Cirru::Leaf(text) if is_dynamic_type_leaf(text) => found.push(path.clone()),
Cirru::Leaf(_) => {}
Cirru::List(items) => {
for (idx, item) in items.iter().enumerate() {
path.push(idx);
collect_dynamic_leaves(item, path, found);
path.pop();
}
}
}
}
fn scan_data_declaration_dynamic(code: &Cirru, occurrences: &mut Vec<WeakTypeOccurrence>) {
let Cirru::List(items) = code else {
return;
};
let Some(Cirru::Leaf(head)) = items.first() else {
return;
};
let head = head.as_ref();
if !matches!(head, "defstruct" | "defenum" | "defunion" | "deftype") {
return;
}
let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
let body_start = 2 + clauses;
for (idx, item) in items.iter().enumerate().skip(body_start) {
let mut found = vec![];
let label = match (head, item) {
("defunion", _) => {
let mut path = vec![idx];
collect_dynamic_leaves(item, &mut path, &mut found);
format!("union-member:{}", idx - body_start)
}
("deftype", _) => {
let mut path = vec![idx];
collect_dynamic_leaves(item, &mut path, &mut found);
format!("type-alias:{}", idx - body_start)
}
(_, Cirru::List(parts)) => {
let Some(Cirru::Leaf(name)) = parts.first() else {
continue;
};
if !name.starts_with(':') {
continue;
}
for (part_idx, part) in parts.iter().enumerate().skip(1) {
let mut path = vec![idx, part_idx];
collect_dynamic_leaves(part, &mut path, &mut found);
}
let member = name.trim_start_matches(':');
if head == "defstruct" {
format!("struct-field:{member}")
} else {
format!("enum-payload:{member}")
}
}
_ => continue,
};
for path in found {
push_weak_type_occurrence(
occurrences,
WeakTypeKind::DataDynamic,
weak_type_detail(WeakTypeKind::DataDynamic, &label),
format_cirru_path("code", &path),
);
}
}
}
fn weak_type_suggestion(occurrence: &WeakTypeOccurrence) -> &'static str {
if occurrence.kind == WeakTypeKind::DataDynamic {
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.";
}
if occurrence.kind == WeakTypeKind::UnsafeCoerce {
if occurrence.unsafe_evidence.as_ref().is_some_and(|evidence| !evidence.js_ffi_feature) {
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.";
}
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.";
}
if occurrence.intent == WeakTypeIntent::IntentionalJsFfi {
return "Keep the dynamic value isolated at the declared FFI boundary (JS or native) and validate or convert it before typed code consumes it.";
}
if occurrence.intent == WeakTypeIntent::JsFfiNonHost {
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.";
}
if occurrence.intent == WeakTypeIntent::IntentionalMacroSyntax {
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.";
}
if occurrence.intent == WeakTypeIntent::IntentionalDecode {
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.";
}
if occurrence.intent == WeakTypeIntent::IntentionalOpen {
if occurrence.kind == WeakTypeKind::SchemaOpen {
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.";
}
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.";
}
if occurrence.intent == WeakTypeIntent::IntentionalTypeSlotDynamic {
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.";
}
if occurrence.kind == WeakTypeKind::CodeNil {
return match occurrence.intent {
WeakTypeIntent::DeclaredUnit if occurrence.detail.contains("nil-macro") => {
"The legacy `;nil` form returns Nil, not Unit. Replace it with `&unit`, or end the body with an effect that already returns Unit."
}
WeakTypeIntent::DeclaredUnit => {
"The declared return is Unit, so replace this nil with `&unit`, or end the body with an effect that already returns Unit."
}
_ => {
"Declare Unit for a no-value result and remove explicit nil/`;nil` when possible; use Option/Result for application absence or failure."
}
};
}
if occurrence.kind == WeakTypeKind::UnresolvedTypeSlot {
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.";
}
if occurrence.kind == WeakTypeKind::SchemaOpen {
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)`.";
}
if occurrence.kind == WeakTypeKind::CodeDynamic {
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.";
}
if occurrence.detail.contains("ref-item") {
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.";
}
if occurrence.detail.contains("list-item") {
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.";
}
if occurrence.detail.contains("set-item") {
return "Replace a bare `Set` with `quote $ Set T` and choose a concrete type or a declared type variable.";
}
if occurrence.detail.contains("map-key") || occurrence.detail.contains("map-value") {
return "Use `quote $ Map K V` and replace each unresolved slot with a concrete type or a declared type variable.";
}
"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."
}
fn schema_has_feature(annotation: &CalcitTypeAnnotation, feature: &str) -> bool {
matches!(annotation, CalcitTypeAnnotation::Fn(fn_annot) if fn_annot.features.iter().any(|tag| tag.ref_str() == feature))
}
fn entry_schema_issues(ns: &str, def_name: &str, code: &Cirru, schema: &Arc<CalcitTypeAnnotation>) -> Vec<String> {
let annotation = schema.as_ref();
let mut issues = validate_def_vs_schema(ns, def_name, code, annotation);
let has_js_ffi_feature = match annotation {
CalcitTypeAnnotation::Fn(fn_annot) => fn_annot.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
CalcitTypeAnnotation::Macro(signature) => signature.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
_ => false,
};
if matches!(annotation, CalcitTypeAnnotation::Dynamic) {
if matches!(code, Cirru::List(items) if matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "defmacro")) {
let (warning, detail) = if snapshot::schema_annotation_is_missing(schema) {
("W_SCHEMA_MISSING", "has no declared macro schema")
} else {
(
"W_MACRO_SCHEMA_DYNAMIC",
"declares an intentionally untyped whole-Dynamic macro schema",
)
};
issues.push(format!("[{warning}] {ns}/{def_name} {detail}"));
}
return issues;
}
let has_decode_boundary = schema_has_feature(annotation, calcit_core::calcit::DECODE_BOUNDARY_FEATURE);
let mut occurrences = vec![];
scan_schema_dynamic_annotation(annotation, "schema", "root", &mut occurrences);
for occurrence in occurrences {
let decode_input = has_decode_boundary
&& occurrence.kind == WeakTypeKind::SchemaDynamic
&& (occurrence.path.starts_with("schema.args.") || occurrence.path.starts_with("schema.rest"));
if decode_input
|| (has_js_ffi_feature && occurrence.kind == WeakTypeKind::SchemaDynamic)
|| occurrence.intent == WeakTypeIntent::IntentionalMacroSyntax
|| occurrence.intent == WeakTypeIntent::IntentionalOpen
{
continue;
}
let warning = match occurrence.kind {
WeakTypeKind::UnresolvedTypeSlot => "W_UNRESOLVED_TYPE_SLOT",
WeakTypeKind::SchemaOpen => "W_OPEN_FAMILY",
_ => "W_SCHEMA_DYNAMIC",
};
issues.push(format!(
"[{warning}] {} is unresolved ({}). Fix: {}",
occurrence.path,
occurrence.detail,
weak_type_suggestion(&occurrence)
));
}
issues
}
fn downgrade_coverage_for_dynamic_annotation(level: CoverageLevel, annotation: &CalcitTypeAnnotation) -> CoverageLevel {
if level != CoverageLevel::Full {
return level;
}
let mut occurrences = vec![];
scan_schema_dynamic_annotation(annotation, "schema", "root", &mut occurrences);
occurrences.retain(|occurrence| occurrence.intent != WeakTypeIntent::IntentionalOpen);
if occurrences.is_empty() {
CoverageLevel::Full
} else {
CoverageLevel::Partial
}
}
#[derive(Debug, Clone)]
struct WeakCodeParent {
head: Option<String>,
child_index: usize,
}
fn classify_code_dynamic(parent: Option<&WeakCodeParent>) -> &'static str {
match parent.and_then(|it| it.head.as_deref()) {
Some("assert-type") => "assert-type",
Some("hint-fn") => "hint-fn",
Some("::") => "schema-tag",
Some("defstruct") => "defstruct",
Some("defenum") => "defenum",
Some("deftrait") => "deftrait",
Some("[]") => "list-item",
_ => "literal",
}
}
fn classify_code_nil(parent: Option<&WeakCodeParent>) -> &'static str {
match parent.and_then(|it| it.head.as_deref()) {
Some("if") if parent.is_some_and(|it| it.child_index == 2) => "if-then",
Some("if") if parent.is_some_and(|it| it.child_index == 3) => "if-else",
Some("let") | Some("&let") => "let-binding",
Some("do") => "do-step",
Some("[]") => "list-item",
Some("{}") | Some("&{}") | Some("#{}") => "collection-item",
Some("cond") | Some("case") => "branch",
_ => "literal",
}
}
fn nil_return_intent(annotation: &CalcitTypeAnnotation) -> WeakTypeIntent {
let return_type = match annotation {
CalcitTypeAnnotation::Fn(fn_annotation) => fn_annotation.return_type.as_ref(),
CalcitTypeAnnotation::Macro(signature) => match &signature.expansion {
MacroExpansionType::Expr(semantic) | MacroExpansionType::Definition(semantic) => semantic.as_ref(),
MacroExpansionType::Dynamic | MacroExpansionType::Declarations => annotation,
},
other => other,
};
match return_type {
CalcitTypeAnnotation::Unit => WeakTypeIntent::DeclaredUnit,
CalcitTypeAnnotation::Nullable(_, NullableOrigin::JsHost) => WeakTypeIntent::IntentionalJsFfi,
_ => WeakTypeIntent::Unresolved,
}
}
fn child_is_return_position(
is_code_root: bool,
parent_is_return_position: bool,
head: Option<&str>,
child_index: usize,
child_count: usize,
) -> bool {
if !parent_is_return_position {
return false;
}
if is_code_root {
return match head {
Some("defn" | "defmacro" | "defcomp") => child_index >= 3 && child_index + 1 == child_count,
Some("fn" | "macro") => child_index >= 2 && child_index + 1 == child_count,
Some("def") => child_index == 2,
_ => false,
};
}
match head {
Some("if") => matches!(child_index, 2 | 3),
Some("let" | "&let") => child_index >= 2 && child_index + 1 == child_count,
Some("do") => child_index >= 1 && child_index + 1 == child_count,
_ => false,
}
}
fn code_declares_embedded_type_schema(code: &Cirru) -> bool {
let inner = match code {
Cirru::List(items) if items.len() == 3 && matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "def") => &items[2],
other => other,
};
if let Cirru::List(items) = inner
&& matches!(items.first(), Some(Cirru::Leaf(head)) if matches!(head.as_ref(), "defunion" | "deftype"))
{
let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
let mut dynamic_leaves = vec![];
for member in items.iter().skip(2 + clauses) {
collect_dynamic_leaves(member, &mut vec![], &mut dynamic_leaves);
}
return dynamic_leaves.is_empty();
}
matches!(
inner,
Cirru::List(items)
if matches!(
items.first(),
Some(Cirru::Leaf(head)) if matches!(head.as_ref(), "defstruct" | "defenum" | "deftrait" | "defimpl" | "defexternal")
)
)
}
fn classify_unsafe_coerce_source(items: &[Cirru]) -> &'static str {
let Some(source) = items.get(1) else {
return "missing-value";
};
match source {
Cirru::Leaf(name) if name.starts_with("js/") => "raw-js-value",
Cirru::List(parts) => match parts.first() {
Some(Cirru::Leaf(head)) if head.starts_with("js/") => "raw-js-operation",
Some(Cirru::Leaf(head))
if matches!(head.as_ref(), "aget" | "js-get")
|| head.starts_with(".-")
|| head.starts_with(".!")
|| head.starts_with(".?-")
|| head.starts_with(".?!") =>
{
"host-member-operation"
}
_ => "expression",
},
Cirru::Leaf(_) => "value",
}
}
fn is_raw_adapter_namespace(ns: &str) -> bool {
ns == "js-ffi.raw" || ns.starts_with("js-ffi.raw.") || ns.contains(".js-ffi.raw.")
}
#[derive(Debug, Clone, Copy, Default)]
struct QuoteContext {
quoted_depth: usize,
quasiquoted_depth: usize,
}
impl QuoteContext {
fn is_quoted(self) -> bool {
self.quoted_depth > 0 || self.quasiquoted_depth > 0
}
fn for_child(self, head: Option<&str>, child_index: usize) -> Self {
if child_index == 0 {
return self;
}
match head {
Some("quote") => Self {
quoted_depth: self.quoted_depth + 1,
..self
},
Some("quasiquote") => Self {
quasiquoted_depth: self.quasiquoted_depth + 1,
..self
},
Some("~" | "~@") if self.quoted_depth == 0 => Self {
quasiquoted_depth: self.quasiquoted_depth.saturating_sub(1),
..self
},
_ => self,
}
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum WeakTypeContext {
#[default]
Code,
Type,
DeclarationMember,
SchemaEntry,
}
impl WeakTypeContext {
fn for_child(self, head: Option<&str>, index: usize, count: usize) -> Self {
match self {
Self::Type if head == Some("{}") => {
if index > 0 {
Self::SchemaEntry
} else {
Self::Code
}
}
Self::Type => {
if index > 0 {
Self::Type
} else {
Self::Code
}
}
Self::SchemaEntry => {
if index > 0
&& matches!(
head,
Some(":args" | ":return" | ":rest" | ":inputs" | ":expansion" | ":required" | ":optional")
)
{
Self::Type
} else {
Self::Code
}
}
Self::DeclarationMember if count == 1 && head.is_none() => Self::DeclarationMember,
Self::DeclarationMember if index > 0 && head.is_some_and(|name| name.starts_with([':', '.'])) => Self::Type,
Self::Code | Self::DeclarationMember => match head {
Some("assert-type" | "unsafe-coerce") if index == 2 => Self::Type,
Some("hint-fn") if index > 0 && index + 1 == count => Self::Type,
Some("defstruct" | "defenum" | "deftrait" | "defexternal") if index >= 2 => Self::DeclarationMember,
_ => Self::Code,
},
}
}
}
#[derive(Debug, Clone, Copy, Default)]
struct WeakScanState {
nil_return_intent: Option<WeakTypeIntent>,
quote_context: QuoteContext,
type_context: WeakTypeContext,
}
fn scan_cirru_weak_types(
node: &Cirru,
root: &str,
path: &mut Vec<usize>,
parent: Option<&WeakCodeParent>,
state: WeakScanState,
selected: &BTreeSet<WeakTypeKind>,
occurrences: &mut Vec<WeakTypeOccurrence>,
) {
match node {
Cirru::Leaf(text) => {
let is_dynamic = text.as_ref() == ":dynamic";
if is_dynamic && root == "schema" && selected.contains(&WeakTypeKind::SchemaDynamic) {
push_weak_type_occurrence(
occurrences,
WeakTypeKind::SchemaDynamic,
weak_type_detail(WeakTypeKind::SchemaDynamic, "raw-schema"),
format_cirru_path(root, path),
);
} else if is_dynamic
&& root == "code"
&& state.type_context == WeakTypeContext::Type
&& selected.contains(&WeakTypeKind::CodeDynamic)
&& !state.quote_context.is_quoted()
{
let detail = classify_code_dynamic(parent).to_owned();
push_weak_type_occurrence(
occurrences,
WeakTypeKind::CodeDynamic,
weak_type_detail(WeakTypeKind::CodeDynamic, &detail),
format_cirru_path(root, path),
);
} else if text.as_ref() == "nil"
&& root == "code"
&& selected.contains(&WeakTypeKind::CodeNil)
&& !state.quote_context.is_quoted()
{
push_weak_type_occurrence(
occurrences,
WeakTypeKind::CodeNil,
weak_type_detail(WeakTypeKind::CodeNil, classify_code_nil(parent)),
format_cirru_path(root, path),
);
if let (Some(intent), Some(occurrence)) = (state.nil_return_intent, occurrences.last_mut()) {
occurrence.intent = intent;
}
}
}
Cirru::List(items) => {
let head = items.first().and_then(|item| match item {
Cirru::Leaf(text) => Some(text.to_string()),
_ => None,
});
if root == "code"
&& selected.contains(&WeakTypeKind::CodeNil)
&& matches!(head.as_deref(), Some(";nil"))
&& !state.quote_context.is_quoted()
{
push_weak_type_occurrence(
occurrences,
WeakTypeKind::CodeNil,
weak_type_detail(WeakTypeKind::CodeNil, &format!("nil-macro:{}", classify_code_nil(parent))),
format_cirru_path(root, path),
);
if let (Some(intent), Some(occurrence)) = (state.nil_return_intent, occurrences.last_mut()) {
occurrence.intent = intent;
}
}
if root == "code"
&& selected.contains(&WeakTypeKind::UnsafeCoerce)
&& matches!(head.as_deref(), Some("unsafe-coerce"))
&& !state.quote_context.is_quoted()
{
let target = items
.get(2)
.map(render_cirru_inline)
.unwrap_or_else(|| "<missing-target>".to_owned());
occurrences.push(WeakTypeOccurrence {
kind: WeakTypeKind::UnsafeCoerce,
intent: WeakTypeIntent::ExplicitUnsafe,
detail: format!("unsafe-coerce:target={target}"),
path: format_cirru_path(root, path),
unsafe_evidence: Some(UnsafeCoerceEvidence {
source_form: classify_unsafe_coerce_source(items).to_owned(),
target_schema: target,
js_ffi_feature: false,
raw_adapter_namespace: false,
}),
});
}
for (idx, item) in items.iter().enumerate() {
path.push(idx);
let next_parent = WeakCodeParent {
head: head.clone(),
child_index: idx,
};
let child_return_position = child_is_return_position(
root == "code" && path.len() == 1,
state.nil_return_intent.is_some(),
head.as_deref(),
idx,
items.len(),
);
let child_state = WeakScanState {
nil_return_intent: state.nil_return_intent.filter(|_| child_return_position),
quote_context: state.quote_context.for_child(head.as_deref(), idx),
type_context: state.type_context.for_child(head.as_deref(), idx, items.len()),
};
scan_cirru_weak_types(item, root, path, Some(&next_parent), child_state, selected, occurrences);
path.pop();
}
}
}
}
struct JsFfiHostReach {
params: Vec<bool>,
rest: Option<bool>,
ret: bool,
}
impl JsFfiHostReach {
fn schema_path_reaches_host(&self, path: &str) -> bool {
let position = |prefix: &str| {
path
.strip_prefix(prefix)
.is_some_and(|tail| tail.is_empty() || tail.starts_with('.'))
};
if let Some(tail) = path.strip_prefix("schema.args.") {
let index = tail.split('.').next().and_then(|idx| idx.parse::<usize>().ok());
return index.and_then(|idx| self.params.get(idx).copied()).unwrap_or(true);
}
if position("schema.rest") {
return self.rest.unwrap_or(true);
}
if position("schema.return") {
return self.ret;
}
true
}
}
fn is_js_host_head(head: &str) -> bool {
head.starts_with(".-")
|| head.starts_with(".!")
|| head.starts_with(".?-")
|| head.starts_with(".?!")
|| head.starts_with("js/")
|| ffi_postfix_operation(head).is_some()
|| matches!(
head,
"aget"
| "aset"
| "js-get"
| "js-set"
| "js-delete"
| "exists?"
| "instance?"
| "&js-object"
| "js-array"
| "js-await"
| "js-for-await"
| "new"
| "set!"
| "to-calcit-data"
| "to-js-data"
| "&raw-code"
| "js-cast"
| "unsafe-coerce"
)
}
fn collect_cirru_leaves<'a>(code: &'a Cirru, leaves: &mut BTreeSet<&'a str>) {
match code {
Cirru::Leaf(leaf) => {
leaves.insert(leaf.as_ref());
}
Cirru::List(items) => items.iter().for_each(|item| collect_cirru_leaves(item, leaves)),
}
}
fn collect_js_host_uses<'a>(code: &'a Cirru, host_leaves: &mut BTreeSet<&'a str>, bindings: &mut Vec<(&'a str, &'a Cirru)>) {
let Cirru::List(items) = code else {
if let Cirru::Leaf(leaf) = code
&& let Some((receiver, ..)) = ffi_postfix_operation(leaf)
{
host_leaves.insert(&leaf[..receiver.len()]);
}
return;
};
match items.first() {
Some(Cirru::Leaf(head)) if is_js_host_head(head) => collect_cirru_leaves(code, host_leaves),
Some(Cirru::Leaf(head)) if head.as_ref() == "let" => {
if let Some(Cirru::List(pairs)) = items.get(1) {
for pair in pairs {
if let Cirru::List(pair) = pair
&& let [Cirru::Leaf(name), value] = pair.as_slice()
{
bindings.push((name.as_ref(), value));
}
}
}
}
Some(Cirru::Leaf(head)) if head.as_ref() == "&let" => {
if let Some(Cirru::List(pair)) = items.get(1)
&& let [Cirru::Leaf(name), value] = pair.as_slice()
{
bindings.push((name.as_ref(), value));
}
}
_ => {}
}
items.iter().for_each(|item| collect_js_host_uses(item, host_leaves, bindings));
}
fn cirru_contains_host_value(code: &Cirru, host_values: &BTreeSet<&str>) -> bool {
match code {
Cirru::Leaf(leaf) => leaf.starts_with("js/") || ffi_postfix_operation(leaf).is_some() || host_values.contains(leaf.as_ref()),
Cirru::List(items) => {
matches!(items.first(), Some(Cirru::Leaf(head)) if is_js_host_head(head))
|| items.iter().any(|item| cirru_contains_host_value(item, host_values))
}
}
}
fn collect_tail_expressions<'a>(code: &'a Cirru, is_code_root: bool, tails: &mut Vec<&'a Cirru>) {
let Cirru::List(items) = code else {
if !is_code_root {
tails.push(code);
}
return;
};
let head = match items.first() {
Some(Cirru::Leaf(head)) => Some(head.as_ref()),
_ => None,
};
let mut descended = false;
for (idx, item) in items.iter().enumerate() {
if child_is_return_position(is_code_root, true, head, idx, items.len()) {
descended = true;
collect_tail_expressions(item, false, tails);
}
}
if !descended && !is_code_root {
tails.push(code);
}
}
fn js_ffi_host_reach(code: &Cirru) -> Option<JsFfiHostReach> {
let Cirru::List(items) = code else {
return None;
};
if !matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "defn" || head.as_ref() == "defcomp") {
return None;
}
let Some(Cirru::List(raw_params)) = items.get(2) else {
return None;
};
let body = &items[3..];
let mut host_leaves = BTreeSet::new();
let mut bindings = vec![];
body
.iter()
.for_each(|form| collect_js_host_uses(form, &mut host_leaves, &mut bindings));
loop {
let before = host_leaves.len();
for (name, value) in &bindings {
if host_leaves.contains(name) {
collect_cirru_leaves(value, &mut host_leaves);
}
}
if host_leaves.len() == before {
break;
}
}
let mut host_values = BTreeSet::new();
loop {
let before = host_values.len();
for (name, value) in &bindings {
if cirru_contains_host_value(value, &host_values) {
host_values.insert(*name);
}
}
if host_values.len() == before {
break;
}
}
let mut params = vec![];
let mut rest = None;
let mut after_rest_marker = false;
for param in raw_params {
let Cirru::Leaf(name) = param else {
return None;
};
match name.as_ref() {
"&" => after_rest_marker = true,
"?" | "[]" | "," => {}
name if after_rest_marker => rest = Some(host_leaves.contains(name)),
name => params.push(host_leaves.contains(name)),
}
}
let mut tails = vec![];
collect_tail_expressions(code, true, &mut tails);
let ret = tails.iter().any(|tail| cirru_contains_host_value(tail, &host_values));
Some(JsFfiHostReach { params, rest, ret })
}
pub fn analyze_weak_types_entry(
ns: &str,
def_name: &str,
entry: &snapshot::CodeEntry,
selected: &BTreeSet<WeakTypeKind>,
) -> Option<WeakTypeRow> {
let mut occurrences: Vec<WeakTypeOccurrence> = vec![];
let selected_schema_annotations = selected.contains(&WeakTypeKind::SchemaDynamic)
|| selected.contains(&WeakTypeKind::SchemaOpen)
|| selected.contains(&WeakTypeKind::UnresolvedTypeSlot);
if matches!(entry.schema.as_ref(), CalcitTypeAnnotation::Dynamic) {
if selected.contains(&WeakTypeKind::SchemaDynamic) && !code_declares_embedded_type_schema(&entry.code) {
let intent = if ns == calcit_core::calcit::CORE_NS && entry.tags.iter().any(|tag| tag.ref_str() == "syntax") {
WeakTypeIntent::IntentionalMacroSyntax
} else {
WeakTypeIntent::Unresolved
};
occurrences.push(WeakTypeOccurrence {
kind: WeakTypeKind::SchemaDynamic,
intent,
detail: weak_type_detail(WeakTypeKind::SchemaDynamic, "root"),
path: "schema".to_owned(),
unsafe_evidence: None,
});
}
} else if let CalcitTypeAnnotation::Fn(fn_annot) = entry.schema.as_ref() {
if selected_schema_annotations {
for (idx, arg) in fn_annot.arg_types.iter().enumerate() {
scan_schema_dynamic_annotation(arg, &format!("schema.args.{idx}"), "arg", &mut occurrences);
}
scan_schema_dynamic_annotation(&fn_annot.return_type, "schema.return", "return", &mut occurrences);
if let Some(rest) = &fn_annot.rest_type {
scan_schema_dynamic_annotation(rest, "schema.rest", "rest", &mut occurrences);
}
apply_fn_open_reason(&mut occurrences, fn_annot.open_reason.0);
}
} else if selected_schema_annotations {
let before = occurrences.len();
scan_schema_dynamic_annotation(entry.schema.as_ref(), "schema", "root", &mut occurrences);
if occurrences.len() == before
&& selected.contains(&WeakTypeKind::SchemaDynamic)
&& let Ok(schema_cirru) = snapshot::schema_edn_to_cirru(&entry.schema.to_type_edn())
{
let mut path = vec![];
scan_cirru_weak_types(
&schema_cirru,
"schema",
&mut path,
None,
WeakScanState::default(),
selected,
&mut occurrences,
);
}
}
let mut code_path = vec![];
scan_cirru_weak_types(
&entry.code,
"code",
&mut code_path,
None,
WeakScanState {
nil_return_intent: Some(nil_return_intent(entry.schema.as_ref())),
quote_context: QuoteContext::default(),
type_context: WeakTypeContext::Code,
},
selected,
&mut occurrences,
);
if selected.contains(&WeakTypeKind::DataDynamic) {
scan_data_declaration_dynamic(&entry.code, &mut occurrences);
}
occurrences.retain(|occurrence| selected.contains(&occurrence.kind));
let has_js_ffi_feature = match entry.schema.as_ref() {
CalcitTypeAnnotation::Fn(fn_annot) => fn_annot.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
CalcitTypeAnnotation::Macro(signature) => signature.features.iter().any(|feature| feature.ref_str() == "js-ffi"),
_ => false,
};
if has_js_ffi_feature {
let reach = js_ffi_host_reach(&entry.code);
for occurrence in &mut occurrences {
if matches!(occurrence.kind, WeakTypeKind::SchemaDynamic | WeakTypeKind::CodeDynamic) {
let reaches_host = occurrence.kind != WeakTypeKind::SchemaDynamic
|| reach.as_ref().is_none_or(|reach| reach.schema_path_reaches_host(&occurrence.path));
occurrence.intent = if reaches_host {
WeakTypeIntent::IntentionalJsFfi
} else {
WeakTypeIntent::JsFfiNonHost
};
}
}
}
if schema_has_feature(entry.schema.as_ref(), calcit_core::calcit::DECODE_BOUNDARY_FEATURE) {
for occurrence in &mut occurrences {
let decode_position = match occurrence.kind {
WeakTypeKind::SchemaDynamic => occurrence.path.starts_with("schema.args.") || occurrence.path.starts_with("schema.rest"),
WeakTypeKind::CodeDynamic => true,
_ => false,
};
if decode_position && occurrence.intent == WeakTypeIntent::Unresolved {
occurrence.intent = WeakTypeIntent::IntentionalDecode;
}
}
}
for occurrence in &mut occurrences {
if let Some(evidence) = &mut occurrence.unsafe_evidence {
evidence.js_ffi_feature = has_js_ffi_feature;
evidence.raw_adapter_namespace = is_raw_adapter_namespace(ns);
}
}
if occurrences.is_empty() {
None
} else {
Some(WeakTypeRow {
ns: ns.to_owned(),
def: def_name.to_owned(),
occurrences,
})
}
}
#[derive(Debug, Clone, Copy)]
struct AnalysisScope<'a> {
namespace: Option<&'a str>,
namespace_prefix: Option<&'a str>,
include_dependencies: bool,
}
fn visit_scoped_definitions<F>(snapshot: &snapshot::Snapshot, scope: AnalysisScope<'_>, mut visit: F) -> Result<(), String>
where
F: FnMut(&str, &str, &snapshot::CodeEntry),
{
if let Some(namespace) = scope.namespace
&& !snapshot.files.contains_key(namespace)
{
return Err(format!("Namespace not found: {namespace}"));
}
let package = snapshot.package.as_str();
let package_prefix = format!("{package}.");
let explicit_scope = scope.namespace.is_some() || scope.namespace_prefix.is_some();
for (namespace, file) in &snapshot.files {
if !explicit_scope && namespace.ends_with(".$meta") {
continue;
}
if scope.namespace.is_some_and(|exact| namespace != exact) {
continue;
}
if scope.namespace_prefix.is_some_and(|prefix| !namespace.starts_with(prefix)) {
continue;
}
if !(scope.include_dependencies || explicit_scope || namespace == package || namespace.starts_with(&package_prefix)) {
continue;
}
for (definition, entry) in &file.defs {
visit(namespace, definition, entry);
}
}
Ok(())
}
pub(crate) fn scoped_definition_entries<'a>(
snapshot: &'a snapshot::Snapshot,
namespace: Option<&str>,
namespace_prefix: Option<&str>,
include_dependencies: bool,
) -> Result<Vec<(&'a str, &'a str, &'a snapshot::CodeEntry)>, String> {
if let Some(namespace) = namespace
&& !snapshot.files.contains_key(namespace)
{
return Err(format!("Namespace not found: {namespace}"));
}
let mut entries = Vec::new();
let package = snapshot.package.as_str();
let package_prefix = format!("{package}.");
let explicit_scope = namespace.is_some() || namespace_prefix.is_some();
for (current_namespace, file) in &snapshot.files {
if !explicit_scope && current_namespace.ends_with(".$meta") {
continue;
}
if namespace.is_some_and(|exact| current_namespace != exact) {
continue;
}
if namespace_prefix.is_some_and(|prefix| !current_namespace.starts_with(prefix)) {
continue;
}
if !(include_dependencies || explicit_scope || current_namespace == package || current_namespace.starts_with(&package_prefix)) {
continue;
}
for (definition, entry) in &file.defs {
entries.push((current_namespace.as_str(), definition.as_str(), entry));
}
}
entries.sort_by(|left, right| left.0.cmp(right.0).then(left.1.cmp(right.1)));
Ok(entries)
}
pub(crate) fn filter_weak_type_rows(options: &WeakTypesCommand, rows: &mut Vec<WeakTypeRow>) -> Result<(), String> {
let selected = options
.only
.as_deref()
.map(parse_weak_type_kinds)
.transpose()?
.unwrap_or_else(WeakTypeKind::all);
let selected_intents = options
.intent
.as_deref()
.map(parse_weak_type_intents)
.transpose()?
.unwrap_or_else(WeakTypeIntent::all);
for row in rows.iter_mut() {
row
.occurrences
.retain(|occurrence| selected.contains(&occurrence.kind) && selected_intents.contains(&occurrence.intent));
}
rows.retain(|row| !row.occurrences.is_empty());
rows.sort_by(|a, b| a.ns.cmp(&b.ns).then(a.def.cmp(&b.def)));
Ok(())
}
pub fn collect_weak_type_rows(options: &WeakTypesCommand, snapshot: &snapshot::Snapshot) -> Result<Vec<WeakTypeRow>, String> {
let mut rows: Vec<WeakTypeRow> = vec![];
visit_scoped_definitions(
snapshot,
AnalysisScope {
namespace: options.ns.as_deref(),
namespace_prefix: options.ns_prefix.as_deref(),
include_dependencies: options.deps,
},
|namespace, definition, entry| {
if let Some(row) = analyze_weak_types_entry(namespace, definition, entry, &WeakTypeKind::collected()) {
rows.push(row);
}
},
)?;
filter_weak_type_rows(options, &mut rows)?;
Ok(rows)
}
pub(crate) fn collect_schema_candidates(
options: &WeakTypesCommand,
snapshot: &snapshot::Snapshot,
) -> Result<Vec<SchemaEvidenceCandidate>, String> {
if !options.schema_evidence {
return Ok(Vec::new());
}
let rows = collect_weak_type_rows(options, snapshot)?;
let package_prefix = format!("{}.", snapshot.package);
let mut targets = rows
.iter()
.filter(|row| options.deps || row.ns == snapshot.package || row.ns.starts_with(&package_prefix))
.filter(|row| {
row
.occurrences
.iter()
.any(|occurrence| occurrence.kind == WeakTypeKind::SchemaDynamic)
})
.map(|row| (row.ns.clone(), row.def.clone()))
.collect::<Vec<_>>();
targets.sort();
targets.dedup();
let mut project_definitions = snapshot
.files
.iter()
.filter(|(namespace, _)| options.deps || namespace.as_str() == snapshot.package || namespace.starts_with(&package_prefix))
.filter(|(namespace, _)| !namespace.ends_with(".$meta"))
.flat_map(|(namespace, file)| file.defs.keys().map(|definition| (namespace.clone(), definition.clone())))
.collect::<Vec<_>>();
project_definitions.sort();
collect_schema_evidence_candidates(snapshot, &project_definitions, &targets)
}
fn syntactic_value_type(node: &Cirru) -> String {
match node {
Cirru::Leaf(value) if value.as_ref() == "true" || value.as_ref() == "false" => "Bool".to_owned(),
Cirru::Leaf(value) if value.starts_with('|') => "String".to_owned(),
Cirru::Leaf(value) if value.starts_with(':') => "Tag".to_owned(),
Cirru::Leaf(value) if value.parse::<f64>().is_ok() => "Number".to_owned(),
Cirru::List(items) => match items.first() {
Some(Cirru::Leaf(head)) if head.as_ref() == "[]" => "List".to_owned(),
Some(Cirru::Leaf(head)) if head.as_ref() == "{}" || head.as_ref() == "&{}" => "Map".to_owned(),
Some(Cirru::Leaf(head)) if head.as_ref() == "#{}" => "Set".to_owned(),
Some(Cirru::Leaf(head)) if head.as_ref() == "::" => "TupleOrEnum".to_owned(),
Some(Cirru::Leaf(head)) if head.as_ref() == "fn" => "Fn".to_owned(),
_ => "Unknown".to_owned(),
},
Cirru::Leaf(_) => "Unknown".to_owned(),
}
}
#[derive(Default)]
struct MapShapeAggregate {
fields: BTreeMap<String, BTreeSet<String>>,
paths: Vec<String>,
}
fn scan_structural_candidates(
node: &Cirru,
definition: &str,
path: &mut Vec<usize>,
map_shapes: &mut BTreeMap<Vec<String>, MapShapeAggregate>,
dispatch: &mut Vec<DispatchCandidate>,
) {
let Cirru::List(items) = node else {
return;
};
let head = items.first().and_then(|item| match item {
Cirru::Leaf(value) => Some(value.as_ref()),
Cirru::List(_) => None,
});
if matches!(head, Some("quote" | "quasiquote")) {
return;
}
if head == Some("{}") {
let mut fields = BTreeMap::<String, String>::new();
let mut valid = true;
for pair in items.iter().skip(1) {
let Cirru::List(pair_items) = pair else {
valid = false;
break;
};
let (Some(Cirru::Leaf(key)), Some(value)) = (pair_items.first(), pair_items.get(1)) else {
valid = false;
break;
};
if pair_items.len() != 2 || !key.starts_with(':') {
valid = false;
break;
}
fields.insert(key.to_string(), syntactic_value_type(value));
}
if valid && fields.len() >= 2 {
let key = fields.keys().cloned().collect::<Vec<_>>();
let aggregate = map_shapes.entry(key).or_default();
for (field, observed) in fields {
aggregate.fields.entry(field).or_default().insert(observed);
}
aggregate.paths.push(format!("{definition}:{}", format_cirru_path("code", path)));
}
}
if head == Some("match") && items.len() >= 4 {
let mut variants = Vec::new();
for branch in items.iter().skip(2) {
let Cirru::List(branch_items) = branch else {
continue;
};
let pattern = match branch_items.first() {
Some(Cirru::List(pattern)) => pattern,
Some(Cirru::Leaf(tag)) if tag.starts_with(':') => branch_items,
_ => continue,
};
if let Some(Cirru::Leaf(tag)) = pattern.first()
&& tag.starts_with(':')
{
variants.push(tag.to_string());
}
}
variants.sort();
variants.dedup();
if variants.len() >= 2 {
dispatch.push(DispatchCandidate {
diagnostic_code: "I_DISPATCH_CANDIDATE_EVIDENCE",
suggested_name: format!("{}-dispatch", definition.rsplit('/').next().unwrap_or(definition)),
confidence: "usage-derived",
variants,
evidence_paths: vec![format!("{definition}:{}", format_cirru_path("code", path))],
contract_status: "review-required",
});
}
}
for (index, child) in items.iter().enumerate() {
path.push(index);
scan_structural_candidates(child, definition, path, map_shapes, dispatch);
path.pop();
}
}
pub(crate) fn collect_structural_candidates(
options: &WeakTypesCommand,
snapshot: &snapshot::Snapshot,
) -> Result<StructuralCandidates, String> {
if !options.schema_evidence {
return Ok(StructuralCandidates::default());
}
let mut shapes = BTreeMap::<Vec<String>, MapShapeAggregate>::new();
let mut dispatch = Vec::new();
visit_scoped_definitions(
snapshot,
AnalysisScope {
namespace: options.ns.as_deref(),
namespace_prefix: options.ns_prefix.as_deref(),
include_dependencies: options.deps,
},
|namespace, definition, entry| {
let id = format!("{namespace}/{definition}");
if let Cirru::List(items) = &entry.code
&& matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "quote")
&& let Some(body) = items.get(1)
{
scan_structural_candidates(body, &id, &mut vec![1], &mut shapes, &mut dispatch);
} else {
scan_structural_candidates(&entry.code, &id, &mut Vec::new(), &mut shapes, &mut dispatch);
}
},
)?;
let mut map_shapes = shapes
.into_iter()
.filter(|(_, aggregate)| aggregate.paths.len() >= 2)
.map(|(field_names, mut aggregate)| {
aggregate.paths.sort();
aggregate.paths.dedup();
let fields = field_names
.into_iter()
.map(|name| MapShapeFieldCandidate {
observed_types: aggregate.fields.remove(&name).unwrap_or_default().into_iter().collect(),
name,
})
.collect::<Vec<_>>();
let has_conflict = fields.iter().any(|field| field.observed_types.len() > 1);
let has_unknown = fields
.iter()
.any(|field| field.observed_types.iter().any(|observed| observed == "Unknown"));
MapShapeCandidate {
diagnostic_code: "I_MAP_SHAPE_CANDIDATE_EVIDENCE",
suggested_name: format!(
"record-{}",
fields
.iter()
.map(|field| field.name.trim_start_matches(':'))
.collect::<Vec<_>>()
.join("-")
),
confidence: if has_conflict {
"conflict"
} else if has_unknown {
"boundary-unknown"
} else {
"usage-derived"
},
fields,
evidence_paths: aggregate.paths,
contract_status: "review-required",
}
})
.collect::<Vec<_>>();
map_shapes.sort_by(|left, right| left.suggested_name.cmp(&right.suggested_name));
dispatch.sort_by(|left, right| left.evidence_paths.cmp(&right.evidence_paths));
Ok(StructuralCandidates { map_shapes, dispatch })
}
pub fn collect_ffi_boundary_evidence(
options: &WeakTypesCommand,
snapshot: &snapshot::Snapshot,
) -> Result<Vec<FfiBoundaryEvidence>, String> {
let active_target = snapshot.active_entry().ok().and_then(|entry| entry.target);
let package_prefix = format!("{}.", snapshot.package);
let mut boundaries = Vec::new();
let mut target_error = None;
let mut import_namespace = None;
let mut imports = BTreeMap::new();
visit_scoped_definitions(
snapshot,
AnalysisScope {
namespace: options.ns.as_deref(),
namespace_prefix: options.ns_prefix.as_deref(),
include_dependencies: options.deps,
},
|namespace, definition, entry| {
if target_error.is_some() {
return;
}
if import_namespace.as_deref() != Some(namespace) {
imports = match snapshot
.files
.get(namespace)
.map(|file| ffi_import_bindings(&file.ns.code, namespace))
.transpose()
{
Ok(imports) => imports.unwrap_or_default(),
Err(error) => {
target_error = Some(error);
return;
}
};
import_namespace = Some(namespace.to_owned());
}
let js_implementation = match selected_js_implementation(namespace, entry) {
Ok(implementation) => implementation,
Err(error) => {
target_error = Some(format!("Invalid FFI metadata for {namespace}/{definition}: {error}"));
return;
}
};
let mut operations = Vec::new();
if js_implementation.is_none() {
scan_ffi_operations(&entry.code, &mut Vec::new(), QuoteContext::default(), &imports, &mut operations);
}
operations.sort_by(|left, right| left.path.cmp(&right.path).then(left.kind.cmp(&right.kind)));
operations.dedup();
let js_ffi_feature = schema_has_js_ffi(entry.schema.as_ref());
if operations.is_empty() && !js_ffi_feature && entry.ffi.is_none() {
return;
}
let target = match ffi_target_name(entry, active_target) {
Ok(target) => target,
Err(error) => {
target_error = Some(format!("Invalid FFI metadata for {namespace}/{definition}: {error}"));
return;
}
};
let mut classifications = BTreeSet::new();
for operation in &mut operations {
let import_source = operation
.source
.split_once('/')
.and_then(|(binding, _)| imports.get(binding))
.or_else(|| imports.get(&operation.source))
.map(|binding| binding.source.as_str());
let classification = ffi_classification(&operation.source, import_source, active_target);
operation.classification = classification.to_owned();
classifications.insert(classification);
}
if classifications.is_empty() {
let target = entry
.ffi
.as_ref()
.and_then(|ffi| snapshot::parse_ffi_target(ffi).ok().flatten())
.or(active_target);
classifications.insert(ffi_classification("", None, target));
}
let classification = if classifications.len() == 1 {
classifications.iter().next().copied().unwrap_or("unknown-host").to_owned()
} else {
"mixed".to_owned()
};
let unsafe_paths = operations
.iter()
.filter(|operation| operation.kind == "unsafe-coerce")
.map(|operation| operation.path.clone())
.collect::<Vec<_>>();
let mut callers = Vec::new();
for (caller_ns, file) in &snapshot.files {
for (caller_def, caller_entry) in &file.defs {
if caller_ns == namespace && caller_def == definition {
continue;
}
match selected_js_implementation(caller_ns, caller_entry) {
Ok(Some(_)) => continue,
Ok(None) => {}
Err(error) => {
target_error = Some(format!("Invalid FFI metadata for {caller_ns}/{caller_def}: {error}"));
return;
}
}
if code_calls_definition(&caller_entry.code, caller_ns, namespace, definition) {
callers.push(format!("{caller_ns}/{caller_def}"));
}
}
}
callers.sort();
callers.dedup();
let schema_is_concrete = {
let mut findings = Vec::new();
scan_schema_dynamic_annotation(entry.schema.as_ref(), "schema", "root", &mut findings);
findings.is_empty() && !matches!(entry.schema.as_ref(), CalcitTypeAnnotation::Dynamic)
};
let mut helper_candidates = Vec::new();
if schema_is_concrete && js_implementation.is_none() {
for (candidate_ns, file) in &snapshot.files {
for (candidate_def, candidate) in &file.defs {
if candidate_ns == namespace && candidate_def == definition {
continue;
}
if candidate.schema != entry.schema || !schema_has_js_ffi(candidate.schema.as_ref()) {
continue;
}
let candidate_target = ffi_target_name(candidate, active_target).unwrap_or_else(|_| "invalid".to_owned());
if target != "unspecified" && candidate_target != "unspecified" && candidate_target != target {
continue;
}
let project_candidate = candidate_ns == &snapshot.package || candidate_ns.starts_with(&package_prefix);
helper_candidates.push(FfiHelperCandidate {
definition: format!("{candidate_ns}/{candidate_def}"),
origin: if project_candidate { "project" } else { "dependency" }.to_owned(),
compatibility: "exact-schema".to_owned(),
target: candidate_target,
});
}
}
}
helper_candidates.sort_by(|left, right| {
let left_rank = if left.origin == "dependency" { 0 } else { 1 };
let right_rank = if right.origin == "dependency" { 0 } else { 1 };
left_rank.cmp(&right_rank).then(left.definition.cmp(&right.definition))
});
let mut member_groups = BTreeMap::<String, (BTreeSet<String>, BTreeSet<String>)>::new();
for operation in &operations {
if operation.kind == "module-call" {
continue;
}
let Some(member) = &operation.member else {
continue;
};
let group = member_groups.entry(operation.source.clone()).or_default();
if operation.kind.contains("method") {
group.1.insert(member.clone());
} else if matches!(
operation.kind.as_str(),
"field-read" | "optional-field-read" | "aget" | "aset" | "js-get" | "js-set"
) {
group.0.insert(member.clone());
}
}
let trait_candidates = member_groups
.into_iter()
.filter(|(_, (fields, methods))| !fields.is_empty() || !methods.is_empty())
.map(|(receiver, (fields, methods))| {
let suggested_name = suggested_trait_name(definition);
let fields: Vec<String> = fields.into_iter().collect();
let methods: Vec<String> = methods.into_iter().collect();
FfiTraitCandidate {
receiver,
defexternal_skeleton: defexternal_skeleton(&suggested_name, &target, &fields, &methods),
suggested_name,
fields,
methods,
contract_status: "review-required".to_owned(),
}
})
.collect::<Vec<_>>();
let schema = schema_cirru_edn(entry.schema.as_ref()).unwrap_or_else(|error| format!("<unavailable: {error}>"));
let mut adapter_sources = BTreeSet::new();
for operation in &operations {
if operation.kind != "module-call" {
continue;
}
if let Some((binding, export)) = operation.source.split_once('/')
&& let Some(import) = imports.get(binding)
{
adapter_sources.insert(format!("{}/{}", import.source, export));
} else if let Some(import) = imports.get(&operation.source)
&& let Some(member) = &operation.member
{
adapter_sources.insert(format!("{}/{member}", import.source));
}
}
let adapter_candidates = adapter_sources
.into_iter()
.map(|source| FfiAdapterCandidate {
source,
suggested_definition: format!("{definition}-adapter"),
schema_cirru_edn: schema.clone(),
contract_status: "review-required".to_owned(),
})
.collect();
boundaries.push(FfiBoundaryEvidence {
diagnostic_code: "I_FFI_BOUNDARY_EVIDENCE".to_owned(),
definition: format!("{namespace}/{definition}"),
classification,
target,
js_ffi_feature,
raw_adapter_namespace: is_raw_adapter_namespace(namespace),
operations,
unsafe_paths,
callers,
helper_candidates,
trait_candidates,
adapter_candidates,
provenance: match js_implementation {
Some(implementation) => vec![
match implementation.source {
calcit_core::js_ffi_source::JsFfiSource::Inline(_) => "js-inline".to_owned(),
calcit_core::js_ffi_source::JsFfiSource::File { path } => format!("js-file:{path}"),
},
"declared-schema".to_owned(),
"no-runtime-trust-inference".to_owned(),
],
None => vec![
"snapshot-source".to_owned(),
"declared-schema".to_owned(),
"namespace-imports".to_owned(),
"no-runtime-trust-inference".to_owned(),
],
},
});
},
)?;
if let Some(error) = target_error {
return Err(error);
}
boundaries.sort_by(|left, right| left.definition.cmp(&right.definition));
Ok(boundaries)
}
pub fn run_weak_types_report(options: &WeakTypesCommand, snapshot: &snapshot::Snapshot, out: &mut String) -> Result<(), String> {
let rows = collect_weak_type_rows(options, snapshot)?;
run_weak_types_report_with_rows(options, snapshot, &rows, out)
}
pub(crate) fn run_weak_types_report_with_rows(
options: &WeakTypesCommand,
snapshot: &snapshot::Snapshot,
rows: &[WeakTypeRow],
out: &mut String,
) -> Result<(), String> {
let ffi_boundaries = if options.ffi_evidence {
collect_ffi_boundary_evidence(options, snapshot)?
} else {
Vec::new()
};
let schema_candidates = collect_schema_candidates(options, snapshot)?;
let structural_candidates = collect_structural_candidates(options, snapshot)?;
if rows.is_empty()
&& ffi_boundaries.is_empty()
&& schema_candidates.is_empty()
&& structural_candidates.map_shapes.is_empty()
&& structural_candidates.dispatch.is_empty()
{
let _ = writeln!(out, "No weak type usage found in selected namespace scope.");
return Ok(());
}
let mut kind_count: BTreeMap<&'static str, usize> = BTreeMap::new();
let mut intent_count: BTreeMap<&'static str, usize> = BTreeMap::new();
let mut detail_count: BTreeMap<&'static str, BTreeMap<String, usize>> = BTreeMap::new();
let mut ns_set: BTreeSet<&str> = BTreeSet::new();
let mut def_count = 0usize;
for row in rows {
def_count += 1;
ns_set.insert(row.ns.as_str());
for occurrence in &row.occurrences {
*kind_count.entry(occurrence.kind.as_str()).or_insert(0) += 1;
*intent_count.entry(occurrence.intent.as_str()).or_insert(0) += 1;
if options.summary_only {
continue;
}
*detail_count
.entry(occurrence.kind.as_str())
.or_default()
.entry(occurrence.detail.clone())
.or_insert(0) += 1;
}
}
let _ = writeln!(out, "Weak type usage check");
let _ = writeln!(out, "- namespaces: {}", ns_set.len());
let _ = writeln!(out, "- defs with hits: {def_count}");
if let Some(raw) = &options.only {
let _ = writeln!(out, "- only: {raw}");
}
if let Some(raw) = &options.intent {
let _ = writeln!(out, "- intent-filter: {raw}");
}
let _ = writeln!(
out,
"- hits: schema-dynamic={} schema-open={} unresolved-type-slot={} code-dynamic={} code-nil={} unsafe-coerce={}",
kind_count.get("schema-dynamic").copied().unwrap_or(0),
kind_count.get("schema-open").copied().unwrap_or(0),
kind_count.get("unresolved-type-slot").copied().unwrap_or(0),
kind_count.get("code-dynamic").copied().unwrap_or(0),
kind_count.get("code-nil").copied().unwrap_or(0),
kind_count.get("unsafe-coerce").copied().unwrap_or(0)
);
if let Some(count) = kind_count.get("data-dynamic") {
let _ = writeln!(out, "- data-dynamic hits: {count}");
}
let _ = writeln!(
out,
"- intents: unresolved={} intentional-js-ffi={} js-ffi-non-host={} intentional-macro-syntax={} intentional-type-slot-dynamic={} intentional-decode={} intentional-open={} explicit-unsafe={} declared-unit={}",
intent_count.get("unresolved").copied().unwrap_or(0),
intent_count.get("intentional-js-ffi").copied().unwrap_or(0),
intent_count.get("js-ffi-non-host").copied().unwrap_or(0),
intent_count.get("intentional-macro-syntax").copied().unwrap_or(0),
intent_count.get("intentional-type-slot-dynamic").copied().unwrap_or(0),
intent_count.get("intentional-decode").copied().unwrap_or(0),
intent_count.get("intentional-open").copied().unwrap_or(0),
intent_count.get("explicit-unsafe").copied().unwrap_or(0),
intent_count.get("declared-unit").copied().unwrap_or(0)
);
if options.ffi_evidence {
let mut classifications = BTreeMap::<&str, usize>::new();
for boundary in &ffi_boundaries {
*classifications.entry(boundary.classification.as_str()).or_insert(0) += 1;
}
let _ = writeln!(out, "- FFI boundaries: {}", ffi_boundaries.len());
let _ = writeln!(
out,
"- FFI classifications: {}",
classifications
.iter()
.map(|(name, count)| format!("{name}={count}"))
.collect::<Vec<_>>()
.join(" ")
);
}
if options.schema_evidence {
let _ = writeln!(out, "- schema candidates: {}", schema_candidates.len());
let _ = writeln!(out, "- repeated map-shape candidates: {}", structural_candidates.map_shapes.len());
let _ = writeln!(out, "- dispatch candidates: {}", structural_candidates.dispatch.len());
}
let unresolved_dynamic = rows
.iter()
.flat_map(|row| row.occurrences.iter())
.filter(|occurrence| {
occurrence.intent == WeakTypeIntent::Unresolved
&& matches!(occurrence.kind, WeakTypeKind::SchemaDynamic | WeakTypeKind::CodeDynamic)
})
.count();
if unresolved_dynamic > 0 {
let _ = writeln!(
out,
"- agent-note: {unresolved_dynamic} unresolved dynamic slot(s) can erase generic relations, callback checks, and compile-time method specialization."
);
let _ = writeln!(
out,
"- next: rerun without `--summary-only`; prefer concrete types, `:generics` type variables, or trait `:where` bounds before retaining a documented dynamic boundary."
);
}
let unresolved_type_slots = rows
.iter()
.flat_map(|row| row.occurrences.iter())
.filter(|occurrence| occurrence.intent == WeakTypeIntent::Unresolved && occurrence.kind == WeakTypeKind::UnresolvedTypeSlot)
.count();
if unresolved_type_slots > 0 {
let _ = writeln!(
out,
"- agent-note: {unresolved_type_slots} type slot(s) are not bound for the selected entry and currently behave like Dynamic."
);
let _ = writeln!(
out,
"- next: bind each slot with `calcit config set-type-slot` to a named type; a `Dynamic` binding does not count as bound."
);
}
let nil_debt = rows
.iter()
.flat_map(|row| row.occurrences.iter())
.filter(|occurrence| {
occurrence.kind == WeakTypeKind::CodeNil && matches!(occurrence.intent, WeakTypeIntent::Unresolved | WeakTypeIntent::DeclaredUnit)
})
.count();
if nil_debt > 0 {
let _ = writeln!(
out,
"- agent-note: {nil_debt} nil occurrence(s) are unresolved, or violate Unit returns."
);
let _ = writeln!(
out,
"- next: filter `--only code-nil --intent unresolved,declared-unit`; use `&unit` for no-value returns, then prefer Option/Result for application absence or failure."
);
}
let unsafe_coercions = rows
.iter()
.flat_map(|row| row.occurrences.iter())
.filter(|occurrence| occurrence.kind == WeakTypeKind::UnsafeCoerce)
.count();
if unsafe_coercions > 0 {
let _ = writeln!(
out,
"- agent-note: {unsafe_coercions} explicit unsafe coercion(s) bypass static compatibility and need a documented runtime contract."
);
let _ = writeln!(
out,
"- next: rerun with `--only unsafe-coerce`; keep each assertion in a minimal adapter and add positive and negative boundary-contract tests."
);
}
if options.summary_only {
return Ok(());
}
if options.schema_evidence && !schema_candidates.is_empty() {
let _ = writeln!(out, "\n## Schema candidate evidence");
let _ = writeln!(
out,
"\nCompiler and usage evidence only: every candidate remains review-required until explicitly selected."
);
for candidate in &schema_candidates {
let _ = writeln!(out, "\n### `{}`", candidate.definition);
let _ = writeln!(out, "\n- diagnostic code: `{}`", candidate.diagnostic_code);
let _ = writeln!(out, "- confidence: `{}`", candidate.confidence);
let _ = writeln!(out, "- unresolved slots: `{}`", candidate.unresolved_slots.join(", "));
let _ = writeln!(out, "- affected usages: `{}`", candidate.affected_usages.join(", "));
let _ = writeln!(out, "- contract status: `{}`", candidate.contract_status);
}
}
if options.schema_evidence && (!structural_candidates.map_shapes.is_empty() || !structural_candidates.dispatch.is_empty()) {
let _ = writeln!(out, "\n## Structural candidate evidence");
for candidate in &structural_candidates.map_shapes {
let _ = writeln!(
out,
"\n- map shape `{}` confidence=`{}` fields=`{}` evidence=`{}`",
candidate.suggested_name,
candidate.confidence,
candidate
.fields
.iter()
.map(|field| field.name.as_str())
.collect::<Vec<_>>()
.join(","),
candidate.evidence_paths.join(", ")
);
}
for candidate in &structural_candidates.dispatch {
let _ = writeln!(
out,
"\n- dispatch `{}` confidence=`{}` variants=`{}` evidence=`{}`",
candidate.suggested_name,
candidate.confidence,
candidate.variants.join(","),
candidate.evidence_paths.join(", ")
);
}
}
if options.ffi_evidence && !ffi_boundaries.is_empty() {
let _ = writeln!(out, "\n## FFI boundary evidence");
let _ = writeln!(
out,
"\nStatic migration evidence only: every candidate remains review-required and does not assert runtime trust."
);
for boundary in &ffi_boundaries {
let _ = writeln!(out, "\n### `{}`", boundary.definition);
let _ = writeln!(out, "\n- diagnostic code: `{}`", boundary.diagnostic_code);
let _ = writeln!(out, "- classification: `{}`", boundary.classification);
let _ = writeln!(out, "- target: `{}`", boundary.target);
let _ = writeln!(out, "- js-ffi feature: `{}`", boundary.js_ffi_feature);
let _ = writeln!(out, "- callers: `{}`", boundary.callers.join(", "));
for operation in &boundary.operations {
let _ = writeln!(
out,
" - `{}` classification=`{}` source=`{}` member=`{}` path=`{}` nullable=`{}`",
operation.kind,
operation.classification,
operation.source,
operation.member.as_deref().unwrap_or("-"),
operation.path,
operation.nullable_evidence
);
}
for helper in &boundary.helper_candidates {
let _ = writeln!(
out,
" - helper candidate: `{}` origin=`{}` compatibility=`{}`",
helper.definition, helper.origin, helper.compatibility
);
}
for candidate in &boundary.trait_candidates {
let _ = writeln!(
out,
" - trait manifest: `{}` receiver=`{}` fields=`{}` methods=`{}` status=`{}`",
candidate.suggested_name,
candidate.receiver,
candidate.fields.join(","),
candidate.methods.join(","),
candidate.contract_status
);
if !candidate.defexternal_skeleton.is_empty() {
let _ = writeln!(out, " defexternal skeleton:");
for line in candidate.defexternal_skeleton.lines() {
let _ = writeln!(out, " {line}");
}
}
}
for candidate in &boundary.adapter_candidates {
let _ = writeln!(
out,
" - adapter manifest: `{}` source=`{}` status=`{}`",
candidate.suggested_definition, candidate.source, candidate.contract_status
);
}
}
}
let _ = writeln!(out, "\n## Weak type details\n");
let _ = writeln!(out, "- detail:");
for kind in [
"schema-dynamic",
"schema-open",
"unresolved-type-slot",
"code-dynamic",
"code-nil",
"unsafe-coerce",
"data-dynamic",
] {
if matches!(kind, "data-dynamic" | "schema-open") && !detail_count.contains_key(kind) {
continue;
}
let _ = writeln!(out, " - {kind}");
if let Some(items) = detail_count.get(kind) {
for (detail, count) in items {
let _ = writeln!(out, " - {detail}={count}");
}
}
}
let _ = writeln!(out,);
if !rows.is_empty() {
let _ = writeln!(out, "## Weak type occurrences\n");
}
let mut current_ns: Option<&str> = None;
for row in rows {
if current_ns != Some(row.ns.as_str()) {
let _ = writeln!(out, "namespace: {}", row.ns);
current_ns = Some(row.ns.as_str());
}
let _ = writeln!(out, "- def: {}", row.def);
for occurrence in &row.occurrences {
let _ = writeln!(
out,
" - {} [{}] ({}) @ {}",
occurrence.kind.as_str(),
occurrence.intent.as_str(),
occurrence.detail,
occurrence.path
);
if let Some(evidence) = &occurrence.unsafe_evidence {
let _ = writeln!(
out,
" evidence: source-form={} target={} js-ffi-feature={} raw-adapter-namespace={}",
evidence.source_form, evidence.target_schema, evidence.js_ffi_feature, evidence.raw_adapter_namespace
);
}
let _ = writeln!(out, " fix: {}", weak_type_suggestion(occurrence));
}
let _ = writeln!(out,);
}
Ok(())
}
pub fn collect_type_coverage_rows(options: &CheckTypesCommand, snapshot: &snapshot::Snapshot) -> Result<Vec<TypeCoverageRow>, String> {
let mut rows: Vec<TypeCoverageRow> = Vec::new();
visit_scoped_definitions(
snapshot,
AnalysisScope {
namespace: options.ns.as_deref(),
namespace_prefix: options.ns_prefix.as_deref(),
include_dependencies: options.deps,
},
|namespace, definition, entry| rows.push(analyze_code_entry(namespace, definition, entry)),
)?;
filter_type_coverage_rows(options, &mut rows)?;
Ok(rows)
}
pub(crate) fn filter_type_coverage_rows(options: &CheckTypesCommand, rows: &mut Vec<TypeCoverageRow>) -> Result<(), String> {
if let Some(raw) = &options.only {
let selected = parse_coverage_levels(raw)?;
rows.retain(|row| selected.contains(&row.level));
}
rows.sort_by(|a, b| {
a.ns
.cmp(&b.ns)
.then(a.level.cmp(&b.level))
.then(a.kind.as_str().cmp(b.kind.as_str()))
.then(a.def.cmp(&b.def))
});
Ok(())
}
pub fn run_check_types_report(options: &CheckTypesCommand, snapshot: &snapshot::Snapshot, out: &mut String) -> Result<(), String> {
let rows = collect_type_coverage_rows(options, snapshot)?;
run_check_types_report_with_rows(options, &rows, out)
}
pub(crate) fn run_check_types_report_with_rows(
options: &CheckTypesCommand,
rows: &[TypeCoverageRow],
out: &mut String,
) -> Result<(), String> {
if rows.is_empty() {
let _ = writeln!(out, "No definitions found in selected namespace scope.");
return Ok(());
}
let mut level_count: BTreeMap<&'static str, usize> = BTreeMap::new();
let mut kind_count: BTreeMap<&'static str, usize> = BTreeMap::new();
let mut ns_set: BTreeSet<String> = BTreeSet::new();
let mut polymorphic_defs = 0usize;
let mut bounded_polymorphic_defs = 0usize;
for row in rows {
*level_count.entry(row.level.as_str()).or_insert(0) += 1;
*kind_count.entry(row.kind.as_str()).or_insert(0) += 1;
ns_set.insert(row.ns.clone());
if !row.generics.is_empty() {
polymorphic_defs += 1;
if !row.where_bounds.is_empty() {
bounded_polymorphic_defs += 1;
}
}
}
let _ = writeln!(out, "Type coverage check");
let _ = writeln!(out, "- namespaces: {}", ns_set.len());
let _ = writeln!(out, "- defs: {}", rows.len());
if let Some(raw) = &options.only {
let _ = writeln!(out, "- only: {raw}");
}
let _ = writeln!(
out,
"- levels: full={} partial={} none={}",
level_count.get("full").copied().unwrap_or(0),
level_count.get("partial").copied().unwrap_or(0),
level_count.get("none").copied().unwrap_or(0)
);
let _ = writeln!(
out,
"- kinds: fn={} macro={} proc={} syntax={} data={} other={}",
kind_count.get("fn").copied().unwrap_or(0),
kind_count.get("macro").copied().unwrap_or(0),
kind_count.get("proc").copied().unwrap_or(0),
kind_count.get("syntax").copied().unwrap_or(0),
kind_count.get("data").copied().unwrap_or(0),
kind_count.get("other").copied().unwrap_or(0)
);
let _ = writeln!(
out,
"- polymorphism: generic={polymorphic_defs} trait-bounded={bounded_polymorphic_defs}"
);
let coverage_gaps = level_count.get("partial").copied().unwrap_or(0) + level_count.get("none").copied().unwrap_or(0);
if coverage_gaps > 0 {
let _ = writeln!(
out,
"- agent-note: {coverage_gaps} definition(s) lack full static coverage; unresolved dynamic slots can hide parametric relationships and force runtime method dispatch."
);
let _ = writeln!(
out,
"- 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`."
);
}
if options.summary_only {
return Ok(());
}
let _ = writeln!(out,);
let mut current_ns: Option<&str> = None;
for row in rows {
let typed_params = count_typed_params(&row.params, &row.param_annotations);
let total_params = row.params.len();
if current_ns != Some(row.ns.as_str()) {
let _ = writeln!(out, "namespace: {}", row.ns);
current_ns = Some(row.ns.as_str());
}
let _ = writeln!(out, "- def: {}", row.def);
let _ = writeln!(out, " kind: {}", row.kind.as_str());
let _ = writeln!(out, " coverage: {}", row.level.as_str());
if !row.generics.is_empty() {
let _ = writeln!(out, " generics: {}", row.generics.join(", "));
}
if !row.where_bounds.is_empty() {
let _ = writeln!(out, " where:");
for bound in &row.where_bounds {
let _ = writeln!(out, " - {bound}");
}
}
match row.kind {
DefKind::Data => {
let _ = writeln!(
out,
" data-type: {}",
row.data_type.clone().unwrap_or_else(|| "unknown".to_string())
);
}
DefKind::Fn => {
if row.return_type_hints.is_empty() {
let _ = writeln!(out, " return: (no hint)");
} else {
let _ = writeln!(out, " return:");
for item in &row.return_type_hints {
let _ = writeln!(out, " - {item}");
}
}
let _ = writeln!(out, " params ({typed_params}/{total_params}):");
if total_params == 0 {
let _ = writeln!(out, " - (no params)");
} else {
for name in &row.params {
match row.param_annotations.get(name) {
Some(types) if !types.is_empty() => {
let _ = writeln!(out, " - {} => {}", name, types.join(" | "));
}
_ => {
let _ = writeln!(out, " - {name} => (no assert-type)");
}
}
}
}
}
DefKind::Macro => {
let _ = writeln!(out, " params ({typed_params}/{total_params}):");
if total_params == 0 {
let _ = writeln!(out, " - (no params)");
} else {
for name in &row.params {
match row.param_annotations.get(name) {
Some(types) if !types.is_empty() => {
let _ = writeln!(out, " - {} => {}", name, types.join(" | "));
}
_ => {
let _ = writeln!(out, " - {name} => (no assert-type)");
}
}
}
}
}
DefKind::Proc => {
if row.return_type_hints.is_empty() {
let _ = writeln!(out, " return: (no hint)");
} else {
let _ = writeln!(out, " return:");
for item in &row.return_type_hints {
let _ = writeln!(out, " - {item}");
}
}
let _ = writeln!(out, " params ({typed_params}/{total_params}):");
if total_params == 0 {
let _ = writeln!(out, " - (no params)");
} else {
for name in &row.params {
match row.param_annotations.get(name) {
Some(types) if !types.is_empty() => {
let _ = writeln!(out, " - {} => {}", name, types.join(" | "));
}
_ => {
let _ = writeln!(out, " - {name} => (no assert-type)");
}
}
}
}
}
DefKind::Syntax => {
if row.return_type_hints.is_empty() {
let _ = writeln!(out, " return: (no hint)");
} else {
let _ = writeln!(out, " return:");
for item in &row.return_type_hints {
let _ = writeln!(out, " - {item}");
}
}
let _ = writeln!(out, " params ({typed_params}/{total_params}):");
if total_params == 0 {
let _ = writeln!(out, " - (no params)");
} else {
for name in &row.params {
match row.param_annotations.get(name) {
Some(types) if !types.is_empty() => {
let _ = writeln!(out, " - {} => {}", name, types.join(" | "));
}
_ => {
let _ = writeln!(out, " - {name} => (no assert-type)");
}
}
}
}
}
DefKind::Other => {
let _ = writeln!(out, " details: no type pattern recognized");
}
}
if !row.schema_issues.is_empty() {
let _ = writeln!(out, " schema-issues:");
for issue in &row.schema_issues {
let _ = writeln!(out, " - {issue}");
}
}
let _ = writeln!(out,);
}
Ok(())
}
fn analyze_builtin_syntax(def_name: &str, sig: &SyntaxTypeSignature) -> TypeCoverageRow {
let params: Vec<String> = sig.param_names.iter().map(|s| s.to_string()).collect();
let param_annotations: BTreeMap<String, Vec<String>> = sig
.param_types
.iter()
.zip(sig.param_names.iter())
.map(|(t, name)| {
let type_str = t.describe();
(name.to_string(), vec![type_str])
})
.collect();
let return_type_hints = vec![sig.return_type.describe()];
let typed_count = param_annotations.values().filter(|v| !v.is_empty()).count();
let level = if params.is_empty() || typed_count == params.len() {
CoverageLevel::Full
} else if typed_count > 0 {
CoverageLevel::Partial
} else {
CoverageLevel::None
};
TypeCoverageRow {
ns: calcit_core::calcit::CORE_NS.to_owned(),
def: def_name.to_owned(),
kind: DefKind::Syntax,
level,
params,
param_annotations,
return_type_hints,
generics: vec![],
where_bounds: vec![],
data_type: None,
schema_issues: vec![],
}
}
fn analyze_builtin_proc(def_name: &str, sig: &ProcTypeSignature) -> TypeCoverageRow {
let params: Vec<String> = sig.arg_types.iter().enumerate().map(|(i, _)| format!("arg{i}")).collect();
let param_annotations: BTreeMap<String, Vec<String>> = sig
.arg_types
.iter()
.enumerate()
.map(|(i, t)| {
let name = format!("arg{i}");
let type_str = t.describe();
(name, vec![type_str])
})
.collect();
let return_type_hints = vec![sig.return_type.describe()];
let typed_count = param_annotations.values().filter(|v| !v.is_empty()).count();
let level = if params.is_empty() || typed_count == params.len() {
CoverageLevel::Full
} else if typed_count > 0 {
CoverageLevel::Partial
} else {
CoverageLevel::None
};
TypeCoverageRow {
ns: calcit_core::calcit::CORE_NS.to_owned(),
def: def_name.to_owned(),
kind: DefKind::Proc,
level,
params,
param_annotations,
return_type_hints,
generics: vec![],
where_bounds: vec![],
data_type: None,
schema_issues: vec![],
}
}
pub fn validate_def_vs_schema(ns: &str, def_name: &str, code: &Cirru, schema: &CalcitTypeAnnotation) -> Vec<String> {
if matches!(code, Cirru::Leaf(s) if s.as_ref() == "&runtime-implementation") {
return vec![];
}
if !matches!(schema, CalcitTypeAnnotation::Fn(_) | CalcitTypeAnnotation::Macro(_)) {
return vec![];
}
let Cirru::List(xs) = code else { return vec![] };
let code_kind = xs
.first()
.and_then(|head| match head {
Cirru::Leaf(head) => Some(head.as_ref()),
_ => None,
})
.unwrap_or("non-macro definition");
if matches!(schema, CalcitTypeAnnotation::Fn(_)) && !matches!(code_kind, "defn" | "defmacro") {
return vec![];
}
let code_shape = analyze_param_shape(xs.get(2));
validate_definition_schema_shape(&format!("{ns}/{def_name}"), code_kind, &code_shape, schema)
}
pub fn analyze_param_arity(args: Option<&Cirru>) -> (usize, bool) {
let shape = analyze_param_shape(args);
(shape.required, shape.has_rest)
}
fn analyze_param_shape(args: Option<&Cirru>) -> ParamShape {
let Some(Cirru::List(xs)) = args else {
return ParamShape::from_tokens([]);
};
ParamShape::from_tokens(xs.iter().filter_map(|item| match item {
Cirru::Leaf(s) if matches!(s.as_ref(), "[]" | ",") => None,
Cirru::Leaf(s) if s.as_ref() == "?" => Some(ParamShapeToken::LegacyOptionalMark),
Cirru::Leaf(s) if s.as_ref() == "&" => Some(ParamShapeToken::RestMark),
_ => Some(ParamShapeToken::Binding),
}))
}
pub fn analyze_code_entry(ns: &str, def_name: &str, entry: &snapshot::CodeEntry) -> TypeCoverageRow {
if ns == calcit_core::calcit::CORE_NS {
if let Ok(proc) = (*def_name).parse::<CalcitProc>()
&& let Some(sig) = proc.get_type_signature()
{
return analyze_builtin_proc(def_name, sig);
}
if let Ok(syntax) = (*def_name).parse::<CalcitSyntax>()
&& let Some(sig) = syntax.get_type_signature()
{
return analyze_builtin_syntax(def_name, &sig);
}
}
if let CalcitTypeAnnotation::Macro(signature) = entry.schema.as_ref() {
let contract_label = |contract: &MacroSyntaxType| match contract {
MacroSyntaxType::Syntax => "Syntax".to_owned(),
MacroSyntaxType::SyntaxSymbol => "SyntaxSymbol".to_owned(),
MacroSyntaxType::SyntaxList => "SyntaxList".to_owned(),
MacroSyntaxType::Expr(semantic) => format!("Expr<{}>", semantic.to_brief_string()),
};
let mut params = vec![];
let mut param_annotations = BTreeMap::new();
for (idx, contract) in signature.required_inputs.iter().enumerate() {
let name = format!("arg-{}", idx + 1);
params.push(name.clone());
param_annotations.insert(name, vec![contract_label(contract)]);
}
for (idx, contract) in signature.optional_inputs.iter().enumerate() {
let name = format!("optional-{}", idx + 1);
params.push(name.clone());
param_annotations.insert(name, vec![contract_label(contract)]);
}
if let Some(contract) = &signature.rest_input {
params.push("rest".to_owned());
param_annotations.insert("rest".to_owned(), vec![contract_label(contract)]);
}
let expansion = match &signature.expansion {
MacroExpansionType::Dynamic => "Dynamic".to_owned(),
MacroExpansionType::Expr(semantic) => format!("Expr<{}>", semantic.to_brief_string()),
MacroExpansionType::Definition(semantic) => format!("Definition<{}>", semantic.to_brief_string()),
MacroExpansionType::Declarations => "Declarations".to_owned(),
};
let level = if !matches!(signature.expansion, MacroExpansionType::Dynamic) {
CoverageLevel::Full
} else {
CoverageLevel::Partial
};
return TypeCoverageRow {
ns: ns.to_owned(),
def: def_name.to_owned(),
kind: DefKind::Macro,
level: downgrade_coverage_for_dynamic_annotation(level, entry.schema.as_ref()),
params,
param_annotations,
return_type_hints: vec![expansion],
generics: signature.generics.iter().map(|name| format!("'{name}")).collect(),
where_bounds: signature.where_bounds.iter().map(|bound| bound.to_brief_string()).collect(),
data_type: None,
schema_issues: entry_schema_issues(ns, def_name, &entry.code, &entry.schema),
};
}
if let CalcitTypeAnnotation::Fn(fn_annot) = entry.schema.as_ref()
&& let Ok(schema) = snapshot::schema_edn_to_cirru(&fn_annot.to_schema_edn())
&& let Some((params, param_annotations, return_type_hints, level)) = extract_fn_schema_hints(&schema)
{
let level = downgrade_coverage_for_dynamic_annotation(level, entry.schema.as_ref());
let (generics, where_bounds) = fn_polymorphism(fn_annot);
return TypeCoverageRow {
ns: ns.to_owned(),
def: def_name.to_owned(),
kind: match fn_annot.fn_kind {
SchemaKind::Fn => DefKind::Fn,
SchemaKind::Macro => DefKind::Macro,
},
level,
params,
param_annotations,
return_type_hints,
generics,
where_bounds,
data_type: None,
schema_issues: entry_schema_issues(ns, def_name, &entry.code, &entry.schema),
};
}
fn type_form_contains_dynamic(form: &Cirru) -> bool {
match form {
Cirru::Leaf(value) => value.as_ref() == ":dynamic",
Cirru::List(items) => items.iter().any(type_form_contains_dynamic),
}
}
fn embedded_type_declaration_coverage(head: &str, items: &[Cirru]) -> CoverageLevel {
let mut typed_slots = 0usize;
let mut dynamic_slots = 0usize;
fn entry_parts(node: &Cirru, prefix: char) -> Option<&[Cirru]> {
match unwrap_singleton_group(node) {
Cirru::List(parts) if matches!(parts.first(), Some(Cirru::Leaf(name)) if name.starts_with(prefix)) => Some(parts.as_slice()),
_ => None,
}
}
match head {
"defstruct" => {
let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
for field in items.iter().skip(2 + clauses) {
let Some(parts) = entry_parts(field, ':') else {
continue;
};
let field_type = parts.get(1);
match field_type {
Some(form) if !type_form_contains_dynamic(form) => typed_slots += 1,
_ => dynamic_slots += 1,
}
}
}
"defenum" => {
let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
for variant in items.iter().skip(2 + clauses) {
let Some(parts) = entry_parts(variant, ':') else {
continue;
};
for payload_type in parts.iter().skip(1) {
if type_form_contains_dynamic(payload_type) {
dynamic_slots += 1;
} else {
typed_slots += 1;
}
}
}
}
"defunion" | "deftype" => {
let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
for member in items.iter().skip(2 + clauses) {
let mut dynamic_leaves = vec![];
collect_dynamic_leaves(member, &mut vec![], &mut dynamic_leaves);
if dynamic_leaves.is_empty() {
typed_slots += 1;
} else {
dynamic_slots += 1;
}
}
}
"deftrait" => {
for method in items.iter().skip(2) {
if entry_parts(method, '.').is_none() {
continue;
}
if type_form_contains_dynamic(method) {
dynamic_slots += 1;
} else {
typed_slots += 1;
}
}
}
"defexternal" => {
let clauses = snapshot::data_definition_clause_count(&items[2.min(items.len())..]);
for member in items.iter().skip(2 + clauses) {
if entry_parts(member, '.').is_none() && entry_parts(member, ':').is_none() {
continue;
}
if type_form_contains_dynamic(member) {
dynamic_slots += 1;
} else {
typed_slots += 1;
}
}
}
"defimpl" => {
for method in items.iter().skip(3) {
if entry_parts(method, '.').is_none() {
continue;
}
if type_form_contains_dynamic(method) {
dynamic_slots += 1;
} else {
typed_slots += 1;
}
}
}
_ => {}
}
if dynamic_slots == 0 {
CoverageLevel::Full
} else if typed_slots > 0 || matches!(head, "defstruct" | "defenum") {
CoverageLevel::Partial
} else {
CoverageLevel::None
}
}
fn explicit_data_schema(annotation: &CalcitTypeAnnotation) -> Option<(String, CoverageLevel)> {
if matches!(annotation, CalcitTypeAnnotation::Dynamic) {
return None;
}
let description = annotation.describe();
if matches!(description.as_str(), "dynamic" | "unknown") {
return None;
}
let mut dynamic_parts = vec![];
scan_schema_dynamic_annotation(annotation, "schema", "root", &mut dynamic_parts);
dynamic_parts.retain(|occurrence| occurrence.intent != WeakTypeIntent::IntentionalOpen);
let level = if dynamic_parts.is_empty() {
CoverageLevel::Full
} else {
CoverageLevel::Partial
};
Some((description, level))
}
let (kind, params, param_annotations, return_type_hints, data_type, level) = match &entry.code {
Cirru::List(xs) => match xs.first() {
Some(Cirru::Leaf(head))
if matches!(
head.as_ref(),
"defstruct" | "defenum" | "defunion" | "deftype" | "deftrait" | "defimpl" | "defexternal"
) =>
{
(
DefKind::Data,
Vec::new(),
BTreeMap::new(),
Vec::new(),
Some(head.trim_start_matches("def").to_owned()),
embedded_type_declaration_coverage(head, xs),
)
}
Some(Cirru::Leaf(head)) if &**head == "defn" => {
if let CalcitTypeAnnotation::Fn(fn_annot) = entry.schema.as_ref()
&& let Ok(schema) = snapshot::schema_edn_to_cirru(&fn_annot.to_schema_edn())
&& let Some((params, param_annotations, return_type_hints, level)) = extract_fn_schema_hints(&schema)
{
let level = downgrade_coverage_for_dynamic_annotation(level, entry.schema.as_ref());
let (generics, where_bounds) = fn_polymorphism(fn_annot);
return TypeCoverageRow {
ns: ns.to_owned(),
def: def_name.to_owned(),
kind: DefKind::Fn,
level,
params,
param_annotations,
return_type_hints,
generics,
where_bounds,
data_type: None,
schema_issues: entry_schema_issues(ns, def_name, &entry.code, &entry.schema),
};
}
if std::env::var("CR_DEBUG_SCHEMA").is_ok() {
let schema_kind = match entry.schema.as_ref() {
CalcitTypeAnnotation::Fn(fn_annot) => match snapshot::schema_edn_to_cirru(&fn_annot.to_schema_edn()) {
Ok(schema) => match extract_fn_schema_hints(&schema) {
Some(_) => "Fn/schema-hints-ok".to_owned(),
None => "Fn/schema-hints-none".to_owned(),
},
Err(e) => format!("Fn/edn-to-cirru-err:{e}"),
},
other => format!("non-fn:{other:?}"),
};
eprintln!("[debug] {ns}/{def_name}: schema={schema_kind}");
}
let args = xs.get(2);
let body = &xs[3..];
let params = extract_param_symbols(args);
let param_annotations = extract_assert_type_annotations(body);
let return_type_hints = extract_return_type_hints(body);
let typed_count = count_typed_params(¶ms, ¶m_annotations);
let ret_typed = !return_type_hints.is_empty();
let level = if ret_typed && (params.is_empty() || typed_count == params.len()) {
CoverageLevel::Full
} else if ret_typed || typed_count > 0 {
CoverageLevel::Partial
} else {
CoverageLevel::None
};
(DefKind::Fn, params, param_annotations, return_type_hints, None, level)
}
Some(Cirru::Leaf(head)) if &**head == "defmacro" => {
let args = xs.get(2);
let body = &xs[3..];
let params = extract_param_symbols(args);
let param_annotations = extract_assert_type_annotations(body);
let typed_count = count_typed_params(¶ms, ¶m_annotations);
let level = if typed_count > 0 {
CoverageLevel::Partial
} else {
CoverageLevel::None
};
(DefKind::Macro, params, param_annotations, Vec::new(), None, level)
}
Some(Cirru::Leaf(head)) if &**head == "def" => {
let inferred = xs.get(2).and_then(infer_data_type);
let explicit = explicit_data_schema(entry.schema.as_ref());
let data_type = inferred.or_else(|| explicit.as_ref().map(|(data_type, _)| data_type.clone()));
let level = explicit.map(|(_, level)| level).unwrap_or_else(|| {
if data_type.is_some() {
CoverageLevel::Full
} else {
CoverageLevel::None
}
});
(DefKind::Data, Vec::new(), BTreeMap::new(), Vec::new(), data_type, level)
}
Some(Cirru::Leaf(head)) if head.as_ref() == "defref" => {
let explicit = explicit_data_schema(entry.schema.as_ref());
let (data_type, level) = explicit.unwrap_or_else(|| ("ref<dynamic>".to_owned(), CoverageLevel::Partial));
(DefKind::Data, Vec::new(), BTreeMap::new(), Vec::new(), Some(data_type), level)
}
_ => match explicit_data_schema(entry.schema.as_ref()) {
Some((data_type, level)) => (DefKind::Data, Vec::new(), BTreeMap::new(), Vec::new(), Some(data_type), level),
None => (DefKind::Other, Vec::new(), BTreeMap::new(), Vec::new(), None, CoverageLevel::None),
},
},
_ => match explicit_data_schema(entry.schema.as_ref()) {
Some((data_type, level)) => (DefKind::Data, Vec::new(), BTreeMap::new(), Vec::new(), Some(data_type), level),
None => (DefKind::Other, Vec::new(), BTreeMap::new(), Vec::new(), None, CoverageLevel::None),
},
};
let (generics, where_bounds) = entry_polymorphism(entry);
TypeCoverageRow {
ns: ns.to_owned(),
def: def_name.to_owned(),
kind,
level,
params,
param_annotations,
return_type_hints,
generics,
where_bounds,
data_type,
schema_issues: entry_schema_issues(ns, def_name, &entry.code, &entry.schema),
}
}
fn schema_to_map(schema: &Cirru) -> Option<BTreeMap<&str, &Cirru>> {
let Cirru::List(items) = schema else {
return None;
};
let Some(Cirru::Leaf(head)) = items.first() else {
return None;
};
let mut data = BTreeMap::new();
match &**head {
"&{}" => {
if (items.len() - 1) % 2 != 0 {
return None;
}
for idx in (1..items.len()).step_by(2) {
let key = match &items[idx] {
Cirru::Leaf(s) if s.starts_with(':') => s.as_ref(),
_ => return None,
};
data.insert(key, &items[idx + 1]);
}
}
"{}" => {
for pair in items.iter().skip(1) {
let Cirru::List(xs) = pair else {
return None;
};
if xs.len() != 2 {
return None;
}
let key = match &xs[0] {
Cirru::Leaf(s) if s.starts_with(':') => s.as_ref(),
_ => return None,
};
data.insert(key, &xs[1]);
}
}
_ => return None,
}
Some(data)
}
fn is_schema_list_annotation(node: &Cirru) -> bool {
match node {
Cirru::Leaf(s) => s.as_ref() == ":list",
Cirru::List(xs) => {
matches!(xs.first(), Some(Cirru::Leaf(head)) if &**head == "::")
&& matches!(xs.get(1), Some(Cirru::Leaf(tag)) if &**tag == ":list")
}
}
}
fn render_schema_param_type(ty_node: Option<&Cirru>, wrap_rest_as_list: bool) -> String {
let Some(ty_node) = ty_node else {
return ":dynamic".to_owned();
};
let rendered = render_cirru_inline(ty_node);
if !wrap_rest_as_list || rendered == ":dynamic" || is_schema_list_annotation(ty_node) {
rendered
} else {
format!(":: :list {rendered}")
}
}
fn read_schema_param_wrapped(item: &Cirru, default_name: &str, wrap_rest_as_list: bool) -> Option<(String, String)> {
match item {
Cirru::Leaf(_) => Some((default_name.to_owned(), render_schema_param_type(Some(item), wrap_rest_as_list))),
Cirru::List(xs) => {
let Some(Cirru::Leaf(head)) = xs.first() else {
return None;
};
if &**head != "[]" && &**head != "::" {
return None;
}
match xs.len() {
2 => {
let ty = render_schema_param_type(xs.get(1), wrap_rest_as_list);
Some((default_name.to_owned(), ty))
}
3 => {
let ty_node = match xs.get(1) {
Some(Cirru::Leaf(name)) if name.starts_with('\'') => xs.get(2),
_ => Some(item),
};
let ty = render_schema_param_type(ty_node, wrap_rest_as_list);
Some((default_name.to_owned(), ty))
}
_ => None,
}
}
}
}
type FnSchemaHints = (Vec<String>, BTreeMap<String, Vec<String>>, Vec<String>, CoverageLevel);
pub fn extract_fn_schema_hints(schema: &Cirru) -> Option<FnSchemaHints> {
let schema = schema_to_map(schema)?;
let mut params: Vec<String> = Vec::new();
let mut param_annotations: BTreeMap<String, Vec<String>> = BTreeMap::new();
if let Some(args_node) = schema.get(":args")
&& let Cirru::List(items) = args_node
&& matches!(items.first(), Some(Cirru::Leaf(head)) if &**head == "[]")
{
for (idx, item) in items.iter().skip(1).enumerate() {
if let Some((name, ty)) = read_schema_param_wrapped(item, &format!("arg{idx}"), false) {
params.push(name.clone());
param_annotations.entry(name).or_default().push(ty);
}
}
}
if let Some(rest_node) = schema.get(":rest")
&& let Some((name, ty)) = read_schema_param_wrapped(rest_node, "rest", true)
{
params.push(name.clone());
param_annotations.entry(name).or_default().push(ty);
}
let return_type_hints = vec![
schema
.get(":return")
.map_or_else(|| ":dynamic".to_owned(), |v| render_cirru_inline(v)),
];
let typed_count = params
.iter()
.filter(|name| {
param_annotations
.get(*name)
.is_some_and(|hints| hints.iter().any(|hint| hint != ":dynamic"))
})
.count();
let ret_typed = return_type_hints.iter().any(|hint| hint != ":dynamic");
let level = if ret_typed && (params.is_empty() || typed_count == params.len()) {
CoverageLevel::Full
} else if ret_typed || typed_count > 0 {
CoverageLevel::Partial
} else {
CoverageLevel::None
};
Some((params, param_annotations, return_type_hints, level))
}
fn extract_param_symbols(args: Option<&Cirru>) -> Vec<String> {
let mut out: Vec<String> = vec![];
if let Some(node) = args {
collect_param_symbols(node, &mut out);
}
dedup_keep_order(out)
}
fn collect_param_symbols(node: &Cirru, out: &mut Vec<String>) {
match node {
Cirru::Leaf(s) => {
let name = s.as_ref();
if name == "&" || name == "?" || name == "[]" || name == "," {
return;
}
if name.starts_with('|') || name.starts_with(':') || name.chars().all(|c| c.is_ascii_digit()) {
return;
}
out.push(name.to_string());
}
Cirru::List(xs) => {
for x in xs {
collect_param_symbols(x, out);
}
}
}
}
fn extract_assert_type_annotations(nodes: &[Cirru]) -> BTreeMap<String, Vec<String>> {
let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
for node in nodes {
collect_assert_type_annotations(node, &mut out);
}
for items in out.values_mut() {
let mut seen: BTreeSet<String> = BTreeSet::new();
items.retain(|v| seen.insert(v.to_owned()));
}
out
}
fn collect_assert_type_annotations(node: &Cirru, out: &mut BTreeMap<String, Vec<String>>) {
match node {
Cirru::Leaf(_) => {}
Cirru::List(xs) => {
if let Some(Cirru::Leaf(head)) = xs.first()
&& &**head == "assert-type"
&& let Some(Cirru::Leaf(symbol)) = xs.get(1)
&& let Some(ty_node) = xs.get(2)
{
out.entry(symbol.to_string()).or_default().push(render_cirru_inline(ty_node));
}
for x in xs {
collect_assert_type_annotations(x, out);
}
}
}
}
fn extract_return_type_hints(nodes: &[Cirru]) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for node in nodes {
collect_return_type_hints(node, &mut out);
}
let mut seen: BTreeSet<String> = BTreeSet::new();
out.retain(|v| seen.insert(v.to_owned()));
out
}
fn collect_return_type_hints(node: &Cirru, out: &mut Vec<String>) {
match node {
Cirru::Leaf(_) => {}
Cirru::List(xs) => {
if let Some(Cirru::Leaf(head)) = xs.first()
&& &**head == "return-type"
&& let Some(ty_node) = xs.get(1)
{
out.push(render_cirru_inline(ty_node));
}
for x in xs {
collect_return_type_hints(x, out);
}
}
}
}
pub fn count_typed_params(params: &[String], annotations: &BTreeMap<String, Vec<String>>) -> usize {
params
.iter()
.filter(|name| annotations.get(*name).is_some_and(|items| !items.is_empty()))
.count()
}
fn dedup_keep_order(items: Vec<String>) -> Vec<String> {
let mut seen: BTreeSet<String> = BTreeSet::new();
let mut out: Vec<String> = Vec::new();
for item in items {
if seen.insert(item.to_owned()) {
out.push(item);
}
}
out
}
fn render_cirru_inline(node: &Cirru) -> String {
match node {
Cirru::Leaf(s) => s.to_string(),
Cirru::List(xs) => {
let parts = xs.iter().map(render_cirru_inline).collect::<Vec<_>>().join(" ");
format!("({parts})")
}
}
}
pub fn parse_coverage_levels(raw: &str) -> Result<BTreeSet<CoverageLevel>, String> {
let mut selected: BTreeSet<CoverageLevel> = BTreeSet::new();
for part in raw.split(',') {
let token = part.trim().to_ascii_lowercase();
if token.is_empty() {
continue;
}
match token.as_str() {
"none" => {
selected.insert(CoverageLevel::None);
}
"partial" => {
selected.insert(CoverageLevel::Partial);
}
"full" => {
selected.insert(CoverageLevel::Full);
}
_ => {
return Err(format!(
"Unknown coverage level `{token}` in --only. Expected comma-separated values from: none,partial,full"
));
}
}
}
if selected.is_empty() {
return Err("`--only` is empty. Use one or more of: none,partial,full".to_string());
}
Ok(selected)
}
fn infer_data_type(node: &Cirru) -> Option<String> {
match node {
Cirru::Leaf(s) => {
let raw = s.as_ref();
if raw == "nil" {
Some("nil".to_string())
} else if raw == "true" || raw == "false" {
Some("bool".to_string())
} else if raw.starts_with('|') {
Some("string".to_string())
} else if raw.starts_with(':') {
Some("tag".to_string())
} else if raw.parse::<f64>().is_ok() {
Some("number".to_string())
} else {
None
}
}
Cirru::List(xs) => match xs.first() {
Some(Cirru::Leaf(head)) if &**head == "[]" => Some("list".to_string()),
Some(Cirru::Leaf(head)) if &**head == "{}" || &**head == "&{}" => Some("map".to_string()),
Some(Cirru::Leaf(head)) if &**head == "#{}" => Some("set".to_string()),
Some(Cirru::Leaf(head)) if &**head == "::" => Some("tuple".to_string()),
Some(Cirru::Leaf(head)) if &**head == "defn" || &**head == "fn" => Some("fn".to_string()),
Some(Cirru::Leaf(head)) if &**head == "defmacro" => Some("macro".to_string()),
_ => None,
},
}
}
pub fn analysis_revision(snapshot: &snapshot::Snapshot, definitions: &[(String, String)]) -> Result<String, String> {
let mut ids = definitions.to_vec();
ids.sort();
ids.dedup();
let mut hasher = Md5::new();
for (namespace, definition) in ids {
let entry = snapshot
.files
.get(&namespace)
.and_then(|file| file.defs.get(&definition))
.ok_or_else(|| format!("Definition disappeared while computing analysis revision: {namespace}/{definition}"))?;
let revision = snapshot::definition_revision(entry)?;
let id = format!("{namespace}/{definition}");
hasher.update((id.len() as u64).to_le_bytes());
hasher.update(id.as_bytes());
hasher.update(revision.as_bytes());
}
Ok(format!("md5:{}", hex::encode(hasher.finalize())))
}
pub fn format_check_types_json(options: &CheckTypesCommand, snapshot: &snapshot::Snapshot) -> Result<String, String> {
let rows = collect_type_coverage_rows(options, snapshot)?;
format_check_types_json_with_rows(options, snapshot, &rows)
}
pub fn format_check_types_json_with_rows(
options: &CheckTypesCommand,
snapshot: &snapshot::Snapshot,
rows: &[TypeCoverageRow],
) -> Result<String, String> {
let mut levels = BTreeMap::<&str, usize>::new();
let mut kinds = BTreeMap::<&str, usize>::new();
let mut namespaces = BTreeSet::<&str>::new();
let mut polymorphic_defs = 0usize;
let mut bounded_polymorphic_defs = 0usize;
for row in rows {
*levels.entry(row.level.as_str()).or_insert(0) += 1;
*kinds.entry(row.kind.as_str()).or_insert(0) += 1;
namespaces.insert(row.ns.as_str());
if !row.generics.is_empty() {
polymorphic_defs += 1;
if !row.where_bounds.is_empty() {
bounded_polymorphic_defs += 1;
}
}
}
for level in ["none", "partial", "full"] {
levels.entry(level).or_insert(0);
}
for kind in ["fn", "macro", "proc", "syntax", "data", "other"] {
kinds.entry(kind).or_insert(0);
}
let definitions = rows
.iter()
.filter(|_| !options.summary_only)
.map(|row| {
let parameters = row
.params
.iter()
.map(|name| {
serde_json::json!({
"name": name,
"types": row.param_annotations.get(name).cloned().unwrap_or_default(),
})
})
.collect::<Vec<_>>();
serde_json::json!({
"id": format!("{}/{}", row.ns, row.def),
"namespace": row.ns,
"name": row.def,
"kind": row.kind.as_str(),
"coverage": row.level.as_str(),
"parameters": parameters,
"return_types": row.return_type_hints,
"generics": row.generics,
"where_bounds": row.where_bounds,
"data_type": row.data_type,
"schema_issues": row.schema_issues,
})
})
.collect::<Vec<_>>();
let coverage_gaps = levels.get("partial").copied().unwrap_or(0) + levels.get("none").copied().unwrap_or(0);
let mut diagnostics = vec![];
if coverage_gaps > 0 {
diagnostics.push(serde_json::json!({
"code": "W_TYPE_COVERAGE_GAPS",
"phase": "analysis",
"severity": "warning",
"message": format!("{coverage_gaps} definition(s) lack full static coverage; unresolved dynamic slots can hide generic relations and force runtime method dispatch."),
"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.",
}));
}
let ids = rows.iter().map(|row| (row.ns.clone(), row.def.clone())).collect::<Vec<_>>();
let envelope = serde_json::json!({
"schema_version": 2,
"command": "analyze.check-types",
"revision": analysis_revision(snapshot, &ids)?,
"data": {
"filters": {
"namespace": options.ns,
"namespace_prefix": options.ns_prefix,
"only": options.only,
"include_dependencies": options.deps,
"summary_only": options.summary_only,
"incremental": options.incremental,
},
"summary": {
"namespaces": namespaces.len(),
"definitions": rows.len(),
"levels": levels,
"kinds": kinds,
"polymorphism": {
"generic_definitions": polymorphic_defs,
"trait_bounded_definitions": bounded_polymorphic_defs,
},
},
"definitions": definitions,
},
"diagnostics": diagnostics,
});
serde_json::to_string_pretty(&envelope).map_err(|error| format!("Failed to encode type coverage JSON: {error}"))
}
pub fn format_weak_types_json(options: &WeakTypesCommand, snapshot: &snapshot::Snapshot) -> Result<String, String> {
let rows = collect_weak_type_rows(options, snapshot)?;
format_weak_types_json_with_rows(options, snapshot, &rows)
}
pub fn format_weak_types_json_with_rows(
options: &WeakTypesCommand,
snapshot: &snapshot::Snapshot,
rows: &[WeakTypeRow],
) -> Result<String, String> {
let ffi_boundaries = if options.ffi_evidence {
collect_ffi_boundary_evidence(options, snapshot)?
} else {
Vec::new()
};
let schema_candidates = collect_schema_candidates(options, snapshot)?;
let structural_candidates = collect_structural_candidates(options, snapshot)?;
let mut kinds = BTreeMap::<&str, usize>::new();
let mut intents = BTreeMap::<&str, usize>::new();
let mut namespaces = BTreeSet::<&str>::new();
for row in rows {
namespaces.insert(row.ns.as_str());
for occurrence in &row.occurrences {
*kinds.entry(occurrence.kind.as_str()).or_insert(0) += 1;
*intents.entry(occurrence.intent.as_str()).or_insert(0) += 1;
}
}
for kind in [
"schema-dynamic",
"schema-open",
"unresolved-type-slot",
"code-dynamic",
"code-nil",
"unsafe-coerce",
] {
kinds.entry(kind).or_insert(0);
}
for intent in [
"unresolved",
"intentional-js-ffi",
"js-ffi-non-host",
"intentional-macro-syntax",
"intentional-type-slot-dynamic",
"intentional-decode",
"intentional-open",
"explicit-unsafe",
"declared-unit",
] {
intents.entry(intent).or_insert(0);
}
let definitions = rows
.iter()
.filter(|_| !options.summary_only)
.map(|row| {
serde_json::json!({
"id": format!("{}/{}", row.ns, row.def),
"namespace": row.ns,
"name": row.def,
"occurrences": row.occurrences.iter().map(|occurrence| {
let evidence = occurrence.unsafe_evidence.as_ref().map(|evidence| serde_json::json!({
"source_form": evidence.source_form,
"target_schema": evidence.target_schema,
"js_ffi_feature": evidence.js_ffi_feature,
"raw_adapter_namespace": evidence.raw_adapter_namespace,
}));
serde_json::json!({
"kind": occurrence.kind.as_str(),
"intent": occurrence.intent.as_str(),
"detail": occurrence.detail,
"path": occurrence.path,
"evidence": evidence,
"suggestion": weak_type_suggestion(occurrence),
})
}).collect::<Vec<_>>(),
})
})
.collect::<Vec<_>>();
let mut ids = rows.iter().map(|row| (row.ns.clone(), row.def.clone())).collect::<Vec<_>>();
for boundary in &ffi_boundaries {
if let Some((namespace, definition)) = boundary.definition.split_once('/') {
ids.push((namespace.to_owned(), definition.to_owned()));
}
}
ids.sort();
ids.dedup();
let hit_count = rows.iter().map(|row| row.occurrences.len()).sum::<usize>();
let unresolved_dynamic = rows
.iter()
.flat_map(|row| row.occurrences.iter())
.filter(|occurrence| {
occurrence.intent == WeakTypeIntent::Unresolved
&& matches!(occurrence.kind, WeakTypeKind::SchemaDynamic | WeakTypeKind::CodeDynamic)
})
.count();
let unresolved_type_slots = rows
.iter()
.flat_map(|row| row.occurrences.iter())
.filter(|occurrence| occurrence.intent == WeakTypeIntent::Unresolved && occurrence.kind == WeakTypeKind::UnresolvedTypeSlot)
.count();
let nil_debt = rows
.iter()
.flat_map(|row| row.occurrences.iter())
.filter(|occurrence| {
occurrence.kind == WeakTypeKind::CodeNil && matches!(occurrence.intent, WeakTypeIntent::Unresolved | WeakTypeIntent::DeclaredUnit)
})
.count();
let unsafe_coercions = rows
.iter()
.flat_map(|row| row.occurrences.iter())
.filter(|occurrence| occurrence.kind == WeakTypeKind::UnsafeCoerce)
.count();
let mut diagnostics = vec![];
if unresolved_dynamic > 0 {
diagnostics.push(serde_json::json!({
"code": "W_DYNAMIC_TYPE_DEBT",
"phase": "analysis",
"severity": "warning",
"message": format!("{unresolved_dynamic} unresolved dynamic slot(s) erase static relationships used by generic binding, callback checking, and method specialization."),
"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.",
}));
}
if unresolved_type_slots > 0 {
diagnostics.push(serde_json::json!({
"code": "W_UNRESOLVED_TYPE_SLOT",
"phase": "analysis",
"severity": "warning",
"message": format!("{unresolved_type_slots} type slot(s) are unbound for the selected entry and therefore accept every value as though they were Dynamic."),
"suggestion": "Bind each slot with `calcit config set-type-slot <slot> <namespace/definition>`; a `Dynamic` binding does not count as bound.",
}));
}
if nil_debt > 0 {
diagnostics.push(serde_json::json!({
"code": "W_NIL_TYPE_DEBT",
"phase": "analysis",
"severity": "warning",
"message": format!("{nil_debt} nil occurrence(s) are unresolved, or violate Unit returns."),
"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.",
}));
}
if unsafe_coercions > 0 {
diagnostics.push(serde_json::json!({
"code": "W_JS_FFI_UNCHECKED_COERCE",
"phase": "analysis",
"severity": "warning",
"message": format!("{unsafe_coercions} explicit unsafe coercion(s) bypass static compatibility and need an audited runtime contract when they cross an untrusted boundary."),
"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.",
}));
}
let ffi_boundary_count = ffi_boundaries.len();
let schema_candidate_count = schema_candidates.len();
let map_shape_candidate_count = structural_candidates.map_shapes.len();
let dispatch_candidate_count = structural_candidates.dispatch.len();
let ffi_boundary_rows = if options.summary_only { Vec::new() } else { ffi_boundaries };
let schema_candidate_rows = if options.summary_only { Vec::new() } else { schema_candidates };
let structural_candidate_rows = if options.summary_only {
StructuralCandidates::default()
} else {
structural_candidates
};
let envelope = serde_json::json!({
"schema_version": 9,
"command": "analyze.weak-types",
"revision": analysis_revision(snapshot, &ids)?,
"data": {
"filters": {
"namespace": options.ns,
"namespace_prefix": options.ns_prefix,
"only": options.only,
"intent": options.intent,
"include_dependencies": options.deps,
"ffi_evidence": options.ffi_evidence,
"schema_evidence": options.schema_evidence,
"summary_only": options.summary_only,
"incremental": options.incremental,
},
"summary": {
"namespaces": namespaces.len(),
"definitions": rows.len(),
"hits": hit_count,
"ffi_boundaries": ffi_boundary_count,
"schema_candidates": schema_candidate_count,
"map_shape_candidates": map_shape_candidate_count,
"dispatch_candidates": dispatch_candidate_count,
"kinds": kinds,
"intents": intents,
},
"definitions": definitions,
"evidence": {
"ffi_boundaries": ffi_boundary_rows,
"schema_candidates": schema_candidate_rows,
"map_shapes": structural_candidate_rows.map_shapes,
"dispatch": structural_candidate_rows.dispatch,
"contract_status": "review-required",
"runtime_trust_inferred": false,
},
},
"diagnostics": diagnostics,
});
serde_json::to_string_pretty(&envelope).map_err(|error| format!("Failed to encode weak type JSON: {error}"))
}
pub fn format_check_types(options: &CheckTypesCommand, snapshot: &snapshot::Snapshot) -> Result<String, String> {
let mut out = String::new();
run_check_types_report(options, snapshot, &mut out)?;
Ok(out)
}
pub fn format_check_types_with_rows(options: &CheckTypesCommand, rows: &[TypeCoverageRow]) -> Result<String, String> {
let mut out = String::new();
run_check_types_report_with_rows(options, rows, &mut out)?;
Ok(out)
}
pub fn format_weak_types(options: &WeakTypesCommand, snapshot: &snapshot::Snapshot) -> Result<String, String> {
let mut out = String::new();
run_weak_types_report(options, snapshot, &mut out)?;
Ok(out)
}
pub fn format_weak_types_with_rows(
options: &WeakTypesCommand,
snapshot: &snapshot::Snapshot,
rows: &[WeakTypeRow],
) -> Result<String, String> {
let mut out = String::new();
run_weak_types_report_with_rows(options, snapshot, rows, &mut out)?;
Ok(out)
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use std::sync::Arc;
use calcit_core::calcit::{
CalcitTypeAnnotation, MacroExpansionType, MacroSignature, MacroSyntaxType, clear_type_slots, push_type_slot_override,
};
use cirru_parser::Cirru;
use super::{
WeakTypeIntent, WeakTypeKind, classify_unsafe_coerce_source, defexternal_skeleton, entry_schema_issues, is_defexternal_member_name,
is_raw_adapter_namespace, scan_schema_dynamic_annotation,
};
fn leaf(value: &str) -> Cirru {
Cirru::Leaf(Arc::from(value))
}
fn list(items: Vec<Cirru>) -> Cirru {
Cirru::List(items)
}
#[test]
fn ffi_import_origins_reuse_resolver_rules() {
let rule = |source, kind, local| list(vec![leaf(source), leaf(kind), local]);
let code = list(vec![
leaf("ns"),
leaf("app.main"),
list(vec![
leaf(":require"),
rule("app.lib", ":as", leaf("lib")),
rule("app.lib", ":refer", list(vec![leaf("increment")])),
rule("|package", ":as", leaf("npm")),
rule("\"node:fs", ":as", leaf("fs")),
rule("|node:fs", ":refer", list(vec![leaf("existsSync")])),
rule("package-default", ":default", leaf("default-package")),
]),
]);
let imports = super::ffi_import_bindings(&code, "app.main").expect("resolver imports should parse");
assert_eq!(imports.len(), 4);
assert_eq!(imports["npm"].source, "package");
assert_eq!(imports["fs"].source, "node:fs");
assert_eq!(imports["default-package"].member.as_deref(), Some("default"));
assert_eq!(imports["existsSync"].member.as_deref(), Some("existsSync"));
assert!(super::ffi_import_bindings(&leaf("invalid-ns"), "app.main").is_err());
}
fn scan(annotation: CalcitTypeAnnotation) -> Vec<super::WeakTypeOccurrence> {
let mut occurrences = vec![];
scan_schema_dynamic_annotation(&annotation, "schema", "root", &mut occurrences);
occurrences
}
fn macro_schema(
required_inputs: Vec<MacroSyntaxType>,
rest_input: Option<MacroSyntaxType>,
expansion: MacroExpansionType,
) -> CalcitTypeAnnotation {
CalcitTypeAnnotation::Macro(Arc::new(MacroSignature {
generics: Arc::new(vec![]),
where_bounds: Arc::new(vec![]),
required_inputs: Arc::new(required_inputs),
optional_inputs: Arc::new(vec![]),
rest_input,
expansion,
capabilities: Arc::new(HashSet::new()),
features: Arc::new(HashSet::new()),
}))
}
#[test]
fn defexternal_skeleton_filters_unexpressible_members() {
assert!(is_defexternal_member_name("textContent"));
assert!(is_defexternal_member_name("focus!"));
assert!(!is_defexternal_member_name("0"));
assert!(!is_defexternal_member_name("|b"));
assert!(!is_defexternal_member_name(""));
let skeleton = defexternal_skeleton(
"QueryHost",
"browser",
&["length".to_owned(), "0".to_owned()],
&["query".to_owned(), "|b".to_owned()],
);
assert_eq!(
skeleton,
"defexternal QueryHost\n :target :browser\n :length 'Dynamic\n .query $ :: 'Fn $ {} (:args $ [] 'QueryHost) (:return 'Dynamic)"
);
let parsed = cirru_parser::parse(&skeleton)
.expect("skeleton should parse as Cirru")
.into_iter()
.next()
.expect("skeleton should contain one expression");
calcit_core::snapshot::validate_defexternal_shorthand(&parsed, "demo/QueryHost")
.expect("generated skeleton should validate as defexternal");
assert_eq!(defexternal_skeleton("QueryHost", "browser", &["0".to_owned()], &[]), "");
assert!(!defexternal_skeleton("QueryHost", "unspecified", &["length".to_owned()], &[]).contains(":target"));
}
#[test]
fn open_expr_positions_in_strict_macros_have_intentional_syntax_intent() {
let annotation = macro_schema(
vec![MacroSyntaxType::Expr(Arc::new(CalcitTypeAnnotation::Dynamic))],
Some(MacroSyntaxType::Expr(Arc::new(CalcitTypeAnnotation::Dynamic))),
MacroExpansionType::Expr(Arc::new(CalcitTypeAnnotation::Dynamic)),
);
let occurrences = scan(annotation.clone());
assert_eq!(occurrences.len(), 3);
assert!(
occurrences
.iter()
.all(|occurrence| occurrence.intent == WeakTypeIntent::IntentionalMacroSyntax)
);
let issues = entry_schema_issues(
"app.main",
"open-macro",
&list(vec![
leaf("defmacro"),
leaf("open-macro"),
list(vec![leaf("x"), leaf("&"), leaf("xs")]),
leaf("body"),
]),
&Arc::new(annotation),
);
assert!(
issues.is_empty(),
"reviewed Expr<Dynamic> boundaries should not be unresolved: {issues:?}"
);
}
#[test]
fn reasoned_open_signatures_have_intentional_open_intent() {
let schema = |text: &str| {
let form = cirru_parser::parse(text).expect("parse schema").remove(0);
calcit_core::snapshot::parse_schema_annotation_for_write(&form).expect("schema parses")
};
let marked = schema("Fn Dynamic (Fn Dynamic (-> Dynamic)) (-> Dynamic) (:open :intrinsic)");
let occurrences = scan(marked.as_ref().clone());
assert_eq!(occurrences.len(), 4);
assert!(occurrences.iter().all(|it| it.intent == WeakTypeIntent::IntentionalOpen));
assert_eq!(
super::downgrade_coverage_for_dynamic_annotation(super::CoverageLevel::Full, marked.as_ref()),
super::CoverageLevel::Full
);
let inner = schema("Fn Dynamic (Fn Dynamic (-> Dynamic) (:open :reflect)) (-> Number)");
let intents: Vec<WeakTypeIntent> = scan(inner.as_ref().clone()).iter().map(|it| it.intent).collect();
assert_eq!(
intents,
vec![
WeakTypeIntent::Unresolved,
WeakTypeIntent::IntentionalOpen,
WeakTypeIntent::IntentionalOpen
]
);
assert_eq!(
super::downgrade_coverage_for_dynamic_annotation(super::CoverageLevel::Full, inner.as_ref()),
super::CoverageLevel::Partial
);
}
#[test]
fn weak_type_rows_apply_the_root_open_reason() {
let schema = |text: &str| {
let form = cirru_parser::parse(text).expect("parse schema").remove(0);
calcit_core::snapshot::parse_schema_annotation_for_write(&form).expect("schema parses")
};
let row_intents = |text: &str| {
let mut entry = calcit_core::snapshot::CodeEntry::from_code(cirru_parser::parse("defn f (x) x").expect("parse code").remove(0));
entry.schema = schema(text);
super::analyze_weak_types_entry("app.main", "f", &entry, &WeakTypeKind::collected())
.map(|row| {
row
.occurrences
.iter()
.filter(|it| it.kind == WeakTypeKind::SchemaDynamic)
.map(|it| it.intent)
.collect::<Vec<_>>()
})
.unwrap_or_default()
};
let reasoned = row_intents("Fn Dynamic (-> Dynamic) (:open :reflect)");
assert_eq!(reasoned.len(), 2);
assert!(reasoned.iter().all(|intent| *intent == WeakTypeIntent::IntentionalOpen));
let plain = row_intents("Fn Dynamic (-> Dynamic)");
assert_eq!(plain, vec![WeakTypeIntent::Unresolved, WeakTypeIntent::Unresolved]);
}
#[test]
fn schema_open_reports_open_family_types_with_reason_and_filter() {
let schema = |text: &str| {
let form = cirru_parser::parse(text).expect("parse schema").remove(0);
calcit_core::snapshot::parse_schema_annotation_for_write(&form).expect("schema parses")
};
let mut reasoned_entry = calcit_core::snapshot::CodeEntry::from_code(
cirru_parser::parse("defn client-option-callback (k) None")
.expect("parse code")
.remove(0),
);
reasoned_entry.schema = schema("Fn Number (-> (Option AnyFn)) (:open :decode)");
let reasoned_row = super::analyze_weak_types_entry("app.main", "client-option-callback", &reasoned_entry, &WeakTypeKind::all())
.expect("Option AnyFn with (:open :decode) must appear in weak-types");
assert_eq!(reasoned_row.occurrences.len(), 1);
let occ = &reasoned_row.occurrences[0];
assert_eq!(occ.kind, WeakTypeKind::SchemaOpen);
assert_eq!(occ.intent, WeakTypeIntent::IntentionalOpen);
assert_eq!(occ.path, "schema.return.type-arg.0");
assert_eq!(occ.detail, "schema-open:AnyFn:return:type-arg:open=decode");
let dynamic_only = super::analyze_weak_types_entry(
"app.main",
"client-option-callback",
&reasoned_entry,
&super::parse_weak_type_kinds("schema-dynamic").expect("filter parses"),
);
assert!(
dynamic_only.is_none(),
"schema-dynamic filter must keep SchemaDynamic counts unchanged"
);
let mut plain_entry =
calcit_core::snapshot::CodeEntry::from_code(cirru_parser::parse("defn f (x) x").expect("parse code").remove(0));
plain_entry.schema = schema("Fn AnyEnum (-> AnyStruct)");
let plain_row = super::analyze_weak_types_entry("app.main", "f", &plain_entry, &WeakTypeKind::all())
.expect("AnyEnum/AnyStruct must appear in weak-types");
assert_eq!(plain_row.occurrences.len(), 2);
assert!(plain_row.occurrences.iter().all(|it| it.kind == WeakTypeKind::SchemaOpen));
assert!(plain_row.occurrences.iter().all(|it| it.intent == WeakTypeIntent::Unresolved));
assert_eq!(plain_row.occurrences[0].detail, "schema-open:AnyEnum:arg");
assert_eq!(plain_row.occurrences[1].detail, "schema-open:AnyStruct:return");
let mut nested_entry =
calcit_core::snapshot::CodeEntry::from_code(cirru_parser::parse("defn wrap (cb) cb").expect("parse code").remove(0));
nested_entry.schema = schema("Fn (Fn AnyFn (-> Unit) (:open :reflect)) (-> AnyStruct) (:open :host)");
let nested_row = super::analyze_weak_types_entry("app.main", "wrap", &nested_entry, &WeakTypeKind::all())
.expect("nested schema-open should be recorded");
assert_eq!(nested_row.occurrences.len(), 2);
assert_eq!(nested_row.occurrences[0].detail, "schema-open:AnyFn:arg:fn-arg:open=reflect");
assert_eq!(nested_row.occurrences[1].detail, "schema-open:AnyStruct:return:open=host");
}
#[test]
fn whole_dynamic_macro_expansions_and_definitions_remain_unresolved() {
let dynamic_expansion = scan(macro_schema(vec![], None, MacroExpansionType::Dynamic));
let dynamic_definition = scan(macro_schema(
vec![],
None,
MacroExpansionType::Definition(Arc::new(CalcitTypeAnnotation::Dynamic)),
));
assert_eq!(dynamic_expansion.len(), 1);
assert_eq!(dynamic_expansion[0].intent, WeakTypeIntent::Unresolved);
assert_eq!(dynamic_definition.len(), 1);
assert_eq!(dynamic_definition[0].intent, WeakTypeIntent::Unresolved);
}
#[test]
fn nested_unresolved_slots_keep_unresolved_intent() {
clear_type_slots();
push_type_slot_override(
Arc::from("outer"),
Arc::new(CalcitTypeAnnotation::Nullable(
Arc::new(CalcitTypeAnnotation::TypeSlot(Arc::from("inner"))),
calcit_core::calcit::NullableOrigin::JsHost,
)),
);
let occurrences = scan(CalcitTypeAnnotation::TypeSlot(Arc::from("outer")));
assert_eq!(occurrences.len(), 1);
assert_eq!(occurrences[0].kind, WeakTypeKind::UnresolvedTypeSlot);
assert_eq!(occurrences[0].intent, WeakTypeIntent::Unresolved);
clear_type_slots();
}
#[test]
fn js_ffi_host_reach_follows_let_bindings_and_tail_positions() {
let code = cirru_parser::parse(
"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)",
)
.expect("parse adapter")
.remove(0);
let reach = super::js_ffi_host_reach(&code).expect("defn reach");
assert_eq!(reach.params, vec![true, true, false]);
assert_eq!(reach.rest, Some(false));
assert!(reach.ret);
assert!(reach.schema_path_reaches_host("schema.args.1.value"));
assert!(!reach.schema_path_reaches_host("schema.args.2"));
assert!(!reach.schema_path_reaches_host("schema.rest.item"));
let postfix = cirru_parser::parse("defn adapter ([] node label) (node.!focus) (println label) node.-value")
.expect("parse adapter")
.remove(0);
let postfix_reach = super::js_ffi_host_reach(&postfix).expect("defn reach");
assert_eq!(postfix_reach.params, vec![true, false]);
assert!(postfix_reach.ret);
let plain = cirru_parser::parse("defn adapter (node) (.!focus node) nil")
.expect("parse adapter")
.remove(0);
assert!(!super::js_ffi_host_reach(&plain).expect("defn reach").ret);
let comp = cirru_parser::parse("defcomp comp-codearea (states props) (div ({}))")
.expect("parse comp")
.remove(0);
let comp_reach = super::js_ffi_host_reach(&comp).expect("defcomp reach");
assert_eq!(comp_reach.params, vec![false, false]);
assert!(!comp_reach.ret);
let comp_host = cirru_parser::parse("defcomp comp-preview (states props) (println states) props.-hostNode")
.expect("parse comp")
.remove(0);
let comp_host_reach = super::js_ffi_host_reach(&comp_host).expect("defcomp host reach");
assert_eq!(comp_host_reach.params, vec![false, true]);
assert!(comp_host_reach.ret);
}
#[test]
fn nested_js_nullish_dynamic_keeps_ffi_intent() {
clear_type_slots();
push_type_slot_override(
Arc::from("outer"),
Arc::new(CalcitTypeAnnotation::Nullable(
Arc::new(CalcitTypeAnnotation::Dynamic),
calcit_core::calcit::NullableOrigin::JsHost,
)),
);
let occurrences = scan(CalcitTypeAnnotation::TypeSlot(Arc::from("outer")));
assert_eq!(occurrences.len(), 1);
assert_eq!(occurrences[0].kind, WeakTypeKind::SchemaDynamic);
assert_eq!(occurrences[0].intent, WeakTypeIntent::IntentionalJsFfi);
let suggestion = super::weak_type_suggestion(&occurrences[0]);
assert!(suggestion.contains("FFI boundary (JS or native)"), "{suggestion}");
assert!(!suggestion.contains("declared JS FFI"), "{suggestion}");
clear_type_slots();
}
#[test]
fn resolved_dynamic_slots_receive_slot_intent() {
clear_type_slots();
push_type_slot_override(Arc::from("slot"), Arc::new(CalcitTypeAnnotation::Dynamic));
let occurrences = scan(CalcitTypeAnnotation::TypeSlot(Arc::from("slot")));
assert_eq!(occurrences.len(), 1);
assert_eq!(occurrences[0].kind, WeakTypeKind::SchemaDynamic);
assert_eq!(occurrences[0].intent, WeakTypeIntent::IntentionalTypeSlotDynamic);
clear_type_slots();
}
#[test]
fn unsafe_coerce_source_forms_and_adapter_names_are_static_and_distinct() {
assert_eq!(
classify_unsafe_coerce_source(&[Cirru::leaf("unsafe-coerce"), Cirru::leaf("js/window"), Cirru::leaf("Number")]),
"raw-js-value"
);
assert_eq!(
classify_unsafe_coerce_source(&[
Cirru::leaf("unsafe-coerce"),
Cirru::List(vec![Cirru::leaf("js/fetch"), Cirru::leaf("url")]),
Cirru::leaf("Response"),
]),
"raw-js-operation"
);
assert_eq!(
classify_unsafe_coerce_source(&[
Cirru::leaf("unsafe-coerce"),
Cirru::List(vec![Cirru::leaf("aget"), Cirru::leaf("host"), Cirru::leaf("key")]),
Cirru::leaf("String"),
]),
"host-member-operation"
);
assert_eq!(
classify_unsafe_coerce_source(&[Cirru::leaf("unsafe-coerce"), Cirru::leaf("value"), Cirru::leaf("String")]),
"value"
);
assert!(is_raw_adapter_namespace("js-ffi.raw.node"));
assert!(is_raw_adapter_namespace("app.js-ffi.raw.browser"));
assert!(!is_raw_adapter_namespace("app.js-ffi.host.browser"));
}
#[test]
fn wrapped_def_nominal_types_and_core_syntax_forms_are_not_counted_as_unresolved() {
let mut enum_entry = calcit_core::snapshot::CodeEntry::from_code(
cirru_parser::parse("def Wrapped\n defenum Wrapped (:a) (:b Number)")
.expect("parse wrapped defenum")
.remove(0),
);
enum_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
assert!(
super::analyze_weak_types_entry("calcit.core", "Wrapped", &enum_entry, &WeakTypeKind::all()).is_none(),
"wrapped (def Name (defenum ...)) without internal Dynamic must not report schema-dynamic"
);
let mut syntax_entry = calcit_core::snapshot::CodeEntry::from_code(Cirru::leaf("&runtime-implementation"));
syntax_entry.tags.insert(cirru_edn::EdnTag::from("syntax"));
syntax_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
let syntax_row = super::analyze_weak_types_entry("calcit.core", "recur", &syntax_entry, &WeakTypeKind::all())
.expect("syntax-tagged core form retains SchemaDynamic record");
assert_eq!(syntax_row.occurrences.len(), 1);
assert_eq!(syntax_row.occurrences[0].intent, WeakTypeIntent::IntentionalMacroSyntax);
let mut plain_core_entry = calcit_core::snapshot::CodeEntry::from_code(Cirru::leaf("&runtime-implementation"));
plain_core_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
let plain_row = super::analyze_weak_types_entry("calcit.core", "untyped-core-op", &plain_core_entry, &WeakTypeKind::all())
.expect("untagged Dynamic core entry should still report");
assert_eq!(plain_row.occurrences[0].intent, WeakTypeIntent::Unresolved);
let mut deftype_entry = calcit_core::snapshot::CodeEntry::from_code(
cirru_parser::parse("deftype Pair (:generics A B) (Tuple A B)")
.expect("parse deftype")
.remove(0),
);
deftype_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
assert!(
super::analyze_weak_types_entry("app.main", "Pair", &deftype_entry, &WeakTypeKind::all()).is_none(),
"clean deftype without internal Dynamic must not report unresolved schema-dynamic"
);
let deftype_cov = super::analyze_code_entry("app.main", "Pair", &deftype_entry);
assert_eq!(deftype_cov.level, super::CoverageLevel::Full);
let mut open_deftype_entry = calcit_core::snapshot::CodeEntry::from_code(
cirru_parser::parse("deftype OpenMap (Map Tag Dynamic)")
.expect("parse open deftype")
.remove(0),
);
open_deftype_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
let open_deftype_row = super::analyze_weak_types_entry("app.main", "OpenMap", &open_deftype_entry, &WeakTypeKind::all())
.expect("deftype containing Dynamic must still report schema-dynamic");
assert!(
open_deftype_row
.occurrences
.iter()
.any(|occ| occ.kind == WeakTypeKind::SchemaDynamic && occ.path == "schema"),
"got: {:?}",
open_deftype_row.occurrences
);
let data_dynamic_row = super::analyze_weak_types_entry(
"app.main",
"OpenMap",
&open_deftype_entry,
&std::collections::BTreeSet::from([super::WeakTypeKind::DataDynamic]),
)
.expect("deftype containing Dynamic must report data-dynamic when selected");
assert!(
data_dynamic_row
.occurrences
.iter()
.any(|occ| occ.kind == super::WeakTypeKind::DataDynamic && occ.detail == "data-dynamic:type-alias:0"),
"got: {:?}",
data_dynamic_row.occurrences
);
let mut external_entry = calcit_core::snapshot::CodeEntry::from_code(
cirru_parser::parse("defexternal DomHost (:target :browser) (:label String)")
.expect("parse defexternal")
.remove(0),
);
external_entry.schema = Arc::new(CalcitTypeAnnotation::Dynamic);
assert!(
super::analyze_weak_types_entry("app.main", "DomHost", &external_entry, &WeakTypeKind::all()).is_none(),
"clean defexternal without Dynamic must not report unresolved schema-dynamic"
);
let external_cov = super::analyze_code_entry("app.main", "DomHost", &external_entry);
assert_eq!(external_cov.level, super::CoverageLevel::Full);
}
#[test]
fn ref_open_cache_boundary_has_intentional_open_intent_and_full_coverage() {
let schema = |text: &str| {
let form = cirru_parser::parse(text).expect("parse schema").remove(0);
calcit_core::snapshot::parse_schema_annotation_for_write(&form).expect("schema parses")
};
let mut cached_entry =
calcit_core::snapshot::CodeEntry::from_code(cirru_parser::parse("defref *cache $ {}").expect("parse defref").remove(0));
cached_entry.schema = schema("Ref Dynamic (:open :cache)");
let cached_cov = super::analyze_code_entry("app.main", "*cache", &cached_entry);
assert_eq!(cached_cov.level, super::CoverageLevel::Full);
assert!(
cached_cov.schema_issues.is_empty(),
"reviewed Ref cache must not fail schema audit: {:?}",
cached_cov.schema_issues
);
let cached_row = super::analyze_weak_types_entry("app.main", "*cache", &cached_entry, &WeakTypeKind::all())
.expect("open ref still surfaces under explicit weak-types query");
assert!(
cached_row
.occurrences
.iter()
.all(|occ| occ.intent == WeakTypeIntent::IntentionalOpen),
"got: {:?}",
cached_row.occurrences
);
let mut plain_entry =
calcit_core::snapshot::CodeEntry::from_code(cirru_parser::parse("defref *plain $ {}").expect("parse defref").remove(0));
plain_entry.schema = schema("Ref Dynamic");
let plain_cov = super::analyze_code_entry("app.main", "*plain", &plain_entry);
assert_eq!(plain_cov.level, super::CoverageLevel::Partial);
let plain_row =
super::analyze_weak_types_entry("app.main", "*plain", &plain_entry, &WeakTypeKind::all()).expect("unmarked Ref Dynamic");
assert!(
plain_row.occurrences.iter().all(|occ| occ.intent == WeakTypeIntent::Unresolved),
"got: {:?}",
plain_row.occurrences
);
}
}