use super::chunk_display::{ChunkDisplayOptions, ChunkedDisplay, maybe_chunk_node};
use super::common::{
cirru_to_json_value, deps_path_for_snapshot, emit_cli_output, format_path, markdown_fenced_block, parse_path,
print_cli_warning_block, resolve_definition_lookup, shell_quote,
};
use super::cursor::{
CursorLastQuery, resolve_active_cursor_reference, resolve_cursor_path_argument, resolve_cursor_target_argument,
set_cursor_from_query_match,
};
use super::fix::{SOURCE_SCOPE_HEADS, source_reference_paths};
use super::stdout::{cli_print as print, cli_println as println};
use super::structured_output::{StructuredOutputFormat, format_json_value_as_edn, json_value_to_edn};
use super::tips::command_guidance_enabled;
use crate::call_tree::{CallTreeAnalyzer, CallTreeConfig};
use crate::cli_args::{
ConfigCommand, ConfigShowCommand, ConfigSubcommand, QueryCommand, QueryConfigCommand, QueryContextCommand, QueryDefCommand,
QueryDefsCommand, QuerySubcommand, QueryTypeAtCommand, QueryTypeCommand,
};
use calcit_core::CalcitTypeAnnotation;
use calcit_core::calcit::{Calcit, CalcitFnTypeAnnotation, CalcitProc, CalcitSyntax, DYNAMIC_TYPE, LocatedWarning};
use calcit_core::call_stack::CallStackList;
use calcit_core::data::cirru::code_to_calcit;
use calcit_core::data::edn::format_edn_display;
use calcit_core::js_ffi_source::{JsFfiSource, parse_js_source};
use calcit_core::load_core_snapshot;
use calcit_core::project_state::{self, ERROR_STATE_FILE};
use calcit_core::snapshot;
use calcit_core::util::string::strip_shebang;
use calcit_core::{program, runner};
use cirru_edn::EdnTag;
use cirru_parser::Cirru;
use colored::Colorize;
use md5::{Digest, Md5};
use serde::Serialize;
use std::cell::RefCell;
use std::collections::{BTreeMap, HashSet};
use std::fmt::Write as _;
use std::fs;
use std::path::Path;
use std::sync::Arc;
use super::edit::navigate_to_path;
type SearchResults = Vec<(String, String, Vec<(Vec<usize>, Cirru)>)>;
type RefResults = Vec<(String, String, String, Vec<Vec<usize>>, &'static str)>;
struct SearchCommonOpts<'a> {
filter: Option<&'a str>,
loose: bool,
regex: bool,
max_depth: usize,
entry: Option<&'a str>,
source: SearchSource,
detail_offset: usize,
parent_path: bool,
format: QueryRenderFormat,
set_cursor: Option<usize>,
compact_output: bool,
}
const DETAILED_RESULTS_WINDOW: usize = 3;
const TYPE_AT_SCHEMA_VERSION: u32 = 2;
struct SpecialBuiltinQueryMeta {
doc: &'static str,
schema: Arc<CalcitTypeAnnotation>,
runtime_arity: Option<RuntimeCallArity>,
examples: Vec<Cirru>,
expr_preview: &'static str,
cirru_note: &'static str,
semantic_tags: &'static [&'static str],
}
type QueryRenderFormat = StructuredOutputFormat;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
enum SearchSource {
Project,
Core,
Deps,
All,
}
impl SearchSource {
fn parse(raw: &str) -> Result<Self, String> {
match raw {
"project" => Ok(Self::Project),
"core" => Ok(Self::Core),
"deps" => Ok(Self::Deps),
"all" => Ok(Self::All),
other => Err(format!(
"Unknown query search source `{other}`. Expected `project`, `core`, `deps`, or `all`."
)),
}
}
fn as_str(self) -> &'static str {
match self {
Self::Project => "project",
Self::Core => "core",
Self::Deps => "deps",
Self::All => "all",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct SearchOrigin {
package: String,
module: Option<String>,
}
#[derive(Debug)]
struct SearchCatalog {
snapshot: snapshot::Snapshot,
sources: BTreeMap<String, (SearchSource, SearchOrigin)>,
}
fn parse_query_render_format(raw: &str) -> Result<QueryRenderFormat, String> {
StructuredOutputFormat::parse(raw, "query output")
}
fn emit_query_structured<T: Serialize>(value: &T, format: QueryRenderFormat, context: &str) -> Result<(), String> {
let rendered = match format {
QueryRenderFormat::Edn => {
let json = serde_json::to_value(value).map_err(|error| format!("Failed to encode {context}: {error}"))?;
format_json_value_as_edn(&json)?
}
QueryRenderFormat::Json => serde_json::to_string_pretty(value).map_err(|error| format!("Failed to encode {context}: {error}"))?,
QueryRenderFormat::Human => return Err(format!("Cannot emit human {context} as structured output")),
};
println!("{rendered}");
Ok(())
}
fn semantic_revision(parts: &[&str]) -> String {
let mut hasher = Md5::new();
for part in parts {
hasher.update((part.len() as u64).to_le_bytes());
hasher.update(part.as_bytes());
}
format!("md5:{}", hex::encode(hasher.finalize()))
}
#[derive(Debug, Serialize)]
struct SemanticQueryEnvelope<T> {
schema_version: u32,
command: &'static str,
revision: String,
data: T,
diagnostics: Vec<ContextDiagnostic>,
next: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
struct ContextCallTypes {
parameters: Vec<serde_json::Value>,
rest: Option<serde_json::Value>,
returns: serde_json::Value,
}
#[derive(Debug, Clone, Serialize)]
struct ContextMethod {
name: String,
origin: String,
status: &'static str,
parameter_types: Option<Vec<String>>,
rest_type: Option<String>,
return_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
call_types: Option<ContextCallTypes>,
generics: Vec<String>,
bounds: Vec<String>,
features: Vec<String>,
definition: Option<String>,
detail: Option<String>,
}
fn context_method(
descriptor: runner::preprocess::StaticMethodDescriptor,
contract: runner::preprocess::StaticMethodContract,
) -> ContextMethod {
let call_types = method_call_types(&contract);
ContextMethod {
name: descriptor.name,
origin: descriptor.origin,
status: contract.status,
parameter_types: contract
.arg_types
.map(|args| args.iter().map(|annotation| annotation.describe()).collect()),
rest_type: contract.rest_type.map(|annotation| annotation.describe()),
return_type: contract.return_type.map(|annotation| annotation.describe()),
call_types,
generics: contract
.generics
.into_iter()
.map(|name| match CalcitTypeAnnotation::TypeVar(Arc::from(name)).to_type_edn() {
cirru_edn::Edn::Symbol(source) => source.to_string(),
_ => unreachable!("a type variable projects to its source symbol"),
})
.collect(),
bounds: contract.bounds,
features: contract.features,
definition: contract.definition,
detail: contract.detail,
}
}
fn method_call_types(contract: &runner::preprocess::StaticMethodContract) -> Option<ContextCallTypes> {
if contract.status != "proven" {
return None;
}
let node = |annotation: &CalcitTypeAnnotation| {
canonical_schema_cirru(annotation, true)
.ok()
.flatten()
.map(|cirru| cirru_to_json(&cirru))
};
Some(ContextCallTypes {
parameters: contract
.arg_types
.as_ref()?
.iter()
.map(|annotation| node(annotation))
.collect::<Option<Vec<_>>>()?,
rest: match contract.rest_type.as_ref() {
Some(annotation) => Some(node(annotation)?),
None => None,
},
returns: node(contract.return_type.as_ref()?)?,
})
}
fn method_contract_fingerprint(methods: &Option<Vec<ContextMethod>>) -> Result<String, String> {
serde_json::to_string(methods).map_err(|error| format!("Failed to encode method contracts for revision: {error}"))
}
fn render_context_method(method: &ContextMethod) -> String {
let mut rendered = format!("- `{}` (`{}`): {}", method.name, method.origin, method.status);
if !method.generics.is_empty() {
let generics = method.generics.iter().map(|name| format!("'{name}")).collect::<Vec<_>>();
rendered.push_str(&format!(" for<{}>", generics.join(", ")));
}
if let (Some(args), Some(result)) = (&method.parameter_types, &method.return_type) {
let mut parameters = args.clone();
if let Some(rest) = &method.rest_type {
parameters.push(format!("...{rest}"));
}
rendered.push_str(&format!(" `({}) -> {result}`", parameters.join(", ")));
}
if !method.bounds.is_empty() {
rendered.push_str(&format!("; where {}", method.bounds.join(", ")));
}
if !method.features.is_empty() {
rendered.push_str(&format!("; features {}", method.features.join(", ")));
}
if let Some(definition) = &method.definition {
rendered.push_str(&format!("; `calcit query context '{definition}'`"));
}
if let Some(detail) = &method.detail {
rendered.push_str(&format!("; {detail}"));
}
rendered
}
fn render_type_query_methods(methods: &[ContextMethod]) -> String {
let mut out = String::new();
let _ = writeln!(&mut out, "Count: {}\n", methods.len());
for method in methods {
let _ = writeln!(&mut out, "{}", render_context_method(method));
}
out
}
#[derive(Debug, Serialize)]
struct TypeQueryData {
target: String,
canonical_type: String,
resolved_from: &'static str,
methods: Option<Vec<ContextMethod>>,
}
#[derive(Debug, Clone, Serialize)]
struct TypeAtEvidence {
kind: String,
detail: String,
path: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
struct TypeAtBinding {
name: String,
r#type: String,
path: Option<String>,
}
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
struct TypeAtLowering {
status: &'static str,
kind: &'static str,
source_head: Option<String>,
lowered_head: Option<String>,
detail: String,
}
#[derive(Debug, Serialize)]
struct TypeAtData {
id: String,
path: String,
expression: String,
tree: serde_json::Value,
inferred_type: Option<String>,
expected_type: Option<String>,
expected_from: Option<String>,
confidence: &'static str,
dynamic_intent: Option<&'static str>,
evidence: Vec<TypeAtEvidence>,
bindings: Vec<TypeAtBinding>,
bindings_complete: bool,
static_methods: Option<Vec<ContextMethod>>,
lowering: TypeAtLowering,
}
#[derive(Debug, Clone, Serialize)]
struct ContextCollection<T> {
total: usize,
returned: usize,
truncated: bool,
items: Vec<T>,
}
impl<T> ContextCollection<T> {
fn new(total: usize, items: Vec<T>) -> Self {
let returned = items.len();
Self {
total,
returned,
truncated: returned < total,
items,
}
}
}
#[derive(Debug, Clone, Serialize)]
struct ContextCode {
root: &'static str,
nodes: usize,
cirru: String,
tree: Option<serde_json::Value>,
truncated: bool,
}
#[derive(Debug, Clone, Serialize)]
struct ContextExample {
index: usize,
cirru: String,
tree: Option<serde_json::Value>,
truncated: bool,
}
#[derive(Debug, Clone, Serialize)]
struct ContextTest {
name: String,
tags: Vec<String>,
cirru: String,
tree: Option<serde_json::Value>,
truncated: bool,
}
#[derive(Debug, Clone, Serialize)]
struct ContextDependency {
id: String,
source: String,
}
#[derive(Debug, Clone, Serialize)]
struct ContextUsage {
id: String,
source: String,
area: String,
paths: Vec<String>,
}
#[derive(Debug, Clone, Serialize)]
struct ContextDocLink {
id: String,
path: String,
title: Option<String>,
summary: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
struct ContextDiagnostic {
code: String,
phase: &'static str,
severity: &'static str,
message: String,
path: Option<String>,
intent: Option<String>,
provenance: Vec<calcit_core::calcit::CalcitErrProvenance>,
}
#[derive(Debug, Serialize)]
struct DefinitionContextData {
id: String,
uri: String,
source: String,
kind: String,
layer: &'static str,
coverage: String,
doc: Option<String>,
doc_truncated: bool,
tags: Vec<String>,
schema: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
inferred_schema: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
runtime_arity: Option<RuntimeCallArity>,
#[serde(skip_serializing_if = "Option::is_none")]
failure: Option<ProcFailureInfo>,
features: Vec<String>,
js_ffi: Option<JsFfiQueryInfo>,
code: ContextCode,
examples: ContextCollection<ContextExample>,
tests: ContextCollection<ContextTest>,
dependencies: ContextCollection<ContextDependency>,
usages: ContextCollection<ContextUsage>,
docs: ContextCollection<ContextDocLink>,
static_methods: Option<ContextCollection<ContextMethod>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
struct RuntimeCallArity {
min: usize,
max: Option<usize>,
}
fn core_runtime_call_arity(namespace: &str, definition: &str, entry: &snapshot::CodeEntry) -> Option<RuntimeCallArity> {
let arity = core_runtime_proc(namespace, definition, entry)?.arity()?;
Some(RuntimeCallArity {
min: arity.min,
max: arity.max,
})
}
fn core_runtime_proc(namespace: &str, definition: &str, entry: &snapshot::CodeEntry) -> Option<CalcitProc> {
if namespace != calcit_core::calcit::CORE_NS {
return None;
}
let proc_name = if crate::public_api_check::is_core_runtime_intrinsic(namespace, definition, entry) {
definition
} else if let Cirru::Leaf(value) = &entry.code {
value.as_ref()
} else {
return None;
};
proc_name.parse::<CalcitProc>().ok()
}
#[derive(Debug, Clone, Serialize)]
struct ProcFailureInfo {
class: &'static str,
#[serde(skip_serializing_if = "Option::is_none")]
condition: Option<&'static str>,
}
fn core_proc_failure(namespace: &str, definition: &str, entry: &snapshot::CodeEntry) -> Option<ProcFailureInfo> {
let failure = core_runtime_proc(namespace, definition, entry)?.failure();
Some(ProcFailureInfo {
class: failure.class_name(),
condition: failure.condition(),
})
}
fn render_proc_failure(failure: &ProcFailureInfo) -> String {
match failure.condition {
Some(condition) => format!("`{}` when {condition}", failure.class),
None => format!("`{}`", failure.class),
}
}
fn render_runtime_call_arity(arity: RuntimeCallArity) -> String {
match arity.max {
Some(max) if max == arity.min => format!("{}", arity.min),
Some(max) => format!("{}..={max}", arity.min),
None => format!("{}..", arity.min),
}
}
#[derive(Debug, Clone, Serialize)]
struct JsFfiQueryInfo {
target: Option<String>,
owner_module: Option<String>,
owner_version: Option<String>,
module_root: Option<String>,
source_kind: Option<&'static str>,
source_file: Option<String>,
modules: BTreeMap<String, String>,
metadata_error: Option<String>,
}
fn special_builtin_dynamic_fn(arg_types: Vec<Arc<CalcitTypeAnnotation>>) -> Arc<CalcitTypeAnnotation> {
Arc::new(CalcitTypeAnnotation::from_function_parts(arg_types, DYNAMIC_TYPE.clone()))
}
fn parse_special_builtin_examples(snippets: &[&str]) -> Result<Vec<Cirru>, String> {
let mut examples = Vec::with_capacity(snippets.len());
for snippet in snippets {
let parsed = cirru_parser::parse(snippet).map_err(|e| format!("Failed to parse builtin example `{snippet}`: {e}"))?;
let Some(example) = parsed.into_iter().next() else {
return Err(format!("Builtin example is empty: {snippet}"));
};
examples.push(example);
}
Ok(examples)
}
fn lookup_special_builtin_query_meta(namespace: &str, definition: &str) -> Result<Option<SpecialBuiltinQueryMeta>, String> {
if namespace != calcit_core::calcit::CORE_NS {
return Ok(None);
}
let meta = match definition {
"to-calcit-data" => Some(SpecialBuiltinQueryMeta {
doc: "convert JS values recursively; optional second Bool noKeyword defaults to false (keyword text becomes Tag); true preserves String values and object keys; existing Calcit containers are unchanged",
schema: special_builtin_dynamic_fn(vec![DYNAMIC_TYPE.clone(), Arc::new(CalcitTypeAnnotation::Bool)]),
runtime_arity: Some(RuntimeCallArity { min: 1, max: Some(2) }),
examples: parse_special_builtin_examples(&[
"to-calcit-data $ js-array 1 ([] 2 3) (:: :quote $ [] 'a 'b)",
"to-calcit-data $ &js-object |a 1 |:b 2 :c ([] 3 4)",
"assert= ([] |:keyword) $ to-calcit-data (js-array |:keyword) true",
"assert= ([] :keyword) $ to-calcit-data (js-array |:keyword) false",
"assert= ([] :keyword) $ to-calcit-data $ js-array |:keyword",
])?,
expr_preview: "builtin proc to-calcit-data (JS interop helper)",
cirru_note: "(builtin proc; runtime helper without snapshot source)",
semantic_tags: &["js-ffi"],
}),
"to-js-data" => Some(SpecialBuiltinQueryMeta {
doc: "convert Calcit data into JS-compatible data recursively; JS FFI keeps value and options dynamically typed",
schema: special_builtin_dynamic_fn(vec![DYNAMIC_TYPE.clone(), DYNAMIC_TYPE.clone()]),
runtime_arity: None,
examples: parse_special_builtin_examples(&[
"to-js-data $ [] 1 2 3",
"to-js-data $ &{} |a 1 :b ([] 2 3)",
"to-js-data ([] 1 2 3) $ {} (:js-array true)",
])?,
expr_preview: "builtin proc to-js-data (JS interop helper)",
cirru_note: "(builtin proc; runtime helper without snapshot source)",
semantic_tags: &["js-ffi"],
}),
"to-cirru-edn" => Some(SpecialBuiltinQueryMeta {
doc: "convert Calcit data into Cirru EDN data",
schema: special_builtin_dynamic_fn(vec![DYNAMIC_TYPE.clone()]),
runtime_arity: None,
examples: vec![],
expr_preview: "builtin proc to-cirru-edn (data conversion helper)",
cirru_note: "(builtin proc; runtime helper without snapshot source)",
semantic_tags: &[],
}),
"extract-cirru-edn" => Some(SpecialBuiltinQueryMeta {
doc: "extract Cirru EDN data into regular Calcit values when possible",
schema: special_builtin_dynamic_fn(vec![DYNAMIC_TYPE.clone()]),
runtime_arity: None,
examples: vec![],
expr_preview: "builtin proc extract-cirru-edn (data conversion helper)",
cirru_note: "(builtin proc; runtime helper without snapshot source)",
semantic_tags: &[],
}),
"js-array" => Some(SpecialBuiltinQueryMeta {
doc: "build a JS array value in JS interop contexts",
schema: runner::preprocess::special_js_intrinsic_signature("js-array").expect("js-array intrinsic signature"),
runtime_arity: None,
examples: vec![],
expr_preview: "builtin proc js-array (JS interop helper)",
cirru_note: "(builtin proc; runtime helper without snapshot source)",
semantic_tags: &["js-ffi"],
}),
"&js-object" => Some(SpecialBuiltinQueryMeta {
doc: "build a plain JS object value in JS interop contexts",
schema: runner::preprocess::special_js_intrinsic_signature("&js-object").expect("&js-object intrinsic signature"),
runtime_arity: None,
examples: vec![],
expr_preview: "builtin proc &js-object (JS interop helper)",
cirru_note: "(builtin proc; runtime helper without snapshot source)",
semantic_tags: &["js-ffi"],
}),
_ => None,
};
Ok(meta)
}
fn query_schema_cirru(annotation: &CalcitTypeAnnotation, wrapped: bool) -> Result<Option<Cirru>, String> {
if wrapped
&& !matches!(annotation, CalcitTypeAnnotation::Dynamic)
&& let Some(compact) = snapshot::compact_type_display(&query_schema_edn(annotation, wrapped))
{
return Ok(Some(compact));
}
canonical_schema_cirru(annotation, wrapped)
}
fn definition_schema_cirru(schema: &Arc<CalcitTypeAnnotation>, wrapped: bool) -> Result<Option<Cirru>, String> {
match schema.as_ref() {
CalcitTypeAnnotation::Dynamic if !snapshot::schema_annotation_is_missing(schema) => Ok(Some(Cirru::Leaf("Dynamic".into()))),
annotation => query_schema_cirru(annotation, wrapped),
}
}
fn query_schema_edn(annotation: &CalcitTypeAnnotation, wrapped: bool) -> cirru_edn::Edn {
match annotation {
CalcitTypeAnnotation::Fn(fn_annot) if wrapped => fn_annot.to_wrapped_schema_edn(),
CalcitTypeAnnotation::Fn(fn_annot) => fn_annot.to_schema_edn(),
CalcitTypeAnnotation::Macro(signature) => signature.to_wrapped_schema_edn(),
other => other.to_type_edn(),
}
}
fn canonical_schema_cirru(annotation: &CalcitTypeAnnotation, wrapped: bool) -> Result<Option<Cirru>, String> {
if matches!(annotation, CalcitTypeAnnotation::Dynamic) {
return Ok(None);
}
let schema_edn = query_schema_edn(annotation, wrapped);
snapshot::schema_edn_to_cirru(&schema_edn).map(|cirru| {
let normalized = match cirru {
Cirru::List(items) if items.len() == 2 && matches!(items.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "do") => {
items[1].clone()
}
other => other,
};
Some(normalized)
})
}
fn normalize_single_schema_display(text: String) -> String {
let trimmed = text.trim();
trimmed.strip_prefix("do ").unwrap_or(trimmed).to_owned()
}
fn format_query_schema_oneline(cirru: &Cirru) -> Result<String, String> {
match cirru {
Cirru::Leaf(value) => Ok(value.to_string()),
Cirru::List(_) => cirru.format_one_liner().map(normalize_single_schema_display),
}
}
fn format_query_schema(annotation: &CalcitTypeAnnotation, wrapped: bool) -> String {
format_schema_display(query_schema_cirru(annotation, wrapped))
}
fn format_schema_display(schema: Result<Option<Cirru>, String>) -> String {
match schema {
Ok(Some(Cirru::Leaf(value))) => value.to_string(),
Ok(Some(cirru @ Cirru::List(_))) => cirru_parser::format(std::slice::from_ref(&cirru), true.into())
.map(normalize_single_schema_display)
.unwrap_or_else(|_| "(failed to format)".to_string()),
Ok(None) => "(none)".to_string(),
Err(error) => format!("(schema error: {error})"),
}
}
fn format_schema_query_json(
id: &str,
source: &str,
annotation: &CalcitTypeAnnotation,
revision: String,
runtime_arity: Option<RuntimeCallArity>,
) -> Result<String, String> {
format_schema_cirru_query_json(id, source, query_schema_cirru(annotation, true)?, revision, runtime_arity)
}
fn intrinsic_checker_rules(namespace: &str, definition: &str, schema: &CalcitTypeAnnotation) -> Option<&'static [&'static str]> {
if namespace != calcit_core::calcit::CORE_NS {
return None;
}
match schema {
CalcitTypeAnnotation::Fn(signature) if signature.open_reason.0 == Some(calcit_core::calcit::FnOpenReason::Intrinsic) => {
calcit_core::runner::preprocess::intrinsic_rule_summary(definition)
}
_ => None,
}
}
fn write_intrinsic_checker_rules(out: &mut String, rules: &[&str]) {
let _ = writeln!(
out,
"\n## Checker rules\n\nThe schema keeps the open shape the runtime accepts; the checker decides the types per receiver:\n"
);
for rule in rules {
let _ = writeln!(out, "- `{rule}`");
}
}
fn schema_cases_lines(schema: &CalcitTypeAnnotation) -> Result<Option<Vec<String>>, String> {
let CalcitTypeAnnotation::Fn(signature) = schema else {
return Ok(None);
};
if signature.cases.is_empty() {
return Ok(None);
}
let mut lines = Vec::with_capacity(signature.cases.len());
for case in signature.cases.iter() {
let case_annotation = CalcitTypeAnnotation::Fn(case.clone());
if let Some(cirru) = query_schema_cirru(&case_annotation, true)? {
lines.push(format_query_schema_oneline(&cirru)?);
}
}
Ok((!lines.is_empty()).then_some(lines))
}
fn write_schema_cases(out: &mut String, cases: &[String]) {
let _ = writeln!(out, "\n## Cases\n");
for case in cases {
let _ = writeln!(out, "- `{case}`");
}
}
fn format_schema_cirru_query_json(
id: &str,
source: &str,
schema: Option<Cirru>,
revision: String,
runtime_arity: Option<RuntimeCallArity>,
) -> Result<String, String> {
let canonical_schema = schema.as_ref().map(format_query_schema_oneline).transpose()?;
let tree = schema.as_ref().map(cirru_to_json_value);
let mut envelope = serde_json::json!({
"schema_version": 1,
"command": "query.schema",
"revision": revision,
"data": {
"id": id,
"source": source,
"canonical_schema": canonical_schema,
"tree": tree,
},
"diagnostics": [],
});
if let Some(arity) = runtime_arity {
envelope["data"]["runtime_arity"] =
serde_json::to_value(arity).map_err(|error| format!("Failed to encode runtime arity: {error}"))?;
}
serde_json::to_string_pretty(&envelope).map_err(|error| format!("Failed to encode schema query JSON: {error}"))
}
fn detailed_window(detail_offset: usize, total: usize) -> (usize, usize) {
if total == 0 {
return (0, 0);
}
let start = detail_offset.min(total.saturating_sub(1));
let end = (start + DETAILED_RESULTS_WINDOW).min(total);
(start, end)
}
fn print_detail_window_hint(total: usize, detail_offset: usize, subject: &str) {
if total > DETAILED_RESULTS_WINDOW {
let (start, end) = detailed_window(detail_offset, total);
println!("Detail window for {subject}: [{start}, {end}) (detail-offset={detail_offset}); other entries are compressed.");
}
}
fn in_detail_window(index: usize, total: usize, detail_offset: usize) -> bool {
if total <= DETAILED_RESULTS_WINDOW {
return true;
}
let (start, end) = detailed_window(detail_offset, total);
index >= start && index < end
}
fn preview_node_oneline(node: &Cirru, max_len: usize) -> (String, bool) {
let text = match node {
Cirru::Leaf(s) => s.to_string(),
_ => node.format_one_liner().unwrap_or_default(),
};
if text.is_empty() {
return ("(matched)".to_string(), false);
}
match char_prefix_if_truncated(&text, max_len) {
Some(prefix) => (prefix.to_owned(), true),
None => (text, false),
}
}
fn is_token_delimiter(ch: Option<char>) -> bool {
ch.is_none_or(|c| c.is_whitespace() || matches!(c, '(' | ')' | '[' | ']' | '{' | '}' | '$' | ','))
}
fn highlight_target_text(text: &str, target: Option<&str>, loose: bool) -> String {
let Some(target) = target else {
return text.to_string();
};
if target.is_empty() || !text.contains(target) {
return text.to_string();
}
if loose {
return text.replace(target, &format!("{}", target.bright_yellow().bold()));
}
let mut highlighted = String::with_capacity(text.len());
let mut last_index = 0;
for (idx, _) in text.match_indices(target) {
let prev_char = text[..idx].chars().next_back();
let next_char = text[idx + target.len()..].chars().next();
if is_token_delimiter(prev_char) && is_token_delimiter(next_char) {
highlighted.push_str(&text[last_index..idx]);
highlighted.push_str(&format!("{}", target.bright_yellow().bold()));
last_index = idx + target.len();
}
}
if last_index == 0 {
text.to_string()
} else {
highlighted.push_str(&text[last_index..]);
highlighted
}
}
fn path_parent(path: &[usize]) -> Option<Vec<usize>> {
if path.is_empty() {
None
} else {
Some(path[..path.len() - 1].to_vec())
}
}
fn get_node_at_path(code: &Cirru, path: &[usize]) -> Option<Cirru> {
if path.is_empty() {
return Some(code.clone());
}
let mut current = code;
for &idx in path {
match current {
Cirru::List(items) => current = items.get(idx)?,
Cirru::Leaf(_) => return None,
}
}
Some(current.clone())
}
fn count_nodes_limited(node: &Cirru, limit: usize) -> usize {
fn walk(node: &Cirru, acc: &mut usize, limit: usize) {
if *acc >= limit {
return;
}
*acc += 1;
if let Cirru::List(items) = node {
for item in items {
if *acc >= limit {
break;
}
walk(item, acc, limit);
}
}
}
let mut acc = 0;
walk(node, &mut acc, limit);
acc
}
fn can_show_parent_preview(expr_path: &[usize], parent_node: &Cirru) -> bool {
if expr_path.len() > 8 {
return false;
}
if let Cirru::List(items) = parent_node
&& items.len() > 8
{
return false;
}
count_nodes_limited(parent_node, 40) < 40
}
fn expression_and_parent_preview(
code: &Cirru,
match_path: &[usize],
matched_node: &Cirru,
highlight_target: Option<&str>,
loose: bool,
) -> ((String, bool), Vec<(String, bool)>) {
let expr_path = if matches!(matched_node, Cirru::Leaf(_)) {
path_parent(match_path).unwrap_or_else(|| match_path.to_vec())
} else {
match_path.to_vec()
};
let expr_node = get_node_at_path(code, &expr_path).unwrap_or_else(|| matched_node.clone());
let (expr_text, expr_truncated) = preview_node_oneline(&expr_node, 110);
let expr_preview = (highlight_target_text(&expr_text, highlight_target, loose), expr_truncated);
let mut parent_previews: Vec<(String, bool)> = Vec::new();
let mut current_path = expr_path;
for _ in 0..2 {
let Some(parent_path) = path_parent(¤t_path) else {
break;
};
let Some(parent_node) = get_node_at_path(code, &parent_path) else {
break;
};
if can_show_parent_preview(&parent_path, &parent_node) {
let (preview_text, preview_truncated) = preview_node_oneline(&parent_node, 110);
parent_previews.push((highlight_target_text(&preview_text, highlight_target, loose), preview_truncated));
}
current_path = parent_path;
}
(expr_preview, parent_previews)
}
fn parse_target(target: &str) -> Result<(&str, &str), String> {
target
.split_once('/')
.ok_or_else(|| format!("Invalid target format: '{target}'. Expected 'namespace/definition' (e.g. 'app.core/main')"))
}
fn resolve_search_cursor_references(
input_path: &str,
filter: &mut Option<String>,
start_path: &mut Option<String>,
) -> Result<(), String> {
if filter.as_deref() == Some("@cursor") || start_path.as_deref() == Some("@cursor") {
let (cursor_target, cursor_path) = resolve_active_cursor_reference(input_path)?;
if let Some(filter_target) = filter.as_deref()
&& filter_target != "@cursor"
&& filter_target != cursor_target
{
return Err(format!(
"Cursor-scoped search targets '{cursor_target}', but --filter targets '{filter_target}'. Omit --filter or use --filter @cursor."
));
}
*filter = Some(cursor_target);
if start_path.as_deref() == Some("@cursor") {
*start_path = Some(cursor_path);
}
}
Ok(())
}
fn resolve_query_cursor_references(cmd: &mut QueryCommand, input_path: &str) -> Result<(), String> {
match &mut cmd.subcommand {
QuerySubcommand::Def(opts) => opts.target = resolve_cursor_target_argument(input_path, &opts.target)?,
QuerySubcommand::Usages(opts) => opts.target = resolve_cursor_target_argument(input_path, &opts.target)?,
QuerySubcommand::Search(opts) => {
resolve_search_cursor_references(input_path, &mut opts.filter, &mut opts.start_path)?;
}
QuerySubcommand::SearchExpr(opts) => {
resolve_search_cursor_references(input_path, &mut opts.filter, &mut opts.start_path)?;
}
QuerySubcommand::Schema(opts) => opts.target = resolve_cursor_target_argument(input_path, &opts.target)?,
QuerySubcommand::Type(opts) => opts.target = resolve_cursor_target_argument(input_path, &opts.target)?,
QuerySubcommand::TypeAt(opts) => {
if opts.target == "@cursor" && opts.path == "@cursor" {
(opts.target, opts.path) = resolve_active_cursor_reference(input_path)?;
} else {
opts.target = resolve_cursor_target_argument(input_path, &opts.target)?;
opts.path = resolve_cursor_path_argument(input_path, &opts.target, &opts.path)?;
}
}
QuerySubcommand::Context(opts) => opts.target = resolve_cursor_target_argument(input_path, &opts.target)?,
QuerySubcommand::Ns(_)
| QuerySubcommand::Defs(_)
| QuerySubcommand::Config(_)
| QuerySubcommand::Error(_)
| QuerySubcommand::Find(_) => {}
}
Ok(())
}
fn structured_query_request(cmd: &QueryCommand) -> Option<(QueryRenderFormat, &'static str, &str)> {
let (raw_format, command, target) = match &cmd.subcommand {
QuerySubcommand::Type(opts) => (opts.format.as_str(), "query.type", opts.target.as_str()),
QuerySubcommand::TypeAt(opts) => (opts.format.as_str(), "query.type-at", opts.target.as_str()),
QuerySubcommand::Context(opts) => (opts.format.as_str(), "query.context", opts.target.as_str()),
QuerySubcommand::Def(opts) => (opts.format.as_str(), "query.def", opts.target.as_str()),
QuerySubcommand::Defs(opts) => (opts.format.as_str(), "query.defs", opts.namespace.as_str()),
QuerySubcommand::Search(opts) => (opts.format.as_str(), "query.search", opts.pattern.as_str()),
QuerySubcommand::SearchExpr(opts) => (opts.format.as_str(), "query.search-expr", opts.pattern.as_str()),
_ => return None,
};
match parse_query_render_format(raw_format).ok()? {
QueryRenderFormat::Human => None,
format => Some((format, command, target)),
}
}
fn query_failure_code(command: &str, error: &str) -> &'static str {
let legacy_tag = format!("[{}]", snapshot::LEGACY_TYPE_SYNTAX_CODE);
if error.starts_with(&legacy_tag) || (error.starts_with("Failed to load Snapshot ") && error.contains(&legacy_tag)) {
snapshot::LEGACY_TYPE_SYNTAX_CODE
} else if command == "query.type" && (error.starts_with("Unknown builtin type") || error.contains("Failed to parse type")) {
"E_QUERY_INVALID_TYPE"
} else if error.starts_with("Path index") || error.starts_with("Invalid path") || error.starts_with("Invalid start path") {
"E_QUERY_INVALID_PATH"
} else if error.contains("not found") || error.contains("does not exist") {
"E_QUERY_TARGET_NOT_FOUND"
} else if error.contains("preprocess") || error.contains("compile") {
"E_QUERY_PREPROCESS"
} else {
"E_QUERY_FAILED"
}
}
fn query_failure_envelope(command: &str, target: &str, error: &str) -> serde_json::Value {
serde_json::json!({
"schema_version": if command == "query.type-at" { TYPE_AT_SCHEMA_VERSION } else { 1 },
"command": command,
"revision": null,
"data": null,
"diagnostics": [{
"code": query_failure_code(command, error),
"phase": "query",
"severity": "error",
"message": error,
"path": null,
"intent": null,
"provenance": [],
"target": target,
}],
"next": [],
})
}
pub fn handle_query_command(cmd: &QueryCommand, input_path: &str, entry: Option<&str>) -> Result<(), String> {
let result = handle_query_command_inner(cmd, input_path, entry);
if let Err(error) = &result
&& let Some((format, command, target)) = structured_query_request(cmd)
{
let envelope = query_failure_envelope(command, target, error);
emit_query_structured(&envelope, format, "query failure")?;
}
result
}
fn validate_query_entry(input_path: &str, entry: Option<&str>) -> Result<(), String> {
if entry.is_none() {
return Ok(());
}
load_main_snapshot(input_path)?.select_entry(entry)
}
fn handle_query_command_inner(cmd: &QueryCommand, input_path: &str, entry: Option<&str>) -> Result<(), String> {
let mut resolved = cmd.clone();
resolve_query_cursor_references(&mut resolved, input_path)?;
validate_query_entry(input_path, entry)?;
match &resolved.subcommand {
QuerySubcommand::Ns(opts) => match (opts.format.as_str(), opts.namespace.as_deref()) {
("cirru", Some(namespace)) => handle_ns_cirru_view(input_path, namespace, entry),
("cirru", None) => Err("`query ns --format cirru` needs a namespace: `query ns <namespace> --format cirru`".to_owned()),
(raw, namespace) => {
let format = StructuredOutputFormat::parse(raw, "query ns")
.map_err(|_| format!("Unsupported query ns format '{raw}'. Expected human, edn, json, or cirru."))?;
handle_ns(input_path, namespace, opts.deps, format, entry)
}
},
QuerySubcommand::Defs(opts) => handle_defs(input_path, opts, entry),
QuerySubcommand::Config(opts) => handle_config(input_path, opts),
QuerySubcommand::Error(_) => handle_error(input_path),
QuerySubcommand::Def(opts) => {
let (ns, def) = parse_target(&opts.target)?;
handle_def(input_path, ns, def, opts, entry)
}
QuerySubcommand::Find(opts) => {
if opts.exact {
handle_find(input_path, &opts.symbol, opts.deps, opts.detail_offset, entry)
} else {
handle_fuzzy_search(input_path, &opts.symbol, opts.deps, opts.limit, opts.detail_offset, entry)
}
}
QuerySubcommand::Usages(opts) => {
let (ns, def) = parse_target(&opts.target)?;
handle_usages(input_path, ns, def, opts.deps, opts.detail_offset, entry)
}
QuerySubcommand::Search(opts) => {
let common_opts = SearchCommonOpts {
filter: opts.filter.as_deref(),
loose: !opts.exact,
regex: opts.regex,
max_depth: opts.max_depth,
entry: opts.entry.as_deref().or(entry),
source: SearchSource::parse(&opts.source)?,
detail_offset: opts.detail_offset,
parent_path: opts.parent_path,
format: parse_query_render_format(&opts.format)?,
set_cursor: opts.set_cursor,
compact_output: false,
};
handle_search_leaf(input_path, &opts.pattern, opts.start_path.as_deref(), &common_opts)
}
QuerySubcommand::SearchExpr(opts) => {
let common_opts = SearchCommonOpts {
filter: opts.filter.as_deref(),
loose: !opts.exact,
regex: false,
max_depth: opts.max_depth,
entry: opts.entry.as_deref().or(entry),
source: SearchSource::All,
detail_offset: opts.detail_offset,
parent_path: false,
format: parse_query_render_format(&opts.format)?,
set_cursor: opts.set_cursor,
compact_output: false,
};
handle_search_expr(input_path, &opts.pattern, opts.json, opts.start_path.as_deref(), &common_opts)
}
QuerySubcommand::Schema(opts) => {
let (ns, def) = parse_target(&opts.target)?;
let format = StructuredOutputFormat::parse(&opts.format, "query schema")?;
handle_schema(input_path, ns, def, format, entry)
}
QuerySubcommand::Type(opts) => handle_type(input_path, opts, entry),
QuerySubcommand::TypeAt(opts) => handle_type_at(input_path, opts, entry),
QuerySubcommand::Context(opts) => handle_context(input_path, opts, entry),
}
}
pub fn prepare_program_for_type_query(snapshot: &snapshot::Snapshot) -> Result<(), String> {
program::clear_runtime_caches_for_reload(Arc::from("query.type"), Arc::from("query.type"), true)?;
{
let mut program_data = program::PROGRAM_CODE_DATA
.write()
.map_err(|_| "Failed to open program data".to_owned())?;
*program_data = program::extract_program_data(snapshot)?;
}
let warnings = RefCell::<Vec<LocatedWarning>>::new(vec![]);
runner::preprocess::ensure_ns_def_compiled(
calcit_core::calcit::CORE_NS,
calcit_core::calcit::BUILTIN_IMPLS_ENTRY,
&warnings,
&CallStackList::default(),
)
.map_err(|error| error.msg)
}
fn parse_type_annotation_query(target: &str) -> Result<Arc<CalcitTypeAnnotation>, String> {
const LEGACY_SIMPLE_TYPES: &[&str] = &[
"bool",
"number",
"string",
"symbol",
"tag",
"list",
"map",
"set",
"tuple",
"fn",
"ref",
"buffer",
"cirru-quote",
"unit",
"nil",
"js-object",
"dynamic",
];
let trimmed = target.trim();
if trimmed.is_empty() {
return Err("Type query cannot be empty".to_owned());
}
if matches!(trimmed.trim_start_matches('\''), "any" | ":any") {
return Err(format!(
"[{}] `{trimmed}` is retired; `:any` is no longer a valid type alias. Use `Dynamic` only for genuinely dynamic boundaries, or use `:generics`/TypeVar or trait `:where` for polymorphism.",
snapshot::LEGACY_TYPE_SYNTAX_CODE,
));
}
if trimmed.starts_with('(') {
return Err(format!(
"Type annotation `{target}` has an extra outer parenthesis layer. Use Cirru directly, for example `List Number`."
));
}
if !trimmed.chars().any(char::is_whitespace) {
let is_quoted_symbol = trimmed.starts_with('\'');
let name = trimmed.strip_prefix(':').or_else(|| trimmed.strip_prefix('\'')).unwrap_or(trimmed);
let is_legacy_type_name = LEGACY_SIMPLE_TYPES.contains(&name);
let is_builtin_type_symbol = (is_quoted_symbol || !trimmed.starts_with(':'))
&& !name.starts_with(':')
&& !name.starts_with('\'')
&& CalcitTypeAnnotation::canonical_type_symbol_name(name).is_some()
&& !matches!(name, "Optional" | "JsNullish" | "Variadic" | "Dyn");
if !is_legacy_type_name && !is_builtin_type_symbol {
return Err(format!(
"Unknown builtin type `{target}`. Use a builtin type name such as `Number`, a type expression such as `List Number`, or `namespace/definition`."
));
}
return Ok(Arc::new(CalcitTypeAnnotation::from_tag_name(name)));
}
let nodes = cirru_parser::parse(trimmed).map_err(|error| format!("Failed to parse type annotation `{target}`: {error}"))?;
if nodes.len() != 1 {
return Err(format!("Type annotation must contain exactly one expression, got {}", nodes.len()));
}
let node = match &nodes[0] {
Cirru::List(items)
if matches!(items.first(), Some(Cirru::Leaf(head))
if head.rsplit('/').next().is_some_and(|name| name.starts_with(|c: char| c.is_ascii_uppercase()))) =>
{
Cirru::List(vec![Cirru::leaf("quote"), nodes[0].clone()])
}
other => other.clone(),
};
let form = code_to_calcit(&node, "query.type", "target", vec![])?;
if snapshot::find_legacy_any_in_type(&node).is_some() {
return Err(format!(
"[{}] `{target}` uses retired `:any` type syntax; write `Dynamic` only for genuinely dynamic boundaries, or use `:generics`/TypeVar or trait `:where` for polymorphism.",
snapshot::LEGACY_TYPE_SYNTAX_CODE,
));
}
if let Some(error) = calcit_core::calcit::compact_type_syntax_error(&form) {
return Err(format!("Invalid type expression `{target}`: {error}"));
}
Ok(CalcitTypeAnnotation::parse_type_annotation_form(&form))
}
#[cfg(test)]
#[allow(clippy::items_after_test_module)]
mod type_query_tests {
use super::*;
use crate::cli_handlers::test_support::TestProject;
#[test]
fn untyped_signatures_keep_parameters_but_not_values() {
let signature = |source: &str| {
let code = cirru_parser::parse(source).expect("parse").remove(0);
definition_signature(&snapshot::CodeEntry::from_code(code))
};
assert_eq!(signature("defn helper (x y) (+ x y)"), "(untyped) defn helper $ x y");
assert_eq!(signature("defcomp comp-item (item) (div)"), "(untyped) defcomp comp-item $ item");
assert_eq!(signature("defref *store ({} (:count 0))"), "(untyped) defref *store");
assert_eq!(signature("def config ([] 1 2)"), "(untyped) def config");
}
#[test]
fn runtime_call_arity_uses_core_proc_values_not_schema_or_spelling_guesses() {
let snapshot = load_core_snapshot().expect("core snapshot");
let core = &snapshot.files["calcit.core"];
for (name, min, max) in [("read-dir", 1, 2), ("read-file", 1, 1), ("trim", 1, 2), ("range", 1, 3)] {
let entry = &core.defs[name];
let arity = core_runtime_call_arity("calcit.core", name, entry).expect("registered runtime Proc");
assert_eq!(arity, RuntimeCallArity { min, max: Some(max) });
assert_eq!(serde_json::to_value(arity).unwrap(), serde_json::json!({ "min": min, "max": max }));
assert!(
format_json_value_as_edn(&serde_json::to_value(arity).unwrap())
.unwrap()
.contains(":min")
);
assert!(core_runtime_call_arity("app.main", name, entry).is_none());
}
assert!(core_runtime_call_arity("calcit.core", "to-string", &core.defs["to-string"]).is_none());
let mut renamed = core.defs["read-dir"].clone();
renamed.schema = DYNAMIC_TYPE.clone();
assert_eq!(
core_runtime_call_arity("calcit.core", "unrelated-name", &renamed),
Some(RuntimeCallArity { min: 1, max: Some(2) })
);
renamed.code = Cirru::Leaf("&runtime-implementation".into());
renamed.tags.clear();
assert!(core_runtime_call_arity("calcit.core", "read-dir", &renamed).is_none());
renamed.code = Cirru::List(vec![Cirru::Leaf("&read-dir".into())]);
assert!(
core_runtime_call_arity("calcit.core", "read-dir", &renamed).is_none(),
"a call expression is not a Proc value"
);
assert_eq!(render_runtime_call_arity(RuntimeCallArity { min: 1, max: Some(2) }), "1..=2");
assert_eq!(render_runtime_call_arity(RuntimeCallArity { min: 1, max: None }), "1..");
}
#[test]
fn definition_ffi_json_is_complete_and_round_trips() {
use cirru_edn::{Edn, EdnMapView};
let mut names = EdnMapView::default();
for index in 0..300 {
names.insert(Edn::tag(format!("member-{index}")), Edn::str(format!("宿主\\\"\n{index}")));
}
let mut ffi = EdnMapView::default();
ffi.insert(Edn::tag("names"), names.into());
let ffi: Edn = ffi.into();
let mut entry = snapshot::CodeEntry::from_code(vec!["def", "example", "nil"].into());
entry.ffi = Some(ffi.clone());
let legacy = code_entry_to_json(&entry).unwrap();
let full = legacy["ffi"].as_str().unwrap();
assert!(full.len() > 5000);
assert_eq!(cirru_edn::parse(full).unwrap(), ffi);
assert_ne!(format_edn_display(&ffi), full);
let structured = serde_json::to_value(&ffi).unwrap();
assert_eq!(structured[":names"].as_object().unwrap().len(), 300);
assert_eq!(structured[":names"][":member-299"], "宿主\\\"\n299");
let encoded = format_def_query_json(structured.clone(), Some(snapshot::definition_revision(&entry).unwrap())).unwrap();
let decoded: serde_json::Value = serde_json::from_str(&encoded).unwrap();
assert_eq!(decoded["data"], structured);
assert_eq!(decoded["command"], "query.def");
entry.ffi = None;
assert!(code_entry_to_json(&entry).unwrap()["ffi"].is_null());
}
fn on_cli_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
std::thread::Builder::new()
.name("calcit-query-test".into())
.stack_size(16 * 1024 * 1024)
.spawn(f)
.expect("query test thread should start")
.join()
.expect("query test thread should finish")
}
fn prepare_program_for_type_query_on_cli_stack(snapshot: snapshot::Snapshot) {
on_cli_stack(move || prepare_program_for_type_query(&snapshot)).expect("static type metadata should prepare");
}
#[test]
fn helper_analysis_does_not_leak_strict_compilation_cache() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
on_cli_stack(|| {
let snapshot = load_snapshot_for_static_analysis(
concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/test-helper-inference.cirru"),
None,
)
.expect("helper fixture");
let strict = runner::preprocess::is_strict_types_enabled();
let effective =
crate::type_coverage::with_proven_helper_contracts(&snapshot, Some("app.main"), None, false).expect("helper analysis");
assert!(matches!(
effective.files["app.main"].defs["helper-count"].schema.as_ref(),
CalcitTypeAnnotation::Fn(_)
));
assert_eq!(runner::preprocess::is_strict_types_enabled(), strict);
assert!(program::lookup_compiled_def("app.main", "helper-count").is_none());
assert!(program::lookup_compiled_def(calcit_core::calcit::CORE_NS, calcit_core::calcit::BUILTIN_IMPLS_ENTRY).is_none());
});
}
#[test]
fn parses_simple_type_tag_without_treating_it_as_a_call() {
let annotation = parse_type_annotation_query(":number").expect("number type should parse");
assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::Number));
}
#[test]
fn parses_canonical_builtin_type_symbol_without_treating_it_as_a_type_variable() {
let annotation = parse_type_annotation_query("'String").expect("String type symbol should parse");
assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::String));
}
#[test]
fn unknown_builtin_type_suggests_canonical_symbols() {
let annotation = parse_type_annotation_query("String").expect("bare builtin name reads like the compact syntax");
assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::String));
let error = parse_type_annotation_query("Banana").expect_err("unknown bare name should be rejected");
assert_eq!(
error,
"Unknown builtin type `Banana`. Use a builtin type name such as `Number`, a type expression such as `List Number`, or `namespace/definition`."
);
}
#[test]
fn parses_bare_compact_type_expressions() {
let annotation = parse_type_annotation_query("Map String (List Number)").expect("compact map type should parse");
assert_eq!(
format_type_query_annotation(annotation.as_ref()).expect("map should format"),
"Map String $ List Number"
);
let error = parse_type_annotation_query("Fn Number").expect_err("Fn without a return clause should be rejected");
assert!(error.contains("return clause"), "unexpected error: {error}");
let error = parse_type_annotation_query("List Number String").expect_err("surplus type arguments should be rejected");
assert!(error.contains("takes 1 type argument"), "unexpected error: {error}");
let annotation = parse_type_annotation_query("calcit.core/Option Number").expect("qualified compact head should parse");
assert_eq!(
format_type_query_annotation(annotation.as_ref()).expect("option should format"),
"calcit.core/Option Number"
);
for name in ["Optional", "'Optional", "JsNullish", "Variadic"] {
assert!(parse_type_annotation_query(name).is_err(), "{name} needs a payload");
}
}
#[test]
fn rejects_excess_type_symbol_prefixes() {
assert!(parse_type_annotation_query("''String").is_err());
assert!(parse_type_annotation_query("':String").is_err());
}
#[test]
fn rejects_retired_any_type_query() {
for target in [":any", "any", "'any", "List :any"] {
let error = parse_type_annotation_query(target).expect_err(&format!("{target} must be rejected"));
assert!(error.contains("E_LEGACY_TYPE_SYNTAX"), "{target}: {error}");
let envelope = query_failure_envelope("query.type", target, &error);
assert_eq!(envelope["diagnostics"][0]["code"], "E_LEGACY_TYPE_SYNTAX", "{target}: {error}");
}
for target in ["Dynamic", ":dynamic", "'Dynamic"] {
let annotation = parse_type_annotation_query(target).expect("Dynamic should parse");
assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::Dynamic));
}
let boxed = parse_type_annotation_query("Any").expect("Any should parse");
assert!(matches!(boxed.as_ref(), CalcitTypeAnnotation::Any));
}
#[test]
fn context_query_failure_preserves_legacy_type_syntax_code_on_snapshot_load() {
let project = TestProject::from_fixture();
fs::write(
&project.path,
r#"{} (:package |mini)
:version |0.0.0
:entries $ {}
:default $ {} (:mode :native) (:init-fn |mini/main!) (:reload-fn |mini/main!)
:modules $ []
:files $ {}
|mini $ %{} :FileEntry
:ns $ %{} :CodeEntry (:doc |) (:code $ quote (ns mini)) (:examples $ []) (:schema nil)
:defs $ {}
|main! $ %{} :CodeEntry (:doc |)
:code $ quote (def main! 1)
:examples $ []
:schema :any
"#,
)
.expect("write fixture");
let error = handle_context(
project.path.to_str().expect("utf-8 fixture path"),
&QueryContextCommand {
target: "mini/main!".to_owned(),
budget: 2400,
format: "json".to_owned(),
deps: false,
dependency_limit: 12,
usage_limit: 8,
example_limit: 3,
test_limit: 3,
include_core: false,
},
None,
)
.expect_err("snapshot with :schema :any must fail");
let envelope = query_failure_envelope("query.context", "mini/main!", &error);
assert_eq!(envelope["diagnostics"][0]["code"], "E_LEGACY_TYPE_SYNTAX", "{error}");
}
#[test]
fn parses_compound_type_with_cirru_structure() {
let annotation = parse_type_annotation_query(":: :list :number").expect("compound list type should parse");
assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::List(inner) if matches!(inner.as_ref(), CalcitTypeAnnotation::Number)));
let annotation = parse_type_annotation_query(":: 'List 'Number").expect("canonical compound list type should parse");
assert!(matches!(annotation.as_ref(), CalcitTypeAnnotation::List(inner) if matches!(inner.as_ref(), CalcitTypeAnnotation::Number)));
}
#[test]
fn rejects_extra_outer_parenthesis_layer() {
let error = parse_type_annotation_query("(:: :list :number)").expect_err("extra call layer should be rejected");
assert!(error.contains("extra outer parenthesis"));
}
#[test]
fn renders_type_annotations_without_edn_top_level_wrapper() {
assert_eq!(
format_type_query_annotation(&CalcitTypeAnnotation::Number).expect("number should format"),
"Number"
);
let list_type = CalcitTypeAnnotation::List(Arc::new(CalcitTypeAnnotation::Number));
assert_eq!(format_type_query_annotation(&list_type).expect("list should format"), "List Number");
assert_eq!(
format_query_schema(&CalcitTypeAnnotation::Ref(DYNAMIC_TYPE.clone(), Default::default()), true),
"Ref"
);
}
#[test]
fn schema_json_is_a_versioned_machine_readable_envelope() {
let annotation = CalcitTypeAnnotation::Ref(Arc::new(CalcitTypeAnnotation::Bool), Default::default());
let output = format_schema_query_json("app.main/*enabled?", "local", &annotation, "revision-1".to_owned(), None)
.expect("schema JSON should format");
let value: serde_json::Value = serde_json::from_str(&output).expect("schema output should be valid JSON");
assert_eq!(value["schema_version"], 1);
assert_eq!(value["command"], "query.schema");
assert_eq!(value["data"]["id"], "app.main/*enabled?");
assert_eq!(value["data"]["canonical_schema"], "Ref Bool");
assert_eq!(value["data"]["tree"], serde_json::json!(["Ref", "Bool"]));
let broad_ref = CalcitTypeAnnotation::Ref(DYNAMIC_TYPE.clone(), Default::default());
let output = format_schema_query_json("app.main/*cache", "local", &broad_ref, "revision-2".to_owned(), None)
.expect("broad ref JSON should format");
let value: serde_json::Value = serde_json::from_str(&output).expect("schema output should be valid JSON");
assert_eq!(value["data"]["canonical_schema"], "Ref");
assert_eq!(value["data"]["tree"], "Ref");
}
#[test]
fn strict_macro_schema_queries_preserve_phase_contracts() {
let schema = cirru_parser::parse(
":: 'Macro\n {} (:required $ [] 'SyntaxList)\n :rest 'Syntax\n :expansion $ :: 'Expr 'Dynamic\n :capabilities $ #{}",
)
.expect("strict macro schema syntax")
.into_iter()
.next()
.expect("schema node");
let annotation = snapshot::parse_schema_annotation_for_write(&schema).expect("strict macro schema");
let displayed = format_query_schema(annotation.as_ref(), true);
assert_eq!(displayed, "Macro SyntaxList (& Syntax)\n -> $ Expr Dynamic");
assert_eq!(
context_schema(annotation.as_ref()).expect("context schema"),
Some(displayed.trim().to_owned())
);
let output = format_schema_query_json(
"app.main/with-bindings",
"project",
annotation.as_ref(),
"revision-1".to_owned(),
None,
)
.expect("macro schema JSON");
let value: serde_json::Value = serde_json::from_str(&output).expect("schema output should be valid JSON");
assert_eq!(value["data"]["tree"][0], "Macro");
}
#[test]
fn examples_render_leaf_nodes_without_formatter_failure() {
assert_eq!(format_example_node(&Cirru::Leaf("|literal".into())), "|literal");
assert_eq!(
format_example_node(&Cirru::List(vec![Cirru::Leaf("inc".into()), Cirru::Leaf("1".into())])),
"inc 1"
);
}
#[test]
fn search_results_share_cursor_indices_and_can_select_one() {
let fixture = TestProject::from_fixture();
let snapshot_path = fixture.snapshot_string();
let tail_path = format!("@{}.1", fixture.main_tail);
let results = vec![(
"app.main".to_string(),
"main!".to_string(),
vec![
(vec![fixture.main_tail, 0], Cirru::leaf("do")),
(vec![fixture.main_tail, 1], Cirru::leaf("true")),
],
)];
let saved_query = CursorLastQuery {
command: "search".to_string(),
pattern: "true".to_string(),
filter: Some("app.main/main!".to_string()),
exact: true,
regex: false,
max_depth: 0,
start_path: None,
entry: None,
source: "project".to_string(),
pattern_is_json: false,
selected_index: 1,
snapshot_revision: snapshot_content_revision(&snapshot_path).expect("snapshot revision should compute"),
};
maybe_set_cursor_from_search_results(&snapshot_path, &results, 1, saved_query.clone())
.expect("second search result should become cursor");
assert_eq!(
crate::cli_handlers::cursor::resolve_cursor_path_argument(&snapshot_path, "app.main/main!", "@cursor")
.expect("query-selected cursor should resolve"),
tail_path.as_str()
);
let mut filter = None;
let mut start_path = Some("@cursor".to_string());
resolve_search_cursor_references(&snapshot_path, &mut filter, &mut start_path)
.expect("cursor-scoped search should infer target and path");
assert_eq!(filter.as_deref(), Some("app.main/main!"));
assert_eq!(start_path.as_deref(), Some(tail_path.as_str()));
let mut type_at = QueryCommand {
subcommand: QuerySubcommand::TypeAt(QueryTypeAtCommand {
target: "@cursor".to_string(),
path: "@cursor".to_string(),
format: "json".to_string(),
}),
};
resolve_query_cursor_references(&mut type_at, &snapshot_path).expect("type-at should resolve cursor target and path");
let QuerySubcommand::TypeAt(type_at) = type_at.subcommand else {
panic!("type-at command should remain type-at")
};
assert_eq!(type_at.target, "app.main/main!");
assert_eq!(type_at.path, tail_path);
let mut mismatched_filter = Some("app.other/demo".to_string());
let mut cursor_start = Some("@cursor".to_string());
let error = resolve_search_cursor_references(&snapshot_path, &mut mismatched_filter, &mut cursor_start)
.expect_err("cursor search should reject mismatched target");
assert!(error.contains("Cursor-scoped search targets"), "error: {error}");
let error = maybe_set_cursor_from_search_results(&snapshot_path, &results, 2, saved_query)
.expect_err("out-of-range search cursor index should fail");
assert!(error.contains("returned 2 match"), "error: {error}");
let snapshot = load_main_snapshot(&snapshot_path).expect("query cursor fixture should load");
let options = SearchCommonOpts {
filter: Some("app.main/main!"),
loose: false,
regex: false,
max_depth: 0,
entry: None,
source: SearchSource::Project,
detail_offset: 0,
parent_path: false,
format: QueryRenderFormat::Json,
set_cursor: None,
compact_output: false,
};
let sources = snapshot_search_sources(&snapshot, SearchSource::Project, None);
let catalog = SearchCatalog { snapshot, sources };
let output =
format_search_results_json("query.search", "true", false, None, &options, &catalog, &results).expect("search JSON should format");
let value: serde_json::Value = serde_json::from_str(&output).expect("search output should be valid JSON");
assert_eq!(value["data"]["filters"]["source"], "project");
assert_eq!(value["data"]["definitions"][0]["source"], "project");
assert_eq!(value["data"]["definitions"][0]["origin"]["package"], "app");
assert_eq!(value["data"]["definitions"][0]["matches"][0]["cursor_index"], 0);
assert_eq!(value["data"]["definitions"][0]["matches"][0]["node_kind"], "call");
assert_eq!(value["data"]["definitions"][0]["matches"][1]["cursor_index"], 1);
assert_eq!(value["data"]["definitions"][0]["matches"][1]["node_kind"], "leaf");
}
#[test]
fn number_type_query_uses_static_dispatch_metadata() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot = load_core_snapshot().expect("core snapshot should load");
prepare_program_for_type_query_on_cli_stack(snapshot);
let methods = runner::preprocess::static_method_descriptors(&CalcitTypeAnnotation::Number)
.expect("number method metadata should resolve")
.into_iter()
.map(|method| method.name)
.collect::<Vec<_>>();
assert_eq!(
methods,
vec![
".ceil",
".compare",
".display-by",
".empty",
".floor",
".format",
".fract",
".inc",
".integer?",
".negate",
".pow",
".rem",
".round",
".sqrt",
".debug",
".eq?",
".hash",
".add",
".multiply",
".to-string",
]
);
let integer = runner::preprocess::static_method_contracts(&CalcitTypeAnnotation::Number)
.expect("number method contracts should resolve")
.into_iter()
.find(|(method, _)| method.name == ".integer?")
.map(|(method, contract)| context_method(method, contract))
.expect("integer predicate should be discoverable");
assert_eq!(integer.status, "proven");
assert_eq!(integer.parameter_types, Some(vec![]));
assert_eq!(integer.return_type.as_deref(), Some("bool"));
assert_eq!(integer.definition.as_deref(), Some("calcit.core/integer?"));
let retired = runner::preprocess::static_method_contract(&CalcitTypeAnnotation::Number, ".round?");
assert_ne!(retired.status, "proven", "the retired `.round?` alias is no longer a Number method");
}
#[test]
fn originless_enum_methods_are_not_reported_as_strict_callable() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot = load_core_snapshot().expect("core snapshot should load");
prepare_program_for_type_query_on_cli_stack(snapshot);
let contracts =
runner::preprocess::static_method_contracts(&CalcitTypeAnnotation::AnonymousEnum).expect("enum methods should resolve");
let status_of = |name: &str| {
contracts
.iter()
.find(|(method, _)| method.name == name)
.map(|(_, contract)| contract.clone())
.unwrap_or_else(|| panic!("enum method {name} should be discoverable"))
};
let assoc = status_of(".assoc");
assert_eq!(assoc.status, "open", "{assoc:?}");
let detail = assoc
.detail
.as_deref()
.expect("originless method should explain the strict rejection");
assert!(detail.contains("E_ORIGINLESS_METHOD_DISPATCH"), "{detail}");
assert!(detail.contains("`calcit.core/assoc`"), "{detail}");
assert_eq!(
runner::preprocess::static_method_contract(&CalcitTypeAnnotation::AnonymousEnum, ".assoc").status,
"open"
);
assert!(!runner::preprocess::core_function_accepts_receiver(
"trim",
&CalcitTypeAnnotation::AnonymousEnum
));
assert!(runner::preprocess::core_function_accepts_receiver(
"trim",
&CalcitTypeAnnotation::String
));
assert_eq!(status_of(".count").status, "proven");
}
#[test]
fn tuple_method_query_matches_trait_bound_checking() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot = load_core_snapshot().expect("core snapshot should load");
prepare_program_for_type_query_on_cli_stack(snapshot);
let homogeneous = parse_type_annotation_query("Tuple Number Number Number").expect("tuple should parse");
let add = runner::preprocess::static_method_contract(&homogeneous, ".add");
assert_eq!(add.status, "proven", "{add:?}");
let list_number = CalcitTypeAnnotation::List(Arc::new(CalcitTypeAnnotation::Number));
assert_eq!(add.return_type.as_deref(), Some(&list_number), "{add:?}");
assert!(
add
.arg_types
.as_ref()
.is_some_and(|args| args.iter().all(|arg| arg.as_ref() == &list_number)),
"{add:?}"
);
assert!(add.detail.as_deref().is_some_and(|detail| detail.contains("`Add`")), "{add:?}");
let heterogeneous = parse_type_annotation_query("Tuple Number String").expect("tuple should parse");
let add = runner::preprocess::static_method_contract(&heterogeneous, ".add");
assert_eq!(add.status, "open", "{add:?}");
assert_eq!(runner::preprocess::static_method_contract(&homogeneous, ".count").status, "proven");
}
#[test]
fn predicate_method_query_distinguishes_index_key_and_value_origins() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot = load_core_snapshot().expect("core snapshot should load");
prepare_program_for_type_query_on_cli_stack(snapshot);
let list = parse_type_annotation_query(":: 'List 'Number").expect("typed list should parse");
let string = CalcitTypeAnnotation::String;
for (receiver, definition) in [
(list.as_ref(), "calcit.core/&list:contains?"),
(&string, "calcit.core/&str:contains?"),
] {
let contract = runner::preprocess::static_method_contract(receiver, ".contains-index?");
assert_eq!(contract.status, "proven", "{contract:?}");
assert_eq!(contract.definition.as_deref(), Some(definition));
assert_eq!(contract.arg_types.unwrap()[0].describe(), "number");
assert_eq!(contract.return_type.unwrap().describe(), "bool");
}
let map = parse_type_annotation_query(":: 'Map 'String 'String").expect("same-type map should parse");
for (method, definition) in [
(".contains-key?", "calcit.core/&map:contains?"),
(".contains-value?", "calcit.core/&map:includes?"),
] {
let contract = runner::preprocess::static_method_contract(map.as_ref(), method);
assert_eq!(contract.status, "proven", "{contract:?}");
assert_eq!(contract.definition.as_deref(), Some(definition));
assert_eq!(contract.arg_types.unwrap()[0].describe(), "string");
assert_eq!(contract.return_type.unwrap().describe(), "bool");
}
}
#[test]
fn indexed_sequence_methods_expose_proven_agent_contracts() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot = load_core_snapshot().expect("core snapshot should load");
prepare_program_for_type_query_on_cli_stack(snapshot);
for (receiver, member, index_method) in [
(
parse_type_annotation_query(":: 'List 'Number").expect("typed list"),
"number",
".get",
),
(parse_type_annotation_query("'String").expect("string"), "string", ".nth"),
] {
for method in [".first", ".last", index_method] {
let contract = runner::preprocess::static_method_contract(receiver.as_ref(), method);
assert_eq!(contract.status, "proven", "{method}: {contract:?}");
assert_eq!(
contract.return_type.unwrap().describe(),
format!("type calcit.core/Option<{member}>")
);
let args = contract.arg_types.expect("proven method parameters");
assert_eq!(args.len(), usize::from(method == index_method));
if method == index_method {
assert_eq!(args[0].describe(), "number");
}
}
}
}
#[test]
fn structured_method_call_types_preserve_specialized_container_and_callback_nodes() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot = load_core_snapshot().expect("core snapshot should load");
prepare_program_for_type_query_on_cli_stack(snapshot);
let receiver = parse_type_annotation_query(":: 'List 'Number").expect("list type");
let get = runner::preprocess::static_method_contract(receiver.as_ref(), ".get");
let nodes = method_call_types(&get).expect("proven positional lookup should export nodes");
assert_eq!(nodes.parameters, vec![serde_json::json!("'Number")]);
assert_eq!(nodes.returns, serde_json::json!(["::", "'calcit.core/Option", "'Number"]));
assert!(nodes.rest.is_none());
let fold = runner::preprocess::static_method_contract(receiver.as_ref(), ".fold");
let nodes = method_call_types(&fold).expect("proven callback should export syntax nodes");
assert_eq!(nodes.parameters[0], serde_json::json!("'U"));
assert_eq!(nodes.parameters[1][0], "::");
assert_eq!(nodes.parameters[1][1], "'Fn");
assert_eq!(nodes.returns, serde_json::json!("'U"));
let open = runner::preprocess::static_method_contract(receiver.as_ref(), ".each");
assert_eq!(open.status, "open");
assert_eq!(
open.arg_types.as_ref().unwrap()[0].describe(),
"fn(number) -> dynamic (:features :pass)"
);
assert_eq!(open.return_type.as_ref().unwrap().describe(), "unit");
assert!(open.rest_type.is_none());
assert_eq!(open.definition.as_deref(), Some("calcit.core/each"));
assert!(
method_call_types(&open).is_none(),
"unproven calls must not fabricate syntax evidence"
);
}
#[test]
fn parse_method_queries_keep_open_results_open_and_prove_cirru_rows() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot = load_core_snapshot().expect("core snapshot should load");
prepare_program_for_type_query_on_cli_stack(snapshot);
let methods = runner::preprocess::static_method_contracts(&CalcitTypeAnnotation::String)
.expect("String methods")
.into_iter()
.map(|(descriptor, contract)| context_method(descriptor, contract))
.collect::<Vec<_>>();
for (name, result) in [
(".parse-json", "type calcit.core/Result<dynamic, string>"),
(".parse-cirru-edn", "type calcit.core/Result<dynamic, string>"),
] {
let method = methods.iter().find(|method| method.name == name).expect("parse method");
assert_eq!(method.status, "open");
assert_eq!(method.parameter_types, Some(vec![]));
assert_eq!(method.return_type.as_deref(), Some(result));
assert!(method.call_types.is_none(), "declared open types do not prove a closed call");
assert!(render_context_method(method).contains(&format!("() -> {result}")));
}
let rows = methods
.iter()
.find(|method| method.name == ".parse-cirru-list")
.expect("parse method");
assert_eq!(rows.status, "proven");
assert!(
rows.return_type.as_deref().is_some_and(|result| result.contains("CirruNode")),
"{:?}",
rows.return_type
);
assert_eq!(rows.parameter_types, Some(vec![]));
assert!(rows.call_types.is_some(), "proven rows must export call types");
let missing = runner::preprocess::static_method_contract(&CalcitTypeAnnotation::String, ".missing-method");
assert_eq!(missing.status, "open");
assert!(missing.arg_types.is_none());
assert!(missing.return_type.is_none());
assert!(method_call_types(&missing).is_none());
}
#[test]
fn method_query_reuses_bound_collection_contracts_and_keeps_open_schemas_explicit() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot = load_core_snapshot().expect("core snapshot should load");
prepare_program_for_type_query_on_cli_stack(snapshot.clone());
let list = parse_type_annotation_query(":: 'List 'Number").expect("typed list should parse");
let list_get = runner::preprocess::static_method_contracts(list.as_ref())
.expect("list methods should resolve")
.into_iter()
.find(|(method, _)| method.name == ".get")
.map(|(method, contract)| context_method(method, contract))
.expect("list get should exist");
assert_eq!(list_get.status, "proven");
assert_eq!(list_get.parameter_types, Some(vec!["number".to_owned()]));
assert_eq!(list_get.return_type.as_deref(), Some("type calcit.core/Option<number>"));
assert_eq!(list_get.definition.as_deref(), Some("calcit.core/get"));
assert!(render_context_method(&list_get).contains("(number) -> type calcit.core/Option<number>"));
let list_concat = runner::preprocess::static_method_contract(list.as_ref(), ".concat");
assert_eq!(list_concat.status, "proven", "the first variadic argument is the method receiver");
assert!(list_concat.arg_types.unwrap().is_empty());
assert_eq!(list_concat.rest_type.unwrap().describe(), "list<number>");
assert_eq!(list_concat.return_type.unwrap().describe(), "list<number>");
assert_eq!(list_concat.definition.as_deref(), Some("calcit.core/&list:concat"));
let list_append = runner::preprocess::static_method_contract(list.as_ref(), ".append");
assert_eq!(
list_append.status, "proven",
"core definition schema should survive method dispatch: {list_append:?}"
);
assert_eq!(list_append.arg_types.unwrap()[0].describe(), "number");
assert_eq!(list_append.return_type.unwrap().describe(), "list<number>");
assert_eq!(list_append.definition.as_deref(), Some("calcit.core/append"));
let open_list = parse_type_annotation_query(":: 'List 'Dynamic").expect("open list should parse");
let open_append = runner::preprocess::static_method_contract(open_list.as_ref(), ".append");
assert_eq!(open_append.status, "open", "an explicitly dynamic element still needs narrowing");
assert_eq!(open_append.arg_types.unwrap()[0].describe(), "dynamic");
assert_eq!(open_append.return_type.unwrap().describe(), "list");
let open_concat = runner::preprocess::static_method_contract(open_list.as_ref(), ".concat");
assert_eq!(open_concat.status, "open");
assert!(open_concat.arg_types.as_ref().unwrap().is_empty());
assert_eq!(open_concat.rest_type.as_ref().unwrap().describe(), "list");
assert_eq!(open_concat.return_type.as_ref().unwrap().describe(), "list");
assert!(method_call_types(&open_concat).is_none());
let rendered_concat = context_method(
runner::preprocess::StaticMethodDescriptor {
name: ".concat".to_owned(),
origin: "test".to_owned(),
},
open_concat,
);
assert!(render_context_method(&rendered_concat).contains("(...list) -> list"));
let original_fingerprint = method_contract_fingerprint(&Some(vec![list_get.clone()])).expect("method serialization");
let mut changed = list_get;
changed.return_type = Some("type calcit.core/Option<string>".to_owned());
let changed_fingerprint = method_contract_fingerprint(&Some(vec![changed])).expect("method serialization");
assert_ne!(
original_fingerprint, changed_fingerprint,
"a changed callable contract must change the query revision"
);
let map = parse_type_annotation_query(":: 'Map 'String 'Number").expect("typed map should parse");
let map_get = runner::preprocess::static_method_contract(map.as_ref(), ".get");
assert_eq!(map_get.status, "proven");
assert_eq!(map_get.arg_types.unwrap()[0].describe(), "string");
assert_eq!(map_get.return_type.unwrap().describe(), "type calcit.core/Option<number>");
let option = parse_type_annotation_query(":: 'Option 'Number").expect("typed Option should parse");
let unwrap_or = runner::preprocess::static_method_contract(option.as_ref(), ".unwrap-or");
assert_eq!(unwrap_or.status, "proven");
assert_eq!(unwrap_or.arg_types.unwrap()[0].describe(), "number");
assert_eq!(unwrap_or.return_type.unwrap().describe(), "number");
assert!(unwrap_or.generics.is_empty(), "receiver-bound generic must not appear unbound");
let open_option = parse_type_annotation_query(":: 'Option 'Dynamic").expect("open Option should parse");
let open_unwrap_or = runner::preprocess::static_method_contract(open_option.as_ref(), ".unwrap-or");
assert_eq!(
open_unwrap_or.status, "open",
"receiver-bound Dynamic must not become a precise contract"
);
assert_eq!(open_unwrap_or.arg_types.unwrap()[0].describe(), "dynamic");
assert_eq!(open_unwrap_or.return_type.unwrap().describe(), "dynamic");
let open_and_then = runner::preprocess::static_method_contract(open_option.as_ref(), ".and-then");
assert_eq!(open_and_then.status, "open", "nested Dynamic callback input must remain open");
let some = runner::preprocess::static_method_contract(open_option.as_ref(), ".some?");
assert_eq!(some.status, "proven", "presence check does not expose the Dynamic payload");
assert_eq!(some.return_type.unwrap().describe(), "bool");
let option_map = runner::preprocess::static_method_contract(option.as_ref(), ".map");
assert_eq!(
option_map.status, "proven",
"the selected implementation supplies its generic callback relation"
);
assert_eq!(
option_map.arg_types.as_ref().unwrap()[0].describe(),
"fn(number) -> 'U (:features :pass)"
);
assert_eq!(option_map.return_type.as_ref().unwrap().describe(), "type calcit.core/Option<'U>");
assert_eq!(option_map.generics, vec!["U"]);
let nodes = method_call_types(&option_map).expect("generic output should retain callable syntax evidence");
assert_eq!(nodes.returns, serde_json::json!(["::", "'calcit.core/Option", "'U"]));
let open_map = runner::preprocess::static_method_contract(open_option.as_ref(), ".map");
assert_eq!(open_map.status, "open", "an open receiver payload still needs call-site proof");
assert!(method_call_types(&open_map).is_none());
let result = parse_type_annotation_query(":: 'Result 'Number 'String").expect("typed Result should parse");
let result_map = runner::preprocess::static_method_contract(result.as_ref(), ".map");
assert_eq!(
result_map.generics,
vec!["ResultMapOutput"],
"specialized output variables must be discoverable"
);
let map_err = runner::preprocess::static_method_contract(result.as_ref(), ".map-err");
assert_eq!(map_err.status, "proven");
let rendered = render_context_method(&context_method(
runner::preprocess::StaticMethodDescriptor {
name: ".map-err".to_owned(),
origin: "calcit.core/ResultOps".to_owned(),
},
map_err.clone(),
));
assert!(rendered.contains("for<'F>"));
assert_eq!(map_err.arg_types.unwrap()[0].describe(), "fn(string) -> 'F");
assert_eq!(map_err.return_type.unwrap().describe(), "type Result<number, 'F>");
assert_eq!(map_err.generics, vec!["F"]);
let (fs_path, source) =
on_cli_stack(move || resolve_type_query_target(&snapshot, "calcit.core/FsPath")).expect("core FsPath type should resolve");
assert_eq!(source, "resolved core nominal definition");
let read_text = on_cli_stack(move || runner::preprocess::static_method_contract(fs_path.as_ref(), ".read-text"));
assert_eq!(read_text.status, "proven");
assert!(read_text.arg_types.unwrap().is_empty());
assert_eq!(read_text.return_type.unwrap().describe(), "type Result<string, string>");
assert_eq!(read_text.definition.as_deref(), Some("calcit.core/fs-path:read-text"));
}
#[test]
fn method_query_reads_source_external_object_trait_without_project_initialization() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot =
load_snapshot(concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/test-js.cirru"), None).expect("JS fixture should load");
prepare_program_for_type_query_on_cli_stack(snapshot.clone());
let (trait_type, source) =
on_cli_stack(move || resolve_type_query_target(&snapshot, "test-js.main/TestDate")).expect("external trait should resolve");
assert_eq!(source, "source trait definition");
let method = on_cli_stack(move || runner::preprocess::static_method_contract(trait_type.as_ref(), ".now"));
assert_eq!(method.status, "proven");
assert!(method.arg_types.unwrap().is_empty());
assert_eq!(method.return_type.unwrap().describe(), "number");
}
#[test]
fn query_format_and_unicode_truncation_are_deterministic() {
assert_eq!(parse_query_render_format("human"), Ok(QueryRenderFormat::Human));
assert_eq!(parse_query_render_format("json"), Ok(QueryRenderFormat::Json));
assert_eq!(parse_query_render_format("edn"), Ok(QueryRenderFormat::Edn));
assert_eq!(truncate_chars("你好 Calcit", 2), ("你好…".to_owned(), true));
assert_eq!(truncate_chars("你好", 2), ("你好".to_owned(), false));
}
#[test]
fn js_ffi_query_exposes_dependency_owner_and_source_without_executing_js() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let input = concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/js-ffi-consumer.cirru");
let snapshot = load_snapshot(input, None).expect("JS FFI consumer should load");
let file = snapshot.files.get("app.main").expect("dependency namespace");
let inline = file
.defs
.get("plus-one")
.and_then(|entry| entry.ffi.as_ref())
.expect("inline metadata");
let inline_info = js_ffi_query_info(input, &snapshot, "app.main", inline).expect("inline query info");
assert_eq!(inline_info.target.as_deref(), Some("node"));
assert_eq!(inline_info.owner_module.as_deref(), Some("app"));
assert_eq!(inline_info.source_kind, Some("inline"));
assert!(render_js_ffi_info(&inline_info, Some("(x)=>x+1")).contains("```javascript\n(x)=>x+1"));
let file_ffi = file
.defs
.get("base-name")
.and_then(|entry| entry.ffi.as_ref())
.expect("file metadata");
let file_info = js_ffi_query_info(input, &snapshot, "app.main", file_ffi).expect("file query info");
assert_eq!(file_info.source_kind, Some("file"));
assert_eq!(file_info.source_file.as_deref(), Some("js-ffi-assets/base-name.js"));
assert_eq!(file_info.modules.get("path").map(String::as_str), Some("node:path"));
assert!(file_info.module_root.as_deref().is_some_and(|root| root.ends_with("js-ffi-module")));
}
fn context_test_options(target: &str) -> QueryContextCommand {
QueryContextCommand {
target: target.to_owned(),
budget: 2400,
format: "json".to_owned(),
deps: false,
dependency_limit: 12,
usage_limit: 8,
example_limit: 3,
test_limit: 3,
include_core: false,
}
}
#[test]
fn context_examples_render_symbol_leaf_without_failing_collection() {
let examples = vec![
Cirru::Leaf("ConsoleHost".into()),
Cirru::List(vec![Cirru::Leaf("identity".into()), Cirru::Leaf("1".into())]),
];
let collection = build_context_examples(&examples, 2, 1200).expect("leaf and list examples should render");
assert_eq!(collection.total, 2);
assert_eq!(collection.items[0].cirru, "ConsoleHost");
assert_eq!(collection.items[0].tree, Some(serde_json::json!("ConsoleHost")));
assert_eq!(collection.items[1].cirru, "identity 1");
}
#[test]
fn special_builtin_context_preserves_examples_and_intent() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot = load_core_snapshot().expect("core snapshot should load");
let envelope = on_cli_stack(move || {
let meta = lookup_special_builtin_query_meta("calcit.core", "to-js-data")
.expect("metadata lookup should work")
.expect("to-js-data metadata should exist");
build_special_builtin_context(
&snapshot,
"calcit.core",
"to-js-data",
meta,
&context_test_options("calcit.core/to-js-data"),
)
.expect("context should build")
});
assert_eq!(envelope.command, "query.context");
assert_eq!(envelope.data.coverage, "intentional-dynamic");
assert_eq!(envelope.data.examples.total, 3);
assert_eq!(
envelope.data.examples.items[2]
.tree
.as_ref()
.and_then(|tree| tree.as_array())
.map(Vec::len),
Some(3)
);
assert!(
envelope
.diagnostics
.iter()
.any(|diagnostic| diagnostic.code == "I_DYNAMIC_TYPE_INTENTIONAL")
);
}
#[test]
fn namespace_source_uses_bundled_core_identity() {
for package in ["calcit.std", "calcit-test", "app"] {
let mut snapshot = snapshot::Snapshot {
package: package.to_owned(),
..Default::default()
};
let namespace = format!("{package}.main");
snapshot.files.insert(namespace.clone(), snapshot::gen_meta_ns(&namespace, "test"));
assert_eq!(namespace_source(&snapshot, package), "project");
assert_eq!(namespace_source(&snapshot, &format!("{package}.main")), "project");
assert_eq!(namespace_source(&snapshot, &format!("{package}-other.main")), "dependency");
for namespace in [
"calcit.core",
"calcit.internal",
"calcit.internal.helpers",
"calcit.test",
"calcit.gen",
] {
assert_eq!(namespace_source(&snapshot, namespace), "core");
}
if package != "calcit.std" {
assert_eq!(namespace_source(&snapshot, "calcit.std.time"), "dependency");
}
let owner = js_ffi_owner(
concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/test.cirru"),
&snapshot,
&namespace,
)
.expect("project JS FFI owner");
assert_eq!(owner.module, package);
}
}
#[test]
fn regular_context_carries_snapshot_revision_and_tree_location() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot = load_core_snapshot().expect("core snapshot should load");
let (envelope, expected_revision) = on_cli_stack(move || {
let entry = snapshot
.files
.get("calcit.core")
.and_then(|file| file.defs.get("map"))
.expect("core map should exist");
let expected_revision = snapshot::definition_revision(entry).expect("revision should compute");
let envelope = build_regular_context(&snapshot, "calcit.core", "map", entry, &context_test_options("calcit.core/map"))
.expect("context should build");
(envelope, expected_revision)
});
assert_eq!(envelope.data.id, "calcit.core/map");
assert_eq!(envelope.data.source, "core");
assert_eq!(envelope.data.code.root, "code");
assert!(envelope.data.code.nodes > 0);
assert_eq!(envelope.revision, expected_revision);
}
#[test]
fn project_function_schema_argument_resolves_source_backed_struct() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot =
load_snapshot(concat!(env!("CARGO_MANIFEST_DIR"), "/../../calcit/test.cirru"), None).expect("test snapshot should load");
prepare_program_for_type_query_on_cli_stack(snapshot.clone());
let schema = program::lookup_def_schema("test-struct.main", "sum-point");
let CalcitTypeAnnotation::Fn(annotation) = schema.as_ref() else {
panic!("sum-point should have a function schema");
};
let argument_type = annotation.arg_types.first().expect("sum-point argument type");
let struct_def =
calcit_core::calcit::with_type_annotation_warning_context("test-struct.main/sum-point", || argument_type.resolve_to_struct())
.expect("source-backed Point2D should resolve");
assert_eq!(struct_def.name.ref_str(), "Point2D");
assert_eq!(struct_def.index_of("x"), Some(0));
assert!(matches!(
struct_def.field_types.first().map(AsRef::as_ref),
Some(CalcitTypeAnnotation::Number)
));
let result_type = CalcitTypeAnnotation::TypeRef(Arc::from("test-enum.main/Result0"), Arc::new(vec![]));
assert!(result_type.resolve_to_enum().is_some(), "source-backed Result0 should resolve");
assert!(
result_type.is_compatible_with(&CalcitTypeAnnotation::AnonymousEnum),
"a source-backed enum reference should satisfy enum operations"
);
let person_symbol =
code_to_calcit(&Cirru::Leaf(Arc::from("Person")), "test-struct.main", "test-struct", vec![]).expect("Person symbol should parse");
let person_type = runner::preprocess::infer_static_type_from_expr(&person_symbol).expect("Person type should infer statically");
assert!(
matches!(person_type.as_ref(), CalcitTypeAnnotation::StructDef(definition)
if definition.definition_ref.as_deref() == Some("test-struct.main/Person")),
"definition expressions should retain definition identity rather than instance evidence: {person_type}"
);
let (queried_person_type, source) =
resolve_type_query_target(&snapshot, "test-struct.main/Person").expect("type query should infer defstruct type");
assert_eq!(source, "definition inference");
assert!(
matches!(queried_person_type.as_ref(), CalcitTypeAnnotation::TypeRef(name, _) if name.as_ref() == "test-struct.main/Person"),
"query type should expose the source-backed struct type: {queried_person_type}"
);
let warnings = RefCell::new(vec![]);
runner::preprocess::compile_source_def_for_snapshot("test-struct.main", "sum-point", &warnings, &CallStackList::default())
.expect("sum-point should preprocess");
let compiled = program::lookup_compiled_def("test-struct.main", "sum-point").expect("compiled sum-point");
let sum_point_source = &snapshot.files["test-struct.main"].defs["sum-point"].code;
let target = find_preprocessed_node_at_path(
&compiled.preprocessed_code,
sum_point_source,
"test-struct.main",
"sum-point",
&[3, 1],
true,
)
.expect("field access expression should retain a source path");
let Calcit::List(field_access) = target else {
panic!("field access should remain a call");
};
assert!(
matches!(field_access.first(), Some(Calcit::Proc(calcit_core::CalcitProc::NativeStructNth))),
"typed tag access should specialize to struct nth, got {target}"
);
let source = parse_query_test_expression(":x p");
let lowering = type_at_lowering(&source, Some(target));
assert_eq!(lowering.status, "specialized");
assert_eq!(lowering.kind, "nominal-struct-field");
assert_eq!(lowering.source_head.as_deref(), Some(":x"));
assert_eq!(lowering.lowered_head.as_deref(), Some("&struct:nth"));
}
#[test]
fn type_at_path_parser_accepts_semantic_code_prefixes() {
assert_eq!(parse_type_at_path("code@3.2"), Ok(vec![3, 2]));
assert_eq!(parse_type_at_path("@3.2"), Ok(vec![3, 2]));
assert_eq!(parse_type_at_path("3.2"), Ok(vec![3, 2]));
}
#[test]
fn context_diagnostic_always_serializes_provenance_array() {
let diagnostic = ContextDiagnostic {
code: "W_TYPE_AT_UNRESOLVED".to_owned(),
phase: "type-inference",
severity: "warning",
message: "unresolved".to_owned(),
path: Some("code@1".to_owned()),
intent: None,
provenance: vec![],
};
let value = serde_json::to_value(&diagnostic).expect("diagnostic should serialize");
assert_eq!(
value["provenance"],
serde_json::json!([]),
"the documented contract requires an always-present provenance array"
);
}
fn parse_query_test_expression(source: &str) -> Calcit {
let mut nodes = cirru_parser::parse(source).expect("test expression should parse");
assert_eq!(nodes.len(), 1);
code_to_calcit(&nodes.remove(0), "tests.type-at", "demo", vec![]).expect("test expression should convert")
}
#[test]
fn type_at_lowering_distinguishes_typed_specialization_from_direct_primitives() {
let source = parse_query_test_expression("count xs");
let processed = Calcit::from(vec![Calcit::Proc(calcit_core::CalcitProc::NativeListCount), Calcit::Number(1.0)]);
assert_eq!(
type_at_lowering(&source, Some(&processed)),
TypeAtLowering {
status: "specialized",
kind: "typed-polymorphic-call",
source_head: Some("count".to_owned()),
lowered_head: Some("&list:count".to_owned()),
detail:
"Static receiver type selected a collection-specific primitive or core implementation, removing generic runtime dispatch."
.to_owned(),
}
);
let direct = Calcit::from(vec![Calcit::Proc(calcit_core::CalcitProc::NativeListCount), Calcit::Number(1.0)]);
let lowering = type_at_lowering(&direct, Some(&direct));
assert_eq!(lowering.status, "unchanged");
assert_eq!(lowering.kind, "core-expression");
}
#[test]
fn type_at_lowering_exposes_dynamic_method_dispatch() {
let source = parse_query_test_expression(".show value");
let lowering = type_at_lowering(&source, Some(&source));
assert_eq!(lowering.status, "dynamic");
assert_eq!(lowering.kind, "dynamic-method-dispatch");
assert_eq!(lowering.source_head.as_deref(), Some(".show"));
assert_eq!(lowering.lowered_head.as_deref(), Some(".show"));
}
#[test]
fn type_at_lowering_recognizes_postfix_method_heads() {
let source = parse_query_test_expression("value .show");
let lowering = type_at_lowering(&source, Some(&source));
assert_eq!(lowering.status, "dynamic");
assert_eq!(lowering.kind, "dynamic-method-dispatch");
assert_eq!(lowering.source_head.as_deref(), Some(".show"));
assert_eq!(lowering.lowered_head.as_deref(), Some(".show"));
}
#[test]
fn definition_return_schema_does_not_leak_into_nested_functions() {
let mut nodes = cirru_parser::parse("fn ()\n fn () 1").expect("test function should parse");
let mut entry = snapshot::CodeEntry::from_code(nodes.remove(0));
entry.schema = Arc::new(CalcitTypeAnnotation::from_function_parts(
vec![],
Arc::new(CalcitTypeAnnotation::String),
));
let root_expected = expected_type_at_path(&entry, None, "tests.type-at", "demo", &[2])
.expect("root body should inherit the definition return schema");
assert!(matches!(root_expected.0.as_ref(), CalcitTypeAnnotation::String));
assert!(
expected_type_at_path(&entry, None, "tests.type-at", "demo", &[2, 2]).is_none(),
"nested fn body must use its own context rather than the enclosing definition schema"
);
}
#[test]
fn definition_return_schema_propagates_into_if_branches() {
let mut nodes = cirru_parser::parse("fn ()\n if true (Option :none) (Option :none)").expect("test function should parse");
let mut entry = snapshot::CodeEntry::from_code(nodes.remove(0));
let option_number = Arc::new(CalcitTypeAnnotation::TypeRef(
Arc::from("calcit.core/Option"),
Arc::new(vec![Arc::new(CalcitTypeAnnotation::Number)]),
));
entry.schema = Arc::new(CalcitTypeAnnotation::from_function_parts(vec![], option_number.clone()));
for path in [&[2, 2][..], &[2, 3][..]] {
let (expected, source) = expected_type_at_path(&entry, None, "tests.type-at", "demo", path)
.expect("each if result branch should inherit the definition return schema");
assert_eq!(expected, option_number);
assert_eq!(source, "if branch inherited from definition return schema");
}
}
#[test]
fn type_at_does_not_borrow_global_schema_for_unresolved_shadowed_symbol() {
let _guard = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
let snapshot = load_core_snapshot().expect("core snapshot should load");
prepare_program_for_type_query_on_cli_stack(snapshot);
assert!(
!matches!(
program::lookup_def_schema(calcit_core::calcit::CORE_NS, "count").as_ref(),
CalcitTypeAnnotation::Dynamic
),
"the regression requires a real same-named global schema"
);
let source = Calcit::Symbol {
sym: Arc::from("count"),
info: Arc::new(calcit_core::calcit::CalcitSymbolInfo {
at_ns: Arc::from("tests.type-at"),
at_def: Arc::from("demo"),
}),
location: None,
};
assert!(
infer_type_at_target(&source, None).is_none(),
"a core function of the same name cannot prove an unresolved local symbol"
);
assert!(
infer_type_at_target(&source, Some(&source)).is_none(),
"an unlowered symbol is still not lexical binding evidence"
);
let local = Calcit::Local(calcit_core::calcit::CalcitLocal {
idx: 0,
sym: Arc::from("count"),
info: Arc::new(calcit_core::calcit::CalcitSymbolInfo {
at_ns: Arc::from("tests.type-at"),
at_def: Arc::from("demo"),
}),
location: None,
type_info: Arc::new(CalcitTypeAnnotation::String),
});
let inferred = infer_type_at_target(&source, Some(&local)).expect("resolved local should retain its lexical type");
assert!(matches!(inferred.as_ref(), CalcitTypeAnnotation::String));
}
#[test]
fn type_at_reports_expected_type_mismatches_without_rejecting_optional_values() {
let mismatch = type_at_expected_mismatch_diagnostic(
&CalcitTypeAnnotation::Number,
&CalcitTypeAnnotation::String,
"callable parameter",
"code@3.1",
)
.expect("number should not satisfy string");
assert_eq!(mismatch.code, "W_TYPE_AT_EXPECTED_MISMATCH");
assert_eq!(mismatch.path.as_deref(), Some("code@3.1"));
assert!(
type_at_expected_mismatch_diagnostic(
&CalcitTypeAnnotation::Number,
&CalcitTypeAnnotation::Nullable(
Arc::new(CalcitTypeAnnotation::Number),
calcit_core::calcit::NullableOrigin::Inferred
),
"return schema",
"code@3",
)
.is_none(),
"a concrete number satisfies optional<number>"
);
}
}
fn definition_type_query_target(target: &str) -> Option<(&str, &str)> {
let (namespace, definition) = target.split_once('/')?;
if namespace.is_empty() || definition.is_empty() || target.chars().any(char::is_whitespace) {
None
} else {
Some((namespace, definition))
}
}
fn resolve_type_query_target(snapshot: &snapshot::Snapshot, target: &str) -> Result<(Arc<CalcitTypeAnnotation>, &'static str), String> {
if let Some((namespace, definition)) = definition_type_query_target(target) {
let file = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace `{namespace}` not found"))?;
if !file.defs.contains_key(definition) {
return Err(format!("Definition `{target}` not found"));
}
if let Some(trait_type) = runner::preprocess::resolve_source_trait_instance_type(namespace, definition) {
return Ok((trait_type, "source trait definition"));
}
let annotation = program::lookup_def_schema(namespace, definition);
let is_data_definition_marker = matches!(
annotation.as_ref(),
CalcitTypeAnnotation::Custom(value)
if matches!(value.as_ref(), Calcit::Tag(tag) if matches!(tag.ref_str(), "struct-def" | "enum-def"))
);
if !matches!(annotation.as_ref(), CalcitTypeAnnotation::Dynamic) && !is_data_definition_marker {
return Ok((annotation, "definition schema"));
}
if is_data_definition_marker && let Some(inferred) = runner::preprocess::resolve_core_nominal_instance_type(namespace, definition) {
return Ok((inferred, "resolved core nominal definition"));
}
let symbol = code_to_calcit(&Cirru::Leaf(Arc::from(definition)), namespace, "&query:type", vec![])?;
if let Some(inferred) = runner::preprocess::infer_static_type_from_expr(&symbol)
&& !matches!(inferred.as_ref(), CalcitTypeAnnotation::Dynamic)
{
if matches!(
inferred.as_ref(),
CalcitTypeAnnotation::StructDef(_) | CalcitTypeAnnotation::EnumDef(_)
) {
return Ok((
Arc::new(CalcitTypeAnnotation::TypeRef(Arc::from(target), Arc::new(vec![]))),
"definition inference",
));
}
return Ok((inferred, "definition inference"));
}
return Err(format!(
"Definition `{target}` has neither an explicit schema nor an inferable static type. Add a schema or query a concrete type annotation such as `'Number`."
));
}
Ok((parse_type_annotation_query(target)?, "type annotation"))
}
pub fn format_type_query_annotation(annotation: &CalcitTypeAnnotation) -> Result<String, String> {
let edn = annotation.to_type_edn();
match snapshot::compact_type_display(&edn) {
Some(Cirru::Leaf(name)) => return Ok(name.to_string()),
Some(compact) => {
return cirru_parser::format(std::slice::from_ref(&compact), true.into())
.map(normalize_single_schema_display)
.map_err(|error| format!("Failed to format resolved type: {error}"));
}
None => {}
}
cirru_edn::format(&edn, true)
.map(|text| {
let rendered = text.trim();
rendered.strip_prefix("do ").unwrap_or(rendered).to_owned()
})
.map_err(|error| format!("Failed to format resolved type: {error}"))
}
fn handle_type(input_path: &str, opts: &QueryTypeCommand, entry: Option<&str>) -> Result<(), String> {
let format = parse_query_render_format(&opts.format)?;
let snapshot = match definition_type_query_target(&opts.target) {
Some((namespace, _)) if namespace == calcit_core::calcit::CORE_NS || namespace == "calcit.internal" => load_core_snapshot()?,
Some(_) => load_snapshot_with_entry(input_path, entry)?,
None => load_core_snapshot()?,
};
prepare_program_for_type_query(&snapshot)?;
let (annotation, source) = resolve_type_query_target(&snapshot, &opts.target)?;
let rendered_type = format_type_query_annotation(annotation.as_ref())?;
let methods = runner::preprocess::static_method_contracts(annotation.as_ref()).map(|items| {
items
.into_iter()
.map(|(method, contract)| context_method(method, contract))
.collect::<Vec<_>>()
});
let method_fingerprint = method_contract_fingerprint(&methods)?;
let source_revision = definition_type_query_target(&opts.target)
.and_then(|(namespace, definition)| snapshot.files.get(namespace).and_then(|file| file.defs.get(definition)))
.map(snapshot::definition_revision)
.transpose()?
.unwrap_or_default();
let revision = semantic_revision(&[&rendered_type, &method_fingerprint, &source_revision]);
let data = TypeQueryData {
target: opts.target.clone(),
canonical_type: rendered_type,
resolved_from: source,
methods,
};
let diagnostics = vec![];
if format != QueryRenderFormat::Human {
let envelope = SemanticQueryEnvelope {
schema_version: 1,
command: "query.type",
revision,
data,
diagnostics,
next: vec![],
};
return emit_query_structured(&envelope, format, "type query result");
}
println!("# Type\n\n- Resolved from: `{}`\n- Revision: `{revision}`\n", data.resolved_from);
print!("{}", markdown_fenced_block("cirru", &data.canonical_type));
println!("\n## Methods\n");
println!(
"Call a method on a typed receiver. Each entry shows its origin, proof status and available type contract. A definition path is its implementation reference, not a second recommended call form. `open` or `ambiguous` does not prove a typed call; use `query def` for constructors and `docs read api-roles.md` for API roles.\n"
);
match data.methods {
Some(methods) if methods.is_empty() => {
println!("_No methods registered for this type._");
}
Some(methods) => {
print!("{}", render_type_query_methods(&methods));
}
None => {
println!("_This type has no statically resolvable method metadata._");
}
}
Ok(())
}
fn parse_type_at_path(raw: &str) -> Result<Vec<usize>, String> {
let path = raw.strip_prefix("code").unwrap_or(raw);
parse_path(path)
}
fn semantic_code_path(path: &[usize]) -> String {
if path.is_empty() {
"code".to_owned()
} else {
format!("code@{}", path.iter().map(usize::to_string).collect::<Vec<_>>().join("."))
}
}
pub fn format_cirru_expression(node: &Cirru) -> String {
match node {
Cirru::Leaf(value) => cirru_parser::generate_leaf(value),
Cirru::List(_) => cirru_parser::format(std::slice::from_ref(node), true.into())
.map(|text| text.trim().to_owned())
.unwrap_or_else(|_| format!("{node:?}")),
}
}
fn calcit_direct_source_path(node: &Calcit, namespace: &str, definition: &str) -> Option<Vec<usize>> {
let location = node.get_location()?;
if location.ns.as_ref() != namespace || location.def.as_ref() != definition {
return None;
}
Some(location.coord.iter().map(|idx| *idx as usize).collect())
}
fn calcit_expression_source_path(node: &Calcit, source: &Cirru, namespace: &str, definition: &str) -> Option<Vec<usize>> {
if let Some(path) = calcit_direct_source_path(node, namespace, definition) {
return Some(path);
}
let Calcit::List(items) = node else {
return None;
};
for (index, child) in items.iter().enumerate() {
if let Some(mut child_path) = calcit_expression_source_path(child, source, namespace, definition) {
let reader_expansion = items.len() == 2
&& index == 1
&& calcit_direct_source_path(child, namespace, definition).is_some()
&& source_leaf_expands_to_list(source, &child_path, namespace, definition);
if !reader_expansion {
child_path.pop();
}
return Some(child_path);
}
}
None
}
fn source_leaf_expands_to_list(source: &Cirru, path: &[usize], namespace: &str, definition: &str) -> bool {
matches!(navigate_to_path(source, path), Ok(leaf @ Cirru::Leaf(_))
if matches!(code_to_calcit(&leaf, namespace, definition, vec![]), Ok(Calcit::List(_))))
}
pub(super) fn find_preprocessed_node_at_path<'a>(
node: &'a Calcit,
source: &Cirru,
namespace: &str,
definition: &str,
target_path: &[usize],
target_is_list: bool,
) -> Option<&'a Calcit> {
let shape_matches = matches!(node, Calcit::List(_)) == target_is_list;
if shape_matches
&& calcit_expression_source_path(node, source, namespace, definition)
.as_deref()
.is_some_and(|path| path == target_path)
{
return Some(node);
}
if let Calcit::List(items) = node {
for child in items.iter() {
if let Some(found) = find_preprocessed_node_at_path(child, source, namespace, definition, target_path, target_is_list) {
return Some(found);
}
}
}
None
}
#[derive(Debug, Clone)]
struct StaticCallableSignature {
arg_types: Vec<Arc<CalcitTypeAnnotation>>,
rest_type: Option<Arc<CalcitTypeAnnotation>>,
}
impl StaticCallableSignature {
fn from_fn_annotation(annotation: &CalcitFnTypeAnnotation) -> Self {
Self {
arg_types: annotation.arg_types.clone(),
rest_type: annotation.rest_type.clone(),
}
}
fn expected_arg(&self, index: usize) -> Option<Arc<CalcitTypeAnnotation>> {
if let Some(value) = self.arg_types.get(index) {
return match value.as_ref() {
CalcitTypeAnnotation::Variadic(inner) => Some(inner.clone()),
_ => Some(value.clone()),
};
}
self.rest_type.clone().or_else(|| {
self.arg_types.last().and_then(|value| match value.as_ref() {
CalcitTypeAnnotation::Variadic(inner) => Some(inner.clone()),
_ => None,
})
})
}
}
fn callable_signature_from_head(head: &Calcit) -> Option<StaticCallableSignature> {
match head {
Calcit::Proc(proc) => {
let signature = proc.get_type_signature()?;
Some(StaticCallableSignature {
arg_types: signature.arg_types.clone(),
rest_type: None,
})
}
Calcit::Fn { info, .. } => Some(StaticCallableSignature {
arg_types: info.arg_types.clone(),
rest_type: info.rest_type.clone(),
}),
Calcit::Local(local) => local
.type_info
.resolve_to_fn()
.map(|annotation| StaticCallableSignature::from_fn_annotation(annotation.as_ref())),
Calcit::Import(import) => program::lookup_def_schema(&import.ns, &import.def)
.resolve_to_fn()
.map(|annotation| StaticCallableSignature::from_fn_annotation(annotation.as_ref())),
Calcit::Symbol { sym, info, .. } => program::lookup_def_schema(&info.at_ns, sym)
.resolve_to_fn()
.map(|annotation| StaticCallableSignature::from_fn_annotation(annotation.as_ref())),
_ => None,
}
}
fn expected_type_at_path(
entry: &snapshot::CodeEntry,
processed_root: Option<&Calcit>,
namespace: &str,
definition: &str,
target_path: &[usize],
) -> Option<(Arc<CalcitTypeAnnotation>, String)> {
let (&target_index, parent_path) = target_path.split_last()?;
let parent_node = navigate_to_path(&entry.code, parent_path).ok()?;
let Cirru::List(parent_items) = parent_node else {
return None;
};
let head_name = parent_items.first().and_then(|head| match head {
Cirru::Leaf(name) => Some(name.as_ref()),
Cirru::List(_) => None,
});
if parent_path.is_empty()
&& matches!(head_name, Some("defn" | "fn"))
&& target_index == parent_items.len().saturating_sub(1)
&& let CalcitTypeAnnotation::Fn(annotation) = entry.schema.as_ref()
{
return Some((annotation.return_type.clone(), "definition return schema".to_owned()));
}
if matches!(head_name, Some("if" | "&if")) && target_index == 1 {
return Some((Arc::new(CalcitTypeAnnotation::Bool), "if condition".to_owned()));
}
if matches!(head_name, Some("if" | "&if")) && matches!(target_index, 2 | 3) {
return expected_type_at_path(entry, processed_root, namespace, definition, parent_path)
.map(|(expected, source)| (expected, format!("if branch inherited from {source}")));
}
let processed_parent = processed_root.and_then(|root| {
find_preprocessed_node_at_path(root, &entry.code, namespace, definition, parent_path, true).and_then(|node| match node {
Calcit::List(items) => Some(items),
_ => None,
})
})?;
if matches!(
processed_parent.first(),
Some(Calcit::Syntax(calcit_core::CalcitSyntax::AssertType, _))
) && target_index == 1
&& let Some(type_form) = processed_parent.get(2)
{
return Some((
CalcitTypeAnnotation::parse_type_annotation_form(type_form),
"assert-type annotation".to_owned(),
));
}
let signature = callable_signature_from_head(processed_parent.first()?)?;
let arg_index = target_index.checked_sub(1)?;
signature
.expected_arg(arg_index)
.map(|expected| (expected, "callable parameter".to_owned()))
}
pub(super) fn infer_type_at_target(source: &Calcit, processed: Option<&Calcit>) -> Option<Arc<CalcitTypeAnnotation>> {
if let Calcit::Symbol { .. } = source {
return processed
.filter(|node| !matches!(node, Calcit::Symbol { .. }))
.and_then(runner::preprocess::infer_static_type_from_expr);
}
processed
.and_then(runner::preprocess::infer_static_type_from_expr)
.or_else(|| runner::preprocess::infer_static_type_from_expr(source))
}
pub fn source_expression_type_at(
root: &Cirru,
source: &Cirru,
namespace: &str,
definition: &str,
path: &[usize],
evidence: &[runner::preprocess::SourceExpressionEvidence],
) -> Option<Arc<CalcitTypeAnnotation>> {
if let Some(expression) = runner::preprocess::unique_source_expression_at_path(evidence, namespace, definition, path) {
return expression.inferred_type.clone();
}
if matches!(source, Cirru::List(_)) {
return None;
}
let source = code_to_calcit(
source,
namespace,
definition,
path.iter().map(|index| u16::try_from(*index)).collect::<Result<Vec<_>, _>>().ok()?,
)
.ok()?;
if matches!(source, Calcit::List(_)) {
return None;
}
let compiled = program::lookup_compiled_def(namespace, definition);
let processed = compiled
.as_ref()
.and_then(|compiled| find_preprocessed_node_at_path(&compiled.preprocessed_code, root, namespace, definition, path, false));
infer_type_at_target(&source, processed)
}
fn type_at_evidence(node: &Calcit, path: &str, used_preprocessed: bool) -> TypeAtEvidence {
let kind = match node {
Calcit::Number(_) | Calcit::Str(_) | Calcit::Bool(_) | Calcit::Nil | Calcit::Tag(_) => "literal",
Calcit::Local(_) => "local-binding",
Calcit::Import(_) | Calcit::Symbol { .. } => "definition-schema",
Calcit::Proc(_) => "proc-signature",
Calcit::Fn { .. } => "function-schema",
Calcit::List(items) => match items.first() {
Some(Calcit::Proc(calcit_core::CalcitProc::List | calcit_core::CalcitProc::Set | calcit_core::CalcitProc::NativeMap)) => {
"collection-literal"
}
Some(Calcit::Proc(_)) => "proc-return",
Some(Calcit::Import(_) | Calcit::Symbol { .. }) => "definition-return",
Some(Calcit::Local(_)) => "local-function-return",
Some(Calcit::Method(_, _)) => "method-dispatch",
Some(Calcit::Syntax(_, _)) => "syntax-rule",
_ => "expression-synthesis",
},
_ => "value-shape",
};
TypeAtEvidence {
kind: kind.to_owned(),
detail: if used_preprocessed {
"inferred from preprocessed code and lexical type metadata".to_owned()
} else {
"inferred from the selected source subtree; lexical bindings were unavailable".to_owned()
},
path: Some(path.to_owned()),
}
}
fn type_at_definition_reference(namespace: &str, definition: &str, path: &[usize]) -> Option<runner::preprocess::ResolvedSourceUsage> {
let usages =
runner::preprocess::trace_definition_source_usages(namespace, definition, &RefCell::new(vec![]), &CallStackList::default()).ok()?;
let mut matching = usages.into_iter().filter(|usage| {
usage.location.as_ref().is_some_and(|location| {
location.ns.as_ref() == namespace
&& location.def.as_ref() == definition
&& location.coord.iter().map(|index| usize::from(*index)).eq(path.iter().copied())
})
});
let selected = matching.next()?;
matching
.all(|usage| usage.target_ns == selected.target_ns && usage.target_def == selected.target_def)
.then_some(selected)
}
fn type_at_definition_reference_evidence(reference: &runner::preprocess::ResolvedSourceUsage, path: &str) -> TypeAtEvidence {
let macro_origin = if reference.macro_origin.is_empty() {
String::new()
} else {
format!(" inside the expansion of {}", reference.macro_origin.join(" -> "))
};
TypeAtEvidence {
kind: "definition-schema".to_owned(),
detail: format!(
"declared contract of `{}/{}`, which the compiler resolved at this source path{macro_origin}; it describes the definition, not a call-site instantiation proof",
reference.target_ns, reference.target_def
),
path: Some(path.to_owned()),
}
}
fn type_at_call_head(node: &Calcit) -> Option<&Calcit> {
match node {
Calcit::List(items) => match (items.first(), items.get(1)) {
(Some(head @ Calcit::Method(..)), _) => Some(head),
(_, Some(head @ Calcit::Method(..))) => Some(head),
(head, _) => head,
},
_ => None,
}
}
fn type_at_head_label(head: &Calcit) -> Option<String> {
match head {
Calcit::Proc(proc) => Some(proc.to_string()),
Calcit::Import(import) => Some(format!("{}/{}", import.ns, import.def)),
Calcit::Symbol { sym, .. } | Calcit::Local(calcit_core::calcit::CalcitLocal { sym, .. }) => Some(sym.to_string()),
Calcit::Method(..) => Some(head.turn_string()),
Calcit::Tag(tag) => Some(format!(":{tag}")),
Calcit::Syntax(syntax, _) => Some(syntax.to_string()),
Calcit::StructDef(definition) => Some(definition.name.to_string()),
Calcit::EnumDef(definition) => Some(definition.name().to_string()),
Calcit::Fn { info, .. } => Some(info.name.to_string()),
Calcit::Registered(name) => Some(name.to_string()),
_ => None,
}
}
fn type_at_source_method(node: &Calcit) -> Option<String> {
let Calcit::List(items) = node else {
return None;
};
items.iter().take(2).find_map(|item| match item {
Calcit::Method(name, calcit_core::calcit::MethodKind::Invoke(_)) => Some(format!(".{name}")),
_ => None,
})
}
fn is_typed_collection_target(head: &Calcit) -> bool {
match head {
Calcit::Proc(proc) => {
let name = proc.as_ref();
name.starts_with("&list:")
|| name.starts_with("&map:")
|| name.starts_with("&set:")
|| name.starts_with("&str:")
|| name.starts_with("&enum:")
}
Calcit::Import(import) if import.ns.as_ref() == calcit_core::calcit::CORE_NS => {
let name = import.def.as_ref();
name.starts_with("&list:") || name.starts_with("&map:") || name.starts_with("&set:")
}
_ => false,
}
}
fn type_at_lowering(source: &Calcit, processed: Option<&Calcit>) -> TypeAtLowering {
let source_head = type_at_call_head(source).and_then(type_at_head_label);
let Some(processed) = processed else {
return TypeAtLowering {
status: "unavailable",
kind: "preprocess-unavailable",
source_head,
lowered_head: None,
detail: "No source-correlated preprocessed node was produced; inspect diagnostics before relying on runtime dispatch.".to_owned(),
};
};
let processed_head = type_at_call_head(processed);
let lowered_head = processed_head.and_then(type_at_head_label);
let source_method = type_at_source_method(source);
let (status, kind, detail) = match processed_head {
Some(Calcit::Proc(calcit_core::CalcitProc::NativeStructNth)) => (
"specialized",
"nominal-struct-field",
"The typed Struct field access was validated and lowered to indexed field access.",
),
Some(Calcit::Proc(calcit_core::CalcitProc::NativeStructGet)) => (
"specialized",
"struct-field",
"The Struct field access was lowered to the core Struct primitive; indexed access needs a resolved nominal field layout.",
),
Some(Calcit::Proc(calcit_core::CalcitProc::NativeStruct)) => (
"specialized",
"nominal-struct-constructor",
"The Struct constructor was checked against its nominal definition and lowered to the core constructor primitive.",
),
Some(Calcit::Proc(calcit_core::CalcitProc::NativeNamedEnumNew)) => (
"specialized",
"nominal-enum-constructor",
"The Enum variant and payload were checked against the nominal definition and lowered to the core constructor primitive.",
),
Some(Calcit::Proc(calcit_core::CalcitProc::NativeEnum)) => (
"specialized",
"anonymous-enum-constructor",
"The anonymous Enum constructor was lowered to the core constructor primitive.",
),
Some(head) if is_typed_collection_target(head) && source_head != lowered_head => (
"specialized",
"typed-polymorphic-call",
"Static receiver type selected a collection-specific primitive or core implementation, removing generic runtime dispatch.",
),
Some(Calcit::Method(
_,
calcit_core::calcit::MethodKind::ExternalAccess(_)
| calcit_core::calcit::MethodKind::ExternalGet(_)
| calcit_core::calcit::MethodKind::ExternalSet(_)
| calcit_core::calcit::MethodKind::ExternalInvoke(_),
)) => (
"specialized",
"typed-external-operation",
"Static external-object type selected a backend-native property or method operation.",
),
Some(Calcit::Method(_, calcit_core::calcit::MethodKind::Invoke(receiver)))
if matches!(receiver.as_ref(), CalcitTypeAnnotation::Dynamic) =>
{
(
"dynamic",
"dynamic-method-dispatch",
"The receiver type is still Dynamic, so the method cannot be lowered to a direct callable.",
)
}
Some(Calcit::Method(_, calcit_core::calcit::MethodKind::Invoke(_))) => (
"dynamic",
"typed-method-dispatch",
"The receiver type is known, but this method remains on the explicit dispatch path because no stable direct callable was selected.",
),
Some(_) if source_method.is_some() && source_head != lowered_head => (
"specialized",
"static-method-call",
"The typed method was resolved during preprocessing and lowered to a direct callable.",
),
Some(_) if source_head != lowered_head => (
"resolved",
"static-call-resolution",
"Preprocessing resolved the callable head, but no type-directed specialization was identified.",
),
Some(_) => (
"unchanged",
"core-expression",
"The expression already uses its final callable shape; no additional type-directed lowering was needed.",
),
None if source_method.is_some() => (
"specialized",
"static-method-call",
"The typed method was resolved and folded into a non-call expression during preprocessing.",
),
None => (
"resolved",
"preprocessed-value",
"Preprocessing produced a value rather than a callable expression.",
),
};
TypeAtLowering {
status,
kind,
source_head: source_method.or(source_head),
lowered_head,
detail: detail.to_owned(),
}
}
fn collect_type_at_bindings(node: &Calcit, values: &mut BTreeMap<String, (Arc<CalcitTypeAnnotation>, Option<String>)>) {
match node {
Calcit::Local(local) => {
let path = local
.location
.as_ref()
.map(|coord| semantic_code_path(&coord.iter().map(|idx| *idx as usize).collect::<Vec<_>>()));
let should_replace = values
.get(local.sym.as_ref())
.is_none_or(|(current, _)| matches!(current.as_ref(), CalcitTypeAnnotation::Dynamic));
if should_replace {
values.insert(local.sym.to_string(), (local.type_info.clone(), path));
}
}
Calcit::List(items) => {
for child in items.iter() {
collect_type_at_bindings(child, values);
}
}
_ => {}
}
}
fn format_type_at_bindings(processed_root: Option<&Calcit>, target: Option<&Calcit>) -> Result<Vec<TypeAtBinding>, String> {
let mut values: BTreeMap<String, (Arc<CalcitTypeAnnotation>, Option<String>)> = BTreeMap::new();
if let Some(Calcit::List(root_items)) = processed_root
&& let Some(Calcit::List(params)) = root_items.get(2)
{
collect_type_at_bindings(&Calcit::List(params.clone()), &mut values);
}
if let Some(target) = target {
collect_type_at_bindings(target, &mut values);
}
values
.into_iter()
.map(|(name, (annotation, path))| {
Ok(TypeAtBinding {
name,
r#type: format_type_query_annotation(annotation.as_ref())?,
path,
})
})
.collect()
}
pub fn type_at_confidence(annotation: Option<&CalcitTypeAnnotation>) -> &'static str {
let Some(annotation) = annotation else {
return "unknown";
};
if matches!(annotation, CalcitTypeAnnotation::Dynamic) {
return "unknown";
}
let rendered = annotation.to_brief_string();
if rendered.contains("dynamic") || matches!(annotation, CalcitTypeAnnotation::DynFn | CalcitTypeAnnotation::Custom(_)) {
"partial"
} else if annotation.contains_type_var() {
"generic"
} else {
"exact"
}
}
fn warning_matches_type_at(warning: &LocatedWarning, namespace: &str, definition: &str, path: &[usize]) -> bool {
let location = warning.location();
if location.ns.as_ref() != namespace || location.def.as_ref() != definition {
return false;
}
let warning_path = location.coord.iter().map(|idx| *idx as usize).collect::<Vec<_>>();
warning_path.starts_with(path) || path.starts_with(&warning_path)
}
fn warning_to_context_diagnostic(warning: &LocatedWarning) -> ContextDiagnostic {
ContextDiagnostic {
code: warning.code().unwrap_or("W_PREPROCESS").to_owned(),
phase: "type-check",
severity: "warning",
message: warning.message().to_owned(),
path: Some(semantic_code_path(
&warning.location().coord.iter().map(|idx| *idx as usize).collect::<Vec<_>>(),
)),
intent: None,
provenance: vec![],
}
}
fn type_at_expected_mismatch_diagnostic(
actual: &CalcitTypeAnnotation,
required: &CalcitTypeAnnotation,
source: &str,
path: &str,
) -> Option<ContextDiagnostic> {
if actual.is_compatible_with(required) {
return None;
}
Some(ContextDiagnostic {
code: "W_TYPE_AT_EXPECTED_MISMATCH".to_owned(),
phase: "type-check",
severity: "warning",
message: format!(
"Inferred type `{}` does not satisfy expected type `{}` from {source}",
actual.to_brief_string(),
required.to_brief_string()
),
path: Some(path.to_owned()),
intent: None,
provenance: vec![],
})
}
fn render_type_at_human(envelope: &SemanticQueryEnvelope<TypeAtData>) -> String {
let data = &envelope.data;
let mut out = String::new();
let _ = writeln!(&mut out, "# Type at `{}`\n", data.id);
let _ = writeln!(&mut out, "- Path: `{}`", data.path);
let _ = writeln!(&mut out, "- Revision: `{}`", envelope.revision);
let _ = writeln!(
&mut out,
"- Inferred type: `{}`",
data.inferred_type.as_deref().unwrap_or("unknown")
);
if let Some(expected) = &data.expected_type {
let _ = writeln!(
&mut out,
"- Expected type: `{}` ({})",
expected,
data.expected_from.as_deref().unwrap_or("static context")
);
}
let _ = writeln!(&mut out, "- Confidence: `{}`", data.confidence);
if let Some(intent) = data.dynamic_intent {
let _ = writeln!(&mut out, "- Dynamic intent: `{intent}`");
}
let _ = writeln!(&mut out, "\n## Expression\n");
out.push_str(&markdown_fenced_block("cirru", &data.expression));
let _ = writeln!(
&mut out,
"\n## Lowering\n\n- Status: `{}`\n- Kind: `{}`",
data.lowering.status, data.lowering.kind
);
let source_head = data.lowering.source_head.as_deref().unwrap_or("value");
let lowered_head = data.lowering.lowered_head.as_deref().unwrap_or("value");
let _ = writeln!(&mut out, "- Heads: `{source_head}` → `{lowered_head}`\n\n{}", data.lowering.detail);
let _ = writeln!(&mut out, "\n## Evidence\n");
for evidence in &data.evidence {
let _ = writeln!(&mut out, "- `{}`: {}", evidence.kind, evidence.detail);
}
let _ = writeln!(
&mut out,
"\n## Bindings\n\n{} referenced/top-level binding(s); not a complete scope dump.",
data.bindings.len()
);
for binding in &data.bindings {
let location = binding.path.as_deref().map(|path| format!(" @ {path}")).unwrap_or_default();
let _ = writeln!(&mut out, "- `{}`: `{}`{}", binding.name, binding.r#type, location);
}
let _ = writeln!(&mut out, "\n## Static methods\n");
match &data.static_methods {
Some(methods) => {
for method in methods {
let _ = writeln!(&mut out, "{}", render_context_method(method));
}
}
None => {
let _ = writeln!(&mut out, "_Unknown._");
}
}
let _ = writeln!(&mut out, "\n## Diagnostics\n\nCount: {}.", envelope.diagnostics.len());
for diagnostic in &envelope.diagnostics {
let location = diagnostic.path.as_deref().map(|path| format!(" @ {path}")).unwrap_or_default();
let _ = writeln!(
&mut out,
"- **{}** `{}`{}: {}",
diagnostic.severity, diagnostic.code, location, diagnostic.message
);
}
if !envelope.next.is_empty() {
let _ = writeln!(&mut out, "\n## Next\n");
for command in &envelope.next {
let _ = writeln!(&mut out, "- `{command}`");
}
}
out
}
fn handle_type_at(input_path: &str, opts: &QueryTypeAtCommand, selected_entry: Option<&str>) -> Result<(), String> {
let format = parse_query_render_format(&opts.format)?;
let target_path = parse_type_at_path(&opts.path)?;
let (namespace, requested_definition) = parse_target(&opts.target)?;
let resolved_input = Path::new(input_path);
calcit_core::validate_snapshot_path(resolved_input)?;
let snapshot = if resolved_input.exists() {
load_snapshot_with_entry(input_path, selected_entry)?
} else if namespace == calcit_core::calcit::CORE_NS || namespace == "calcit.internal" {
load_core_snapshot()?
} else {
return Err(format!("{} does not exist", resolved_input.display()));
};
let file = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace `{namespace}` not found"))?;
let lookup = resolve_definition_lookup(namespace, requested_definition, file.defs.keys().map(String::as_str), true)?;
if let Some(warning) = lookup.warning.as_deref() {
print_cli_warning_block(warning);
}
let definition = lookup.resolved;
let entry = file.defs.get(&definition).expect("resolved definition exists");
let target_node = navigate_to_path(&entry.code, &target_path)?;
let semantic_path = semantic_code_path(&target_path);
let expression = format_cirru_expression(&target_node);
let source_revision = snapshot::definition_revision(entry)?;
prepare_program_for_type_query(&snapshot)?;
let warnings = RefCell::<Vec<LocatedWarning>>::new(vec![]);
let compile_error =
runner::preprocess::compile_source_def_for_snapshot(namespace, &definition, &warnings, &CallStackList::default()).err();
let compiled = program::lookup_compiled_def(namespace, &definition);
let processed_root = compiled.as_ref().map(|compiled| &compiled.preprocessed_code);
let source_target = code_to_calcit(
&target_node,
namespace,
&definition,
target_path
.iter()
.map(|idx| u16::try_from(*idx).map_err(|_| format!("Path index {idx} exceeds Snapshot coordinate range")))
.collect::<Result<Vec<_>, _>>()?,
)?;
let reader_expanded = matches!(target_node, Cirru::Leaf(_)) && matches!(source_target, Calcit::List(_));
let source_method_call = matches!(&source_target, Calcit::List(items) if matches!(items.first(), Some(Calcit::Method(..))));
let located_target = processed_root.and_then(|root| {
find_preprocessed_node_at_path(
root,
&entry.code,
namespace,
&definition,
&target_path,
matches!(target_node, Cirru::List(_)),
)
});
let changed_call_head = matches!(
type_at_call_head(&source_target),
Some(Calcit::Symbol { .. } | Calcit::Import(_) | Calcit::Proc(_) | Calcit::Syntax(..) | Calcit::Tag(_))
) && matches!(target_node, Cirru::List(_))
&& located_target.is_some_and(|target| {
type_at_call_head(&source_target).and_then(type_at_head_label) != type_at_call_head(target).and_then(type_at_head_label)
});
let generic_receiver = located_target
.and_then(|target| infer_type_at_target(&source_target, Some(target)))
.is_some_and(|annotation| matches!(annotation.as_ref(), CalcitTypeAnnotation::TypeVar(_)));
let needs_source_trace = reader_expanded || source_method_call || changed_call_head || generic_receiver;
let traced = if compile_error.is_none() && (needs_source_trace || (located_target.is_none() && matches!(target_node, Cirru::List(_))))
{
runner::preprocess::trace_snapshot_source_expressions(
&entry.code,
namespace,
&definition,
&RefCell::new(vec![]),
&CallStackList::default(),
)
.unwrap_or_default()
} else {
vec![]
};
let traced_target = runner::preprocess::unique_source_expression_at_path(&traced, namespace, &definition, &target_path);
let processed_target = if needs_source_trace {
traced_target.map(|item| &item.processed)
} else {
located_target.or_else(|| traced_target.map(|item| &item.processed))
};
let inference_target = processed_target.unwrap_or(&source_target);
let inferred = traced_target
.and_then(|item| item.inferred_type.clone())
.or_else(|| infer_type_at_target(&source_target, processed_target));
let definition_reference = if inferred.is_none() && matches!(source_target, Calcit::Symbol { .. }) {
type_at_definition_reference(namespace, &definition, &target_path)
} else {
None
};
let inferred = inferred.or_else(|| {
definition_reference
.as_ref()
.and_then(|reference| runner::preprocess::infer_static_definition_type(&reference.target_ns, &reference.target_def))
});
let expected = expected_type_at_path(entry, processed_root, namespace, &definition, &target_path);
let inferred_rendered = inferred
.as_ref()
.map(|annotation| format_type_query_annotation(annotation.as_ref()))
.transpose()?;
let (expected_rendered, expected_from) = match expected.as_ref() {
Some((annotation, source)) => (Some(format_type_query_annotation(annotation.as_ref())?), Some(source.clone())),
None => (None, None),
};
let methods = inferred.as_ref().and_then(|annotation| {
traced_target
.and_then(runner::preprocess::SourceExpressionEvidence::static_method_contracts)
.or_else(|| runner::preprocess::static_method_contracts(annotation.as_ref()))
.map(|items| {
items
.into_iter()
.map(|(method, contract)| context_method(method, contract))
.collect::<Vec<_>>()
})
});
let method_fingerprint = method_contract_fingerprint(&methods)?;
let revision = semantic_revision(&[&source_revision, &method_fingerprint]);
let fn_features = context_features(entry.schema.as_ref());
let dynamic_intent = if inferred
.as_ref()
.is_some_and(|annotation| matches!(annotation.as_ref(), CalcitTypeAnnotation::Dynamic))
&& fn_features.iter().any(|feature| feature == "js-ffi")
{
Some("intentional-js-ffi")
} else if inferred
.as_ref()
.is_some_and(|annotation| matches!(annotation.as_ref(), CalcitTypeAnnotation::Dynamic))
{
Some("unresolved")
} else {
None
};
let mut diagnostics = warnings
.borrow()
.iter()
.filter(|warning| warning_matches_type_at(warning, namespace, &definition, &target_path))
.map(warning_to_context_diagnostic)
.collect::<Vec<_>>();
if let Some(error) = compile_error {
diagnostics.push(ContextDiagnostic {
code: error
.code
.clone()
.unwrap_or_else(|| format!("E_{}", error.kind.to_string().to_uppercase())),
phase: "preprocess",
severity: "error",
message: error.msg,
path: error
.location
.as_ref()
.map(|location| semantic_code_path(&location.coord.iter().map(|idx| *idx as usize).collect::<Vec<_>>())),
intent: None,
provenance: *error.provenance,
});
}
if inferred.is_none() {
diagnostics.push(ContextDiagnostic {
code: "W_TYPE_AT_UNRESOLVED".to_owned(),
phase: "type-inference",
severity: "warning",
message: "Static inference could not determine a type for this expression without executing the program".to_owned(),
path: Some(semantic_path.clone()),
intent: dynamic_intent.map(str::to_owned),
provenance: vec![],
});
}
if let (Some(actual), Some((required, source))) = (inferred.as_ref(), expected.as_ref())
&& let Some(diagnostic) = type_at_expected_mismatch_diagnostic(actual.as_ref(), required.as_ref(), source, &semantic_path)
{
diagnostics.push(diagnostic);
}
let mut evidence = vec![match definition_reference.as_ref() {
Some(reference) => type_at_definition_reference_evidence(reference, &semantic_path),
None => type_at_evidence(inference_target, &semantic_path, processed_target.is_some()),
}];
if let Some(source) = &expected_from {
evidence.push(TypeAtEvidence {
kind: "expected-context".to_owned(),
detail: source.clone(),
path: target_path
.split_last()
.map(|(_, parent)| semantic_code_path(parent))
.or_else(|| Some("code".to_owned())),
});
}
let bindings = format_type_at_bindings(processed_root, processed_target)?;
let confidence = type_at_confidence(inferred.as_deref());
let lowering = type_at_lowering(&source_target, processed_target);
let data = TypeAtData {
id: format!("{namespace}/{definition}"),
path: semantic_path,
expression,
tree: cirru_to_json_value(&target_node),
inferred_type: inferred_rendered,
expected_type: expected_rendered,
expected_from,
confidence,
dynamic_intent,
evidence,
bindings,
bindings_complete: false,
static_methods: methods,
lowering,
};
let command_prefix = format!("calcit {}", shell_quote(input_path));
let quoted_target = shell_quote(&format!("{namespace}/{definition}"));
let tree_path = if target_path.is_empty() {
String::new()
} else {
format!(" --path {}", shell_quote(&format_path(&target_path)))
};
let mut next = vec![format!("{command_prefix} tree show {quoted_target}{tree_path}")];
if let Some(reference) = definition_reference.as_ref() {
next.push(format!(
"{command_prefix} query def {}",
shell_quote(&format!("{}/{}", reference.target_ns, reference.target_def))
));
}
if confidence != "exact" {
next.push(format!("{command_prefix} query schema {quoted_target}"));
next.push(format!(
"{command_prefix} analyze weak-types --ns {} --intent unresolved --format edn",
shell_quote(namespace)
));
}
let envelope = SemanticQueryEnvelope {
schema_version: TYPE_AT_SCHEMA_VERSION,
command: "query.type-at",
revision,
data,
diagnostics,
next,
};
match format {
QueryRenderFormat::Human => print!("{}", render_type_at_human(&envelope)),
QueryRenderFormat::Edn | QueryRenderFormat::Json => emit_query_structured(&envelope, format, "type-at result")?,
}
Ok(())
}
fn char_prefix_if_truncated(text: &str, max_chars: usize) -> Option<&str> {
text.char_indices().nth(max_chars).map(|(byte_index, _)| &text[..byte_index])
}
fn truncate_chars(text: &str, max_chars: usize) -> (String, bool) {
match char_prefix_if_truncated(text, max_chars) {
Some(prefix) => (format!("{prefix}…"), true),
None => (text.to_owned(), false),
}
}
fn truncate_chars_with_dots(text: &str, max_chars: usize) -> String {
match char_prefix_if_truncated(text, max_chars) {
Some(prefix) => format!("{prefix}..."),
None => text.to_owned(),
}
}
fn count_cirru_nodes(node: &Cirru) -> usize {
match node {
Cirru::Leaf(_) => 1,
Cirru::List(items) => 1 + items.iter().map(count_cirru_nodes).sum::<usize>(),
}
}
fn namespace_source(snapshot: &snapshot::Snapshot, namespace: &str) -> String {
if calcit_core::calcit::is_bundled_core_ns(namespace) {
"core".to_owned()
} else if namespace == snapshot.package || namespace.starts_with(&format!("{}.", snapshot.package)) {
"project".to_owned()
} else {
"dependency".to_owned()
}
}
fn js_ffi_owner(input_path: &str, snapshot: &snapshot::Snapshot, namespace: &str) -> Option<calcit_core::JsNamespaceSource> {
let base_dir = Path::new(input_path).parent().unwrap_or_else(|| Path::new("."));
if snapshot.files.contains_key(namespace) && namespace_source(snapshot, namespace) == "project" {
return Some(calcit_core::JsNamespaceSource {
module: snapshot.package.clone(),
version: calcit_core::module_manifest_version(base_dir)
.ok()
.flatten()
.unwrap_or_else(|| snapshot.version.clone()),
root: base_dir.to_path_buf(),
});
}
let module_folder = calcit_core::project_module_folder(base_dir);
for module_path in &snapshot.active_entry().ok()?.modules {
if let Ok(loaded) = load_module_with_sources_silent(module_path, base_dir, &module_folder)
&& let Some(owner) = loaded.namespace_sources.get(namespace)
{
return Some(owner.clone());
}
}
None
}
fn js_ffi_query_info(input_path: &str, snapshot: &snapshot::Snapshot, namespace: &str, ffi: &cirru_edn::Edn) -> Option<JsFfiQueryInfo> {
snapshot::ffi_metadata_value(ffi, "js")?;
let owner = js_ffi_owner(input_path, snapshot, namespace);
let target = snapshot::parse_ffi_target(ffi)
.ok()
.flatten()
.map(|target| target.as_str().to_owned());
let (source_kind, source_file, modules, metadata_error) = match parse_js_source(ffi) {
Ok(Some(source)) => {
let (kind, file) = match source.source {
JsFfiSource::Inline(_) => (Some("inline"), None),
JsFfiSource::File { path } => (Some("file"), Some(path)),
};
(kind, file, source.modules.into_iter().collect(), None)
}
Ok(None) => (None, None, BTreeMap::new(), None),
Err(error) => (None, None, BTreeMap::new(), Some(error)),
};
Some(JsFfiQueryInfo {
target,
owner_module: owner.as_ref().map(|source| source.module.clone()),
owner_version: owner.as_ref().map(|source| source.version.clone()),
module_root: owner.map(|source| source.root.canonicalize().unwrap_or(source.root).to_string_lossy().into_owned()),
source_kind,
source_file,
modules,
metadata_error,
})
}
fn render_js_ffi_info(info: &JsFfiQueryInfo, inline_source: Option<&str>) -> String {
let mut out = String::new();
let _ = writeln!(&mut out, "## JavaScript implementation\n");
let _ = writeln!(&mut out, "- Target: `{}`", info.target.as_deref().unwrap_or("unknown"));
let _ = writeln!(&mut out, "- Owner module: `{}`", info.owner_module.as_deref().unwrap_or("unknown"));
let _ = writeln!(
&mut out,
"- Owner version: `{}`",
info.owner_version.as_deref().unwrap_or("unknown")
);
if let Some(root) = &info.module_root {
let _ = writeln!(&mut out, "- Module root: `{root}`");
}
if let Some(kind) = info.source_kind {
let _ = writeln!(&mut out, "- Source kind: `{kind}`");
}
if let Some(file) = &info.source_file {
let _ = writeln!(&mut out, "- Source file: `{file}` (relative to module root)");
}
if !info.modules.is_empty() {
let _ = writeln!(&mut out, "- External modules:");
for (alias, specifier) in &info.modules {
let _ = writeln!(&mut out, " - `{alias}` → `{specifier}`");
}
}
if let Some(error) = &info.metadata_error {
let _ = writeln!(&mut out, "- Metadata error: {error}");
}
let _ = writeln!(
&mut out,
"- Contract: the Fn schema is declared by the module author; it does not prove the JavaScript implementation."
);
if let Some(source) = inline_source {
let _ = writeln!(&mut out, "\n### Inline JavaScript\n");
out.push_str(&markdown_fenced_block("javascript", source));
}
out
}
fn context_schema(annotation: &CalcitTypeAnnotation) -> Result<Option<String>, String> {
match annotation {
CalcitTypeAnnotation::Dynamic => Ok(None),
CalcitTypeAnnotation::Fn(_) | CalcitTypeAnnotation::Macro(_) => Ok(Some(format_query_schema(annotation, true).trim().to_owned())),
_ => Ok(Some(format_type_query_annotation(annotation)?)),
}
}
fn definition_context_schema(schema: &Arc<CalcitTypeAnnotation>) -> Result<Option<String>, String> {
match schema.as_ref() {
CalcitTypeAnnotation::Dynamic if !snapshot::schema_annotation_is_missing(schema) => Ok(Some("Dynamic".to_owned())),
annotation => context_schema(annotation),
}
}
fn context_features(annotation: &CalcitTypeAnnotation) -> Vec<String> {
let mut features = match annotation {
CalcitTypeAnnotation::Fn(fn_annot) => fn_annot
.features
.iter()
.map(|feature| feature.ref_str().to_owned())
.collect::<Vec<_>>(),
CalcitTypeAnnotation::Macro(signature) => signature
.features
.iter()
.map(|feature| feature.ref_str().to_owned())
.collect::<Vec<_>>(),
_ => vec![],
};
features.sort();
features
}
fn build_context_code(node: &Cirru, max_chars: usize) -> Result<ContextCode, String> {
let nodes = count_cirru_nodes(node);
let rendered = match node {
Cirru::Leaf(value) => value.to_string(),
Cirru::List(_) => cirru_parser::format(std::slice::from_ref(node), true.into())
.map_err(|error| format!("Failed to format definition code: {error}"))?,
};
let (cirru, truncated) = truncate_chars(rendered.trim(), max_chars);
let tree = if !truncated && nodes <= 180 {
Some(cirru_to_json(node))
} else {
None
};
Ok(ContextCode {
root: "code",
nodes,
cirru,
tree,
truncated,
})
}
fn build_context_examples(examples: &[Cirru], limit: usize, budget: usize) -> Result<ContextCollection<ContextExample>, String> {
let returned_count = examples.len().min(limit);
let per_example_budget = budget
.checked_div(returned_count)
.map(|value| value.clamp(120, 1200))
.unwrap_or_default();
let mut items = Vec::with_capacity(returned_count);
for (index, example) in examples.iter().take(returned_count).enumerate() {
let nodes = count_cirru_nodes(example);
let rendered = match example {
Cirru::Leaf(value) => value.to_string(),
Cirru::List(_) => cirru_parser::format(std::slice::from_ref(example), true.into())
.map_err(|error| format!("Failed to format definition example {index}: {error}"))?,
};
let (cirru, truncated) = truncate_chars(rendered.trim(), per_example_budget);
items.push(ContextExample {
index,
cirru,
tree: if !truncated && nodes <= 100 {
Some(cirru_to_json(example))
} else {
None
},
truncated,
});
}
Ok(ContextCollection::new(examples.len(), items))
}
fn build_context_tests(tests: &[snapshot::TestEntry], limit: usize, budget: usize) -> Result<ContextCollection<ContextTest>, String> {
let returned_count = tests.len().min(limit);
let per_test_budget = budget
.checked_div(returned_count)
.map(|value| value.clamp(120, 1200))
.unwrap_or_default();
let mut items = Vec::with_capacity(returned_count);
for test in tests.iter().take(returned_count) {
let nodes = count_cirru_nodes(&test.code);
let rendered = cirru_parser::format(std::slice::from_ref(&test.code), true.into())
.map_err(|error| format!("Failed to format definition test `{}`: {error}", test.name))?;
let (cirru, truncated) = truncate_chars(rendered.trim(), per_test_budget);
let mut tags = test.tags.iter().map(|tag| tag.ref_str().to_owned()).collect::<Vec<_>>();
tags.sort();
items.push(ContextTest {
name: test.name.clone(),
tags,
cirru,
tree: if !truncated && nodes <= 100 {
Some(cirru_to_json(&test.code))
} else {
None
},
truncated,
});
}
Ok(ContextCollection::new(tests.len(), items))
}
fn is_core_syntax_dependency(id: &str, source: &str) -> bool {
if source != "core" {
return false;
}
let Some(name) = id.strip_prefix(&format!("{}/", calcit_core::calcit::CORE_NS)) else {
return false;
};
calcit_core::calcit::CalcitSyntax::is_valid(name)
|| program::lookup_def_code(calcit_core::calcit::CORE_NS, name).is_some_and(|code| {
matches!(&code, Calcit::List(items) if matches!(
items.first(),
Some(Calcit::Syntax(calcit_core::calcit::CalcitSyntax::Defmacro, _))
) || matches!(items.first(), Some(Calcit::Symbol { sym, .. }) if sym.as_ref() == "defmacro"))
})
}
fn collect_direct_dependencies(
snapshot: &snapshot::Snapshot,
namespace: &str,
definition: &str,
) -> Result<Vec<(String, String)>, String> {
let mut analyzer = CallTreeAnalyzer::new(CallTreeConfig {
include_core: true,
max_depth: 1,
show_unused: false,
package_name: Some(snapshot.package.clone()),
ns_prefix: None,
});
let result = analyzer.analyze(namespace, definition)?;
let mut dependencies = result
.tree
.calls
.into_iter()
.map(|node| (node.fqn, node.source))
.collect::<Vec<_>>();
dependencies.sort();
dependencies.dedup_by(|left, right| left.0 == right.0);
Ok(dependencies)
}
fn context_usages(
snapshot: &snapshot::Snapshot,
namespace: &str,
definition: &str,
include_deps: bool,
limit: usize,
) -> Result<ContextCollection<ContextUsage>, String> {
let mut usages = collect_usages_from_snapshot(snapshot, namespace, definition, true)?
.into_iter()
.filter_map(|(usage_ns, usage_def, _context, coords, area)| {
let source = namespace_source(snapshot, &usage_ns);
if !include_deps && source != "project" {
return None;
}
Some(ContextUsage {
id: format!("{usage_ns}/{usage_def}"),
source,
area: area.to_owned(),
paths: coords.iter().map(|path| format!("{area}{}", format_path(path))).collect(),
})
})
.collect::<Vec<_>>();
usages.sort_by(|left, right| (&left.id, &left.area).cmp(&(&right.id, &right.area)));
let total = usages.len();
usages.truncate(limit);
Ok(ContextCollection::new(total, usages))
}
fn context_docs(definition: &str, diagnostics: &mut Vec<ContextDiagnostic>) -> ContextCollection<ContextDocLink> {
match super::docs::lookup_definition_docs(definition) {
Ok(lookup) => {
for (path, err) in lookup.unreadable_files {
diagnostics.push(ContextDiagnostic {
code: "I_DOC_INDEX_UNAVAILABLE".to_owned(),
phase: "documentation",
severity: "info",
message: format!("Failed to read documentation file '{path}': {err}"),
path: Some(path),
intent: None,
provenance: vec![],
});
}
let total = lookup.links.len();
let items = lookup
.links
.into_iter()
.take(6)
.map(|link| ContextDocLink {
id: link.id,
path: link.path,
title: link.title,
summary: link.summary,
})
.collect();
ContextCollection::new(total, items)
}
Err(error) => {
diagnostics.push(ContextDiagnostic {
code: "I_DOC_INDEX_UNAVAILABLE".to_owned(),
phase: "documentation",
severity: "info",
message: error.lines().next().unwrap_or(&error).to_owned(),
path: None,
intent: None,
provenance: vec![],
});
ContextCollection::new(0, vec![])
}
}
}
fn context_methods(annotation: &CalcitTypeAnnotation, budget: usize, include_core: bool) -> Option<ContextCollection<ContextMethod>> {
let mut methods = runner::preprocess::static_method_contracts(annotation)?;
if !include_core {
methods.retain(|(descriptor, _)| !descriptor.origin.ends_with("/&core-fn-methods"));
}
let total = methods.len();
let limit = (budget / 240).clamp(4, 80);
let items = methods
.into_iter()
.take(limit)
.map(|(method, contract)| context_method(method, contract))
.collect::<Vec<_>>();
Some(ContextCollection::new(total, items))
}
fn weak_type_diagnostics(entry: &snapshot::CodeEntry, budget: usize) -> Vec<ContextDiagnostic> {
let Some(row) =
crate::type_coverage::analyze_weak_types_entry("context", "target", entry, &crate::type_coverage::WeakTypeKind::all())
else {
return vec![];
};
let limit = (budget / 220).clamp(4, 24);
let total = row.occurrences.len();
let mut diagnostics = row
.occurrences
.into_iter()
.take(limit)
.map(|occurrence| {
let intentional = matches!(
occurrence.intent,
crate::type_coverage::WeakTypeIntent::IntentionalJsFfi
| crate::type_coverage::WeakTypeIntent::IntentionalMacroSyntax
| crate::type_coverage::WeakTypeIntent::IntentionalTypeSlotDynamic
| crate::type_coverage::WeakTypeIntent::IntentionalDecode
| crate::type_coverage::WeakTypeIntent::IntentionalOpen
);
ContextDiagnostic {
code: if intentional {
"I_DYNAMIC_TYPE_INTENTIONAL".to_owned()
} else {
"W_DYNAMIC_TYPE_UNRESOLVED".to_owned()
},
phase: "static-analysis",
severity: if intentional { "info" } else { "warning" },
message: format!("{} ({})", occurrence.kind.as_str(), occurrence.detail),
path: Some(occurrence.path),
intent: Some(occurrence.intent.as_str().to_owned()),
provenance: vec![],
}
})
.collect::<Vec<_>>();
if diagnostics.len() < total {
diagnostics.push(ContextDiagnostic {
code: "I_DIAGNOSTICS_TRUNCATED".to_owned(),
phase: "static-analysis",
severity: "info",
message: format!(
"{} additional weak-type diagnostic(s) omitted by the context budget",
total - diagnostics.len()
),
path: None,
intent: None,
provenance: vec![],
});
}
diagnostics
}
fn build_regular_context(
snapshot: &snapshot::Snapshot,
namespace: &str,
definition: &str,
entry: &snapshot::CodeEntry,
opts: &QueryContextCommand,
) -> Result<SemanticQueryEnvelope<DefinitionContextData>, String> {
let mut revision = snapshot::definition_revision(entry)?;
let mut coverage = crate::type_coverage::analyze_code_entry(namespace, definition, entry);
let intentional_ffi = context_features(entry.schema.as_ref()).iter().any(|feature| feature == "js-ffi");
let mut diagnostics = weak_type_diagnostics(entry, opts.budget);
if matches!(&entry.code, Cirru::Leaf(_)) {
diagnostics.push(ContextDiagnostic {
code: "I_SOURCE_BODY_UNAVAILABLE".to_owned(),
phase: "source",
severity: "info",
message: "definition has a leaf placeholder rather than a source body".to_owned(),
path: Some("code".to_owned()),
intent: None,
provenance: vec![],
});
}
if coverage.level == crate::type_coverage::CoverageLevel::None && !intentional_ffi {
diagnostics.insert(
0,
ContextDiagnostic {
code: "W_TYPE_COVERAGE_NONE".to_owned(),
phase: "static-analysis",
severity: "warning",
message: "definition has no trusted static type coverage".to_owned(),
path: Some("schema".to_owned()),
intent: None,
provenance: vec![],
},
);
}
for issue in &coverage.schema_issues {
diagnostics.push(ContextDiagnostic {
code: "W_SCHEMA_MISMATCH".to_owned(),
phase: "static-analysis",
severity: "warning",
message: issue.clone(),
path: Some("schema".to_owned()),
intent: None,
provenance: vec![],
});
}
let metadata_ready = prepare_program_for_type_query(snapshot);
let inferred_schema = if metadata_ready.is_ok() && snapshot::schema_annotation_is_missing(&entry.schema) {
let warnings = RefCell::new(vec![]);
let result = runner::preprocess::compile_source_def_for_snapshot(namespace, definition, &warnings, &CallStackList::default());
diagnostics.extend(warnings.borrow().iter().map(warning_to_context_diagnostic));
if let Err(error) = &result {
diagnostics.push(ContextDiagnostic {
code: error.code.clone().unwrap_or_else(|| "E_PREPROCESS".to_owned()),
phase: "preprocess",
severity: "error",
message: error.msg.clone(),
path: Some("code".to_owned()),
intent: None,
provenance: error.provenance.as_ref().clone(),
});
}
if result.is_ok() && warnings.borrow().is_empty() {
program::lookup_compiled_def(namespace, definition)
.and_then(|compiled| runner::preprocess::infer_static_type_from_expr(&compiled.preprocessed_code))
.filter(|annotation| matches!(annotation.as_ref(), CalcitTypeAnnotation::Fn(_)))
} else {
None
}
} else {
None
};
if let Some(schema) = &inferred_schema {
let mut effective = entry.clone();
effective.schema = schema.clone();
coverage = crate::type_coverage::analyze_code_entry(namespace, definition, &effective);
diagnostics = weak_type_diagnostics(&effective, opts.budget);
diagnostics.push(ContextDiagnostic {
code: "I_SCHEMA_INFERRED".to_owned(),
phase: "preprocess",
severity: "info",
message: "Function contract is proven by ordinary preprocessing; no root schema was written to source".to_owned(),
path: Some("code".to_owned()),
intent: None,
provenance: vec![],
});
revision = semantic_revision(&[&revision, &format_type_query_annotation(schema)?]);
}
if let Err(error) = &metadata_ready {
diagnostics.push(ContextDiagnostic {
code: "W_STATIC_METADATA_UNAVAILABLE".to_owned(),
phase: "preprocess",
severity: "warning",
message: error.clone(),
path: None,
intent: None,
provenance: vec![],
});
}
let dependencies = if metadata_ready.is_ok() {
match collect_direct_dependencies(snapshot, namespace, definition) {
Ok(items) => items,
Err(error) => {
diagnostics.push(ContextDiagnostic {
code: "W_DEPENDENCY_ANALYSIS_FAILED".to_owned(),
phase: "static-analysis",
severity: "warning",
message: error,
path: Some("code".to_owned()),
intent: None,
provenance: vec![],
});
vec![]
}
}
} else {
vec![]
};
let dependencies = dependencies
.into_iter()
.filter(|(id, source)| opts.include_core || !is_core_syntax_dependency(id, source))
.collect::<Vec<_>>();
let dependency_total = dependencies.len();
let dependency_items = dependencies
.into_iter()
.take(opts.dependency_limit)
.map(|(id, source)| ContextDependency { id, source })
.collect();
let mut tags = entry.tags.iter().map(|tag| tag.ref_str().to_owned()).collect::<Vec<_>>();
tags.sort();
let doc_limit = (opts.budget / 6).clamp(160, 1200);
let (doc, doc_truncated) = if entry.doc.trim().is_empty() {
(None, false)
} else {
let (text, truncated) = truncate_chars(entry.doc.trim(), doc_limit);
(Some(text), truncated)
};
let code = build_context_code(&entry.code, (opts.budget / 3).clamp(320, 2600))?;
let examples = build_context_examples(&entry.examples, opts.example_limit, opts.budget / 4)?;
let tests = build_context_tests(&entry.tests, opts.test_limit, opts.budget / 4)?;
let usages = context_usages(snapshot, namespace, definition, opts.deps, opts.usage_limit)?;
let id = format!("{namespace}/{definition}");
let docs = context_docs(&id, &mut diagnostics);
let effective_schema = inferred_schema.as_deref().unwrap_or_else(|| entry.schema.as_ref());
let static_methods = if metadata_ready.is_ok() {
context_methods(effective_schema, opts.budget / 3, opts.include_core)
} else {
None
};
let layer = runner::preprocess::classify_code_entry(namespace, definition, entry);
let data = DefinitionContextData {
id,
uri: format!("calcit://definition/{namespace}/{definition}"),
source: namespace_source(snapshot, namespace),
kind: coverage.kind.as_str().to_owned(),
layer: layer.as_str(),
coverage: if intentional_ffi && coverage.level == crate::type_coverage::CoverageLevel::None {
"intentional-dynamic"
} else {
coverage.level.as_str()
}
.to_owned(),
doc,
doc_truncated,
tags,
schema: definition_context_schema(&entry.schema)?,
inferred_schema: inferred_schema.as_ref().map(|schema| context_schema(schema)).transpose()?.flatten(),
runtime_arity: core_runtime_call_arity(namespace, definition, entry),
failure: core_proc_failure(namespace, definition, entry),
features: context_features(effective_schema),
js_ffi: None,
code,
examples,
tests,
dependencies: ContextCollection::new(dependency_total, dependency_items),
usages,
docs,
static_methods,
};
let mut next = vec![
format!("calcit query schema {namespace}/{definition}"),
format!("calcit docs search {definition}"),
];
if data.code.truncated || data.code.tree.is_none() {
next.push(format!("calcit query def {namespace}/{definition}"));
}
if data.examples.truncated {
next.push(format!("calcit query def {namespace}/{definition} --only examples"));
}
if data.tests.truncated {
next.push(format!("calcit query def {namespace}/{definition} --only tests"));
}
if data.usages.truncated {
next.push(format!("calcit query usages {namespace}/{definition}"));
}
Ok(SemanticQueryEnvelope {
schema_version: 1,
command: "query.context",
revision,
data,
diagnostics,
next,
})
}
fn build_special_builtin_context(
snapshot: &snapshot::Snapshot,
namespace: &str,
definition: &str,
meta: SpecialBuiltinQueryMeta,
opts: &QueryContextCommand,
) -> Result<SemanticQueryEnvelope<DefinitionContextData>, String> {
let schema = format_query_schema(meta.schema.as_ref(), true).trim().to_owned();
let examples_fingerprint = meta
.examples
.iter()
.map(|example| example.format_one_liner().unwrap_or_default())
.collect::<Vec<_>>()
.join("\n");
let arity_fingerprint = meta.runtime_arity.map(render_runtime_call_arity).unwrap_or_default();
let revision = semantic_revision(&[meta.doc, &schema, &examples_fingerprint, meta.cirru_note, &arity_fingerprint]);
let tags = meta.semantic_tags.iter().map(|tag| (*tag).to_owned()).collect::<Vec<_>>();
let intentional_ffi = meta.semantic_tags.contains(&"js-ffi");
let (doc, doc_truncated) = truncate_chars(meta.doc, (opts.budget / 6).clamp(160, 1200));
let usages = context_usages(snapshot, namespace, definition, opts.deps, opts.usage_limit)?;
let examples = build_context_examples(&meta.examples, opts.example_limit, opts.budget / 4)?;
let id = format!("{namespace}/{definition}");
let mut diagnostics = vec![];
let docs = context_docs(&id, &mut diagnostics);
let metadata_ready = prepare_program_for_type_query(snapshot).is_ok();
let static_methods = if metadata_ready {
context_methods(meta.schema.as_ref(), opts.budget / 3, opts.include_core)
} else {
None
};
let layer = runner::preprocess::classify_special_builtin(namespace, definition, meta.semantic_tags);
let data = DefinitionContextData {
id,
uri: format!("calcit://definition/{namespace}/{definition}"),
source: "core-builtin".to_owned(),
kind: "proc".to_owned(),
layer: layer.as_str(),
coverage: if intentional_ffi { "intentional-dynamic" } else { "partial" }.to_owned(),
doc: Some(doc),
doc_truncated,
tags: tags.clone(),
schema: Some(schema),
inferred_schema: None,
runtime_arity: meta.runtime_arity,
failure: None,
features: tags,
js_ffi: None,
code: ContextCode {
root: "code",
nodes: 0,
cirru: meta.cirru_note.to_owned(),
tree: None,
truncated: false,
},
examples,
tests: ContextCollection::new(0, vec![]),
dependencies: ContextCollection::new(0, vec![]),
usages,
docs,
static_methods,
};
if intentional_ffi {
diagnostics.insert(
0,
ContextDiagnostic {
code: "I_DYNAMIC_TYPE_INTENTIONAL".to_owned(),
phase: "static-analysis",
severity: "info",
message: "dynamic values are intentional at this JS FFI boundary".to_owned(),
path: Some("schema".to_owned()),
intent: Some("intentional-js-ffi".to_owned()),
provenance: vec![],
},
);
}
Ok(SemanticQueryEnvelope {
schema_version: 1,
command: "query.context",
revision,
data,
diagnostics,
next: vec![
format!("calcit query def {namespace}/{definition}"),
format!("calcit query def {namespace}/{definition} --only examples"),
],
})
}
fn render_context_human(envelope: &SemanticQueryEnvelope<DefinitionContextData>) -> String {
let data = &envelope.data;
let mut out = String::new();
let _ = writeln!(&mut out, "# Definition context `{}`\n", data.id);
let _ = writeln!(&mut out, "- Resource: `{}`", data.uri);
let _ = writeln!(&mut out, "- Revision: `{}`", envelope.revision);
let _ = writeln!(&mut out, "- Source: `{}`", data.source);
let _ = writeln!(&mut out, "- Kind: `{}`", data.kind);
let _ = writeln!(&mut out, "- Layer: `{}`", data.layer);
let _ = writeln!(&mut out, "- Type coverage: `{}`", data.coverage);
if let Some(arity) = data.runtime_arity {
let _ = writeln!(&mut out, "- Runtime Proc arity: `{}`", render_runtime_call_arity(arity));
}
if let Some(failure) = &data.failure {
let _ = writeln!(&mut out, "- Failure: {}", render_proc_failure(failure));
}
if let Some(info) = &data.js_ffi {
let _ = writeln!(&mut out, "- JavaScript FFI: `{}`", info.source_kind.unwrap_or("invalid"));
}
let _ = writeln!(
&mut out,
"- Tags: {}",
if data.tags.is_empty() {
"-".to_owned()
} else {
data.tags.iter().map(|tag| format!(":{tag}")).collect::<Vec<_>>().join(" ")
}
);
let _ = writeln!(
&mut out,
"- Features: {}",
if data.features.is_empty() {
"-".to_owned()
} else {
data
.features
.iter()
.map(|feature| format!(":{feature}"))
.collect::<Vec<_>>()
.join(" ")
}
);
let _ = writeln!(&mut out, "\n## Documentation\n");
if let Some(doc) = &data.doc {
for line in doc.lines() {
let _ = writeln!(&mut out, "> {line}");
}
if data.doc_truncated {
let _ = writeln!(&mut out, "\n_Truncated._");
}
} else {
let _ = writeln!(&mut out, "_No documentation._");
}
let _ = writeln!(&mut out, "\n## Schema\n");
if let Some(schema) = &data.schema {
out.push_str(&markdown_fenced_block("cirru", schema));
} else {
let _ = writeln!(&mut out, "_No explicit schema._");
}
if let Some(schema) = &data.inferred_schema {
let _ = writeln!(&mut out, "\n## Inferred schema\n\n_Compiler evidence; not written to source._\n");
out.push_str(&markdown_fenced_block("cirru", schema));
}
if let Some(info) = &data.js_ffi {
let _ = writeln!(&mut out);
out.push_str(&render_js_ffi_info(info, None));
}
let _ = writeln!(
&mut out,
"\n## Code preview\n\n- Nodes: {}{}\n",
data.code.nodes,
if data.code.truncated { " (truncated)" } else { "" }
);
out.push_str(&markdown_fenced_block("cirru", &data.code.cirru));
let _ = writeln!(
&mut out,
"\n## Examples\n\nReturned {}/{}{}.",
data.examples.returned,
data.examples.total,
if data.examples.truncated { " (truncated)" } else { "" }
);
for example in &data.examples.items {
let _ = writeln!(
&mut out,
"\n### Example {}{}\n",
example.index,
if example.truncated { " (truncated)" } else { "" }
);
out.push_str(&markdown_fenced_block("cirru", &example.cirru));
}
let _ = writeln!(
&mut out,
"\n## Tests\n\nReturned {}/{}{}.",
data.tests.returned,
data.tests.total,
if data.tests.truncated { " (truncated)" } else { "" }
);
for test in &data.tests.items {
let tags = if test.tags.is_empty() {
String::new()
} else {
format!(" [{}]", test.tags.iter().map(|tag| format!(":{tag}")).collect::<Vec<_>>().join(" "))
};
let _ = writeln!(
&mut out,
"\n### Test `{}`{}{}\n",
test.name,
tags,
if test.truncated { " (truncated)" } else { "" }
);
out.push_str(&markdown_fenced_block("cirru", &test.cirru));
}
let _ = writeln!(
&mut out,
"\n## Direct dependencies\n\nReturned {}/{}{}.",
data.dependencies.returned,
data.dependencies.total,
if data.dependencies.truncated { " (truncated)" } else { "" }
);
for dependency in &data.dependencies.items {
let _ = writeln!(&mut out, "- `{}` [{}]", dependency.id, dependency.source);
}
let _ = writeln!(
&mut out,
"\n## Usages\n\nReturned {}/{}{}.",
data.usages.returned,
data.usages.total,
if data.usages.truncated { " (truncated)" } else { "" }
);
for usage in &data.usages.items {
let paths = if usage.paths.is_empty() {
"-".to_owned()
} else {
usage.paths.join(", ")
};
let _ = writeln!(&mut out, "- `{}` [{}:{}] @ `{}`", usage.id, usage.source, usage.area, paths);
}
let _ = writeln!(
&mut out,
"\n## Related docs\n\nReturned {}/{}{}.",
data.docs.returned,
data.docs.total,
if data.docs.truncated { " (truncated)" } else { "" }
);
for doc in &data.docs.items {
let title = doc.title.as_deref().unwrap_or("untitled");
let summary = doc.summary.as_deref().map(|summary| format!(" — {summary}")).unwrap_or_default();
let _ = writeln!(&mut out, "- `{}`: {} (`{}`){}", doc.id, title, doc.path, summary);
}
let _ = writeln!(&mut out, "\n## Static methods\n");
match &data.static_methods {
Some(methods) => {
let _ = writeln!(
&mut out,
"Returned {}/{}{}.",
methods.returned,
methods.total,
if methods.truncated { " (truncated)" } else { "" }
);
for method in &methods.items {
let _ = writeln!(&mut out, "{}", render_context_method(method));
}
}
None => {
let _ = writeln!(&mut out, "_Unknown._");
}
}
let _ = writeln!(&mut out, "\n## Diagnostics\n\nCount: {}.", envelope.diagnostics.len());
for diagnostic in &envelope.diagnostics {
let location = diagnostic.path.as_deref().map(|path| format!(" @ {path}")).unwrap_or_default();
let intent = diagnostic
.intent
.as_deref()
.map(|intent| format!(" [{intent}]"))
.unwrap_or_default();
let _ = writeln!(
&mut out,
"- **{}** `{}`{}{}: {}",
diagnostic.severity, diagnostic.code, intent, location, diagnostic.message
);
}
if !envelope.next.is_empty() {
let _ = writeln!(&mut out, "\n## Next\n");
for command in &envelope.next {
let _ = writeln!(&mut out, "- `{command}`");
}
}
out
}
fn handle_context(input_path: &str, opts: &QueryContextCommand, selected_entry: Option<&str>) -> Result<(), String> {
if opts.budget < 512 {
return Err("Context budget must be at least 512 characters".to_owned());
}
let format = parse_query_render_format(&opts.format)?;
let (namespace, requested_definition) = parse_target(&opts.target)?;
let resolved_input = Path::new(input_path);
calcit_core::validate_snapshot_path(resolved_input)?;
let snapshot = if resolved_input.exists() {
load_snapshot_with_entry(input_path, selected_entry)?
} else if namespace == calcit_core::calcit::CORE_NS || namespace == "calcit.internal" {
load_core_snapshot()?
} else {
return Err(format!("{} does not exist", resolved_input.display()));
};
let file = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace `{namespace}` not found"))?;
let mut envelope = if !file.defs.contains_key(requested_definition) {
if let Some(meta) = lookup_special_builtin_query_meta(namespace, requested_definition)? {
build_special_builtin_context(&snapshot, namespace, requested_definition, meta, opts)?
} else {
let lookup = resolve_definition_lookup(namespace, requested_definition, file.defs.keys().map(|name| name.as_str()), true)?;
if let Some(warning) = lookup.warning.as_deref() {
print_cli_warning_block(warning);
}
let entry = file.defs.get(&lookup.resolved).expect("resolved definition exists");
build_regular_context(&snapshot, namespace, &lookup.resolved, entry, opts)?
}
} else {
let entry = file.defs.get(requested_definition).expect("checked definition exists");
build_regular_context(&snapshot, namespace, requested_definition, entry, opts)?
};
if let Some((_, definition)) = envelope.data.id.split_once('/')
&& let Some(entry) = file.defs.get(definition)
&& let Some(ffi) = &entry.ffi
{
envelope.data.js_ffi = js_ffi_query_info(input_path, &snapshot, namespace, ffi);
if envelope.data.js_ffi.is_some() {
let command = format!("calcit query def {namespace}/{definition}");
if !envelope.next.contains(&command) {
envelope.next.push(command);
}
}
}
match format {
QueryRenderFormat::Human => print!("{}", render_context_human(&envelope)),
QueryRenderFormat::Edn | QueryRenderFormat::Json => emit_query_structured(&envelope, format, "context query result")?,
}
Ok(())
}
fn load_module_silent(path: &str, base_dir: &Path, module_folder: &Path) -> Result<snapshot::Snapshot, String> {
let previous = calcit_core::quiet_tool_output();
calcit_core::set_quiet_tool_output(true);
let result = calcit_core::load_module(path, base_dir, module_folder);
calcit_core::set_quiet_tool_output(previous);
result
}
pub fn load_module_with_sources_silent(
path: &str,
base_dir: &Path,
module_folder: &Path,
) -> Result<calcit_core::LoadedModuleSnapshot, String> {
let previous = calcit_core::quiet_tool_output();
calcit_core::set_quiet_tool_output(true);
let result = calcit_core::load_module_with_sources(path, base_dir, module_folder);
calcit_core::set_quiet_tool_output(previous);
result
}
fn load_snapshot(input_path: &str, entry: Option<&str>) -> Result<snapshot::Snapshot, String> {
load_snapshot_with_entry(input_path, entry)
}
pub fn load_main_snapshot(input_path: &str) -> Result<snapshot::Snapshot, String> {
let resolved_input_path = Path::new(input_path);
calcit_core::validate_snapshot_path(resolved_input_path)?;
let resolved_input_str = resolved_input_path.to_string_lossy().to_string();
if !resolved_input_path.exists() {
return Err(format!("{} does not exist", resolved_input_path.display()));
}
let mut content = fs::read_to_string(resolved_input_path).map_err(|e| format!("Failed to read file: {e}"))?;
strip_shebang(&mut content);
let data = cirru_edn::parse(&content).map_err(|e| {
eprintln!("\nFailed to parse file '{}':", resolved_input_path.display());
eprintln!("{e}");
format!("Failed to parse file '{}'", resolved_input_path.display())
})?;
let snapshot = snapshot::load_snapshot_data(&data, &resolved_input_str)?;
let project_namespaces = snapshot.files.keys().cloned().collect::<HashSet<_>>();
runner::preprocess::set_project_namespaces(&project_namespaces);
Ok(snapshot)
}
fn load_snapshot_for_namespace(input_path: &str, namespace: &str, entry: Option<&str>) -> Result<snapshot::Snapshot, String> {
let mut main_snapshot = load_main_snapshot(input_path)?;
if entry.is_some() {
main_snapshot.select_entry(entry)?;
}
if main_snapshot.files.contains_key(namespace) {
return Ok(main_snapshot);
}
if namespace == calcit_core::calcit::CORE_NS || namespace == "calcit.internal" {
return load_core_snapshot();
}
load_snapshot(input_path, entry)
}
fn snapshot_search_sources(
snapshot: &snapshot::Snapshot,
source: SearchSource,
module: Option<&str>,
) -> BTreeMap<String, (SearchSource, SearchOrigin)> {
snapshot
.files
.keys()
.map(|namespace| {
(
namespace.clone(),
(
source,
SearchOrigin {
package: snapshot.package.clone(),
module: module.map(str::to_owned),
},
),
)
})
.collect()
}
fn load_snapshot_for_search(input_path: &str, options: &SearchCommonOpts) -> Result<SearchCatalog, String> {
let mut snapshot = load_main_snapshot(input_path)?;
snapshot.select_entry(options.entry)?;
if options.source == SearchSource::Core {
let snapshot = load_core_snapshot()?;
let sources = snapshot_search_sources(&snapshot, SearchSource::Core, Some("builtin"));
return Ok(SearchCatalog { snapshot, sources });
}
let mut sources = snapshot_search_sources(&snapshot, SearchSource::Project, None);
if options.source == SearchSource::Project {
return Ok(SearchCatalog { snapshot, sources });
}
if options.source == SearchSource::All
&& options.entry.is_none()
&& let Some(filter) = options.filter
{
let namespace = filter.split_once('/').map(|(namespace, _)| namespace).unwrap_or(filter);
if snapshot.files.contains_key(namespace) {
return Ok(SearchCatalog { snapshot, sources });
}
if namespace == calcit_core::calcit::CORE_NS || namespace == "calcit.internal" {
let snapshot = load_core_snapshot()?;
let sources = snapshot_search_sources(&snapshot, SearchSource::Core, Some("builtin"));
return Ok(SearchCatalog { snapshot, sources });
}
}
let mut modules_to_load = snapshot.active_entry()?.modules.clone();
let mut seen_modules = HashSet::new();
modules_to_load.retain(|module_path| seen_modules.insert(module_path.to_owned()));
let base_dir = Path::new(input_path).parent().unwrap_or_else(|| Path::new("."));
let module_folder = calcit_core::project_module_folder(base_dir);
for module_path in &modules_to_load {
match load_module_silent(module_path, base_dir, &module_folder) {
Ok(module_snapshot) => {
let module_package = module_snapshot.package.clone();
let module_namespaces = module_snapshot.files.keys().cloned().collect::<Vec<_>>();
calcit_core::merge_project_module_files(&mut snapshot, &module_snapshot, module_path)?;
for namespace in module_namespaces {
if snapshot.files.contains_key(&namespace) && !sources.contains_key(&namespace) {
sources.insert(
namespace,
(
SearchSource::Deps,
SearchOrigin {
package: module_package.clone(),
module: Some(module_path.clone()),
},
),
);
}
}
}
Err(error) => eprintln!("Warning: Failed to load module '{module_path}': {error}"),
}
}
if options.source == SearchSource::All {
let core_snapshot = load_core_snapshot()?;
let core_package = core_snapshot.package.clone();
for (namespace, file_data) in core_snapshot.files {
if let std::collections::hash_map::Entry::Vacant(entry) = snapshot.files.entry(namespace.clone()) {
sources.insert(
namespace,
(
SearchSource::Core,
SearchOrigin {
package: core_package.clone(),
module: Some("builtin".to_owned()),
},
),
);
entry.insert(file_data);
}
}
}
if options.source == SearchSource::Deps {
snapshot
.files
.retain(|namespace, _| sources.get(namespace).is_some_and(|(source, _)| *source == SearchSource::Deps));
sources.retain(|_, (source, _)| *source == SearchSource::Deps);
}
Ok(SearchCatalog { snapshot, sources })
}
pub fn load_snapshot_for_static_analysis(input_path: &str, entry: Option<&str>) -> Result<snapshot::Snapshot, String> {
load_snapshot_with_entry(input_path, entry)
}
fn load_snapshot_with_entry(input_path: &str, entry: Option<&str>) -> Result<snapshot::Snapshot, String> {
let mut snapshot = load_main_snapshot(input_path)?;
snapshot.select_entry(entry)?;
let mut modules_to_load = snapshot.active_entry()?.modules.clone();
let mut seen_modules = HashSet::new();
modules_to_load.retain(|module_path| seen_modules.insert(module_path.to_owned()));
let base_dir = Path::new(input_path).parent().unwrap_or_else(|| Path::new("."));
let module_folder = calcit_core::project_module_folder(base_dir);
for module_path in &modules_to_load {
match load_module_silent(module_path, base_dir, &module_folder) {
Ok(module_snapshot) => {
calcit_core::merge_project_module_files(&mut snapshot, &module_snapshot, module_path)?;
}
Err(e) => {
eprintln!("Warning: Failed to load module '{module_path}': {e}");
}
}
}
let core_snapshot = load_core_snapshot()?;
for (ns_name, file_data) in core_snapshot.files {
snapshot.files.entry(ns_name).or_insert(file_data);
}
Ok(snapshot)
}
fn handle_ns(
input_path: &str,
namespace: Option<&str>,
include_deps: bool,
format: StructuredOutputFormat,
entry: Option<&str>,
) -> Result<(), String> {
if let Some(ns_name) = namespace {
return handle_ns_details(input_path, ns_name, format, entry);
}
if !Path::new(input_path).exists() {
return Err(format!("{input_path} does not exist"));
}
let mut content = fs::read_to_string(input_path).map_err(|e| format!("Failed to read file: {e}"))?;
strip_shebang(&mut content);
let data = cirru_edn::parse(&content).map_err(|e| {
eprintln!("\nFailed to parse file '{input_path}':");
eprintln!("{e}");
format!("Failed to parse file '{input_path}'")
})?;
let main_snapshot = snapshot::load_snapshot_data(&data, input_path)?;
let main_package = main_snapshot.package.clone();
let snapshot = if include_deps {
load_snapshot(input_path, entry)?
} else {
main_snapshot
};
let mut namespaces: Vec<&String> = snapshot.files.keys().collect();
namespaces.sort();
let filtered: Vec<_> = namespaces
.iter()
.filter(|ns| {
if !include_deps {
ns.as_str() == main_package || ns.starts_with(&format!("{main_package}."))
} else {
true
}
})
.collect();
if format != StructuredOutputFormat::Human {
let generated: Vec<_> = filtered.iter().filter(|ns| snapshot::is_generated_namespace(ns)).collect();
return format.print_value(&serde_json::json!({
"schema_version": 1,
"command": "query.ns",
"data": {
"include_dependencies": include_deps,
"count": filtered.len(),
"namespaces": filtered,
"generated": generated,
},
}));
}
println!(
"{} ({} namespaces)",
if include_deps { "All namespaces:" } else { "Project namespaces:" }.bold(),
filtered.len()
);
for ns in &filtered {
if snapshot::is_generated_namespace(ns) {
println!(" {} {}", ns.cyan(), "(generated, not in Snapshot)".dimmed());
} else {
println!(" {}", ns.cyan());
}
}
Ok(())
}
fn handle_ns_cirru_view(input_path: &str, namespace: &str, entry: Option<&str>) -> Result<(), String> {
if snapshot::is_generated_namespace(namespace) {
return Err(format!(
"Namespace '{namespace}' is generated at load time and is not stored in the Snapshot, so it has no FileEntry source to edit"
));
}
let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
print!("{}", super::ns_view::render_ns_view(file_data)?);
Ok(())
}
fn handle_ns_details(input_path: &str, namespace: &str, format: StructuredOutputFormat, entry: Option<&str>) -> Result<(), String> {
let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let generated = snapshot::is_generated_namespace(namespace);
if format != StructuredOutputFormat::Human {
return format.print_value(&serde_json::json!({
"schema_version": 1,
"command": "query.ns",
"data": {
"namespace": namespace,
"generated": generated,
"doc": file_data.ns.doc,
"ns_code": cirru_to_json_value(&file_data.ns.code),
"definition_count": file_data.defs.len(),
},
}));
}
if generated {
println!("{}", "Generated at load time, not stored in the Snapshot.".dimmed());
}
if !file_data.ns.doc.is_empty() {
println!("{} {}", "Doc:".bold(), file_data.ns.doc);
}
println!("\n{}", "NS declaration:".bold());
let ns_str =
cirru_parser::format(std::slice::from_ref(&file_data.ns.code), true.into()).unwrap_or_else(|_| "(failed to format)".to_string());
println!("{}", ns_str.dimmed());
println!("\n{} {}", "Definitions:".bold(), file_data.defs.len());
Ok(())
}
fn parse_query_tag(raw: &str) -> Result<EdnTag, String> {
let trimmed = raw.trim();
if trimmed.is_empty() {
return Err("empty tag".to_string());
}
let name = trimmed.strip_prefix(':').unwrap_or(trimmed);
if name.is_empty() {
return Err(format!("invalid tag: {raw}"));
}
Ok(EdnTag::new(name))
}
fn format_tags_display(tags: &HashSet<EdnTag>) -> String {
let mut items: Vec<String> = tags.iter().map(|tag| format!(":{}", tag.ref_str())).collect();
items.sort();
items.join(",")
}
fn definition_signature(entry: &snapshot::CodeEntry) -> String {
if let Ok(Some(schema)) = definition_schema_cirru(&entry.schema, true)
&& let Ok(text) = format_query_schema_oneline(&schema)
{
return text;
}
let Cirru::List(items) = &entry.code else {
return "(untyped)".to_owned();
};
let takes_params = items
.first()
.is_some_and(|head| ["defn", "defmacro", "defcomp", "defeffect"].iter().any(|name| head.eq_leaf(name)));
let keep = if takes_params && matches!(items.get(2), Some(Cirru::List(_))) {
3
} else {
2
};
let head = Cirru::List(items.iter().take(keep).cloned().collect());
let text = head.format_one_liner().unwrap_or_else(|_| "(untyped)".to_owned());
format!("(untyped) {text}")
}
fn handle_defs(input_path: &str, opts: &QueryDefsCommand, entry: Option<&str>) -> Result<(), String> {
let format = parse_query_render_format(&opts.format)?;
let filter_tag = opts.tag.as_deref().map(parse_query_tag).transpose()?;
let namespace = &opts.namespace;
let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let mut defs: Vec<&String> = file_data.defs.keys().collect();
defs.sort();
let total = defs.len();
if let Some(tag) = &filter_tag {
defs.retain(|def| file_data.defs[*def].tags.contains(tag));
}
if format != QueryRenderFormat::Human {
let definitions = defs
.iter()
.map(|name| {
let mut definition = serde_json::json!({ "name": name });
if opts.signatures {
definition["signature"] = serde_json::json!(definition_signature(&file_data.defs[*name]));
}
definition
})
.collect::<Vec<_>>();
let data = serde_json::json!({
"namespace": namespace,
"count": defs.len(),
"definition_count": total,
"filters": {
"tag": filter_tag.as_ref().map(EdnTag::ref_str),
"signatures": opts.signatures,
},
"definitions": definitions,
});
let fingerprint = serde_json::to_string(&data).map_err(|error| format!("Failed to encode definition list: {error}"))?;
return emit_query_structured(
&SemanticQueryEnvelope {
schema_version: 1,
command: "query.defs",
revision: semantic_revision(&["query.defs", &fingerprint]),
data,
diagnostics: vec![],
next: vec![],
},
format,
"definition list",
);
}
if let Some(tag) = &filter_tag {
println!(
"{} {} (filtered by {}, {} total)",
"Definitions:".bold(),
defs.len(),
format!(":{}", tag.ref_str()).yellow(),
total
);
} else {
println!("{} {}", "Definitions:".bold(), defs.len());
}
for def in &defs {
let entry = &file_data.defs[*def];
let tags_hint = if entry.tags.is_empty() {
String::new()
} else {
format!(" [{}]", format_tags_display(&entry.tags))
};
let schema_hint = if opts.signatures {
format!(" {}", definition_signature(entry))
} else if !snapshot::schema_annotation_is_missing(&entry.schema) {
" [schema]".to_owned()
} else {
String::new()
};
if !entry.doc.is_empty() {
let doc_first_line = entry.doc.lines().next().unwrap_or("");
let doc_display = truncate_chars_with_dots(doc_first_line, 50);
println!(
" {}{}{} - {}",
def.green(),
tags_hint.yellow(),
schema_hint.dimmed(),
doc_display.dimmed()
);
} else {
println!(" {}{}{}", def.green(), tags_hint.yellow(), schema_hint.dimmed());
}
}
Ok(())
}
fn handle_config(input_path: &str, opts: &QueryConfigCommand) -> Result<(), String> {
let format = parse_query_render_format(&opts.format)?;
if format != QueryRenderFormat::Human {
let command = ConfigCommand {
subcommand: ConfigSubcommand::Show(ConfigShowCommand {
entry: None,
format: opts.format.clone(),
}),
};
return super::config::handle_config_command(&command, input_path);
}
let snapshot = load_main_snapshot(input_path)?;
println!("# Project configuration\n");
println!("Package: `{}`\n", snapshot.package);
let deps_path = deps_path_for_snapshot(input_path);
println!("Version: managed in `deps.cirru` (use `caps version get {deps_path}`).\n");
println!("## Snapshot entries\n");
let mut names: Vec<&String> = snapshot.entries.keys().collect();
names.sort();
for name in names {
let entry = snapshot
.entries
.get(name)
.ok_or_else(|| format!("Missing entry config for '{name}'"))?;
println!("### `{name}`\n");
println!("- Mode: `{}`", entry.mode);
println!("- Init: `{}`", entry.init_fn);
println!("- Reload: `{}`", entry.reload_fn);
println!("- Modules: `{:?}`", entry.modules);
println!("- Type slots: `{:?}`\n", entry.type_slots);
}
Ok(())
}
fn handle_error(input_path: &str) -> Result<(), String> {
let project_directory = project_state::project_directory_for_snapshot(input_path);
let error_file = project_state::state_file(project_directory, ERROR_STATE_FILE);
let legacy_error_file = project_directory.join(".calcit-error.cirru");
let mut selected_file = None;
for candidate in [&error_file, &legacy_error_file] {
match fs::symlink_metadata(candidate) {
Ok(_) => {
selected_file = Some(candidate);
break;
}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
if let Some(parent) = candidate.parent() {
match fs::symlink_metadata(parent) {
Ok(metadata) if metadata.is_symlink() => {
fs::metadata(parent).map_err(|error| format!("Failed to get metadata of error file: {error}"))?;
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("Failed to get metadata of error file: {error}")),
}
}
}
Err(error) => return Err(format!("Failed to get metadata of error file: {error}")),
}
}
let Some(error_file) = selected_file else {
println!("{}", "No .calcit/error.cirru file found.".yellow());
if command_guidance_enabled() {
println!();
println!("{}", "Next steps:".blue().bold());
println!(" • Start watcher: {} or {}", "calcit".cyan(), "calcit js".cyan());
println!(" • Run syntax check: {}", "calcit --check-only".cyan());
}
return Ok(());
};
let metadata = fs::metadata(error_file).map_err(|e| format!("Failed to get metadata of error file: {e}"))?;
if let Ok(modified) = metadata.modified()
&& let Ok(elapsed) = modified.elapsed()
&& elapsed.as_secs() > 10
{
println!(
"{}",
format!("Warning: {} was modified {} seconds ago.", error_file.display(), elapsed.as_secs()).yellow()
);
println!("{}", "It might be outdated, please recompile or check the watcher.".yellow());
println!();
}
let content = fs::read_to_string(error_file).map_err(|e| format!("Failed to read error file: {e}"))?;
if error_file == &legacy_error_file {
eprintln!("Reading legacy error state from '{}' without moving it.", error_file.display());
}
if content.trim().is_empty() {
println!("{}", "✓ Error file is empty (no recent errors).".green());
println!();
println!("{}", "Your code compiled successfully!".dimmed());
println!(
"{}",
"Note: this only reflects recent Calcit parsing/preprocess/runtime status; still validate browser rendering, CSS values, and external side effects separately."
.dimmed()
);
} else {
println!("{}", "Last error stack trace:".bold().red());
println!("{content}");
if command_guidance_enabled() {
println!();
println!("{}", "Next steps to fix:".blue().bold());
println!(" • Search for error location: {} '<symbol>'", "calcit query search".cyan());
println!(" • View definition: {} '<ns/def>'", "calcit query def".cyan());
println!(" • Find usages: {} '<ns/def>'", "calcit query usages".cyan());
println!();
println!("{}", "Tip: After fixing, watcher will recompile automatically (~300ms).".dimmed());
}
println!(
"{}",
"Note: even when this clears, non-Calcit issues like CSS strings, DOM behavior, and external integrations can still be wrong."
.dimmed()
);
}
Ok(())
}
fn render_chunked_display(display: &ChunkedDisplay) -> String {
let mut out = String::new();
let _ = writeln!(&mut out, "## Chunked Cirru\n");
let _ = writeln!(
&mut out,
"nodes: {}, branches: {}, leaves: {}, max depth: {}, fragments: {}\n",
display.total.nodes,
display.total.branches,
display.total.leaves,
display.total.max_depth,
display.fragments.len()
);
let _ = writeln!(&mut out);
for fragment in &display.fragments {
let _ = writeln!(&mut out, "### Fragment `{}`\n", fragment.id);
let _ = writeln!(
&mut out,
"- Coordinate: `{}`\n- Nodes: {}\n- Max depth: {}\n",
fragment.coord, fragment.nodes, fragment.depth
);
out.push_str(&markdown_fenced_block("cirru", &fragment.cirru));
let _ = writeln!(&mut out);
}
out
}
fn handle_def_cirru_view(input_path: &str, namespace: &str, definition: &str, entry: Option<&str>) -> Result<(), String> {
let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?;
let code_entry = file_data
.defs
.get(lookup.resolved.as_str())
.ok_or_else(|| format!("Definition '{namespace}/{definition}' has no source in this Snapshot"))?;
let quoted = Cirru::List(vec![Cirru::Leaf(Arc::from("quote")), code_entry.code.clone()]);
let text = [true, false]
.into_iter()
.filter_map(|use_inline| cirru_parser::format(std::slice::from_ref("ed), cirru_parser::CirruWriterOptions { use_inline }).ok())
.find(|text| cirru_parser::parse(text).is_ok_and(|parsed| parsed == [quoted.clone()]))
.ok_or_else(|| format!("Cannot render `{namespace}/{definition}` as Cirru text that parses back to the same source"))?;
print!("{}", text.trim_start_matches('\n'));
if !text.ends_with('\n') {
println!();
}
Ok(())
}
fn handle_def(input_path: &str, namespace: &str, definition: &str, opts: &QueryDefCommand, entry: Option<&str>) -> Result<(), String> {
if opts.summary && opts.only.is_some() {
return Err("`query def` accepts either `--summary` or `--only`, not both.".to_owned());
}
if let Some(only) = opts.only.as_deref()
&& !matches!(only, "examples" | "tests")
{
return Err(format!(
"Unsupported `query def --only` value '{only}'. Expected `examples` or `tests`."
));
}
if opts.summary && (opts.format == "cirru" || opts.raw) {
return Err("`query def --summary` cannot be combined with `--format cirru` or `--raw`.".to_owned());
}
if let Some(only) = opts.only.as_deref() {
if opts.raw {
return Err("`query def --only` cannot be combined with `--raw`.".to_owned());
}
if opts.format == "cirru" {
return match only {
"examples" => handle_examples_cirru_view(input_path, namespace, definition, entry),
_ => Err(
"`query def --only tests` cannot be combined with `--format cirru`; default human output already renders Cirru without JSON AST."
.to_owned(),
),
};
}
}
if opts.format == "cirru" {
return handle_def_cirru_view(input_path, namespace, definition, entry);
}
let format = parse_query_render_format(&opts.format)?;
if opts.summary && format == QueryRenderFormat::Human {
return handle_peek(input_path, namespace, definition, entry);
}
match opts.only.as_deref() {
Some("examples") if format == QueryRenderFormat::Human => return handle_examples(input_path, namespace, definition, entry),
Some("tests") if format == QueryRenderFormat::Human => return handle_tests(input_path, namespace, definition, entry),
_ => {}
}
let structured = format != QueryRenderFormat::Human;
let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
if !file_data.defs.contains_key(definition)
&& let Some(meta) = lookup_special_builtin_query_meta(namespace, definition)?
{
if structured {
let schema = meta
.schema
.as_function()
.map(|annot| annot.to_schema_edn())
.unwrap_or(cirru_edn::Edn::Nil);
let layer = runner::preprocess::classify_special_builtin(namespace, definition, meta.semantic_tags).as_str();
let mut data = match opts.only.as_deref() {
Some("examples") => serde_json::json!({
"id": format!("{namespace}/{definition}"),
"examples": meta.examples.iter().map(cirru_to_json).collect::<Vec<_>>(),
"builtin": true,
"kind": "special-proc",
}),
Some("tests") => serde_json::json!({
"id": format!("{namespace}/{definition}"),
"tests": [],
"builtin": true,
"kind": "special-proc",
}),
_ if opts.summary => serde_json::json!({
"id": format!("{namespace}/{definition}"),
"doc": meta.doc,
"tags": meta.semantic_tags,
"examples_count": meta.examples.len(),
"tests_count": 0,
"schema": cirru_to_json(&snapshot::schema_edn_to_cirru(&schema)?),
"cases": schema_cases_lines(meta.schema.as_ref())?,
"checker_rules": intrinsic_checker_rules(namespace, definition, meta.schema.as_ref()),
"builtin": true,
"kind": "special-proc",
"layer": layer,
}),
_ => serde_json::json!({
"id": format!("{namespace}/{definition}"),
"doc": meta.doc,
"tags": meta.semantic_tags,
"examples": meta.examples.iter().map(cirru_to_json).collect::<Vec<_>>(),
"tests": [],
"code": null,
"schema": cirru_to_json(&snapshot::schema_edn_to_cirru(&schema)?),
"ffi": null,
"ffi_edn": null,
"builtin": true,
"kind": "special-proc",
"layer": layer,
}),
};
if let Some(arity) = meta.runtime_arity {
data["runtime_arity"] = serde_json::to_value(arity).map_err(|error| format!("Failed to encode runtime arity: {error}"))?;
}
return emit_def_query(data, None, format, None);
}
let layer = runner::preprocess::classify_special_builtin(namespace, definition, meta.semantic_tags).as_str();
let mut out = String::new();
let _ = writeln!(&mut out, "# Definition `{namespace}/{definition}`\n");
let _ = writeln!(&mut out, "- Type: `{}`", meta.expr_preview);
let _ = writeln!(&mut out, "- Layer: `{layer}`");
if let Some(arity) = meta.runtime_arity {
let _ = writeln!(&mut out, "- Runtime Proc arity: `{}`", render_runtime_call_arity(arity));
}
let _ = writeln!(&mut out, "- Examples: {}", meta.examples.len());
let _ = writeln!(&mut out, "\n## Documentation\n\n> {}", meta.doc);
let _ = writeln!(&mut out, "\n## Schema\n");
out.push_str(&markdown_fenced_block("cirru", &format_query_schema(meta.schema.as_ref(), true)));
let _ = writeln!(&mut out, "\n## Cirru\n");
out.push_str(&markdown_fenced_block("text", meta.cirru_note));
emit_cli_output(&out, false);
return Ok(());
}
let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), true)?;
let render_to_stderr = lookup.warning.is_some();
if let Some(warning) = lookup.warning.as_deref() {
print_cli_warning_block(warning);
}
let resolved_definition = lookup.resolved;
let code_entry = file_data
.defs
.get(resolved_definition.as_str())
.expect("resolved definition exists");
if !structured || !matches!(opts.only.as_deref(), Some("examples" | "tests")) {
let _ = prepare_program_for_type_query(&snapshot);
}
if structured {
let revision = Some(snapshot::definition_revision(code_entry)?);
if opts.only.as_deref() == Some("examples") {
let data = serde_json::json!({
"id": format!("{namespace}/{resolved_definition}"),
"examples": code_entry.examples.iter().map(cirru_to_json).collect::<Vec<_>>(),
});
return emit_def_query(data, revision, format, None);
}
if opts.only.as_deref() == Some("tests") {
let data = serde_json::json!({
"id": format!("{namespace}/{resolved_definition}"),
"tests": code_entry.tests.iter().map(|test| {
let mut tags = test.tags.iter().map(|tag| tag.ref_str().to_owned()).collect::<Vec<_>>();
tags.sort();
serde_json::json!({"name": test.name, "tags": tags, "code": cirru_to_json(&test.code)})
}).collect::<Vec<_>>(),
});
return emit_def_query(data, revision, format, None);
}
if opts.summary {
let mut tags: Vec<String> = code_entry.tags.iter().map(|tag| tag.ref_str().to_string()).collect();
tags.sort();
let layer = runner::preprocess::classify_code_entry(namespace, &resolved_definition, code_entry).as_str();
let mut data = serde_json::json!({
"id": format!("{namespace}/{resolved_definition}"),
"layer": layer,
"doc": code_entry.doc,
"tags": tags,
"schema": definition_schema_cirru(&code_entry.schema, false)?.map(|cirru| cirru_to_json(&cirru)),
"cases": schema_cases_lines(code_entry.schema.as_ref())?,
"checker_rules": intrinsic_checker_rules(namespace, resolved_definition.as_str(), code_entry.schema.as_ref()),
"examples_count": code_entry.examples.len(),
"tests_count": code_entry.tests.len(),
});
if let Some(arity) = core_runtime_call_arity(namespace, &resolved_definition, code_entry) {
data["runtime_arity"] = serde_json::to_value(arity).map_err(|error| format!("Failed to serialize runtime arity: {error}"))?;
}
if let Some(failure) = core_proc_failure(namespace, &resolved_definition, code_entry) {
data["failure"] = serde_json::to_value(failure).map_err(|error| format!("Failed to serialize failure class: {error}"))?;
}
return emit_def_query(data, revision, format, None);
}
let layer = runner::preprocess::classify_code_entry(namespace, &resolved_definition, code_entry).as_str();
let mut data = code_entry_to_json(code_entry)?;
data["id"] = serde_json::json!(format!("{namespace}/{resolved_definition}"));
data["layer"] = serde_json::json!(layer);
if let Some(arity) = core_runtime_call_arity(namespace, &resolved_definition, code_entry) {
data["runtime_arity"] = serde_json::to_value(arity).map_err(|error| format!("Failed to serialize runtime arity: {error}"))?;
}
if let Some(failure) = core_proc_failure(namespace, &resolved_definition, code_entry) {
data["failure"] = serde_json::to_value(failure).map_err(|error| format!("Failed to serialize failure class: {error}"))?;
}
data["ffi_edn"] = data["ffi"].take();
data["ffi"] = serde_json::to_value(&code_entry.ffi).map_err(|e| format!("Failed to serialize FFI metadata: {e}"))?;
data["js_ffi"] = serde_json::to_value(
code_entry
.ffi
.as_ref()
.and_then(|ffi| js_ffi_query_info(input_path, &snapshot, namespace, ffi)),
)
.map_err(|error| format!("Failed to serialize JavaScript FFI provenance: {error}"))?;
return emit_def_query(data, revision, format, code_entry.ffi.as_ref());
}
let layer = runner::preprocess::classify_code_entry(namespace, &resolved_definition, code_entry).as_str();
let mut out = String::new();
let _ = writeln!(&mut out, "# Definition `{namespace}/{resolved_definition}`\n");
let _ = writeln!(&mut out, "- Layer: `{layer}`");
if let Some(arity) = core_runtime_call_arity(namespace, &resolved_definition, code_entry) {
let _ = writeln!(&mut out, "- Runtime Proc arity: `{}`", render_runtime_call_arity(arity));
}
if let Some(failure) = core_proc_failure(namespace, &resolved_definition, code_entry) {
let _ = writeln!(&mut out, "- Failure: {}", render_proc_failure(&failure));
}
if let Ok(code_data) = calcit_core::data::cirru::code_to_calcit(&code_entry.code, namespace, &resolved_definition, vec![])
&& let Some(summary) = CalcitTypeAnnotation::summarize_code(&code_data)
{
let _ = writeln!(&mut out, "- Type: `{summary}`");
}
let tags_text = format_tags_display(&code_entry.tags);
if tags_text.is_empty() {
let _ = writeln!(&mut out, "- Tags: _(none)_");
} else {
let _ = writeln!(&mut out, "- Tags: {tags_text}");
}
if !code_entry.doc.is_empty() {
let _ = writeln!(&mut out, "\n## Documentation\n");
for line in code_entry.doc.lines() {
let _ = writeln!(&mut out, "> {line}");
}
}
if let Some(ffi) = &code_entry.ffi {
let full = format_ffi_edn(ffi)?;
let (label, text) = if opts.raw {
("FFI:", full)
} else {
let preview = format_edn_display(ffi);
(
if preview == full {
"FFI:"
} else {
"FFI (preview; use --raw for full metadata):"
},
preview,
)
};
let _ = writeln!(&mut out, "\n## {}\n", label.trim_end_matches(':'));
out.push_str(&markdown_fenced_block("cirru", &text));
if let Some(info) = js_ffi_query_info(input_path, &snapshot, namespace, ffi) {
let inline_source = parse_js_source(ffi)
.ok()
.flatten()
.and_then(|implementation| match implementation.source {
JsFfiSource::Inline(source) => Some(source),
JsFfiSource::File { .. } => None,
});
let _ = writeln!(&mut out);
out.push_str(&render_js_ffi_info(&info, inline_source.as_deref()));
}
}
if !code_entry.examples.is_empty() {
let _ = writeln!(&mut out, "- Examples: {}", code_entry.examples.len());
}
if !code_entry.tests.is_empty() {
let _ = writeln!(&mut out, "- Tests: {}", code_entry.tests.len());
}
let _ = writeln!(&mut out, "\n## Schema\n");
let schema_str = format_schema_display(definition_schema_cirru(&code_entry.schema, true));
if schema_str == "(none)" {
let _ = writeln!(&mut out, "_No explicit schema._");
} else {
out.push_str(&markdown_fenced_block("cirru", &schema_str));
}
if !opts.raw {
let chunk_options = ChunkDisplayOptions {
trigger_nodes: opts.chunk_trigger_nodes,
target_nodes: opts.chunk_target_nodes,
max_nodes: opts.chunk_max_nodes,
max_branches: 64,
};
let cirru_str =
cirru_parser::format(std::slice::from_ref(&code_entry.code), true.into()).unwrap_or_else(|_| "(failed to format)".to_string());
let chunked = if cirru_str.len() >= opts.chunk_trigger_bytes {
maybe_chunk_node(&code_entry.code, &chunk_options)?
} else {
None
};
if let Some(display) = chunked {
let _ = writeln!(&mut out);
out.push_str(&render_chunked_display(&display));
} else {
let _ = writeln!(&mut out, "\n## Cirru\n");
out.push_str(&markdown_fenced_block("cirru", &cirru_str));
}
} else {
let _ = writeln!(&mut out, "\n## Cirru\n");
let cirru_str =
cirru_parser::format(std::slice::from_ref(&code_entry.code), true.into()).unwrap_or_else(|_| "(failed to format)".to_string());
out.push_str(&markdown_fenced_block("cirru", &cirru_str));
}
emit_cli_output(&out, render_to_stderr);
Ok(())
}
fn cirru_to_json(cirru: &Cirru) -> serde_json::Value {
match cirru {
Cirru::Leaf(s) => serde_json::Value::String(s.to_string()),
Cirru::List(items) => serde_json::Value::Array(items.iter().map(cirru_to_json).collect()),
}
}
fn format_ffi_edn(ffi: &cirru_edn::Edn) -> Result<String, String> {
cirru_edn::format(ffi, true)
.map(|text| text.trim().to_owned())
.map_err(|e| format!("Failed to format FFI metadata: {e}"))
}
fn format_def_query_json(data: serde_json::Value, revision: Option<String>) -> Result<String, String> {
serde_json::to_string(&serde_json::json!({
"schema_version": 1,
"command": "query.def",
"revision": revision,
"data": data,
"diagnostics": [],
}))
.map_err(|e| format!("Failed to encode definition query JSON: {e}"))
}
fn emit_def_query(
mut data: serde_json::Value,
revision: Option<String>,
format: QueryRenderFormat,
ffi: Option<&cirru_edn::Edn>,
) -> Result<(), String> {
if format == QueryRenderFormat::Edn && ffi.is_some() {
data
.as_object_mut()
.ok_or_else(|| "Definition query data must be an object".to_owned())?
.remove("ffi");
}
let json = format_def_query_json(data, revision)?;
match format {
QueryRenderFormat::Json => println!("{json}"),
QueryRenderFormat::Edn => {
let json_value = serde_json::from_str::<serde_json::Value>(&json)
.map_err(|error| format!("Failed to decode definition query result: {error}"))?;
let mut value = json_value_to_edn(&json_value)?;
if let Some(ffi) = ffi {
let cirru_edn::Edn::Map(root) = &mut value else {
return Err("Definition query envelope must be a map".to_owned());
};
let Some(cirru_edn::Edn::Map(data)) = root.0.get_mut(&cirru_edn::Edn::tag("data")) else {
return Err("Definition query data must be a map".to_owned());
};
data.insert(cirru_edn::Edn::tag("ffi"), ffi.clone());
}
println!(
"{}",
cirru_edn::format(&value, true).map_err(|error| format!("Failed to format definition EDN: {error}"))?
);
}
QueryRenderFormat::Human => return Err("Cannot emit human definition as structured output".to_owned()),
}
Ok(())
}
fn code_entry_to_json(entry: &snapshot::CodeEntry) -> Result<serde_json::Value, String> {
let schema_json = definition_schema_cirru(&entry.schema, false)?.map(|cirru| cirru_to_json(&cirru));
let mut tags: Vec<String> = entry.tags.iter().map(|tag| tag.ref_str().to_string()).collect();
tags.sort();
Ok(serde_json::json!({
"doc": entry.doc,
"tags": tags,
"examples": entry.examples.iter().map(cirru_to_json).collect::<Vec<_>>(),
"tests": entry.tests.iter().map(|test| {
let mut tags = test.tags.iter().map(|tag| tag.ref_str().to_owned()).collect::<Vec<_>>();
tags.sort();
serde_json::json!({"name": test.name, "tags": tags, "code": cirru_to_json(&test.code)})
}).collect::<Vec<_>>(),
"code": cirru_to_json(&entry.code),
"schema": schema_json,
"ffi": entry.ffi.as_ref().map(format_ffi_edn).transpose()?,
}))
}
fn format_example_node(example: &Cirru) -> String {
match example {
Cirru::Leaf(value) => value.to_string(),
Cirru::List(_) => cirru_parser::format(std::slice::from_ref(example), true.into())
.map(|text| text.trim().to_owned())
.unwrap_or_else(|_| format!("{example:?}")),
}
}
fn render_examples_cirru(target: &str, examples: &[Cirru]) -> Result<String, String> {
if examples.is_empty() {
return Ok(String::new());
}
let quoted: Vec<Cirru> = examples
.iter()
.map(|example| Cirru::List(vec![Cirru::Leaf(Arc::from("quote")), example.clone()]))
.collect();
let text = [true, false]
.into_iter()
.filter_map(|use_inline| cirru_parser::format("ed, cirru_parser::CirruWriterOptions { use_inline }).ok())
.find(|text| cirru_parser::parse(text).is_ok_and(|parsed| parsed == quoted))
.ok_or_else(|| format!("Cannot render `{target}` examples as Cirru text that parses back to the same source"))?;
let mut out = text.trim_start_matches('\n').to_owned();
if !out.ends_with('\n') {
out.push('\n');
}
Ok(out)
}
fn handle_examples_cirru_view(input_path: &str, namespace: &str, definition: &str, entry: Option<&str>) -> Result<(), String> {
let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
if !file_data.defs.contains_key(definition)
&& let Some(meta) = lookup_special_builtin_query_meta(namespace, definition)?
{
let text = render_examples_cirru(&format!("{namespace}/{definition}"), &meta.examples)?;
print!("{text}");
return Ok(());
}
let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), false)?;
let code_entry = file_data.defs.get(lookup.resolved.as_str()).expect("resolved definition exists");
let text = render_examples_cirru(&format!("{namespace}/{}", lookup.resolved), &code_entry.examples)?;
print!("{text}");
Ok(())
}
fn render_examples_human(target: &str, examples: &[Cirru]) -> String {
let mut out = String::new();
let _ = writeln!(&mut out, "# Examples for `{target}`\n");
if examples.is_empty() {
let _ = writeln!(&mut out, "_No examples._");
return out;
}
let _ = writeln!(&mut out, "Count: {}.\n", examples.len());
for (index, example) in examples.iter().enumerate() {
let _ = writeln!(&mut out, "## Example {index}\n");
out.push_str(&markdown_fenced_block("cirru", &format_example_node(example)));
let _ = writeln!(&mut out, "\n### JSON AST\n");
out.push_str(&markdown_fenced_block(
"json",
&serde_json::to_string_pretty(&cirru_to_json(example)).unwrap(),
));
let _ = writeln!(&mut out);
}
out
}
fn handle_examples(input_path: &str, namespace: &str, definition: &str, entry: Option<&str>) -> Result<(), String> {
let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
if !file_data.defs.contains_key(definition)
&& let Some(meta) = lookup_special_builtin_query_meta(namespace, definition)?
{
let out = render_examples_human(&format!("{namespace}/{definition}"), &meta.examples);
emit_cli_output(&out, false);
return Ok(());
}
let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), true)?;
let render_to_stderr = lookup.warning.is_some();
if let Some(warning) = lookup.warning.as_deref() {
print_cli_warning_block(warning);
}
let resolved_definition = lookup.resolved;
let code_entry = file_data
.defs
.get(resolved_definition.as_str())
.expect("resolved definition exists");
let out = render_examples_human(&format!("{namespace}/{resolved_definition}"), &code_entry.examples);
emit_cli_output(&out, render_to_stderr);
Ok(())
}
fn handle_tests(input_path: &str, namespace: &str, definition: &str, entry: Option<&str>) -> Result<(), String> {
let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
let file = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
if !file.defs.contains_key(definition) && lookup_special_builtin_query_meta(namespace, definition)?.is_some() {
let out = format!("# Tests for `{namespace}/{definition}`\n\n_No tests._\n");
emit_cli_output(&out, false);
return Ok(());
}
let lookup = resolve_definition_lookup(namespace, definition, file.defs.keys().map(|name| name.as_str()), true)?;
let render_to_stderr = lookup.warning.is_some();
if let Some(warning) = lookup.warning.as_deref() {
print_cli_warning_block(warning);
}
let entry = file.defs.get(lookup.resolved.as_str()).expect("resolved definition exists");
let mut out = String::new();
let _ = writeln!(&mut out, "# Tests for `{namespace}/{}`\n", lookup.resolved);
if entry.tests.is_empty() {
let _ = writeln!(&mut out, "_No tests._");
} else {
let _ = writeln!(&mut out, "Count: {}.\n", entry.tests.len());
for test in &entry.tests {
let mut tags = test.tags.iter().map(|tag| format!(":{}", tag.ref_str())).collect::<Vec<_>>();
tags.sort();
let _ = writeln!(&mut out, "## Test `{}`\n", test.name);
if !tags.is_empty() {
let _ = writeln!(&mut out, "- Tags: {}\n", tags.join(" "));
}
out.push_str(&markdown_fenced_block("cirru", &format_example_node(&test.code)));
let _ = writeln!(&mut out);
}
}
emit_cli_output(&out, render_to_stderr);
Ok(())
}
fn handle_peek(input_path: &str, namespace: &str, definition: &str, entry: Option<&str>) -> Result<(), String> {
let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
if !file_data.defs.contains_key(definition)
&& let Some(meta) = lookup_special_builtin_query_meta(namespace, definition)?
{
let layer = runner::preprocess::classify_special_builtin(namespace, definition, meta.semantic_tags).as_str();
let mut out = String::new();
let _ = writeln!(&mut out, "# Definition preview `{namespace}/{definition}`\n");
let _ = writeln!(&mut out, "- Layer: `{layer}`");
if let Some(arity) = meta.runtime_arity {
let _ = writeln!(&mut out, "- Runtime Proc arity: `{}`", render_runtime_call_arity(arity));
}
let _ = writeln!(&mut out, "- Examples: {}", meta.examples.len());
let _ = writeln!(&mut out, "\n## Documentation\n\n> {}", meta.doc);
let _ = writeln!(&mut out, "\n## Expression\n");
out.push_str(&markdown_fenced_block("cirru", meta.expr_preview));
let _ = writeln!(&mut out, "\n## Schema\n");
out.push_str(&markdown_fenced_block("cirru", &format_query_schema(meta.schema.as_ref(), true)));
emit_cli_output(&out, false);
return Ok(());
}
let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), true)?;
let render_to_stderr = lookup.warning.is_some();
if let Some(warning) = lookup.warning.as_deref() {
print_cli_warning_block(warning);
}
let resolved_definition = lookup.resolved;
let code_entry = file_data
.defs
.get(resolved_definition.as_str())
.expect("resolved definition exists");
let layer = runner::preprocess::classify_code_entry(namespace, &resolved_definition, code_entry).as_str();
let mut out = String::new();
let _ = writeln!(&mut out, "# Definition preview `{namespace}/{resolved_definition}`\n");
let _ = writeln!(&mut out, "- Layer: `{layer}`\n");
if code_entry.doc.is_empty() {
let _ = writeln!(&mut out, "_No documentation._");
} else {
let _ = writeln!(&mut out, "## Documentation\n");
for line in code_entry.doc.lines() {
let _ = writeln!(&mut out, "> {line}");
}
}
let _ = writeln!(&mut out, "\n## Expression preview\n");
match &code_entry.code {
Cirru::List(items) if !items.is_empty() => {
let preview = code_entry.code.format_one_liner()?;
let display = truncate_chars_with_dots(&preview, 120);
out.push_str(&markdown_fenced_block("cirru", &display));
}
Cirru::Leaf(leaf) => {
out.push_str(&markdown_fenced_block("cirru", leaf));
}
_ => {
let _ = writeln!(&mut out, "_Empty or invalid definition._");
}
}
let _ = writeln!(&mut out, "\n- Examples: {}", code_entry.examples.len());
let _ = writeln!(&mut out, "- Tests: {}", code_entry.tests.len());
let _ = writeln!(&mut out, "\n## Schema\n");
if let Some(cirru) = definition_schema_cirru(&code_entry.schema, true)? {
let preview = format_query_schema_oneline(&cirru)?;
let display = truncate_chars_with_dots(&preview, 120);
out.push_str(&markdown_fenced_block("cirru", &display));
} else {
let _ = writeln!(&mut out, "_No explicit schema._");
}
if let Some(cases) = schema_cases_lines(code_entry.schema.as_ref())? {
write_schema_cases(&mut out, &cases);
}
if let Some(rules) = intrinsic_checker_rules(namespace, resolved_definition.as_str(), code_entry.schema.as_ref()) {
write_intrinsic_checker_rules(&mut out, rules);
}
emit_cli_output(&out, render_to_stderr);
Ok(())
}
fn handle_schema(
input_path: &str,
namespace: &str,
definition: &str,
format: StructuredOutputFormat,
entry: Option<&str>,
) -> Result<(), String> {
let structured = format != StructuredOutputFormat::Human;
let snapshot = load_snapshot_for_namespace(input_path, namespace, entry)?;
let file_data = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Namespace '{namespace}' not found"))?;
if !file_data.defs.contains_key(definition)
&& let Some(meta) = lookup_special_builtin_query_meta(namespace, definition)?
{
let mut out = String::new();
if structured {
let id = format!("{namespace}/{definition}");
let schema_fingerprint = format_query_schema(meta.schema.as_ref(), true);
let arity_fingerprint = meta.runtime_arity.map(render_runtime_call_arity).unwrap_or_default();
format.print_json_text(&format_schema_query_json(
&id,
"core-builtin",
meta.schema.as_ref(),
semantic_revision(&[meta.doc, &schema_fingerprint, &arity_fingerprint]),
meta.runtime_arity,
)?)?;
return Ok(());
} else {
let _ = writeln!(&mut out, "# Schema for `{namespace}/{definition}`\n");
if let Some(arity) = meta.runtime_arity {
let _ = writeln!(&mut out, "- Runtime Proc arity: `{}`\n", render_runtime_call_arity(arity));
}
out.push_str(&markdown_fenced_block("cirru", &format_query_schema(meta.schema.as_ref(), true)));
}
emit_cli_output(&out, false);
return Ok(());
}
let lookup = resolve_definition_lookup(namespace, definition, file_data.defs.keys().map(|name| name.as_str()), true)?;
let render_to_stderr = lookup.warning.is_some();
if let Some(warning) = lookup.warning.as_deref() {
print_cli_warning_block(warning);
}
let resolved_definition = lookup.resolved;
let code_entry = file_data
.defs
.get(resolved_definition.as_str())
.expect("resolved definition exists");
let mut out = String::new();
let schema_cases = schema_cases_lines(code_entry.schema.as_ref())?;
let checker_rules = intrinsic_checker_rules(namespace, resolved_definition.as_str(), code_entry.schema.as_ref());
if structured {
let id = format!("{namespace}/{resolved_definition}");
let text = format_schema_cirru_query_json(
&id,
&namespace_source(&snapshot, namespace),
definition_schema_cirru(&code_entry.schema, true)?,
snapshot::definition_revision(code_entry)?,
None,
)?;
let text = if schema_cases.is_some() || checker_rules.is_some() {
let mut envelope: serde_json::Value =
serde_json::from_str(&text).map_err(|error| format!("Failed to decode schema query JSON: {error}"))?;
if let Some(cases) = &schema_cases {
envelope["data"]["cases"] = serde_json::json!(cases);
}
if let Some(rules) = checker_rules {
envelope["data"]["checker_rules"] = serde_json::json!(rules);
}
serde_json::to_string_pretty(&envelope).map_err(|error| format!("Failed to encode schema query JSON: {error}"))?
} else {
text
};
format.print_json_text(&text)?;
return Ok(());
}
if let Some(cirru) = definition_schema_cirru(&code_entry.schema, true)? {
let _ = writeln!(&mut out, "# Schema for `{namespace}/{resolved_definition}`\n");
out.push_str(&markdown_fenced_block("cirru", &format_query_schema_oneline(&cirru)?));
if let Some(cases) = &schema_cases {
write_schema_cases(&mut out, cases);
}
if let Some(rules) = checker_rules {
write_intrinsic_checker_rules(&mut out, rules);
}
} else {
let _ = writeln!(
&mut out,
"# Schema for `{namespace}/{resolved_definition}`\n\n_No explicit schema._"
);
}
emit_cli_output(&out, render_to_stderr);
Ok(())
}
fn handle_find(input_path: &str, symbol: &str, include_deps: bool, detail_offset: usize, entry: Option<&str>) -> Result<(), String> {
let snapshot = load_snapshot(input_path, entry)?;
let mut found_definitions: Vec<(String, String)> = vec![];
let mut found_references: RefResults = vec![];
for (ns_name, file_data) in &snapshot.files {
let is_core = ns_name.starts_with("calcit.") || ns_name.starts_with("calcit-test.");
if file_data.defs.contains_key(symbol) {
found_definitions.push((ns_name.clone(), symbol.to_string()));
}
if !include_deps && is_core {
continue;
}
for (def_name, code_entry) in &file_data.defs {
if find_symbol_in_cirru(&code_entry.code, symbol) {
let coords = find_symbol_coords(&code_entry.code, symbol);
found_references.push((
ns_name.clone(),
def_name.clone(),
get_symbol_context_cirru(&code_entry.code, symbol),
coords,
"code",
));
}
if let Ok(Some(schema)) = query_schema_cirru(code_entry.schema.as_ref(), false)
&& find_symbol_in_cirru(&schema, symbol)
{
let coords = find_symbol_coords(&schema, symbol);
found_references.push((
ns_name.clone(),
def_name.clone(),
get_symbol_context_cirru(&schema, symbol),
coords,
"schema",
));
}
}
}
println!(
"{} {} definition(s), {} reference(s)\n",
"Matches:".bold(),
found_definitions.len(),
found_references.len().saturating_sub(found_definitions.len())
);
if !found_definitions.is_empty() {
println!("{}", "Defined in:".bold().green());
print_detail_window_hint(found_definitions.len(), detail_offset, "definitions");
for (idx, (ns, def)) in found_definitions.iter().enumerate() {
if in_detail_window(idx, found_definitions.len(), detail_offset) {
println!(" {}/{}", ns.cyan(), def.green());
} else {
println!(" ⋯ {}/{}", ns.dimmed(), def.dimmed());
}
}
println!();
}
let references: Vec<_> = found_references
.iter()
.filter(|(ns, def, _, _, _)| !found_definitions.iter().any(|(dns, ddef)| dns == ns && ddef == def))
.collect();
if !references.is_empty() {
println!("{}", "Referenced in:".bold());
print_detail_window_hint(references.len(), detail_offset, "references");
for (idx, (ns, def, context, coords, source)) in references.iter().enumerate() {
if !in_detail_window(idx, references.len(), detail_offset) {
println!(
" ⋯ {}/{} [{}] ({} path{})",
ns.dimmed(),
def.dimmed(),
source.dimmed(),
coords.len(),
if coords.len() == 1 { "" } else { "s" }
);
continue;
}
if !context.is_empty() {
println!(" {}/{} [{}] {}", ns.cyan(), def, source.dimmed(), context.dimmed());
} else {
println!(" {}/{} [{}]", ns.cyan(), def, source.dimmed());
}
if !coords.is_empty() {
let coords_parts: Vec<String> = coords
.iter()
.map(|path| {
let coord_str = format_path(path);
format!("[{coord_str}]")
})
.collect();
println!(" {}", format!("at {}", coords_parts.join(" and ")).dimmed());
}
}
}
if found_definitions.is_empty() && references.is_empty() {
println!("{}", "No matches found.".yellow());
}
Ok(())
}
fn collect_usages_from_snapshot(
snapshot: &snapshot::Snapshot,
target_ns: &str,
target_def: &str,
include_deps: bool,
) -> Result<RefResults, String> {
let mut usages: RefResults = vec![];
for (ns_name, file_data) in &snapshot.files {
if !include_deps && (ns_name.starts_with("calcit.") || ns_name.starts_with("calcit-test.")) {
continue;
}
let defines_target_name = ns_name != target_ns && file_data.defs.contains_key(target_def);
let symbols = target_reference_symbols(ns_name, &file_data.ns.code, defines_target_name, target_ns, target_def)?;
let mut core_heads = BTreeMap::new();
for head in SOURCE_SCOPE_HEADS {
let mut spellings = target_reference_symbols(
ns_name,
&file_data.ns.code,
file_data.defs.contains_key(*head),
calcit_core::calcit::CORE_NS,
head,
)?;
if CalcitSyntax::is_valid(head) {
spellings.push((*head).to_owned());
}
for spelling in spellings {
core_heads.insert(spelling, (*head).to_owned());
}
}
for (def_name, code_entry) in &file_data.defs {
if ns_name == target_ns && def_name == target_def {
continue;
}
if let Some((context, coords)) = find_reference_symbols(&code_entry.code, &symbols, Some(&core_heads)) {
usages.push((ns_name.clone(), def_name.clone(), context, coords, "code"));
}
for test in &code_entry.tests {
if let Some((expression, coords)) = find_reference_symbols(&test.code, &symbols, Some(&core_heads)) {
let context = if expression.is_empty() {
format!("#{}", test.name)
} else {
format!("#{} {expression}", test.name)
};
usages.push((ns_name.clone(), def_name.clone(), context, coords, "tests"));
}
}
if let Ok(Some(schema)) = query_schema_cirru(code_entry.schema.as_ref(), false)
&& let Some((context, coords)) = find_reference_symbols(&strip_schema_quotes(&schema), &symbols, None)
{
usages.push((ns_name.clone(), def_name.clone(), context, coords, "schema"));
}
}
}
usages.sort_by(|left, right| (&left.0, &left.1, left.4).cmp(&(&right.0, &right.1, right.4)));
Ok(usages)
}
fn handle_usages(
input_path: &str,
target_ns: &str,
target_def: &str,
include_deps: bool,
detail_offset: usize,
entry: Option<&str>,
) -> Result<(), String> {
let snapshot = load_snapshot(input_path, entry)?;
let target_file = snapshot
.files
.get(target_ns)
.ok_or_else(|| format!("Namespace '{target_ns}' not found"))?;
let lookup = resolve_definition_lookup(target_ns, target_def, target_file.defs.keys().map(|name| name.as_str()), true)?;
let render_to_stderr = lookup.warning.is_some();
if let Some(warning) = lookup.warning.as_deref() {
print_cli_warning_block(warning);
}
let resolved_target_def = lookup.resolved;
let _ = target_file
.defs
.get(resolved_target_def.as_str())
.expect("resolved definition exists");
let usages = collect_usages_from_snapshot(&snapshot, target_ns, &resolved_target_def, include_deps)?;
let mut out = String::new();
let _ = writeln!(&mut out, "{} {}", "Usages:".bold(), usages.len());
let _ = writeln!(
&mut out,
"{}",
"Source-reference candidates: unexpanded macros can introduce bindings or references; zero usages is not proof of non-use."
.dimmed()
);
if usages.is_empty() {
let _ = writeln!(
&mut out,
"\n{}",
"No usages found. This definition may be unused or only called externally.".yellow()
);
} else {
let _ = writeln!(&mut out);
if usages.len() > DETAILED_RESULTS_WINDOW {
let (start, end) = detailed_window(detail_offset, usages.len());
let _ = writeln!(
&mut out,
"{}",
format!("Detail window for usages: [{start}, {end}) (detail-offset={detail_offset}), other entries are compressed.").dimmed()
);
}
for (idx, (ns, def, context, coords, source)) in usages.iter().enumerate() {
if !in_detail_window(idx, usages.len(), detail_offset) {
let _ = writeln!(
&mut out,
" ⋯ {}/{} [{}] ({} path{})",
ns.dimmed(),
def.dimmed(),
source.dimmed(),
coords.len(),
if coords.len() == 1 { "" } else { "s" }
);
continue;
}
if !context.is_empty() {
let _ = writeln!(
&mut out,
" {}/{} [{}] {}",
ns.cyan(),
def.green(),
source.dimmed(),
context.dimmed()
);
} else {
let _ = writeln!(&mut out, " {}/{} [{}]", ns.cyan(), def.green(), source.dimmed());
}
if !coords.is_empty() {
let coords_parts: Vec<String> = coords
.iter()
.map(|path| {
let coord_str = format_path(path);
format!("[{coord_str}]")
})
.collect();
let _ = writeln!(&mut out, " {}", format!("at {}", coords_parts.join(" and ")).dimmed());
}
}
}
if !usages.is_empty() && command_guidance_enabled() {
let _ = writeln!(
&mut out,
"\n{}",
"Tip: Modifying this definition may affect the above locations.".dimmed()
);
}
emit_cli_output(&out, render_to_stderr);
Ok(())
}
fn find_symbol_coords(code: &Cirru, symbol: &str) -> Vec<Vec<usize>> {
fn search_recursive(node: &Cirru, symbol: &str, current_path: &[usize], results: &mut Vec<Vec<usize>>) {
match node {
Cirru::Leaf(s) if s.as_ref() == symbol => {
results.push(current_path.to_vec());
}
Cirru::List(items) => {
for (i, item) in items.iter().enumerate() {
let mut new_path = current_path.to_vec();
new_path.push(i);
search_recursive(item, symbol, &new_path, results);
}
}
_ => {}
}
}
let mut results = Vec::new();
search_recursive(code, symbol, &[], &mut results);
results
}
fn find_symbol_in_cirru(code: &Cirru, symbol: &str) -> bool {
match code {
Cirru::Leaf(s) => s.as_ref() == symbol,
Cirru::List(items) => items.iter().any(|item| find_symbol_in_cirru(item, symbol)),
}
}
fn get_symbol_context_cirru(code: &Cirru, symbol: &str) -> String {
fn find_smallest_containing(node: &Cirru, symbol: &str) -> Option<Cirru> {
match node {
Cirru::Leaf(s) if s.as_ref() == symbol => Some(node.clone()),
Cirru::List(items) => {
for item in items {
if let Some(found) = find_smallest_containing(item, symbol) {
if matches!(found, Cirru::Leaf(_)) {
return Some(node.clone());
}
return Some(found);
}
}
None
}
_ => None,
}
}
if let Some(context_node) = find_smallest_containing(code, symbol) {
let cirru_str = context_node.format_one_liner().unwrap_or_default();
let trimmed = cirru_str.trim();
return truncate_chars_with_dots(trimmed, 50);
}
String::new()
}
fn target_reference_symbols(
ns_name: &str,
ns_code: &Cirru,
defines_target_name: bool,
target_ns: &str,
target_def: &str,
) -> Result<Vec<String>, String> {
let mut bindings: BTreeMap<Arc<str>, Arc<program::ImportRule>> = BTreeMap::new();
for (index, rule) in super::edit::extract_require_rules(ns_code).into_iter().enumerate() {
let pairs =
program::extract_import_rule(&rule).map_err(|error| format!("in namespace '{ns_name}' import rule {}: {error}", index + 1))?;
bindings.extend(pairs);
}
let mut symbols = vec![];
let qualified_is_rebound = bindings
.get(target_ns)
.is_some_and(|rule| !matches!(rule.as_ref(), program::ImportRule::NsAs(source) if source.as_ref() == target_ns));
if !qualified_is_rebound {
symbols.push(format!("{target_ns}/{target_def}"));
}
for (binding, rule) in &bindings {
if let program::ImportRule::NsAs(source) = rule.as_ref()
&& source.as_ref() == target_ns
{
symbols.push(format!("{binding}/{target_def}"));
}
}
let bare_refers_target = if ns_name == target_ns {
true
} else if let Some(rule) = bindings.get(target_def) {
matches!(rule.as_ref(), program::ImportRule::NsReferDef(source, def) if source.as_ref() == target_ns && def.as_ref() == target_def)
} else {
target_ns == calcit_core::calcit::CORE_NS && !defines_target_name
};
if bare_refers_target {
symbols.push(target_def.to_owned());
}
symbols.sort();
symbols.dedup();
Ok(symbols)
}
fn strip_schema_quotes(code: &Cirru) -> Cirru {
match code {
Cirru::Leaf(s) => match s.strip_prefix('\'') {
Some(name) if !name.is_empty() => Cirru::Leaf(Arc::from(name)),
_ => code.clone(),
},
Cirru::List(items) => Cirru::List(items.iter().map(strip_schema_quotes).collect()),
}
}
fn find_reference_symbols(
code: &Cirru,
symbols: &[String],
core_heads: Option<&BTreeMap<String, String>>,
) -> Option<(String, Vec<Vec<usize>>)> {
let mut coords = vec![];
for symbol in symbols {
let found = match core_heads {
Some(heads) => source_reference_paths(code, symbol, heads),
None => find_symbol_coords(code, symbol),
};
coords.extend(found);
}
coords.sort();
coords.dedup();
let first = coords.first()?;
let parent = first.get(..first.len().saturating_sub(1)).unwrap_or_default();
let node = navigate_to_path(code, parent).unwrap_or_else(|_| code.clone());
let text = node.format_one_liner().unwrap_or_default();
Some((truncate_chars_with_dots(text.trim(), 50), coords))
}
fn handle_fuzzy_search(
input_path: &str,
pattern: &str,
include_deps: bool,
limit: usize,
detail_offset: usize,
entry: Option<&str>,
) -> Result<(), String> {
let snapshot = load_snapshot(input_path, entry)?;
let pattern_lower = pattern.to_lowercase();
let mut results: Vec<(String, String, bool)> = Vec::new();
for (ns_name, file_data) in &snapshot.files {
let is_core = ns_name.starts_with("calcit.") || ns_name.starts_with("calcit-test.");
if !include_deps && is_core {
continue;
}
for def_name in file_data.defs.keys() {
let qualified = format!("{ns_name}/{def_name}");
let qualified_lower = qualified.to_lowercase();
if fuzzy_match(&qualified_lower, &pattern_lower) {
results.push((ns_name.clone(), def_name.clone(), is_core));
}
}
}
results.sort_by(|(ns_a, def_a, _), (ns_b, def_b, _)| {
let qualified_a = format!("{ns_a}/{def_a}").to_lowercase();
let qualified_b = format!("{ns_b}/{def_b}").to_lowercase();
let a_prefix = qualified_a.starts_with(&pattern_lower);
let b_prefix = qualified_b.starts_with(&pattern_lower);
match (a_prefix, b_prefix) {
(true, false) => std::cmp::Ordering::Less,
(false, true) => std::cmp::Ordering::Greater,
_ => qualified_a.cmp(&qualified_b),
}
});
let total = results.len();
let displayed: Vec<_> = results.into_iter().take(limit).collect();
println!("{} {} results", "Search:".bold(), total);
if displayed.is_empty() {
println!(" {}", "No matches found".dimmed());
if command_guidance_enabled() {
println!(
"\n{}",
"Tip: Try a broader pattern, or add --deps to include core namespaces.".dimmed()
);
}
return Ok(());
}
print_detail_window_hint(displayed.len(), detail_offset, "search results");
for (idx, (ns, def, is_core)) in displayed.iter().enumerate() {
if !in_detail_window(idx, displayed.len(), detail_offset) {
println!(" ⋯ {}/{}", ns.dimmed(), def.dimmed());
continue;
}
let qualified = format!("{}/{}", ns.cyan(), def.green());
if *is_core {
println!(" {} {}", qualified, "(core)".dimmed());
} else {
println!(" {qualified}");
}
}
if total > limit {
println!(" ⋯ {} more results...", total - limit);
}
if command_guidance_enabled() {
println!("\n{}", "Tip: Use `query def <ns/def>` to view definition content.".dimmed());
}
Ok(())
}
fn fuzzy_match(text: &str, pattern: &str) -> bool {
if text.contains(pattern) {
return true;
}
let mut text_chars = text.chars().peekable();
for pattern_char in pattern.chars() {
loop {
match text_chars.next() {
Some(c) if c == pattern_char => break,
Some(_) => continue,
None => return false,
}
}
}
true
}
fn snapshot_code_path(path: &[usize]) -> String {
if path.is_empty() {
"code".to_owned()
} else {
format!("code{}", format_path(path))
}
}
fn search_node_kind(code: &Cirru, path: &[usize], node: &Cirru) -> &'static str {
match node {
Cirru::List(_) => "expr",
Cirru::Leaf(_) => {
if path.last() == Some(&0)
&& navigate_to_path(code, &path[..path.len().saturating_sub(1)]).is_ok_and(|parent| matches!(parent, Cirru::List(_)))
{
"call"
} else {
"leaf"
}
}
}
}
fn format_search_results_json(
command: &'static str,
pattern: &str,
pattern_is_json: bool,
start_path: Option<&str>,
common_opts: &SearchCommonOpts,
catalog: &SearchCatalog,
results: &SearchResults,
) -> Result<String, String> {
let snapshot = &catalog.snapshot;
let total_matches = results.iter().map(|(_, _, matches)| matches.len()).sum::<usize>();
let mut cursor_index = 0_usize;
let definitions = results
.iter()
.map(|(namespace, definition, matches)| -> Result<serde_json::Value, String> {
let code_entry = snapshot
.files
.get(namespace)
.and_then(|file| file.defs.get(definition))
.ok_or_else(|| format!("Definition disappeared while formatting search results: {namespace}/{definition}"))?;
let (source, origin) = catalog
.sources
.get(namespace)
.ok_or_else(|| format!("Source origin disappeared while formatting search results: {namespace}/{definition}"))?;
Ok(serde_json::json!({
"id": format!("{namespace}/{definition}"),
"namespace": namespace,
"name": definition,
"source": source,
"origin": origin,
"match_count": matches.len(),
"matches": matches.iter().map(|(path, node)| {
let current_cursor_index = cursor_index;
cursor_index += 1;
let parent_path = common_opts.parent_path.then(|| {
if path.is_empty() {
None
} else {
Some(snapshot_code_path(&path[..path.len() - 1]))
}
}).flatten();
serde_json::json!({
"cursor_index": current_cursor_index,
"path": snapshot_code_path(path),
"parent_path": parent_path,
"node_kind": search_node_kind(&code_entry.code, path, node),
"tree": cirru_to_json_value(node),
"source": source,
"origin": origin,
})
}).collect::<Vec<_>>(),
}))
})
.collect::<Result<Vec<_>, String>>()?;
let mut revision_parts = vec![
command.to_owned(),
pattern.to_owned(),
common_opts.filter.unwrap_or_default().to_owned(),
common_opts.source.as_str().to_owned(),
start_path.unwrap_or_default().to_owned(),
];
for (namespace, definition, _) in results {
let entry = snapshot
.files
.get(namespace)
.and_then(|file| file.defs.get(definition))
.ok_or_else(|| format!("Definition disappeared while formatting search results: {namespace}/{definition}"))?;
revision_parts.push(format!("{namespace}/{definition}:{}", snapshot::definition_revision(entry)?));
}
let revision_refs = revision_parts.iter().map(String::as_str).collect::<Vec<_>>();
let envelope = serde_json::json!({
"schema_version": 1,
"command": command,
"revision": semantic_revision(&revision_refs),
"data": {
"pattern": pattern,
"filters": {
"definition": common_opts.filter,
"exact": !common_opts.loose,
"regex": common_opts.regex,
"max_depth": common_opts.max_depth,
"start_path": start_path,
"entry": common_opts.entry,
"source": common_opts.source,
"pattern_is_json": pattern_is_json,
},
"summary": {
"definitions": results.len(),
"matches": total_matches,
},
"definitions": definitions,
},
"diagnostics": [],
});
serde_json::to_string_pretty(&envelope).map_err(|error| format!("Failed to encode search JSON: {error}"))
}
fn maybe_set_cursor_from_search_results(
input_path: &str,
results: &SearchResults,
selected_index: usize,
last_query: CursorLastQuery,
) -> Result<(), String> {
let total_matches = results.iter().map(|(_, _, matches)| matches.len()).sum::<usize>();
let main_snapshot = load_main_snapshot(input_path)?;
let mut current_index = 0_usize;
for (namespace, definition, matches) in results {
for (path, _) in matches {
if current_index == selected_index {
if !main_snapshot.files.contains_key(namespace) {
return Err(format!(
"Search match #{selected_index} belongs to dependency or builtin namespace '{namespace}', which cannot become a project edit cursor. Narrow the search with `--filter <project-namespace>` and choose its displayed cursor index."
));
}
return set_cursor_from_query_match(
input_path,
&format!("{namespace}/{definition}"),
path.clone(),
selected_index,
last_query,
);
}
current_index += 1;
}
}
Err(format!(
"Search cursor index {selected_index} is out of range; query returned {total_matches} match(es)."
))
}
fn snapshot_content_revision(input_path: &str) -> Result<String, String> {
let content = fs::read(input_path).map_err(|error| format!("Failed to read snapshot revision from '{input_path}': {error}"))?;
let mut hasher = Md5::new();
hasher.update(&content);
Ok(format!("md5:{}", hex::encode(hasher.finalize())))
}
fn cursor_last_query(
input_path: &str,
command: &str,
pattern: &str,
pattern_is_json: bool,
start_path: Option<&str>,
common_opts: &SearchCommonOpts,
selected_index: usize,
) -> Result<CursorLastQuery, String> {
Ok(CursorLastQuery {
command: command.to_string(),
pattern: pattern.to_string(),
filter: common_opts.filter.map(str::to_string),
exact: !common_opts.loose,
regex: common_opts.regex,
max_depth: common_opts.max_depth,
start_path: start_path.map(str::to_string),
entry: common_opts.entry.map(str::to_string),
source: common_opts.source.as_str().to_owned(),
pattern_is_json,
selected_index,
snapshot_revision: snapshot_content_revision(input_path)?,
})
}
fn parse_search_start_path(start_path: Option<&str>) -> Result<Option<Vec<usize>>, String> {
start_path
.map(|path| parse_path(path).map_err(|error| format!("Invalid start path '{path}': {error}")))
.transpose()
}
fn parse_search_filter(filter: Option<&str>) -> Result<(Option<&str>, Option<&str>), String> {
let Some(filter) = filter else {
return Ok((None, None));
};
let mut parts = filter.split('/');
let namespace = parts.next();
let definition = parts.next();
if parts.next().is_some() {
return Err(format!(
"Invalid filter format: '{filter}'. Use 'namespace' or 'namespace/definition'"
));
}
Ok((namespace, definition))
}
fn collect_search_results<F>(
snapshot: &snapshot::Snapshot,
start_path: Option<&[usize]>,
filter: Option<&str>,
mut search: F,
) -> Result<SearchResults, String>
where
F: FnMut(&Cirru, &[usize]) -> Vec<(Vec<usize>, Cirru)>,
{
let (filter_ns, filter_def) = parse_search_filter(filter)?;
let mut all_results: SearchResults = Vec::new();
for (ns, file_data) in &snapshot.files {
if filter_ns.is_some_and(|filter_namespace| ns != filter_namespace) {
continue;
}
for (def_name, code_entry) in &file_data.defs {
if filter_def.is_some_and(|filter_definition| def_name != filter_definition) {
continue;
}
let owned_search_root = if let Some(path) = start_path {
match navigate_to_path(&code_entry.code, path) {
Ok(node) => Some(node),
Err(error) => {
eprintln!(
"{} Failed to navigate to start path in {}/{}: {}",
"Warning:".yellow(),
ns,
def_name,
error
);
continue;
}
}
} else {
None
};
let search_root = owned_search_root.as_ref().unwrap_or(&code_entry.code);
let results = search(search_root, start_path.unwrap_or(&[]));
if !results.is_empty() {
all_results.push((ns.clone(), def_name.clone(), results));
}
}
}
all_results.sort_by(|a, b| b.2.len().cmp(&a.2.len()).then_with(|| a.0.cmp(&b.0)).then_with(|| a.1.cmp(&b.1)));
Ok(all_results)
}
#[derive(Clone, Copy)]
struct SearchResultDisplay {
bracket_path: bool,
show_parent_path: bool,
}
fn print_search_results_human(
catalog: &SearchCatalog,
all_results: &SearchResults,
common_opts: &SearchCommonOpts,
display: SearchResultDisplay,
) {
let snapshot = &catalog.snapshot;
if all_results.is_empty() {
println!("# Search results\n\n_No matches found._");
return;
}
let total_matches: usize = all_results.iter().map(|(_, _, results)| results.len()).sum();
println!(
"# Search results\n\n- Matches: {total_matches}\n- Definitions: {}\n",
all_results.len(),
);
let mut definition_offset = 0_usize;
for (ns, def_name, results) in all_results {
let source_label = catalog
.sources
.get(ns)
.map(|(source, origin)| {
let origin_label = origin.module.as_deref().unwrap_or(origin.package.as_str());
format!("{}:{origin_label}", source.as_str())
})
.unwrap_or_else(|| "unknown".to_owned());
println!("## `{ns}/{def_name}`\n\n- Matches: {}\n- Source: `{source_label}`\n", results.len());
print_detail_window_hint(results.len(), common_opts.detail_offset, "matches");
if let Some(file_data) = snapshot.files.get(ns)
&& let Some(code_entry) = file_data.defs.get(def_name)
{
let total = results.len();
let (start, end) = detailed_window(common_opts.detail_offset, total);
let detailed_count = end.saturating_sub(start);
for (local_index, (path, node)) in results.iter().enumerate().skip(start).take(detailed_count) {
let cursor_index = definition_offset + local_index;
if path.is_empty() {
let (content, truncated) = preview_node_oneline(&code_entry.code, 110);
println!(
"### Match #{cursor_index}\n\n- Path: `root`{}\n\n{}",
if truncated { "\n- Preview: truncated" } else { "" },
markdown_fenced_block("cirru", &content)
);
} else {
let path_str = format_path(path);
let path_label = if display.bracket_path { format!("[{path_str}]") } else { path_str };
let ((expr_preview, expr_truncated), parent_previews) =
expression_and_parent_preview(&code_entry.code, path, node, None, common_opts.loose);
let (display_preview, display_truncated) = parent_previews
.first()
.map(|(text, truncated)| (text.as_str(), *truncated))
.unwrap_or((expr_preview.as_str(), expr_truncated));
println!(
"### Match #{cursor_index}\n\n- Path: `{path_label}`{}\n\n{}",
if display_truncated { "\n- Preview: truncated" } else { "" },
markdown_fenced_block("cirru", display_preview)
);
if display.show_parent_path && common_opts.parent_path {
let parent_path_str = snapshot_code_path(&path[..path.len() - 1]);
println!("- Parent: `{parent_path_str}`\n");
}
}
}
if start > 0 {
println!(
"_Matches #{}–#{} compressed before this window ({})._",
definition_offset,
definition_offset + start - 1,
start,
);
}
if end < total {
println!(
"_Matches #{}–#{} compressed after this window ({})._",
definition_offset + end,
definition_offset + total - 1,
total - end,
);
}
}
definition_offset += results.len();
println!();
}
if total_matches > 10 && common_opts.loose {
println!("## Tip\n\nMany matches ({total_matches}); add `--exact` to show exact matches only.");
}
}
struct SearchCommandInfo<'a> {
envelope_command: &'static str,
cursor_command: &'static str,
pattern: &'a str,
pattern_is_json: bool,
start_path: Option<&'a str>,
display: SearchResultDisplay,
}
fn finish_search_results(
input_path: &str,
catalog: &SearchCatalog,
all_results: &SearchResults,
common_opts: &SearchCommonOpts,
info: SearchCommandInfo<'_>,
) -> Result<(), String> {
if let Some(selected_index) = common_opts.set_cursor {
let last_query = cursor_last_query(
input_path,
info.cursor_command,
info.pattern,
info.pattern_is_json,
info.start_path,
common_opts,
selected_index,
)?;
maybe_set_cursor_from_search_results(input_path, all_results, selected_index, last_query)?;
}
if common_opts.compact_output {
return Ok(());
}
if common_opts.format != QueryRenderFormat::Human {
let json = format_search_results_json(
info.envelope_command,
info.pattern,
info.pattern_is_json,
info.start_path,
common_opts,
catalog,
all_results,
)?;
match common_opts.format {
QueryRenderFormat::Json => println!("{json}"),
QueryRenderFormat::Edn => {
let value =
serde_json::from_str::<serde_json::Value>(&json).map_err(|error| format!("Failed to decode search query result: {error}"))?;
emit_query_structured(&value, QueryRenderFormat::Edn, "search query result")?;
}
QueryRenderFormat::Human => unreachable!("structured search format checked above"),
}
return Ok(());
}
print_search_results_human(catalog, all_results, common_opts, info.display);
Ok(())
}
fn handle_search_leaf(input_path: &str, pattern: &str, start_path: Option<&str>, common_opts: &SearchCommonOpts) -> Result<(), String> {
let catalog = load_snapshot_for_search(input_path, common_opts)?;
let parsed_start_path = parse_search_start_path(start_path)?;
let all_results = collect_search_results(
&catalog.snapshot,
parsed_start_path.as_deref(),
common_opts.filter,
|search_root, base_path| {
search_leaf_nodes(
search_root,
pattern,
common_opts.loose,
common_opts.regex,
common_opts.max_depth,
base_path,
)
},
)?;
finish_search_results(
input_path,
&catalog,
&all_results,
common_opts,
SearchCommandInfo {
envelope_command: "query.search",
cursor_command: "search",
pattern,
pattern_is_json: false,
start_path,
display: SearchResultDisplay {
bracket_path: false,
show_parent_path: true,
},
},
)
}
fn handle_search_expr(
input_path: &str,
pattern: &str,
json: bool,
start_path: Option<&str>,
common_opts: &SearchCommonOpts,
) -> Result<(), String> {
let catalog = load_snapshot_for_search(input_path, common_opts)?;
let parsed_start_path = parse_search_start_path(start_path)?;
let pattern_node = if json {
let json_val: serde_json::Value = serde_json::from_str(pattern).map_err(|e| format!("Failed to parse JSON pattern: {e}"))?;
json_to_cirru(&json_val)?
} else {
cirru_parser::parse(pattern)
.map_err(|e| format!("Failed to parse Cirru pattern: {e}"))?
.first()
.ok_or("Pattern is empty")?
.clone()
};
let all_results = collect_search_results(
&catalog.snapshot,
parsed_start_path.as_deref(),
common_opts.filter,
|search_root, base_path| search_expr_nodes(search_root, &pattern_node, common_opts.loose, common_opts.max_depth, base_path),
)?;
finish_search_results(
input_path,
&catalog,
&all_results,
common_opts,
SearchCommandInfo {
envelope_command: "query.search-expr",
cursor_command: "search-expr",
pattern,
pattern_is_json: json,
start_path,
display: SearchResultDisplay {
bracket_path: true,
show_parent_path: false,
},
},
)
}
fn json_to_cirru(json: &serde_json::Value) -> Result<Cirru, String> {
match json {
serde_json::Value::String(s) => Ok(Cirru::Leaf(s.as_str().into())),
serde_json::Value::Array(arr) => {
let items: Result<Vec<_>, _> = arr.iter().map(json_to_cirru).collect();
Ok(Cirru::List(items?))
}
_ => Err("Pattern must be a string or array".to_string()),
}
}
fn search_leaf_nodes(
node: &Cirru,
pattern: &str,
loose: bool,
regex: bool,
max_depth: usize,
current_path: &[usize],
) -> Vec<(Vec<usize>, Cirru)> {
let mut results = Vec::new();
if max_depth > 0 && current_path.len() >= max_depth {
return results;
}
let regex_pattern = if regex {
match regex::Regex::new(pattern) {
Ok(r) => Some(r),
Err(e) => {
eprintln!("{} Invalid regex '{}': {}", "Error:".red().bold(), pattern, e);
return results;
}
}
} else {
None
};
match node {
Cirru::Leaf(s) => {
let matches = if regex {
regex_pattern.as_ref().is_some_and(|r| r.is_match(s))
} else if loose {
s.to_lowercase().contains(&pattern.to_lowercase())
} else {
s.as_ref() == pattern
};
if matches {
results.push((current_path.to_vec(), node.clone()));
}
}
Cirru::List(items) => {
for (i, item) in items.iter().enumerate() {
let mut new_path = current_path.to_vec();
new_path.push(i);
results.extend(search_leaf_nodes(item, pattern, loose, regex, max_depth, &new_path));
}
}
}
results
}
fn search_expr_nodes(node: &Cirru, pattern: &Cirru, loose: bool, max_depth: usize, current_path: &[usize]) -> Vec<(Vec<usize>, Cirru)> {
let mut results = Vec::new();
if max_depth > 0 && current_path.len() >= max_depth {
return results;
}
let matches = if loose {
contains_pattern(node, pattern)
} else {
matches_exact_structure(node, pattern)
};
if matches {
results.push((current_path.to_vec(), node.clone()));
}
if let Cirru::List(items) = node {
for (i, item) in items.iter().enumerate() {
let mut new_path = current_path.to_vec();
new_path.push(i);
results.extend(search_expr_nodes(item, pattern, loose, max_depth, &new_path));
}
}
results
}
fn contains_pattern(node: &Cirru, pattern: &Cirru) -> bool {
match (node, pattern) {
(Cirru::Leaf(s), Cirru::Leaf(p)) => s.to_lowercase().contains(&p.as_ref().to_lowercase()),
(Cirru::List(items), Cirru::List(pattern_items)) => {
if pattern_items.is_empty() {
return true;
}
if pattern_items.len() > items.len() {
return false;
}
for (i, pattern_item) in pattern_items.iter().enumerate() {
if !matches_prefix_structure(&items[i], pattern_item) {
return false;
}
}
true
}
_ => false,
}
}
fn matches_prefix_structure(node: &Cirru, pattern: &Cirru) -> bool {
super::structural_pattern::match_structure(node, pattern, true, false).is_some()
}
fn matches_exact_structure(node: &Cirru, pattern: &Cirru) -> bool {
super::structural_pattern::match_structure(node, pattern, false, false).is_some()
}
pub(crate) fn resolve_path_expression(root: &Cirru, selector: &str) -> Result<Vec<usize>, String> {
let parsed = cirru_parser::parse(selector).map_err(|e| format!("Failed to parse path selector: {e}"))?;
let Some(first) = parsed.first() else {
return Err("Empty path selector".to_string());
};
let Cirru::List(steps) = first else {
return Err("Path expression must be a list starting with 'path'".to_string());
};
if steps.is_empty() {
return Err("Empty path expression".to_string());
}
let Cirru::Leaf(head) = &steps[0] else {
return Err("Path expression must start with 'path'".to_string());
};
if head.as_ref() != "path" {
return Err(format!("Expected 'path' at start, got '{head}'"));
}
let mut current_node = root.clone();
let mut current_path: Vec<usize> = vec![];
for step in &steps[1..] {
match step {
Cirru::Leaf(leaf_val) => {
let Cirru::Leaf(current_leaf) = ¤t_node else {
return Err(format!("Expected leaf but got list at path {}", format_path(¤t_path)));
};
if current_leaf.as_ref() != leaf_val.as_ref() {
return Err(format!(
"Leaf mismatch at path {}: expected {:?}, got {:?}",
format_path(¤t_path),
leaf_val.as_ref(),
current_leaf.as_ref()
));
}
}
Cirru::List(selector_list) => {
if selector_list.is_empty() {
return Err("Empty selector".to_string());
}
let Cirru::Leaf(op) = &selector_list[0] else {
return Err("Selector must start with an operator leaf".to_string());
};
match op.as_ref() {
"heading" => {
let Cirru::List(ref current_children) = current_node else {
return Err("heading requires a list node".to_string());
};
let pattern = &selector_list[1..];
if !starts_with_pattern(current_children, pattern) {
return Err(format!(
"heading mismatch at path {}: node does not start with expected pattern",
format_path(¤t_path)
));
}
}
"nth" => {
if selector_list.len() < 2 {
return Err("nth requires an index argument".to_string());
}
let Cirru::Leaf(idx_leaf) = &selector_list[1] else {
return Err("nth index must be a number".to_string());
};
let idx: usize = idx_leaf
.as_ref()
.parse()
.map_err(|_| format!("Invalid nth index: '{}'", idx_leaf.as_ref()))?;
let Cirru::List(ref children) = current_node else {
return Err("nth requires a list node".to_string());
};
if idx >= children.len() {
return Err(format!("nth index {} out of bounds ({} children)", idx, children.len()));
}
current_path.push(idx);
current_node = children[idx].clone();
}
_ => return Err(format!("Unknown selector: '{}'", op.as_ref())),
}
}
}
}
Ok(current_path)
}
fn starts_with_pattern(node_children: &[Cirru], pattern: &[Cirru]) -> bool {
if pattern.len() > node_children.len() {
return false;
}
for (i, pat) in pattern.iter().enumerate() {
match pat {
Cirru::Leaf(pat_leaf) => {
let Cirru::Leaf(child_leaf) = &node_children[i] else {
return false;
};
if child_leaf.as_ref() != pat_leaf.as_ref() {
return false;
}
}
Cirru::List(pat_list) => {
let Cirru::List(child_list) = &node_children[i] else {
return false;
};
if !starts_with_pattern(child_list, pat_list) {
return false;
}
}
}
}
true
}
#[cfg(test)]
mod usage_symbol_tests {
use super::*;
fn symbols_for(ns_source: &str, defines_target_name: bool, target: (&str, &str)) -> Vec<String> {
let ns_code = cirru_parser::parse(ns_source).expect("ns form should parse").remove(0);
target_reference_symbols("app.caller", &ns_code, defines_target_name, target.0, target.1)
.expect("canonical require rules should resolve")
}
#[test]
fn legacy_require_list_is_rejected_for_usages() {
let ns_code = cirru_parser::parse("ns app.caller $ :require $ [] app.schema :as s")
.expect("ns form should parse")
.remove(0);
let err = target_reference_symbols("app.caller", &ns_code, false, "app.schema", "decode")
.expect_err("legacy `[]` require list must be rejected");
assert!(err.contains(calcit_core::program::LEGACY_REQUIRE_LIST_ERROR), "{err}");
}
#[test]
fn reference_symbols_follow_require_rules() {
let target = ("app.schema", "decode");
assert_eq!(symbols_for("ns app.caller", false, target), ["app.schema/decode"]);
assert_eq!(
symbols_for(
"ns app.caller $ :require (app.schema :as s) (app.schema :as schema) (app.schema :refer $ decode)",
false,
target
),
["app.schema/decode", "decode", "s/decode", "schema/decode"]
);
assert_eq!(
symbols_for(
"ns app.caller $ :require (app.schema-v2 :as schema) (app.schema-v2 :refer $ decode)",
false,
target
),
["app.schema/decode"]
);
for rebinding in ["app.other :refer $ decode", "app.other :as decode", "|pkg :default decode"] {
let source = format!("ns app.caller $ :require (app.schema :refer $ decode) ({rebinding})");
assert_eq!(symbols_for(&source, false, target), ["app.schema/decode"], "{rebinding}");
}
assert_eq!(
symbols_for("ns app.caller $ :require (app.schema :as s) (app.other :as s)", false, target),
["app.schema/decode"]
);
assert_eq!(
symbols_for(
"ns app.caller $ :require (app.other :as app.schema) (app.schema :as s)",
false,
target
),
["s/decode"]
);
}
#[test]
fn core_names_are_bare_unless_rebound() {
let target = ("calcit.core", "map");
assert_eq!(symbols_for("ns app.caller", false, target), ["calcit.core/map", "map"]);
assert_eq!(symbols_for("ns app.caller", true, target), ["calcit.core/map"]);
assert_eq!(
symbols_for("ns app.caller $ :require (app.util :refer $ map)", false, target),
["calcit.core/map"]
);
}
}
#[cfg(test)]
mod examples_cirru_tests {
use super::*;
#[test]
fn render_examples_cirru_round_trips_expressions_and_leaves() {
let examples = vec![
cirru_parser::parse("+ 1 2").expect("expr should parse").remove(0),
Cirru::Leaf(Arc::from("CounterOps")),
cirru_parser::parse("let ((x 1)) $ + x 2").expect("let expr should parse").remove(0),
];
let rendered = render_examples_cirru("app.main/sample", &examples).expect("should format examples as Cirru");
assert!(!rendered.contains("JSON AST"), "{rendered}");
assert!(!rendered.contains("```"), "{rendered}");
let reparsed = crate::cli_handlers::common::parse_quoted_cirru_nodes(&rendered).expect("rendered Cirru should reparse");
assert_eq!(reparsed, examples);
}
#[test]
fn render_examples_cirru_returns_empty_for_no_examples() {
let rendered = render_examples_cirru("app.main/empty", &[]).expect("empty examples should succeed");
assert!(rendered.is_empty(), "{rendered:?}");
}
#[test]
fn special_js_intrinsics_share_compiler_signature() {
for name in ["js-array", "&js-object"] {
let meta = lookup_special_builtin_query_meta(calcit_core::calcit::CORE_NS, name)
.expect("query meta lookup should succeed")
.expect("intrinsic metadata should exist");
let expected = runner::preprocess::special_js_intrinsic_signature(name).expect("compiler signature should exist");
assert_eq!(meta.schema, expected, "{name} query schema drifted from compiler");
let sig = meta.schema.as_function().expect("schema should be Fn");
assert!(matches!(sig.return_type.as_ref(), CalcitTypeAnnotation::JsObject));
}
}
}