use std::cell::{Cell, RefCell};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs;
use std::path::Path;
use std::process::Command;
use std::sync::Arc;
use crate::cli_args::{FixCommand, WeakTypesCommand};
use calcit_core::calcit::{Calcit, CalcitFnTypeAnnotation, CalcitProc, CalcitTypeAnnotation, LocatedWarning, SchemaKind};
use calcit_core::call_stack::CallStackList;
use calcit_core::data::cirru::code_to_calcit;
use calcit_core::snapshot::Snapshot;
use calcit_core::{program, runner};
use cirru_parser::Cirru;
use md5::{Digest, Md5};
use serde::Serialize;
use serde_json::Value;
use super::common::{cirru_to_json_value, format_path, json_value_to_cirru, markdown_cirru_section};
use super::edit::{load_snapshot, navigate_to_path, run_staged_fix_transaction, snapshot_content_revision};
use super::structured_output::{StructuredOutputFormat, format_json_value_as_edn};
use crate::type_coverage;
const REMOVED_DATA_API_RULE: &str = "removed-data-api-v1";
const REMOVED_DATA_API_DIAGNOSTIC: &str = "E_REMOVED_DATA_API";
const REDUNDANT_DO_RULE: &str = "redundant-do-v1";
const REDUNDANT_DO_DIAGNOSTIC: &str = "FIX_REDUNDANT_DO";
const SINGLE_EXPRESSION_DO_RULE: &str = "single-expression-do-v1";
const SINGLE_EXPRESSION_DO_DIAGNOSTIC: &str = "FIX_SINGLE_EXPRESSION_DO";
const NAMED_ENUM_CONSTRUCTOR_RULE: &str = "named-enum-constructor-v1";
const NAMED_ENUM_CONSTRUCTOR_DIAGNOSTIC: &str = "FIX_NAMED_ENUM_CONSTRUCTOR";
const NAMED_STRUCT_CONSTRUCTOR_RULE: &str = "named-struct-constructor-v1";
const NAMED_STRUCT_CONSTRUCTOR_DIAGNOSTIC: &str = "FIX_NAMED_STRUCT_CONSTRUCTOR";
const CORE_OPTION_METHOD_RULE: &str = "core-option-method-v1";
const CORE_OPTION_METHOD_DIAGNOSTIC: &str = "FIX_CORE_OPTION_METHOD";
const CORE_RESULT_METHOD_RULE: &str = "core-result-method-v1";
const CORE_RESULT_METHOD_DIAGNOSTIC: &str = "FIX_CORE_RESULT_METHOD";
const CORE_IDENTITY_CONVERSION_RULE: &str = "core-identity-conversion-v1";
const CORE_IDENTITY_CONVERSION_DIAGNOSTIC: &str = "FIX_CORE_IDENTITY_CONVERSION";
const RENAME_DEFINITION_RULE: &str = "rename-definition-v1";
const RENAME_DEFINITION_DIAGNOSTIC: &str = "REFACTOR_RENAME_DEFINITION";
const RENAME_LOCAL_RULE: &str = "rename-local-v1";
const RENAME_LOCAL_DIAGNOSTIC: &str = "REFACTOR_RENAME_LOCAL";
const VALUE_TO_ZERO_ARG_FN_RULE: &str = "value-to-zero-arg-fn-v1";
const VALUE_TO_ZERO_ARG_FN_DIAGNOSTIC: &str = "REFACTOR_VALUE_TO_ZERO_ARG_FN";
const SYNTHESIZE_SCHEMA_RULE: &str = "synthesize-schema-v1";
const SYNTHESIZE_SCHEMA_DIAGNOSTIC: &str = "REFACTOR_SYNTHESIZE_SCHEMA";
const SPREAD_CALL_PROOF_RULE: &str = "spread-call-proof-v1";
const SPREAD_CALL_PROOF_DIAGNOSTIC: &str = "REFACTOR_SPREAD_CALL";
const UNSAFE_COERCE_BOUNDARY_RULE: &str = "unsafe-coerce-boundary-v1";
const UNSAFE_COERCE_BOUNDARY_DIAGNOSTIC: &str = "E_UNSCOPED_UNSAFE_COERCE";
const ASSERT_TYPE_PROOF_RULE: &str = "assert-type-proof-v1";
const ASSERT_TYPE_PROOF_DIAGNOSTIC: &str = "E_ASSERT_TYPE_UNPROVEN";
const CONCRETE_RETURN_PROOF_RULE: &str = "concrete-return-proof-v1";
const CONCRETE_RETURN_PROOF_DIAGNOSTIC: &str = "E_FN_RETURN_UNPROVEN";
const CALLABLE_CONTRACT_PROOF_RULE: &str = "callable-contract-proof-v1";
const NOMINAL_WRITE_PROOF_RULE: &str = "nominal-write-proof-v1";
const OPTIONAL_PARAMETERS_RULE: &str = "optional-parameters-v1";
const CORE_ABSENCE_RULE: &str = "core-absence-to-public-v1";
const LEGACY_COMMENT_NIL_RULE: &str = "legacy-comment-nil-v1";
const LEGACY_COMMENT_NIL_DIAGNOSTIC: &str = "E_LEGACY_NIL_USAGE";
const REDUNDANT_HINT_FN_RULE: &str = "redundant-hint-fn-v1";
const REDUNDANT_HINT_FN_DIAGNOSTIC: &str = "W_REDUNDANT_HINT_FN";
const CORE_ABSENCE_DIAGNOSTIC: &str = "FIX_CORE_ABSENCE_TO_PUBLIC";
const SURFACE_LATEST_V1_PRESET: &str = "surface-latest-v1";
const SURFACE_LATEST_V2_PRESET: &str = "surface-latest-v2";
const CORE_API_028_V1_PRESET: &str = "core-api-0.28-v1";
const CORE_API_029_V1_PRESET: &str = "core-api-0.29-v1";
const AVAILABLE_RULES: [&str; 5] = [
REMOVED_DATA_API_RULE,
NAMED_ENUM_CONSTRUCTOR_RULE,
NAMED_STRUCT_CONSTRUCTOR_RULE,
REDUNDANT_DO_RULE,
SINGLE_EXPRESSION_DO_RULE,
];
const SURFACE_LATEST_V1_RULES: [&str; 4] = [
REMOVED_DATA_API_RULE,
NAMED_ENUM_CONSTRUCTOR_RULE,
NAMED_STRUCT_CONSTRUCTOR_RULE,
REDUNDANT_DO_RULE,
];
const SURFACE_LATEST_V2_RULES: [&str; 5] = [
REMOVED_DATA_API_RULE,
NAMED_ENUM_CONSTRUCTOR_RULE,
NAMED_STRUCT_CONSTRUCTOR_RULE,
REDUNDANT_DO_RULE,
SINGLE_EXPRESSION_DO_RULE,
];
// These proven renames replace leaves only, so nested calls retain their source paths.
const CORE_API_028_V1_RULES: [&str; 1] = [CORE_IDENTITY_CONVERSION_RULE];
// The 0.29 preset keeps every 0.28 rule this CLI still ships; its Ref constructor
// rename was retired with `defatom` in 0.31.0.
const CORE_API_029_V1_RULES: [&str; 1] = [CORE_IDENTITY_CONVERSION_RULE];
#[derive(Debug, Clone, PartialEq, Eq)]
enum FixOperation {
ReplaceLeaf {
original: String,
replacement: String,
},
WrapLeafCall {
original: String,
},
ReplaceNode {
original: String,
replacement: String,
},
/// Replace a list node guard-checked by exact JSON AST with a single syntax leaf.
ReplaceNodeWithLeaf {
original_json_ast: String,
replacement_leaf: String,
},
SpliceDo,
/// Remove one list node, guarded by its exact source.
DeleteNode {
original: String,
},
ReplaceImports {
code: String,
},
ReplaceExamples {
code: String,
},
ReplaceTest {
name: String,
tags: String,
code: String,
},
ReplaceSchema {
code: String,
},
ReplaceDefinition {
code: String,
},
RenameDefinition {
new_name: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
struct FixSuggestion {
rule_id: &'static str,
#[serde(skip_serializing_if = "str::is_empty")]
diagnostic_code: &'static str,
semantic_layer: &'static str,
source_file: String,
definition: String,
path: String,
fingerprint: String,
origin_chain: Vec<Value>,
original: Value,
replacement: Option<Value>,
applicability: &'static str,
message: String,
#[serde(skip)]
target_path: Vec<usize>,
#[serde(skip)]
operation: Option<FixOperation>,
}
#[derive(Debug, Serialize)]
struct FixReport<'a> {
schema_version: u8,
command: &'static str,
revision: &'a str,
data: FixReportData<'a>,
diagnostics: Vec<Value>,
next: Vec<Value>,
}
#[derive(Debug, Serialize)]
struct FixReportData<'a> {
mode: &'static str,
filters: FixFilters<'a>,
changed: bool,
new_revision: &'a str,
validation: FixValidation,
suggestions: &'a [FixSuggestion],
#[serde(skip_serializing_if = "Option::is_none")]
workflow: Option<StrictWorkflowManifest>,
}
#[derive(Debug, Serialize)]
struct FixValidation {
status: &'static str,
staged_scope_preprocess: bool,
checked_operations: usize,
}
#[derive(Debug, Serialize)]
struct FixFilters<'a> {
namespace: Option<&'a str>,
definition: Option<&'a str>,
replacement_name: Option<&'a str>,
rule_id: &'a str,
preset_id: Option<&'a str>,
expanded_rule_ids: Vec<&'static str>,
expanded_rules: Vec<FixRuleMetadata>,
#[serde(skip_serializing_if = "Option::is_none")]
source_coverage: Option<FixSourceCoverage>,
}
#[derive(Debug, Serialize)]
struct FixSourceCoverage {
scanned_regions: &'static [&'static str],
manual_review_regions: &'static [&'static str],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
struct FixRuleMetadata {
rule_id: &'static str,
diagnostic_code: &'static str,
evidence_source: &'static str,
lifecycle: &'static str,
source_version_required: bool,
}
#[derive(Debug, Serialize)]
struct StrictWorkflowManifest {
workflow: &'static str,
mode: &'static str,
status: &'static str,
entries: Vec<StrictWorkflowEntry>,
safe_fixes: StrictWorkflowSafeFixes,
review_required: StrictWorkflowReviewRequired,
retained_type_boundaries: Vec<StrictWorkflowTypeFinding>,
preflight: crate::verification::PreflightReport,
verification: StrictWorkflowVerification,
resume: StrictWorkflowResume,
}
#[derive(Debug, Serialize)]
struct StrictWorkflowEntry {
name: String,
mode: String,
target: String,
init_fn: String,
reload_fn: String,
type_slots: BTreeMap<String, String>,
}
#[derive(Debug, Serialize)]
struct StrictWorkflowSafeFixes {
preset: &'static str,
suggestions: usize,
status: &'static str,
}
#[derive(Debug, Serialize)]
struct StrictWorkflowReviewRequired {
source_fixes: Vec<StrictWorkflowSourceReview>,
type_findings: Vec<StrictWorkflowTypeFinding>,
ffi_boundaries: Vec<type_coverage::FfiBoundaryEvidence>,
schema_candidates: Vec<schema_synthesis::SchemaEvidenceCandidate>,
structural_candidates: type_coverage::StructuralCandidates,
}
#[derive(Debug, Serialize)]
struct StrictWorkflowSourceReview {
rule_id: &'static str,
definition: String,
path: String,
message: String,
}
#[derive(Debug, Serialize)]
struct StrictWorkflowTypeFinding {
definition: String,
kind: String,
intent: String,
path: String,
detail: String,
}
struct StrictWorkflowTypeEvidence {
review_required: Vec<StrictWorkflowTypeFinding>,
retained_boundaries: Vec<StrictWorkflowTypeFinding>,
ffi_boundaries: Vec<type_coverage::FfiBoundaryEvidence>,
schema_candidates: Vec<schema_synthesis::SchemaEvidenceCandidate>,
structural_candidates: type_coverage::StructuralCandidates,
}
#[derive(Debug, Serialize)]
struct StrictWorkflowVerification {
commands: Vec<Vec<String>>,
results: Vec<StrictWorkflowVerificationResult>,
external_commands: Vec<Vec<String>>,
}
#[derive(Debug, Serialize)]
struct StrictWorkflowVerificationResult {
scope: String,
status: &'static str,
report: Value,
}
#[derive(Debug, Serialize)]
struct StrictWorkflowResume {
revision: String,
apply_command: Vec<String>,
}
fn strict_workflow_entries(snapshot: &Snapshot) -> Vec<StrictWorkflowEntry> {
let mut entries = snapshot.entries.iter().collect::<Vec<_>>();
entries.sort_by_key(|(name, _)| *name);
entries
.into_iter()
.map(|(name, entry)| StrictWorkflowEntry {
name: name.clone(),
mode: entry.mode.as_str().to_owned(),
target: entry.target.map(|target| target.as_str()).unwrap_or("unspecified").to_owned(),
init_fn: entry.init_fn.clone(),
reload_fn: entry.reload_fn.clone(),
type_slots: entry.type_slots.iter().map(|(name, value)| (name.clone(), value.clone())).collect(),
})
.collect()
}
fn strict_workflow_type_findings(snapshot: &Snapshot) -> Result<StrictWorkflowTypeEvidence, String> {
let options = WeakTypesCommand {
ns: None,
ns_prefix: None,
deps: false,
only: None,
coverage_level: None,
intent: None,
summary_only: false,
format: "json".to_owned(),
ffi_evidence: true,
schema_evidence: true,
incremental: false,
};
let mut review_required = Vec::new();
let mut retained_boundaries = Vec::new();
let rows = collect_rows_by_definition_entry(
|| type_coverage::collect_weak_type_rows(&options, snapshot),
|row| (row.ns.as_str(), row.def.as_str()),
)?;
for row in rows {
let definition = format!("{}/{}", row.ns, row.def);
for occurrence in row.occurrences {
let finding = StrictWorkflowTypeFinding {
definition: definition.clone(),
kind: occurrence.kind.as_str().to_owned(),
intent: occurrence.intent.as_str().to_owned(),
path: occurrence.path,
detail: occurrence.detail,
};
match occurrence.intent {
type_coverage::WeakTypeIntent::Unresolved
| type_coverage::WeakTypeIntent::ExplicitUnsafe
| type_coverage::WeakTypeIntent::JsFfiNonHost => review_required.push(finding),
type_coverage::WeakTypeIntent::IntentionalJsFfi
| type_coverage::WeakTypeIntent::IntentionalTypeSlotDynamic
| type_coverage::WeakTypeIntent::IntentionalDecode
| type_coverage::WeakTypeIntent::IntentionalOpen => retained_boundaries.push(finding),
type_coverage::WeakTypeIntent::IntentionalMacroSyntax | type_coverage::WeakTypeIntent::DeclaredUnit => {}
}
}
}
for findings in [&mut review_required, &mut retained_boundaries] {
findings.sort_by(|left, right| {
left
.definition
.cmp(&right.definition)
.then(left.path.cmp(&right.path))
.then(left.kind.cmp(&right.kind))
.then(left.intent.cmp(&right.intent))
});
}
let ffi_boundaries = type_coverage::collect_ffi_boundary_evidence(&options, snapshot)?;
let schema_candidates = type_coverage::collect_schema_candidates(&options, snapshot)?;
let structural_candidates = type_coverage::collect_structural_candidates(&options, snapshot)?;
Ok(StrictWorkflowTypeEvidence {
review_required,
retained_boundaries,
ffi_boundaries,
schema_candidates,
structural_candidates,
})
}
fn strict_workflow_commands(snapshot_file: &str, snapshot: &Snapshot) -> Vec<(String, Vec<String>)> {
let mut commands = Vec::new();
let mut entries = snapshot.entries.keys().cloned().collect::<Vec<_>>();
entries.sort();
for entry in entries {
commands.push((
format!("entry:{entry}"),
vec![
snapshot_file.to_owned(),
"--entry".to_owned(),
entry,
"--check-only".to_owned(),
"--keep-going".to_owned(),
"--format".to_owned(),
"json".to_owned(),
"--tips-level".to_owned(),
"none".to_owned(),
],
));
}
let mut profiles = snapshot.verification.profiles.keys().cloned().collect::<Vec<_>>();
profiles.sort();
for profile in profiles {
commands.push((
format!("profile:{profile}"),
vec![
snapshot_file.to_owned(),
"--tips-level".to_owned(),
"none".to_owned(),
"analyze".to_owned(),
"verify".to_owned(),
"--profile".to_owned(),
profile,
"--format".to_owned(),
"json".to_owned(),
],
));
}
commands
}
fn run_strict_workflow_verification(commands: &[(String, Vec<String>)]) -> Result<Vec<StrictWorkflowVerificationResult>, String> {
let executable = std::env::current_exe().map_err(|error| format!("Failed to locate current Calcit executable: {error}"))?;
let mut results = Vec::new();
for (scope, arguments) in commands {
let output = Command::new(&executable)
.args(arguments)
.output()
.map_err(|error| format!("Failed to run strict workflow verification for `{scope}`: {error}"))?;
results.push(strict_workflow_verification_result(
scope,
output.status.success(),
&output.stdout,
&output.stderr,
));
}
Ok(results)
}
fn strict_workflow_verification_result(scope: &str, succeeded: bool, stdout: &[u8], stderr: &[u8]) -> StrictWorkflowVerificationResult {
let parsed = serde_json::from_slice::<Value>(stdout)
.map_err(|error| error.to_string())
.and_then(|report| {
if report["data"]["status"].is_string() && report["diagnostics"].is_array() {
Ok(report)
} else {
Err("missing verification data.status or diagnostics array".to_owned())
}
});
let report = parsed.unwrap_or_else(|error| {
serde_json::json!({
"schema_version": 1,
"command": "fix.workflow.verify",
"data": null,
"diagnostics": [{
"code": "E_WORKFLOW_OUTPUT",
"phase": "verification",
"severity": "error",
"message": format!("Expected one JSON report from `{scope}`: {error}"),
"stderr": String::from_utf8_lossy(stderr),
}],
})
});
// A successful process is insufficient when its report failed or was lost.
let passed = succeeded
&& report["data"]["status"] == "passed"
&& report["diagnostics"]
.as_array()
.is_some_and(|diagnostics| diagnostics.iter().all(|diagnostic| diagnostic["severity"] != "error"));
StrictWorkflowVerificationResult {
scope: scope.to_owned(),
status: if passed { "passed" } else { "failed" },
report,
}
}
fn strict_verification_exit(failed: bool) -> Result<(), String> {
if failed {
Err("Strict project workflow verification failed; inspect the structured workflow results.".to_owned())
} else {
Ok(())
}
}
#[derive(Debug, Serialize)]
struct StrictWorkflowMacroDiagnosticLocation {
ns: String,
def: String,
coord: Vec<u16>,
}
#[derive(Debug, Serialize)]
struct StrictWorkflowMacroDiagnostic {
r#macro: String,
definition: String,
path: String,
location: StrictWorkflowMacroDiagnosticLocation,
message: String,
count: usize,
}
/// Deduplicate locatable compile-time project macro diagnostics by
/// `(macro, location, message)` in first-seen order while preserving exact text
/// and occurrence counts.
fn summarize_macro_diagnostics(captured: Vec<crate::injection::CapturedMacroDiagnostic>) -> Vec<StrictWorkflowMacroDiagnostic> {
let mut entries = Vec::<StrictWorkflowMacroDiagnostic>::new();
let mut indices = HashMap::<(String, String, String, Vec<u16>, String), usize>::new();
for item in captured {
let ns = item.location.ns.to_string();
let def = item.location.def.to_string();
let coord = item.location.coord.to_vec();
let key = (
item.macro_name.clone(),
ns.clone(),
def.clone(),
coord.clone(),
item.message.clone(),
);
if let Some(&idx) = indices.get(&key) {
entries[idx].count += 1;
} else {
let path = if coord.is_empty() {
"code".to_owned()
} else {
let path_indices = coord.iter().copied().map(usize::from).collect::<Vec<_>>();
format!("code{}", format_path(&path_indices))
};
let definition = format!("{ns}/{def}");
let idx = entries.len();
entries.push(StrictWorkflowMacroDiagnostic {
r#macro: item.macro_name,
definition,
path,
location: StrictWorkflowMacroDiagnosticLocation { ns, def, coord },
message: item.message,
count: 1,
});
indices.insert(key, idx);
}
}
entries
}
fn strict_verification_summary(result: &StrictWorkflowVerificationResult) -> Value {
let mut summary = serde_json::json!({"scope": result.scope, "status": result.status});
if result.status == "failed" {
let report = &result.report;
summary["diagnostics"] = report["diagnostics"].clone();
if let Some(definitions) = report["data"]["definitions"].as_array() {
summary["definitions"] = Value::Array(definitions.clone());
}
if let Some(checks) = report["data"]["checks"].as_array() {
summary["checks"] = checks.iter().filter(|check| check["status"] != "passed").cloned().collect();
}
if let Some(diagnostics) = report["data"]["preflight"]["diagnostics"].as_array() {
summary["preflight_diagnostics"] = Value::Array(diagnostics.clone());
}
}
summary
}
/// Plan deterministic source migrations, validate them on a staged Snapshot, and optionally commit them atomically.
pub fn handle_fix_command(
options: &FixCommand,
compiled_snapshot: &Snapshot,
project_namespaces: &HashSet<String>,
snapshot_file: &str,
) -> Result<(), String> {
if options.summary_only
&& (options.workflow.as_deref() != Some("strict") || !options.verify || options.pattern.is_some() || options.replacement.is_some())
{
return Err("fix --summary-only requires --workflow strict --verify".to_owned());
}
let _output_guard = crate::ProgramOutputGuard::new(true, options.summary_only);
let _macro_diagnostic_guard = options.summary_only.then(crate::injection::MacroDiagnosticCaptureGuard::new);
if options.pattern.is_some() || options.replacement.is_some() {
return structural_rewrite::handle_pattern_rewrite(options, compiled_snapshot, project_namespaces, snapshot_file);
}
validate_options(options)?;
// A whole-project plan covers definitions from every named entry, so it has
// no single host target. Entry-scoped checks still enforce their own target.
let _target_scope = FixTargetScope::new(options.ns.is_none());
let _type_slot_scope = EntryTypeSlotScope::new(options.ns.is_none(), compiled_snapshot, project_namespaces)?;
let selected_rules = selected_rule_ids(options);
let source_snapshot = load_snapshot(snapshot_file)?;
let source_content = fs::read_to_string(snapshot_file).map_err(|error| format!("Failed to read {snapshot_file}: {error}"))?;
let revision = snapshot_content_revision(&source_content);
if let Some(expected) = options.expect_revision.as_deref()
&& expected != revision
{
return Err(format!(
"Snapshot revision mismatch: expected '{expected}', current revision is '{revision}'. Re-run `calcit fix` and review the new plan."
));
}
let semantic_rename = selected_rules.contains(&RENAME_DEFINITION_RULE);
let local_rename = selected_rules.contains(&RENAME_LOCAL_RULE);
let value_to_zero_arg_fn = selected_rules.contains(&VALUE_TO_ZERO_ARG_FN_RULE);
let schema_synthesis = selected_rules.contains(&SYNTHESIZE_SCHEMA_RULE);
let effect_features = selected_rules.contains(&EFFECT_FEATURES_RULE);
let legacy_comment_nil = selected_rules.contains(&LEGACY_COMMENT_NIL_RULE);
let semantic_refactor = semantic_rename || value_to_zero_arg_fn || local_rename;
let migration_rule = semantic_refactor || schema_synthesis || options.workflow.is_some();
let validation_only = std::env::var("CALCIT_FIX_VALIDATE_ONLY").as_deref() == Ok("1");
let project_definitions = if (semantic_refactor && !local_rename) || schema_synthesis || effect_features {
select_project_definitions(compiled_snapshot, project_namespaces)?
} else {
select_definitions(options, compiled_snapshot, project_namespaces)?
};
let mut selected_definitions = if schema_synthesis && validation_only {
select_definitions(options, compiled_snapshot, project_namespaces)?
} else {
project_definitions.clone()
};
// Stable: definitions keep their sorted order within each owning entry.
selected_definitions.sort_by_key(|(namespace, definition)| definition_entry_rank(namespace, definition));
let mut boundary_suggestions = Vec::new();
let mut boundary_diagnostics = Vec::new();
let review_rule = selected_rules.iter().copied().find(|rule| {
matches!(
*rule,
UNSAFE_COERCE_BOUNDARY_RULE
| ASSERT_TYPE_PROOF_RULE
| CONCRETE_RETURN_PROOF_RULE
| CALLABLE_CONTRACT_PROOF_RULE
| NOMINAL_WRITE_PROOF_RULE
)
});
// Features propagate to callers, so the plan needs every typed project
// function's summary, not only the selected ones.
if effect_features && !validation_only {
runner::preprocess::start_effect_summaries();
}
let warnings = if selected_rules.contains(&CORE_ABSENCE_RULE) && !validation_only {
// Old arities can fail before a migration plan exists. Retain those errors
// as review diagnostics; missing compiler evidence cannot authorize a fix.
with_legacy_migration_mode(|| {
let warnings = RefCell::new(Vec::new());
for (namespace, definition) in &selected_definitions {
if let Err(error) = with_definition_entry_context(namespace, definition, || {
runner::preprocess::ensure_ns_def_compiled(namespace, definition, &warnings, &CallStackList::default())
}) {
boundary_diagnostics.push(compiler_review::boundary_diagnostic(&error, &format!("{namespace}/{definition}")));
}
}
warnings.into_inner()
})
} else if let Some(rule) = review_rule.filter(|_| !validation_only) {
// Planning needs legacy migration evidence even when a later proof pass
// stops early. Read-only verification checks current semantics instead:
// compatibility compilation can change typed macro execution (#2199).
let migration_warnings = if options.workflow.is_some() {
let mut collect_warnings = || {
let warnings = RefCell::new(Vec::new());
for (namespace, definition) in &selected_definitions {
if let Err(error) = with_definition_entry_context(namespace, definition, || {
runner::preprocess::ensure_ns_def_compiled(namespace, definition, &warnings, &CallStackList::default())
}) {
// Keep declaration conflicts and compiler contradictions even when
// a later source-proof pass cannot replay the failing definition.
let owner = error.location.as_ref().map_or_else(
|| format!("{namespace}/{definition}"),
|location| format!("{}/{}", location.ns, location.def),
);
let diagnostic = compiler_review::boundary_diagnostic(&error, &owner);
if !boundary_diagnostics.contains(&diagnostic) {
boundary_diagnostics.push(diagnostic);
}
}
}
warnings.into_inner()
};
Some(if options.verify {
collect_warnings()
} else {
with_legacy_migration_mode(collect_warnings)
})
} else {
None
};
let review = compiler_review::compile_boundary_review(
&source_snapshot,
snapshot_file,
&selected_definitions,
rule,
options.workflow.is_some(),
)?;
boundary_suggestions = review.suggestions;
for diagnostic in review.diagnostics {
if !boundary_diagnostics.contains(&diagnostic) {
boundary_diagnostics.push(diagnostic);
}
}
migration_warnings.unwrap_or(review.warnings)
} else if validation_only {
compile_selected_definitions(&selected_definitions)?
} else if local_rename {
// The planner proves the renamed definition itself; the original may not
// preprocess when its old name is now read as a builtin (#2049).
vec![]
} else if migration_rule || legacy_comment_nil {
compile_selected_definitions_for_migration(&selected_definitions)?
} else {
compile_selected_definitions(&selected_definitions)?
};
let mut semantic_warning_identities = if semantic_rename {
Some(semantic_rename_warning_identities(
&warnings,
options.ns.as_deref().expect("semantic rename requires namespace"),
options.definition.as_deref().expect("semantic rename requires definition"),
options.replacement_name.as_deref().expect("semantic rename requires replacement"),
))
} else if value_to_zero_arg_fn || schema_synthesis || local_rename {
Some(warning_identities(&warnings))
} else {
None
};
let mut suggestions = boundary_suggestions;
if selected_rules.contains(&SPREAD_CALL_PROOF_RULE) {
suggestions.extend(spread_call::plan_spread_call_fixes(
&source_snapshot,
snapshot_file,
&selected_definitions,
)?);
}
if semantic_rename {
suggestions.extend(plan_definition_rename(
options,
&source_snapshot,
snapshot_file,
&project_definitions,
)?);
} else if local_rename {
let namespace = options.ns.as_deref().expect("local rename requires namespace");
let definition = options.definition.as_deref().expect("local rename requires definition");
let at = super::common::parse_path(options.at.as_deref().expect("local rename requires --at"))?;
let file = source_snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Local rename namespace `{namespace}` is not an editable project namespace."))?;
let imports = program::extract_import_map(&file.ns.code, namespace)?;
let mut is_macro = local_rename::macro_head_cache(|head: &str| {
if !super::edit::definition_head_is_macro(snapshot_file, &source_snapshot, namespace, head)? {
return Ok(local_rename::MacroHead::Plain);
}
// Unqualified heads that are neither local definitions nor imports resolve to core.
let core = !head.contains('/') && !file.defs.contains_key(head) && !imports.contains_key(head);
Ok(if core {
local_rename::MacroHead::Core
} else {
local_rename::MacroHead::Other
})
});
let plan = local_rename::plan_local_rename(
namespace,
definition,
&at,
options.replacement_name.as_deref().expect("local rename requires --to"),
&source_snapshot,
snapshot_file,
&mut is_macro,
)?;
// Staged validation recompiles the renamed definition and must reproduce these warnings.
if !validation_only {
semantic_warning_identities = Some(warning_identities(&plan.warnings));
}
suggestions.extend(plan.suggestions);
} else if value_to_zero_arg_fn {
suggestions.extend(plan_value_to_zero_arg_fn(
options,
&source_snapshot,
snapshot_file,
&selected_definitions,
)?);
} else if schema_synthesis {
suggestions.extend(plan_schema_synthesis(
options,
&source_snapshot,
snapshot_file,
&project_definitions,
)?);
} else if selected_rules.contains(&REMOVED_DATA_API_RULE) {
suggestions.extend(plan_removed_data_api_fixes(options, &source_snapshot, snapshot_file, &warnings)?);
}
if selected_rules.contains(&CORE_OPTION_METHOD_RULE) {
suggestions.extend(plan_core_nominal_method_fixes(
&source_snapshot,
snapshot_file,
&selected_definitions,
CoreNominalMethodKind::Option,
)?);
}
if selected_rules.contains(&CORE_RESULT_METHOD_RULE) {
suggestions.extend(plan_core_nominal_method_fixes(
&source_snapshot,
snapshot_file,
&selected_definitions,
CoreNominalMethodKind::Result,
)?);
}
if selected_rules.contains(&CORE_IDENTITY_CONVERSION_RULE) {
suggestions.extend(plan_core_identity_conversion_fixes(
&source_snapshot,
snapshot_file,
&selected_definitions,
)?);
}
if selected_rules.contains(&CORE_ABSENCE_RULE) {
suggestions.extend(absence::plan(&source_snapshot, snapshot_file, &selected_definitions)?);
}
if selected_rules.contains(&LEGACY_COMMENT_NIL_RULE) {
suggestions.extend(plan_legacy_comment_nil_fixes(
&source_snapshot,
snapshot_file,
&selected_definitions,
)?);
}
if effect_features && !validation_only {
let summaries = runner::preprocess::take_effect_summaries();
suggestions.extend(effect_features::plan(options, &source_snapshot, snapshot_file, &summaries)?);
}
if selected_rules.contains(&REDUNDANT_HINT_FN_RULE) {
suggestions.extend(plan_redundant_hint_fn_fixes(
&source_snapshot,
snapshot_file,
&selected_definitions,
)?);
}
let mut constructor_kinds = Vec::new();
if selected_rules.contains(&NAMED_ENUM_CONSTRUCTOR_RULE) {
constructor_kinds.push(NominalKind::Enum);
}
if selected_rules.contains(&NAMED_STRUCT_CONSTRUCTOR_RULE) {
constructor_kinds.push(NominalKind::Struct);
}
if options.include_attached {
suggestions.extend(plan_attached_fixes(
&source_snapshot,
snapshot_file,
&selected_definitions,
&selected_rules,
)?);
}
let compose_redundant_do = selected_rules.contains(&REDUNDANT_DO_RULE);
let compose_single_expression_do = selected_rules.contains(&SINGLE_EXPRESSION_DO_RULE);
let mut constructor_regions = Vec::new();
if !constructor_kinds.is_empty() {
let constructor_suggestions = plan_named_constructor_fixes(
&source_snapshot,
snapshot_file,
&selected_definitions,
&constructor_kinds,
compose_redundant_do,
compose_single_expression_do,
)?;
constructor_regions.extend(
constructor_suggestions
.iter()
.map(|suggestion| (suggestion.definition.clone(), suggestion.target_path.clone())),
);
suggestions.extend(constructor_suggestions);
}
let redundant_do_suggestions = if compose_redundant_do {
plan_redundant_do_fixes(&source_snapshot, snapshot_file, &selected_definitions, &constructor_regions)?
} else {
vec![]
};
let redundant_do_regions = redundant_do_suggestions
.iter()
.map(|suggestion| (suggestion.definition.clone(), suggestion.target_path.clone()))
.collect::<Vec<_>>();
if compose_single_expression_do {
suggestions.extend(plan_single_expression_do_fixes(
&source_snapshot,
snapshot_file,
&selected_definitions,
&constructor_regions,
&redundant_do_regions,
)?);
}
suggestions.extend(redundant_do_suggestions);
if compose_single_expression_do {
suggestions.sort_by(|left, right| {
left
.definition
.cmp(&right.definition)
.then_with(|| right.target_path.cmp(&left.target_path))
.then_with(|| left.rule_id.cmp(right.rule_id))
});
}
let operations = suggestions.iter().flat_map(suggestion_operations).collect::<Vec<_>>();
if validation_only {
if suggestions.iter().any(|suggestion| suggestion.operation.is_some()) {
return Err("Staged fix validation found an applicable migration that was not removed.".to_owned());
}
let unexpected = if semantic_refactor || schema_synthesis {
println!(
"{}",
serde_json::to_string(semantic_warning_identities.as_deref().unwrap_or_default())
.map_err(|error| format!("Failed to encode staged semantic-rename warnings: {error}"))?
);
vec![]
} else if options.workflow.is_some() {
vec![]
} else {
warnings
.iter()
.filter(|warning| warning.code() != Some(REMOVED_DATA_API_DIAGNOSTIC))
// Helper calls left for review keep their own warning; they are what
// `core-option-method-v1` reports, not an effect of the staged fix.
.filter(|warning| warning.code() != Some("E_OPTION_HELPER_CALL"))
// Ambiguous `;nil` / untouched `%::` forms left for manual or follow-up
// rules emit `E_REMOVED_CORE_FUNCTION` once removed in 0.48.0; allow
// staged migration rules/presets to validate without blaming those sites.
.filter(|warning| {
!(warning.code() == Some("E_REMOVED_CORE_FUNCTION")
&& (warning.to_string().contains("unknown `;nil`") || warning.to_string().contains("unknown `%::`")))
})
.map(ToString::to_string)
.collect::<Vec<_>>()
};
if !unexpected.is_empty() {
return Err(format!(
"Staged fix validation produced unrelated compiler warnings:\n{}",
unexpected.join("\n")
));
}
return Ok(());
}
if options.apply && !operations.is_empty() {
guard_git_worktree(snapshot_file, options.allow_dirty, options.allow_no_vcs)?;
}
let dry_run = !options.apply;
let validation_args = fix_scope_args(options);
let transaction = run_staged_fix_transaction(
Path::new(snapshot_file),
&operations,
Some(&revision),
dry_run,
compiled_snapshot.active_entry_name(),
&validation_args,
semantic_warning_identities.as_deref(),
)?;
let mode = if options.verify {
"verify"
} else if options.apply {
"apply"
} else {
"preview"
};
// Source-proof review is independent of later child-report transport errors.
let compiler_review_required = !boundary_diagnostics.is_empty();
let mut workflow_failed = false;
let workflow = if options.workflow.as_deref() == Some("strict") {
let mut commands = strict_workflow_commands(snapshot_file, &source_snapshot);
if options.summary_only {
for (scope, args) in &mut commands {
if scope.starts_with("entry:") {
args.push("--summary-only".to_owned());
}
}
}
let mut active_entries = source_snapshot.entries.keys().cloned().collect::<Vec<_>>();
active_entries.sort();
let preflight = crate::verification::collect_preflight(&source_snapshot, snapshot_file, &revision, &active_entries)?;
let results = if options.verify {
run_strict_workflow_verification(&commands)?
} else {
Vec::new()
};
for result in &results {
if let Some(diagnostics) = result.report["diagnostics"].as_array() {
for diagnostic in diagnostics.iter().filter(|diagnostic| diagnostic["code"] == "E_WORKFLOW_OUTPUT") {
boundary_diagnostics.push(diagnostic.clone());
}
}
}
workflow_failed = options.verify
&& (!boundary_diagnostics.is_empty()
|| !operations.is_empty()
|| preflight.is_failed()
|| results.iter().any(|result| result.status != "passed"));
if options.summary_only {
let fixes: Vec<_> = suggestions
.iter()
.filter(|s| s.operation.is_some())
.map(|s| {
serde_json::json!({
"rule_id": s.rule_id, "definition": s.definition, "path": s.path
})
})
.collect();
let scopes: Vec<_> = results.iter().map(strict_verification_summary).collect();
let macro_diagnostics = summarize_macro_diagnostics(crate::injection::take_captured_macro_diagnostics());
let summary = serde_json::json!({
"schema_version": 1, "command": "fix", "revision": revision,
"data": {"workflow": {"status": if workflow_failed { "failed" } else { "passed" },
"preflight": preflight.summary(), "verification": {"results": scopes}, "pending_fixes": fixes,
"macro_diagnostics": macro_diagnostics}},
"diagnostics": boundary_diagnostics
});
match StructuredOutputFormat::parse(&options.format, "fix")? {
StructuredOutputFormat::Json => println!("{summary}"),
StructuredOutputFormat::Edn => println!("{}", format_json_value_as_edn(&summary)?),
StructuredOutputFormat::Human => println!("## Strict verification\n\n```cirru\n{}\n```", format_json_value_as_edn(&summary)?),
}
return strict_verification_exit(workflow_failed);
}
let type_evidence = strict_workflow_type_findings(&source_snapshot)?;
let resume_revision = if options.apply {
transaction.new_revision.clone()
} else {
transaction.original_revision.clone()
};
Some(StrictWorkflowManifest {
workflow: "strict-v1",
mode,
status: if workflow_failed {
"failed"
} else if !boundary_diagnostics.is_empty() {
"requires-review"
} else if options.verify {
"passed"
} else if options.apply {
"applied"
} else {
"planned"
},
entries: strict_workflow_entries(&source_snapshot),
safe_fixes: StrictWorkflowSafeFixes {
preset: SURFACE_LATEST_V2_PRESET,
suggestions: operations.len(),
status: if operations.is_empty() {
"clear"
} else if options.apply {
"applied"
} else {
"pending"
},
},
review_required: StrictWorkflowReviewRequired {
source_fixes: suggestions
.iter()
.filter(|suggestion| suggestion.operation.is_none())
.map(|suggestion| StrictWorkflowSourceReview {
rule_id: suggestion.rule_id,
definition: suggestion.definition.clone(),
path: suggestion.path.clone(),
message: suggestion.message.clone(),
})
.collect(),
type_findings: type_evidence.review_required,
ffi_boundaries: type_evidence.ffi_boundaries,
schema_candidates: type_evidence.schema_candidates,
structural_candidates: type_evidence.structural_candidates,
},
retained_type_boundaries: type_evidence.retained_boundaries,
preflight,
verification: StrictWorkflowVerification {
commands: commands
.iter()
.map(|(_, arguments)| std::iter::once("calcit".to_owned()).chain(arguments.iter().cloned()).collect())
.collect(),
results,
external_commands: Vec::new(),
},
resume: StrictWorkflowResume {
revision: resume_revision.clone(),
apply_command: vec![
"calcit".to_owned(),
snapshot_file.to_owned(),
"fix".to_owned(),
"--workflow".to_owned(),
"strict".to_owned(),
"--apply".to_owned(),
"--expect-revision".to_owned(),
resume_revision,
"--format".to_owned(),
"edn".to_owned(),
],
},
})
} else {
None
};
let expanded_rules = selected_rules.iter().copied().map(fix_rule_metadata).collect();
let report = FixReport {
schema_version: 1,
command: "fix",
revision: &transaction.original_revision,
data: FixReportData {
mode,
filters: FixFilters {
namespace: options.ns.as_deref(),
definition: options.definition.as_deref(),
replacement_name: options.replacement_name.as_deref(),
rule_id: options
.rule
.as_deref()
.unwrap_or_else(|| if options.workflow.is_some() { "workflow:strict" } else { "all" }),
preset_id: options.preset.as_deref(),
expanded_rule_ids: selected_rules,
expanded_rules,
source_coverage: (options.include_attached
|| options.workflow.is_some()
|| matches!(options.preset.as_deref(), Some(CORE_API_028_V1_PRESET | CORE_API_029_V1_PRESET))
|| matches!(
options.rule.as_deref(),
Some(
SPREAD_CALL_PROOF_RULE
| CORE_ABSENCE_RULE
| UNSAFE_COERCE_BOUNDARY_RULE
| ASSERT_TYPE_PROOF_RULE
| CONCRETE_RETURN_PROOF_RULE
| CALLABLE_CONTRACT_PROOF_RULE
| NOMINAL_WRITE_PROOF_RULE
)
))
.then_some(FixSourceCoverage {
scanned_regions: if options.include_attached {
&["code", "tests", "examples"]
} else {
&["code"]
},
manual_review_regions: if options.include_attached { &[] } else { &["tests", "examples"] },
}),
},
changed: transaction.changed,
new_revision: &transaction.new_revision,
validation: FixValidation {
status: if compiler_review_required {
"requires-review"
} else if operations.is_empty() {
"not-needed"
} else {
"passed"
},
staged_scope_preprocess: !operations.is_empty(),
checked_operations: operations.len(),
},
suggestions: &suggestions,
workflow,
},
diagnostics: boundary_diagnostics,
next: vec![],
};
emit_fix_report(&report, &options.format)?;
if workflow_failed {
strict_verification_exit(true)
} else if !report.diagnostics.is_empty() {
Err(if options.apply && transaction.changed {
"Compiler proof review required; only the reported safe migrations were applied. Review the remaining input evidence or lexical boundary; no proof repair, cast or FFI permission was inserted."
} else {
"Compiler proof review required; the source is unchanged. Review the reported input evidence or lexical boundary without automatically adding casts or granting FFI permission."
}.to_owned())
} else {
Ok(())
}
}
fn emit_fix_report(report: &FixReport<'_>, format: &str) -> Result<(), String> {
match StructuredOutputFormat::parse(format, "fix")? {
StructuredOutputFormat::Json => println!(
"{}",
serde_json::to_string(report).map_err(|error| format!("Failed to serialize fix result: {error}"))?
),
StructuredOutputFormat::Edn => {
let value = serde_json::to_value(report).map_err(|error| format!("Failed to encode fix result: {error}"))?;
println!("{}", format_json_value_as_edn(&value)?);
}
StructuredOutputFormat::Human => print_human_report(report),
}
Ok(())
}
struct FixTargetScope(Option<calcit_core::snapshot::SnapshotTarget>);
impl FixTargetScope {
fn new(whole_project: bool) -> Option<Self> {
if whole_project {
let previous = program::active_entry_target();
program::configure_entry_target(None);
Some(Self(previous))
} else {
None
}
}
}
impl Drop for FixTargetScope {
fn drop(&mut self) {
program::configure_entry_target(self.0);
}
}
thread_local! {
static ENTRY_TYPE_SLOT_PLAN: RefCell<Option<EntryTypeSlotPlan>> = const { RefCell::new(None) };
}
/// Whole-project analysis spans every entry, so each definition is checked with
/// the type-slot bindings of the entry that reaches it instead of the outer
/// `--entry` (#2452). Owners follow the default entry first, then entry names.
struct EntryTypeSlotPlan {
bindings: Vec<std::collections::HashMap<String, String>>,
owners: std::collections::HashMap<(String, String), usize>,
current: Option<usize>,
}
struct EntryTypeSlotScope(std::collections::HashMap<Arc<str>, Arc<CalcitTypeAnnotation>>);
impl EntryTypeSlotScope {
/// Install a per-definition plan for a whole-project run with several entries.
fn new(whole_project: bool, snapshot: &Snapshot, project_namespaces: &HashSet<String>) -> Result<Option<Self>, String> {
if !whole_project || snapshot.entries.len() < 2 {
return Ok(None);
}
let mut names = snapshot.entries.keys().cloned().collect::<Vec<_>>();
names.sort_by_key(|name| (name != calcit_core::snapshot::DEFAULT_ENTRY_NAME, name.clone()));
let mut bindings = Vec::with_capacity(names.len());
let mut owners = std::collections::HashMap::new();
let mut reachable_entries: std::collections::HashMap<(String, String), HashSet<usize>> = std::collections::HashMap::new();
for (index, name) in names.iter().enumerate() {
let entry = &snapshot.entries[name];
for (slot, type_path) in &entry.type_slots {
if let Some((ns, def)) = type_path.rsplit_once('/')
&& !snapshot.files.get(ns).is_some_and(|file| file.defs.contains_key(def))
{
return Err(format!(
"entries.{name}.type-slots.{slot}: unknown type definition `{type_path}`; load its module and use a full `namespace/definition` path"
));
}
}
let mut roots = Vec::new();
for root in [&entry.init_fn, &entry.reload_fn] {
if let Some((ns, def)) = root.rsplit_once('/') {
roots.push((ns.to_owned(), def.to_owned()));
}
}
for definition in crate::call_tree::reachable_definitions(&roots) {
owners.entry(definition.clone()).or_insert(index);
reachable_entries.entry(definition).or_default().insert(index);
}
bindings.push(entry.type_slots.clone());
}
// A project definition may be absent from every entry's call tree while
// depending on entry-specific code (for example a nominal type alias).
// Use a context only when all reachable entry-owned dependencies have one
// common entry. Shared dependencies must not force an arbitrary owner;
// conflicting or ambiguous evidence keeps the existing default context.
for ns in project_namespaces {
let Some(file) = snapshot.files.get(ns) else { continue };
for def in file.defs.keys() {
let root = (ns.to_owned(), def.to_owned());
if owners.contains_key(&root) {
continue;
}
let mut candidates: Option<HashSet<usize>> = None;
for dependency in crate::call_tree::reachable_definitions(std::slice::from_ref(&root)) {
if let Some(entries) = reachable_entries.get(&dependency) {
match &mut candidates {
Some(current) => current.retain(|index| entries.contains(index)),
None => candidates = Some(entries.clone()),
}
}
}
if let Some(entries) = candidates
&& entries.len() == 1
&& let Some(owner) = entries.into_iter().next()
{
owners.insert(root, owner);
}
}
}
let scope = Self(calcit_core::calcit::entry_type_slots());
// Reject malformed bindings before any definition depends on them.
for (name, slots) in names.iter().zip(&bindings) {
calcit_core::calcit::configure_entry_type_slots(slots).map_err(|message| format!("entries.{name}.type-slots: {message}"))?;
}
calcit_core::calcit::install_entry_type_slots(scope.0.clone());
ENTRY_TYPE_SLOT_PLAN.with(|plan| {
*plan.borrow_mut() = Some(EntryTypeSlotPlan {
bindings,
owners,
current: None,
})
});
Ok(Some(scope))
}
}
impl Drop for EntryTypeSlotScope {
fn drop(&mut self) {
ENTRY_TYPE_SLOT_PLAN.with(|plan| plan.borrow_mut().take());
calcit_core::calcit::install_entry_type_slots(std::mem::take(&mut self.0));
}
}
/// Rank used to analyze definitions entry by entry, so a shared dependency is
/// first compiled under the earliest entry that reaches it.
fn definition_entry_rank(namespace: &str, definition: &str) -> usize {
ENTRY_TYPE_SLOT_PLAN.with(|plan| {
plan
.borrow()
.as_ref()
.and_then(|plan| plan.owners.get(&(namespace.to_owned(), definition.to_owned())).copied())
.unwrap_or(0)
})
}
/// Run a whole-project collector once per entry context and keep each row
/// from the context of its owning entry. Rows keep the collector's order.
fn collect_rows_by_definition_entry<T>(
mut collect: impl FnMut() -> Result<Vec<T>, String>,
definition_of: impl Fn(&T) -> (&str, &str),
) -> Result<Vec<T>, String> {
let entry_count = ENTRY_TYPE_SLOT_PLAN.with(|plan| plan.borrow().as_ref().map(|plan| plan.bindings.len()));
let Some(entry_count) = entry_count else {
return collect();
};
let mut ranked = Vec::new();
for owner in 0..entry_count {
ENTRY_TYPE_SLOT_PLAN.with(|plan| {
let mut plan = plan.borrow_mut();
let plan = plan.as_mut().expect("entry plan stays installed while collecting");
if plan.current != Some(owner) {
calcit_core::calcit::configure_entry_type_slots(&plan.bindings[owner]).expect("entry type slots were validated");
plan.current = Some(owner);
}
});
for (position, row) in collect()?.into_iter().enumerate() {
let (namespace, definition) = definition_of(&row);
if definition_entry_rank(namespace, definition) == owner {
ranked.push((position, row));
}
}
}
ranked.sort_by_key(|(position, _)| *position);
Ok(ranked.into_iter().map(|(_, row)| row).collect())
}
/// Install the type slots of the entry owning `namespace/definition`.
/// Definitions that no entry reaches use the default entry. No-op outside a
/// whole-project plan. Slots stay installed until another definition switches
/// them, so planners call this at the top of each per-definition step.
pub(super) fn select_definition_entry_context(namespace: &str, definition: &str) {
ENTRY_TYPE_SLOT_PLAN.with(|plan| {
let mut plan = plan.borrow_mut();
if let Some(plan) = plan.as_mut() {
let owner = plan
.owners
.get(&(namespace.to_owned(), definition.to_owned()))
.copied()
.unwrap_or(0);
if plan.current != Some(owner) {
calcit_core::calcit::configure_entry_type_slots(&plan.bindings[owner]).expect("entry type slots were validated");
plan.current = Some(owner);
}
}
});
}
/// Run `f` with the type slots of the entry owning `namespace/definition`.
pub(super) fn with_definition_entry_context<T>(namespace: &str, definition: &str, f: impl FnOnce() -> T) -> T {
select_definition_entry_context(namespace, definition);
f()
}
/// Recreate the exact selection arguments for staged post-fix validation.
fn fix_scope_args(options: &FixCommand) -> Vec<String> {
let mut args = Vec::new();
if options.include_attached {
args.push("--include-attached".to_owned());
}
if let Some(namespace) = &options.ns {
args.push("--ns".to_owned());
args.push(namespace.clone());
}
if let Some(definition) = &options.definition {
args.push("--def".to_owned());
args.push(definition.clone());
}
if let Some(rule) = &options.rule {
args.push("--rule".to_owned());
args.push(rule.clone());
}
if let Some(preset) = &options.preset {
args.push("--preset".to_owned());
args.push(preset.clone());
}
if let Some(workflow) = &options.workflow {
args.push("--workflow".to_owned());
args.push(workflow.clone());
}
if let Some(replacement) = &options.replacement_name {
args.push("--to".to_owned());
args.push(replacement.clone());
}
if let Some(at) = &options.at {
args.push("--at".to_owned());
args.push(at.clone());
}
args
}
/// Reject ambiguous modes, incomplete scopes, and unknown stable rule IDs.
fn validate_options(options: &FixCommand) -> Result<(), String> {
StructuredOutputFormat::parse(&options.format, "fix")?;
// Rule names answer first so flags such as `--include-attached` cannot hide unknown or retired-rule guidance.
if options.rule.as_deref() == Some(OPTIONAL_PARAMETERS_RULE) {
return Err(format!(
"Fix rule `{OPTIONAL_PARAMETERS_RULE}` was retired in 0.48.0 together with legacy `?` optional parameters. Run it with a 0.47.x Calcit CLI before upgrading, or migrate `?` parameters to trailing `Option<T>` omission; see docs/run/upgrade.md."
));
}
if let Some(rule) = options.rule.as_deref()
&& !matches!(
rule,
REMOVED_DATA_API_RULE
| REDUNDANT_DO_RULE
| SINGLE_EXPRESSION_DO_RULE
| NAMED_ENUM_CONSTRUCTOR_RULE
| NAMED_STRUCT_CONSTRUCTOR_RULE
| CORE_OPTION_METHOD_RULE
| CORE_RESULT_METHOD_RULE
| CORE_IDENTITY_CONVERSION_RULE
| RENAME_DEFINITION_RULE
| RENAME_LOCAL_RULE
| VALUE_TO_ZERO_ARG_FN_RULE
| SYNTHESIZE_SCHEMA_RULE
| SPREAD_CALL_PROOF_RULE
| UNSAFE_COERCE_BOUNDARY_RULE
| ASSERT_TYPE_PROOF_RULE
| CONCRETE_RETURN_PROOF_RULE
| CALLABLE_CONTRACT_PROOF_RULE
| NOMINAL_WRITE_PROOF_RULE
| CORE_ABSENCE_RULE
| LEGACY_COMMENT_NIL_RULE
| REDUNDANT_HINT_FN_RULE
| EFFECT_FEATURES_RULE
)
{
return Err(
format!(
"Unknown fix rule `{rule}`. Available rules: `{REMOVED_DATA_API_RULE}`, `{REDUNDANT_DO_RULE}`, `{SINGLE_EXPRESSION_DO_RULE}`, `{NAMED_ENUM_CONSTRUCTOR_RULE}`, `{NAMED_STRUCT_CONSTRUCTOR_RULE}`, `{CORE_OPTION_METHOD_RULE}`, `{CORE_RESULT_METHOD_RULE}`, `{CORE_IDENTITY_CONVERSION_RULE}`, `{RENAME_DEFINITION_RULE}`, `{RENAME_LOCAL_RULE}`, `{VALUE_TO_ZERO_ARG_FN_RULE}`, `{SYNTHESIZE_SCHEMA_RULE}`, `{SPREAD_CALL_PROOF_RULE}`, `{CORE_ABSENCE_RULE}`, `{LEGACY_COMMENT_NIL_RULE}`, `{REDUNDANT_HINT_FN_RULE}`, `{EFFECT_FEATURES_RULE}`. Rules retired in earlier releases are listed with their last shipping CLI in docs/run/upgrade.md and docs/run/upgrade-history.md."
) + &format!(
" Review-only compiler rules: `{UNSAFE_COERCE_BOUNDARY_RULE}`, `{ASSERT_TYPE_PROOF_RULE}`, `{CONCRETE_RETURN_PROOF_RULE}`, `{CALLABLE_CONTRACT_PROOF_RULE}`, `{NOMINAL_WRITE_PROOF_RULE}`."
),
);
}
if options.include_attached {
let selected = selected_rule_ids(options);
let unsupported = selected
.iter()
.copied()
.filter(|rule| !supports_attached_migrations(rule))
.collect::<Vec<_>>();
if selected.is_empty() || !unsupported.is_empty() {
return Err(format!(
"`--include-attached` requires a fully supported explicit rule or preset; attached coverage is not implemented for: {}.",
if unsupported.is_empty() {
"the selected rule".to_owned()
} else {
unsupported.join(", ")
}
));
}
}
if let Some(workflow) = options.workflow.as_deref()
&& workflow != "strict"
{
return Err(format!("Unknown fix workflow `{workflow}`. Available workflows: `strict`."));
}
if options.workflow.is_none() && options.verify {
return Err("`calcit fix --verify` requires `--workflow strict`.".to_owned());
}
if options.workflow.is_some() && options.apply && options.expect_revision.is_none() {
return Err("`calcit fix --workflow strict --apply` requires `--expect-revision` from a reviewed workflow plan.".to_owned());
}
if options.workflow.is_some()
&& (options.ns.is_some()
|| options.definition.is_some()
|| options.rule.is_some()
|| options.preset.is_some()
|| options.replacement_name.is_some())
{
return Err(
"`calcit fix --workflow strict` is project-scoped and conflicts with --ns, --def, --rule, --preset, and --to.".to_owned(),
);
}
if options.verify && (options.apply || options.dry_run || options.allow_dirty || options.allow_no_vcs) {
return Err(
"`calcit fix --workflow strict --verify` is read-only and conflicts with --apply, --dry-run, --allow-dirty, and --allow-no-vcs."
.to_owned(),
);
}
if options.apply && options.dry_run {
return Err("`calcit fix --apply` conflicts with `--dry-run`; omit both flags to preview.".to_owned());
}
if options.definition.is_some() && options.ns.is_none() {
return Err("`calcit fix --def` requires an exact `--ns` scope.".to_owned());
}
if options.rule.is_some() && options.preset.is_some() {
return Err("`calcit fix --rule` conflicts with `--preset`; choose one explicit migration selection.".to_owned());
}
let semantic_rename = options.rule.as_deref() == Some(RENAME_DEFINITION_RULE);
let local_rename = options.rule.as_deref() == Some(RENAME_LOCAL_RULE);
if local_rename {
if options.ns.is_none() || options.definition.is_none() || options.at.is_none() || options.replacement_name.is_none() {
return Err(format!(
"Fix rule `{RENAME_LOCAL_RULE}` requires exact `--ns`, `--def`, `--at <binding path>`, and `--to` arguments."
));
}
super::common::parse_path(options.at.as_deref().expect("checked --at"))?;
} else if options.at.is_some() {
return Err(format!("`calcit fix --at` is only valid with `--rule {RENAME_LOCAL_RULE}`."));
}
let value_to_zero_arg_fn = options.rule.as_deref() == Some(VALUE_TO_ZERO_ARG_FN_RULE);
let schema_synthesis = options.rule.as_deref() == Some(SYNTHESIZE_SCHEMA_RULE);
if semantic_rename {
if options.ns.is_none() || options.definition.is_none() || options.replacement_name.is_none() {
return Err(format!(
"Fix rule `{RENAME_DEFINITION_RULE}` requires exact `--ns`, `--def`, and `--to` arguments."
));
}
let replacement = options.replacement_name.as_deref().expect("checked replacement name");
if replacement.is_empty() || replacement.contains('/') {
return Err("`calcit fix --to` must be one non-empty unqualified definition name.".to_owned());
}
} else if value_to_zero_arg_fn || schema_synthesis {
if options.ns.is_none() || options.definition.is_none() {
return Err(format!(
"Fix rule `{}` requires exact `--ns` and `--def` arguments.",
options.rule.as_deref().expect("checked exact schema/refactor rule")
));
}
if options.replacement_name.is_some() {
return Err(format!(
"Fix rule `{}` does not accept `--to`.",
options.rule.as_deref().expect("checked exact schema/refactor rule")
));
}
} else if options.replacement_name.is_some() && !local_rename {
return Err(format!(
"`calcit fix --to` is only valid with `--rule {RENAME_DEFINITION_RULE}` or `--rule {RENAME_LOCAL_RULE}`."
));
}
if let Some(preset) = options.preset.as_deref()
&& !matches!(
preset,
SURFACE_LATEST_V1_PRESET | SURFACE_LATEST_V2_PRESET | CORE_API_028_V1_PRESET | CORE_API_029_V1_PRESET
)
{
return Err(format!(
"Unknown fix preset `{preset}`. Available presets: `{SURFACE_LATEST_V1_PRESET}`, `{SURFACE_LATEST_V2_PRESET}`, `{CORE_API_028_V1_PRESET}`, `{CORE_API_029_V1_PRESET}`."
));
}
Ok(())
}
/// Expand one explicit rule or versioned preset into a deterministic rule sequence.
fn selected_rule_ids(options: &FixCommand) -> Vec<&'static str> {
if options.workflow.as_deref() == Some("strict") {
return SURFACE_LATEST_V2_RULES
.iter()
.copied()
.chain([
SPREAD_CALL_PROOF_RULE,
UNSAFE_COERCE_BOUNDARY_RULE,
ASSERT_TYPE_PROOF_RULE,
CONCRETE_RETURN_PROOF_RULE,
CALLABLE_CONTRACT_PROOF_RULE,
NOMINAL_WRITE_PROOF_RULE,
])
.collect();
}
if let Some(rule) = options.rule.as_deref() {
if matches!(
rule,
RENAME_DEFINITION_RULE
| RENAME_LOCAL_RULE
| VALUE_TO_ZERO_ARG_FN_RULE
| SYNTHESIZE_SCHEMA_RULE
| SPREAD_CALL_PROOF_RULE
| UNSAFE_COERCE_BOUNDARY_RULE
| ASSERT_TYPE_PROOF_RULE
| CONCRETE_RETURN_PROOF_RULE
| CALLABLE_CONTRACT_PROOF_RULE
| NOMINAL_WRITE_PROOF_RULE
| CORE_OPTION_METHOD_RULE
| CORE_RESULT_METHOD_RULE
| CORE_IDENTITY_CONVERSION_RULE
| CORE_ABSENCE_RULE
| LEGACY_COMMENT_NIL_RULE
| REDUNDANT_HINT_FN_RULE
| EFFECT_FEATURES_RULE
) {
return vec![match rule {
RENAME_DEFINITION_RULE => RENAME_DEFINITION_RULE,
RENAME_LOCAL_RULE => RENAME_LOCAL_RULE,
VALUE_TO_ZERO_ARG_FN_RULE => VALUE_TO_ZERO_ARG_FN_RULE,
SYNTHESIZE_SCHEMA_RULE => SYNTHESIZE_SCHEMA_RULE,
SPREAD_CALL_PROOF_RULE => SPREAD_CALL_PROOF_RULE,
UNSAFE_COERCE_BOUNDARY_RULE => UNSAFE_COERCE_BOUNDARY_RULE,
ASSERT_TYPE_PROOF_RULE => ASSERT_TYPE_PROOF_RULE,
CONCRETE_RETURN_PROOF_RULE => CONCRETE_RETURN_PROOF_RULE,
CALLABLE_CONTRACT_PROOF_RULE => CALLABLE_CONTRACT_PROOF_RULE,
NOMINAL_WRITE_PROOF_RULE => NOMINAL_WRITE_PROOF_RULE,
CORE_OPTION_METHOD_RULE => CORE_OPTION_METHOD_RULE,
CORE_RESULT_METHOD_RULE => CORE_RESULT_METHOD_RULE,
CORE_IDENTITY_CONVERSION_RULE => CORE_IDENTITY_CONVERSION_RULE,
CORE_ABSENCE_RULE => CORE_ABSENCE_RULE,
LEGACY_COMMENT_NIL_RULE => LEGACY_COMMENT_NIL_RULE,
REDUNDANT_HINT_FN_RULE => REDUNDANT_HINT_FN_RULE,
_ => EFFECT_FEATURES_RULE,
}];
}
return AVAILABLE_RULES.iter().copied().filter(|candidate| *candidate == rule).collect();
}
match options.preset.as_deref() {
Some(SURFACE_LATEST_V1_PRESET) => SURFACE_LATEST_V1_RULES.to_vec(),
Some(SURFACE_LATEST_V2_PRESET) => SURFACE_LATEST_V2_RULES.to_vec(),
Some(CORE_API_028_V1_PRESET) => CORE_API_028_V1_RULES.to_vec(),
Some(CORE_API_029_V1_PRESET) => CORE_API_029_V1_RULES.to_vec(),
_ => AVAILABLE_RULES.to_vec(),
}
}
/// Describe how a current normalization rule is derived without coupling it to a source release.
fn fix_rule_metadata(rule_id: &'static str) -> FixRuleMetadata {
match rule_id {
CORE_ABSENCE_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: CORE_ABSENCE_DIAGNOSTIC,
evidence_source: "legacy-nil-consumer-and-proven-receiver-domain",
lifecycle: "migration-bridge",
source_version_required: false,
},
LEGACY_COMMENT_NIL_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: LEGACY_COMMENT_NIL_DIAGNOSTIC,
evidence_source: "resolved-source-ast-and-schema",
lifecycle: "migration-bridge",
source_version_required: false,
},
CALLABLE_CONTRACT_PROOF_RULE | NOMINAL_WRITE_PROOF_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: "E_CALL_ARGUMENT_UNPROVEN",
evidence_source: "current-diagnostic",
lifecycle: "current-semantics",
source_version_required: false,
},
CONCRETE_RETURN_PROOF_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: CONCRETE_RETURN_PROOF_DIAGNOSTIC,
evidence_source: "current-diagnostic",
lifecycle: "current-semantics",
source_version_required: false,
},
ASSERT_TYPE_PROOF_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: ASSERT_TYPE_PROOF_DIAGNOSTIC,
evidence_source: "current-diagnostic",
lifecycle: "current-semantics",
source_version_required: false,
},
UNSAFE_COERCE_BOUNDARY_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: UNSAFE_COERCE_BOUNDARY_DIAGNOSTIC,
evidence_source: "current-diagnostic",
lifecycle: "current-semantics",
source_version_required: false,
},
REMOVED_DATA_API_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: REMOVED_DATA_API_DIAGNOSTIC,
evidence_source: "current-diagnostic",
lifecycle: "current-semantics",
source_version_required: false,
},
EFFECT_FEATURES_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: EFFECT_FEATURES_DIAGNOSTIC,
evidence_source: "compiled-effect-summary",
lifecycle: "current-semantics",
source_version_required: false,
},
REDUNDANT_HINT_FN_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: REDUNDANT_HINT_FN_DIAGNOSTIC,
evidence_source: "compiled-type-inference",
lifecycle: "current-semantics",
source_version_required: false,
},
REDUNDANT_DO_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: REDUNDANT_DO_DIAGNOSTIC,
evidence_source: "resolved-source-ast",
lifecycle: "current-semantics",
source_version_required: false,
},
SINGLE_EXPRESSION_DO_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: SINGLE_EXPRESSION_DO_DIAGNOSTIC,
evidence_source: "resolved-source-ast",
lifecycle: "current-semantics",
source_version_required: false,
},
NAMED_ENUM_CONSTRUCTOR_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: NAMED_ENUM_CONSTRUCTOR_DIAGNOSTIC,
evidence_source: "resolved-source-ast",
lifecycle: "current-semantics",
source_version_required: false,
},
NAMED_STRUCT_CONSTRUCTOR_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: NAMED_STRUCT_CONSTRUCTOR_DIAGNOSTIC,
evidence_source: "resolved-source-ast",
lifecycle: "current-semantics",
source_version_required: false,
},
CORE_OPTION_METHOD_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: CORE_OPTION_METHOD_DIAGNOSTIC,
evidence_source: "compiler-resolved-reference-and-proven-receiver-method",
lifecycle: "semantic-refactor",
source_version_required: false,
},
CORE_RESULT_METHOD_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: CORE_RESULT_METHOD_DIAGNOSTIC,
evidence_source: "compiler-resolved-reference-and-proven-receiver-method",
lifecycle: "semantic-refactor",
source_version_required: false,
},
CORE_IDENTITY_CONVERSION_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: CORE_IDENTITY_CONVERSION_DIAGNOSTIC,
evidence_source: "reader-resolved-builtin-proc-and-proven-conversion-argument",
lifecycle: "semantic-refactor",
source_version_required: false,
},
RENAME_DEFINITION_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: RENAME_DEFINITION_DIAGNOSTIC,
evidence_source: "compiler-resolved-reference",
lifecycle: "semantic-refactor",
source_version_required: false,
},
RENAME_LOCAL_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: RENAME_LOCAL_DIAGNOSTIC,
evidence_source: "core-binding-scope-and-preprocessed-locals",
lifecycle: "semantic-refactor",
source_version_required: false,
},
VALUE_TO_ZERO_ARG_FN_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: VALUE_TO_ZERO_ARG_FN_DIAGNOSTIC,
evidence_source: "compiler-resolved-reference",
lifecycle: "semantic-refactor",
source_version_required: false,
},
SYNTHESIZE_SCHEMA_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: SYNTHESIZE_SCHEMA_DIAGNOSTIC,
evidence_source: "compiled-type-inference",
lifecycle: "semantic-refactor",
source_version_required: false,
},
SPREAD_CALL_PROOF_RULE => FixRuleMetadata {
rule_id,
diagnostic_code: SPREAD_CALL_PROOF_DIAGNOSTIC,
evidence_source: "compiler-fixed-call-proof",
lifecycle: "semantic-refactor",
source_version_required: false,
},
_ => unreachable!("selected fix rule must have current-semantics metadata"),
}
}
fn select_project_definitions(snapshot: &Snapshot, project_namespaces: &HashSet<String>) -> Result<Vec<(String, String)>, String> {
let mut selected = Vec::new();
for namespace in project_namespaces {
let file = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Project namespace `{namespace}` is missing from the compiled snapshot."))?;
selected.extend(file.defs.keys().map(|definition| (namespace.clone(), definition.clone())));
}
selected.sort();
if selected.is_empty() {
Err("Fix scope selected no project definitions; refusing to report an empty plan as success.".to_owned())
} else {
Ok(selected)
}
}
/// Resolve an editable, deterministic definition list from the requested project scope.
fn select_definitions(
options: &FixCommand,
snapshot: &Snapshot,
project_namespaces: &HashSet<String>,
) -> Result<Vec<(String, String)>, String> {
if let Some(namespace) = options.ns.as_deref()
&& !project_namespaces.contains(namespace)
{
return Err(format!("Fix namespace `{namespace}` is not an editable project namespace."));
}
let mut selected = Vec::new();
for namespace in project_namespaces {
if options.ns.as_deref().is_some_and(|filter| namespace != filter) {
continue;
}
let file = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Project namespace `{namespace}` is missing from the compiled snapshot."))?;
for definition in file.defs.keys() {
if options.definition.as_deref().is_none_or(|filter| definition == filter) {
selected.push((namespace.clone(), definition.clone()));
}
}
}
selected.sort();
if selected.is_empty() {
return Err("Fix scope selected no definitions; refusing to report an empty plan as success.".to_owned());
}
Ok(selected)
}
/// Preprocess selected definitions once and retain compiler evidence used by fix planners.
fn compile_selected_definitions(definitions: &[(String, String)]) -> Result<Vec<LocatedWarning>, String> {
let warnings = RefCell::new(Vec::new());
for (namespace, definition) in definitions {
with_definition_entry_context(namespace, definition, || {
runner::preprocess::ensure_ns_def_compiled(namespace, definition, &warnings, &CallStackList::default())
})
.map_err(|failure| {
let hint = if failure.msg.starts_with("unknown ns/def in program:") {
" Check each entry's declared modules with `calcit <snapshot> config modules --entry <entry>`, then add or install the missing dependency."
} else {
""
};
format!("Failed to preprocess fix target {namespace}/{definition}: {failure}{hint}")
})?;
}
Ok(warnings.into_inner())
}
/// Preprocess legacy source without strict rejection so fix planning can consume compiler warnings and type evidence.
/// The staged validation subprocess still uses strict mode after applying the planned operations.
fn with_legacy_migration_mode<T>(run: impl FnOnce() -> T) -> T {
struct StrictTypesGuard(bool);
impl Drop for StrictTypesGuard {
fn drop(&mut self) {
runner::preprocess::set_strict_types(self.0);
}
}
let guard = StrictTypesGuard(runner::preprocess::is_strict_types_enabled());
runner::preprocess::set_strict_types(false);
let result = run();
drop(guard);
result
}
fn compile_selected_definitions_for_migration(definitions: &[(String, String)]) -> Result<Vec<LocatedWarning>, String> {
with_legacy_migration_mode(|| compile_selected_definitions(definitions))
}
/// Serialize the pre-edit warning multiset for semantic-refactor validation.
fn warning_identities(warnings: &[LocatedWarning]) -> Vec<String> {
let mut identities = warnings
.iter()
.map(|warning| serde_json::to_string(&warning.as_json()).expect("warning identity must serialize"))
.collect::<Vec<_>>();
identities.sort();
identities
}
/// Build stable warning identities while treating the renamed declaration as the same source owner.
fn semantic_rename_warning_identities(warnings: &[LocatedWarning], target_ns: &str, old_name: &str, new_name: &str) -> Vec<String> {
let old_target = format!("{target_ns}/{old_name}");
let new_target = format!("{target_ns}/{new_name}");
let normalize_text = |text: &str| text.replace(&old_target, "<rename-target>").replace(&new_target, "<rename-target>");
let mut identities = warnings
.iter()
.map(|warning| {
let mut value = warning.as_json();
if let Some(message) = value.get_mut("message")
&& let Some(text) = message.as_str()
{
*message = Value::String(normalize_text(text));
}
if let Some(hint) = value.get_mut("hint")
&& let Some(text) = hint.as_str()
{
*hint = Value::String(normalize_text(text));
}
if value.pointer("/location/ns").and_then(Value::as_str) == Some(target_ns)
&& matches!(value.pointer("/location/def").and_then(Value::as_str), Some(name) if name == old_name || name == new_name)
&& let Some(definition) = value.pointer_mut("/location/def")
{
*definition = Value::String("<rename-target>".to_owned());
}
serde_json::to_string(&value).expect("warning identity must serialize")
})
.collect::<Vec<_>>();
identities.sort();
identities
}
fn plan_definition_rename(
options: &FixCommand,
snapshot: &Snapshot,
snapshot_file: &str,
project_definitions: &[(String, String)],
) -> Result<Vec<FixSuggestion>, String> {
let target_ns = options.ns.as_deref().expect("semantic rename requires namespace");
let old_name = options.definition.as_deref().expect("semantic rename requires definition");
let new_name = options.replacement_name.as_deref().expect("semantic rename requires replacement");
let target_file = snapshot
.files
.get(target_ns)
.ok_or_else(|| format!("Semantic rename namespace `{target_ns}` is not an editable project namespace."))?;
if !target_file.defs.contains_key(old_name) {
if target_file.defs.contains_key(new_name) {
if std::env::var("CALCIT_FIX_VALIDATE_ONLY").as_deref() == Ok("1") {
validate_no_stale_attached_references(snapshot, project_definitions, target_ns, old_name, new_name)?;
}
return Ok(vec![]);
}
return Err(format!("Semantic rename source `{target_ns}/{old_name}` does not exist."));
}
if target_file.defs.contains_key(new_name) {
return Err(format!("Semantic rename destination `{target_ns}/{new_name}` already exists."));
}
let warnings = RefCell::new(Vec::new());
let mut resolved = BTreeMap::<(String, String, Vec<usize>), (String, Vec<String>)>::new();
let mut attached_suggestions = Vec::new();
let mut blockers = Vec::new();
for (owner_ns, owner_def) in project_definitions {
let entry = snapshot
.files
.get(owner_ns)
.and_then(|file| file.defs.get(owner_def))
.ok_or_else(|| format!("Project definition `{owner_ns}/{owner_def}` is missing from the source snapshot."))?;
if list_head(&entry.code) == Some("defmacro") && cirru_contains_target_reference(&entry.code, owner_ns, target_ns, old_name) {
blockers.push(format!(
"{owner_ns}/{owner_def}: macro source may produce `{target_ns}/{old_name}` and cannot be rewritten from expanded output"
));
}
if quoted_region_contains_target_reference(&entry.code, owner_ns, target_ns, old_name) {
blockers.push(format!(
"{owner_ns}/{owner_def}: quoted source contains `{target_ns}/{old_name}` and may be consumed dynamically"
));
}
for (index, test) in entry.tests.iter().enumerate() {
if !cirru_contains_target_reference(&test.code, owner_ns, target_ns, old_name) {
continue;
}
let source_label = format!("{owner_ns}/{owner_def}#{}", test.name);
match plan_attached_source_rewrite(
&test.code,
owner_ns,
&format!("&calcit:rename-test:{owner_def}:{index}"),
&source_label,
target_ns,
old_name,
new_name,
) {
Ok(Some(rewrite)) => {
let mut tag_names = test.tags.iter().map(|tag| tag.ref_str()).collect::<Vec<_>>();
tag_names.sort_unstable();
attached_suggestions.push(FixSuggestion {
rule_id: RENAME_DEFINITION_RULE,
diagnostic_code: RENAME_DEFINITION_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{owner_ns}/{owner_def}"),
path: format!("tests.{}", test.name),
fingerprint: node_fingerprint(&test.code),
origin_chain: rewrite.origin_chain,
original: quoted_json(&test.code),
replacement: Some(quoted_json(&rewrite.code)),
applicability: "machine-applicable",
message: format!("Rewrite compiler-resolved references in definition-attached test `{}`.", test.name),
target_path: vec![],
operation: Some(FixOperation::ReplaceTest {
name: test.name.clone(),
tags: tag_names.join(","),
code: format_quoted_nodes(std::slice::from_ref(&rewrite.code))?,
}),
});
}
Ok(None) => {}
Err(error) => blockers.push(error),
}
}
let mut rewritten_examples = entry.examples.clone();
let mut example_origins = Vec::new();
let mut changed_examples = Vec::new();
for (index, example) in entry.examples.iter().enumerate() {
if !cirru_contains_target_reference(example, owner_ns, target_ns, old_name) {
continue;
}
let source_label = format!("{owner_ns}/{owner_def} example {index}");
match plan_attached_source_rewrite(
example,
owner_ns,
&format!("&calcit:rename-example:{owner_def}:{index}"),
&source_label,
target_ns,
old_name,
new_name,
) {
Ok(Some(rewrite)) => {
rewritten_examples[index] = rewrite.code;
example_origins.extend(rewrite.origin_chain);
changed_examples.push(index);
}
Ok(None) => {}
Err(error) => blockers.push(error),
}
}
if !changed_examples.is_empty() {
let original_examples = Cirru::List(entry.examples.clone());
let replacement_examples = Cirru::List(rewritten_examples.clone());
attached_suggestions.push(FixSuggestion {
rule_id: RENAME_DEFINITION_RULE,
diagnostic_code: RENAME_DEFINITION_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{owner_ns}/{owner_def}"),
path: "examples".to_owned(),
fingerprint: node_fingerprint(&original_examples),
origin_chain: example_origins,
original: quoted_json(&original_examples),
replacement: Some(quoted_json(&replacement_examples)),
applicability: "machine-applicable",
message: format!("Rewrite compiler-resolved references in examples at indices {changed_examples:?}."),
target_path: vec![],
operation: Some(FixOperation::ReplaceExamples {
code: format_quoted_nodes(&rewritten_examples)?,
}),
});
}
let (rewritten_annotation, replacement_count) =
rewrite_loaded_schema_type_references(entry.schema.clone(), owner_ns, target_ns, old_name, new_name)?;
if replacement_count > 0 {
let schema_edn = calcit_core::snapshot::schema_annotation_to_edn(entry.schema.as_ref());
let rewritten_schema = calcit_core::snapshot::schema_annotation_to_edn(rewritten_annotation.as_ref());
let original_node = schema_edn_to_source_node(&schema_edn)?;
let replacement_node = schema_edn_to_source_node(&rewritten_schema)?;
attached_suggestions.push(FixSuggestion {
rule_id: RENAME_DEFINITION_RULE,
diagnostic_code: RENAME_DEFINITION_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{owner_ns}/{owner_def}"),
path: "schema".to_owned(),
fingerprint: node_fingerprint(&original_node),
origin_chain: vec![serde_json::json!({
"kind": "resolved-schema-type",
"target": format!("{target_ns}/{old_name}"),
"occurrences": replacement_count,
})],
original: quoted_json(&original_node),
replacement: Some(quoted_json(&replacement_node)),
applicability: "machine-applicable",
message: format!("Rewrite {replacement_count} compiler-loaded schema type reference(s) to `{target_ns}/{new_name}`."),
target_path: vec![],
operation: Some(FixOperation::ReplaceSchema {
code: format_schema_operation(&replacement_node)?,
}),
});
}
let usages = runner::preprocess::trace_definition_source_usages(owner_ns, owner_def, &warnings, &CallStackList::default())
.map_err(|failure| failure.msg)?;
for usage in usages {
if usage.target_ns.as_ref() != target_ns || usage.target_def.as_ref() != old_name {
continue;
}
if !usage.macro_origin.is_empty() {
blockers.push(format!(
"{owner_ns}/{owner_def}: target reference is produced across macro boundary {}",
usage.macro_origin.join(" -> ")
));
continue;
}
let Some(location) = usage.location else {
blockers.push(format!(
"{owner_ns}/{owner_def}: compiler resolved a target reference without a source coordinate"
));
continue;
};
if location.ns.as_ref() != owner_ns || location.def.as_ref() != owner_def {
blockers.push(format!(
"{owner_ns}/{owner_def}: target reference points outside its editable source ({location})"
));
continue;
}
let path = location.coord.iter().map(|value| usize::from(*value)).collect::<Vec<_>>();
let entry = snapshot
.files
.get(owner_ns)
.and_then(|file| file.defs.get(owner_def))
.ok_or_else(|| format!("Traced definition `{owner_ns}/{owner_def}` is missing from the source snapshot."))?;
let node = navigate_to_path(&entry.code, &path)?;
let Cirru::Leaf(source_leaf) = node else {
blockers.push(format!(
"{owner_ns}/{owner_def}{}: resolved reference is not a source leaf",
format_path(&path)
));
continue;
};
let replacement = if let Some((prefix, source_name)) = source_leaf.rsplit_once('/') {
if source_name != old_name {
blockers.push(format!(
"{owner_ns}/{owner_def}{}: resolved leaf `{source_leaf}` does not name `{old_name}`",
format_path(&path)
));
continue;
}
format!("{prefix}/{new_name}")
} else if source_leaf.as_ref() == old_name {
format!("{target_ns}/{new_name}")
} else {
blockers.push(format!(
"{owner_ns}/{owner_def}{}: resolved leaf `{source_leaf}` does not name `{old_name}`",
format_path(&path)
));
continue;
};
resolved.insert(
(owner_ns.clone(), owner_def.clone(), path),
(source_leaf.to_string(), vec![replacement]),
);
}
}
if !blockers.is_empty() {
blockers.sort();
blockers.dedup();
return Err(format!(
"Semantic rename `{target_ns}/{old_name}` is not provably source-editable; no changes were written:\n- {}",
blockers.join("\n- ")
));
}
let mut suggestions = Vec::new();
suggestions.extend(attached_suggestions);
for ((owner_ns, owner_def, target_path), (original_leaf, replacements)) in resolved {
let replacement = replacements.into_iter().next().expect("one deterministic replacement");
let original_node = Cirru::leaf(original_leaf.as_str());
let replacement_node = Cirru::leaf(replacement.as_str());
suggestions.push(FixSuggestion {
rule_id: RENAME_DEFINITION_RULE,
diagnostic_code: RENAME_DEFINITION_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{owner_ns}/{owner_def}"),
path: format!("code{}", format_path(&target_path)),
fingerprint: node_fingerprint(&original_node),
origin_chain: vec![serde_json::json!({"kind": "resolved-definition", "target": format!("{target_ns}/{old_name}")})],
original: quoted_json(&original_node),
replacement: Some(quoted_json(&replacement_node)),
applicability: "machine-applicable",
message: format!("Rewrite the compiler-resolved reference to `{target_ns}/{new_name}`."),
target_path,
operation: Some(FixOperation::ReplaceLeaf {
original: original_leaf,
replacement,
}),
});
}
suggestions.extend(plan_referred_import_removals(
snapshot,
snapshot_file,
target_ns,
old_name,
new_name,
)?);
let target_entry = target_file.defs.get(old_name).expect("checked semantic rename source");
let (renamed_code, declaration_changed) =
super::edit::rename_definition_declaration(snapshot_file, snapshot, target_ns, &target_entry.code, old_name, new_name)?;
let message = if declaration_changed {
format!("Rename the definition and declaration to `{target_ns}/{new_name}`.")
} else {
format!("Rename the definition key to `{target_ns}/{new_name}`.")
};
suggestions.push(FixSuggestion {
rule_id: RENAME_DEFINITION_RULE,
diagnostic_code: RENAME_DEFINITION_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{target_ns}/{old_name}"),
path: "definition".to_owned(),
fingerprint: node_fingerprint(&target_entry.code),
origin_chain: vec![serde_json::json!({"kind": "definition", "target": format!("{target_ns}/{old_name}")})],
original: quoted_json(&target_entry.code),
replacement: Some(quoted_json(&renamed_code)),
applicability: "machine-applicable",
message,
target_path: vec![],
operation: Some(FixOperation::RenameDefinition {
new_name: new_name.to_owned(),
}),
});
Ok(suggestions)
}
mod absence;
mod effect_features;
use effect_features::{EFFECT_FEATURES_DIAGNOSTIC, EFFECT_FEATURES_RULE};
mod compiler_review;
mod local_rename;
mod macro_context;
pub(crate) use local_rename::{SOURCE_SCOPE_HEADS, source_reference_paths};
pub(crate) mod schema_synthesis;
mod spread_call;
mod structural_rewrite;
use schema_synthesis::plan_schema_synthesis;
fn plan_value_to_zero_arg_fn(
options: &FixCommand,
snapshot: &Snapshot,
snapshot_file: &str,
project_definitions: &[(String, String)],
) -> Result<Vec<FixSuggestion>, String> {
let target_ns = options.ns.as_deref().expect("value refactor requires namespace");
let target_def = options.definition.as_deref().expect("value refactor requires definition");
let target_entry = snapshot
.files
.get(target_ns)
.and_then(|file| file.defs.get(target_def))
.ok_or_else(|| format!("Semantic refactor source `{target_ns}/{target_def}` does not exist."))?;
let Cirru::List(target_items) = &target_entry.code else {
return Err(format!(
"Semantic refactor source `{target_ns}/{target_def}` is not a definition form."
));
};
let target_head = target_items.first().and_then(leaf_value);
if target_head == Some("defn") && matches!(target_items.get(2), Some(Cirru::List(args)) if args.is_empty()) {
if std::env::var("CALCIT_FIX_VALIDATE_ONLY").as_deref() == Ok("1") {
validate_zero_arg_value_refactor(snapshot, project_definitions, target_ns, target_def)?;
}
return Ok(vec![]);
}
if target_head != Some("def") || target_items.len() != 3 || !target_items.get(1).is_some_and(|name| name.eq_leaf(target_def)) {
return Err(format!(
"Fix rule `{VALUE_TO_ZERO_ARG_FN_RULE}` requires `{target_ns}/{target_def}` to be an exact `(def {target_def} value)` form."
));
}
let warnings = RefCell::new(Vec::new());
let mut suggestions = Vec::new();
let mut blockers = Vec::new();
for (owner_ns, owner_def) in project_definitions {
let entry = snapshot
.files
.get(owner_ns)
.and_then(|file| file.defs.get(owner_def))
.ok_or_else(|| format!("Project definition `{owner_ns}/{owner_def}` is missing from the source snapshot."))?;
let direct_macro_reference =
list_head(&entry.code) == Some("defmacro") && cirru_contains_target_reference(&entry.code, owner_ns, target_ns, target_def);
if direct_macro_reference {
blockers.push(format!(
"{owner_ns}/{owner_def}: macro source may produce `{target_ns}/{target_def}` and cannot be converted as a runtime value read"
));
}
if quoted_region_contains_target_reference(&entry.code, owner_ns, target_ns, target_def) {
blockers.push(format!(
"{owner_ns}/{owner_def}: quoted source contains `{target_ns}/{target_def}` and may be consumed dynamically"
));
}
for (index, test) in entry.tests.iter().enumerate() {
if !cirru_contains_target_reference(&test.code, owner_ns, target_ns, target_def) {
continue;
}
let source_label = format!("{owner_ns}/{owner_def}#{}", test.name);
match plan_attached_value_call_rewrite(
&test.code,
owner_ns,
&format!("&calcit:value-to-fn-test:{owner_def}:{index}"),
&source_label,
target_ns,
target_def,
) {
Ok(Some(rewrite)) => {
let mut tag_names = test.tags.iter().map(|tag| tag.ref_str()).collect::<Vec<_>>();
tag_names.sort_unstable();
suggestions.push(FixSuggestion {
rule_id: VALUE_TO_ZERO_ARG_FN_RULE,
diagnostic_code: VALUE_TO_ZERO_ARG_FN_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{owner_ns}/{owner_def}"),
path: format!("tests.{}", test.name),
fingerprint: node_fingerprint(&test.code),
origin_chain: rewrite.origin_chain,
original: quoted_json(&test.code),
replacement: Some(quoted_json(&rewrite.code)),
applicability: "machine-applicable",
message: format!("Call the converted zero-argument function from attached test `{}`.", test.name),
target_path: vec![],
operation: Some(FixOperation::ReplaceTest {
name: test.name.clone(),
tags: tag_names.join(","),
code: format_quoted_nodes(std::slice::from_ref(&rewrite.code))?,
}),
});
}
Ok(None) => {}
Err(error) => blockers.push(error),
}
}
let mut rewritten_examples = entry.examples.clone();
let mut example_origins = Vec::new();
let mut changed_examples = Vec::new();
for (index, example) in entry.examples.iter().enumerate() {
if !cirru_contains_target_reference(example, owner_ns, target_ns, target_def) {
continue;
}
let source_label = format!("{owner_ns}/{owner_def} example {index}");
match plan_attached_value_call_rewrite(
example,
owner_ns,
&format!("&calcit:value-to-fn-example:{owner_def}:{index}"),
&source_label,
target_ns,
target_def,
) {
Ok(Some(rewrite)) => {
rewritten_examples[index] = rewrite.code;
example_origins.extend(rewrite.origin_chain);
changed_examples.push(index);
}
Ok(None) => {}
Err(error) => blockers.push(error),
}
}
if !changed_examples.is_empty() {
let original_examples = Cirru::List(entry.examples.clone());
let replacement_examples = Cirru::List(rewritten_examples.clone());
suggestions.push(FixSuggestion {
rule_id: VALUE_TO_ZERO_ARG_FN_RULE,
diagnostic_code: VALUE_TO_ZERO_ARG_FN_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{owner_ns}/{owner_def}"),
path: "examples".to_owned(),
fingerprint: node_fingerprint(&original_examples),
origin_chain: example_origins,
original: quoted_json(&original_examples),
replacement: Some(quoted_json(&replacement_examples)),
applicability: "machine-applicable",
message: format!("Call the converted zero-argument function from examples at indices {changed_examples:?}."),
target_path: vec![],
operation: Some(FixOperation::ReplaceExamples {
code: format_quoted_nodes(&rewritten_examples)?,
}),
});
}
let (_, schema_reference_count) =
rewrite_loaded_schema_type_references(entry.schema.clone(), owner_ns, target_ns, target_def, target_def)?;
if schema_reference_count > 0 {
blockers.push(format!(
"{owner_ns}/{owner_def} schema: `{target_ns}/{target_def}` is used as a type reference and cannot be converted to a value call"
));
}
if direct_macro_reference {
continue;
}
let usages = runner::preprocess::trace_definition_source_usages(owner_ns, owner_def, &warnings, &CallStackList::default())
.map_err(|failure| failure.msg)?;
for usage in usages {
if usage.target_ns.as_ref() != target_ns || usage.target_def.as_ref() != target_def {
continue;
}
if owner_ns == target_ns && owner_def == target_def {
blockers.push(format!(
"{target_ns}/{target_def}: self-referential value initialization cannot be converted without changing its recursive evaluation model"
));
continue;
}
if !usage.macro_origin.is_empty() {
blockers.push(format!(
"{owner_ns}/{owner_def}: target reference is produced across macro boundary {}",
usage.macro_origin.join(" -> ")
));
continue;
}
let Some(location) = usage.location else {
blockers.push(format!(
"{owner_ns}/{owner_def}: compiler resolved a target reference without a source coordinate"
));
continue;
};
if location.ns.as_ref() != owner_ns || location.def.as_ref() != owner_def {
blockers.push(format!(
"{owner_ns}/{owner_def}: target reference points outside its editable source ({location})"
));
continue;
}
let path = location.coord.iter().map(|value| usize::from(*value)).collect::<Vec<_>>();
let original_node = navigate_to_path(&entry.code, &path)?;
let Cirru::Leaf(original_leaf) = &original_node else {
blockers.push(format!(
"{owner_ns}/{owner_def}{}: resolved reference is not a source leaf",
format_path(&path)
));
continue;
};
let replacement_node = Cirru::List(vec![original_node.clone()]);
let original_code = original_leaf.to_string();
suggestions.push(FixSuggestion {
rule_id: VALUE_TO_ZERO_ARG_FN_RULE,
diagnostic_code: VALUE_TO_ZERO_ARG_FN_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{owner_ns}/{owner_def}"),
path: format!("code{}", format_path(&path)),
fingerprint: node_fingerprint(&original_node),
origin_chain: vec![serde_json::json!({
"kind": "resolved-value-read",
"target": format!("{target_ns}/{target_def}"),
"path": format_path(&path),
"macro_origin": [],
})],
original: quoted_json(&original_node),
replacement: Some(quoted_json(&replacement_node)),
applicability: "machine-applicable",
message: format!("Call the converted zero-argument function `{target_ns}/{target_def}`."),
target_path: path,
operation: Some(FixOperation::WrapLeafCall { original: original_code }),
});
}
}
if !blockers.is_empty() {
blockers.sort();
blockers.dedup();
return Err(format!(
"Semantic value-to-function refactor is not safe; no changes were written:\n{}",
blockers.into_iter().map(|item| format!("- {item}")).collect::<Vec<_>>().join("\n")
));
}
let rewritten_schema = std::sync::Arc::new(CalcitTypeAnnotation::Fn(std::sync::Arc::new(CalcitFnTypeAnnotation {
open_reason: Default::default(),
cases: Default::default(),
guard: None,
runtime_arity: None,
generics: std::sync::Arc::new(vec![]),
where_bounds: std::sync::Arc::new(vec![]),
arg_types: vec![],
return_type: target_entry.schema.clone(),
fn_kind: SchemaKind::Fn,
rest_type: None,
features: std::sync::Arc::new(std::collections::HashSet::new()),
})));
let original_schema_node = schema_edn_to_source_node(&calcit_core::snapshot::schema_annotation_to_edn(target_entry.schema.as_ref()))?;
let rewritten_schema_node = schema_edn_to_source_node(&calcit_core::snapshot::schema_annotation_to_edn(rewritten_schema.as_ref()))?;
suggestions.push(FixSuggestion {
rule_id: VALUE_TO_ZERO_ARG_FN_RULE,
diagnostic_code: VALUE_TO_ZERO_ARG_FN_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{target_ns}/{target_def}"),
path: "schema".to_owned(),
fingerprint: node_fingerprint(&original_schema_node),
origin_chain: vec![serde_json::json!({"kind": "derived-zero-arg-function-schema"})],
original: quoted_json(&original_schema_node),
replacement: Some(quoted_json(&rewritten_schema_node)),
applicability: "machine-applicable",
message: "Wrap the existing value schema as the return type of a zero-argument function.".to_owned(),
target_path: vec![],
operation: Some(FixOperation::ReplaceSchema {
code: format_schema_operation(&rewritten_schema_node)?,
}),
});
let rewritten_definition = Cirru::List(vec![
Cirru::leaf("defn"),
Cirru::leaf(target_def),
Cirru::List(vec![]),
target_items[2].clone(),
]);
suggestions.push(FixSuggestion {
rule_id: VALUE_TO_ZERO_ARG_FN_RULE,
diagnostic_code: VALUE_TO_ZERO_ARG_FN_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{target_ns}/{target_def}"),
path: "definition".to_owned(),
fingerprint: node_fingerprint(&target_entry.code),
origin_chain: vec![serde_json::json!({"kind": "definition", "target": format!("{target_ns}/{target_def}")})],
original: quoted_json(&target_entry.code),
replacement: Some(quoted_json(&rewritten_definition)),
applicability: "machine-applicable",
message: format!("Convert `{target_ns}/{target_def}` from `def` to a zero-argument `defn`."),
target_path: vec![],
operation: Some(FixOperation::ReplaceDefinition {
code: format_quoted_nodes(std::slice::from_ref(&rewritten_definition))?,
}),
});
Ok(suggestions)
}
fn validate_zero_arg_value_refactor(
snapshot: &Snapshot,
project_definitions: &[(String, String)],
target_ns: &str,
target_def: &str,
) -> Result<(), String> {
let warnings = RefCell::new(Vec::new());
for (owner_ns, owner_def) in project_definitions {
let entry = snapshot
.files
.get(owner_ns)
.and_then(|file| file.defs.get(owner_def))
.ok_or_else(|| format!("Project definition `{owner_ns}/{owner_def}` is missing from the staged snapshot."))?;
if list_head(&entry.code) == Some("defmacro") && cirru_contains_target_reference(&entry.code, owner_ns, target_ns, target_def) {
return Err(format!(
"{owner_ns}/{owner_def}: staged macro source retains `{target_ns}/{target_def}`"
));
}
if quoted_region_contains_target_reference(&entry.code, owner_ns, target_ns, target_def) {
return Err(format!(
"{owner_ns}/{owner_def}: staged source retains quoted `{target_ns}/{target_def}` data"
));
}
let (_, schema_reference_count) =
rewrite_loaded_schema_type_references(entry.schema.clone(), owner_ns, target_ns, target_def, target_def)?;
if schema_reference_count > 0 {
return Err(format!(
"{owner_ns}/{owner_def} schema: staged source retains `{target_ns}/{target_def}` as a type reference"
));
}
for usage in runner::preprocess::trace_definition_source_usages(owner_ns, owner_def, &warnings, &CallStackList::default())
.map_err(|failure| failure.msg)?
{
if usage.target_ns.as_ref() != target_ns || usage.target_def.as_ref() != target_def {
continue;
}
if !usage.macro_origin.is_empty() {
return Err(format!(
"{owner_ns}/{owner_def}: staged target reference crosses macro boundary {}",
usage.macro_origin.join(" -> ")
));
}
let location = usage
.location
.ok_or_else(|| format!("{owner_ns}/{owner_def}: staged target reference has no source coordinate"))?;
let path = location.coord.iter().map(|value| usize::from(*value)).collect::<Vec<_>>();
if !source_path_is_zero_arg_call(&entry.code, &path)? {
return Err(format!(
"{owner_ns}/{owner_def}{}: staged value reference is not a zero-argument call",
format_path(&path)
));
}
}
for (index, test) in entry.tests.iter().enumerate() {
validate_attached_zero_arg_calls(
&test.code,
owner_ns,
&format!("&calcit:validate-value-to-fn-test:{owner_def}:{index}"),
&format!("{owner_ns}/{owner_def}#{}", test.name),
target_ns,
target_def,
)?;
}
for (index, example) in entry.examples.iter().enumerate() {
validate_attached_zero_arg_calls(
example,
owner_ns,
&format!("&calcit:validate-value-to-fn-example:{owner_def}:{index}"),
&format!("{owner_ns}/{owner_def} example {index}"),
target_ns,
target_def,
)?;
}
}
Ok(())
}
fn validate_attached_zero_arg_calls(
source: &Cirru,
owner_ns: &str,
synthetic_def: &str,
source_label: &str,
target_ns: &str,
target_def: &str,
) -> Result<(), String> {
if quoted_region_contains_target_reference(source, owner_ns, target_ns, target_def) {
return Err(format!(
"{source_label}: staged attached source retains quoted `{target_ns}/{target_def}` data"
));
}
if !cirru_contains_target_reference(source, owner_ns, target_ns, target_def) {
return Ok(());
}
let wrapper = Cirru::List(vec![Cirru::leaf("fn"), Cirru::List(vec![]), source.clone()]);
let parsed = code_to_calcit(&wrapper, owner_ns, synthetic_def, vec![])
.map_err(|error| format!("{source_label}: failed to parse staged attached source: {error}"))?;
let warnings = RefCell::new(Vec::new());
for usage in runner::preprocess::trace_source_usages(&parsed, owner_ns, synthetic_def, &warnings, &CallStackList::default())
.map_err(|failure| format!("{source_label}: failed to preprocess staged attached source: {}", failure.msg))?
{
if usage.target_ns.as_ref() != target_ns || usage.target_def.as_ref() != target_def {
continue;
}
let macro_origin = usage
.macro_origin
.into_iter()
.filter(|origin| origin != "calcit.core/fn")
.collect::<Vec<_>>();
if !macro_origin.is_empty() {
return Err(format!(
"{source_label}: staged target reference crosses macro boundary {}",
macro_origin.join(" -> ")
));
}
let location = usage
.location
.ok_or_else(|| format!("{source_label}: staged target reference has no source coordinate"))?;
let wrapper_path = location.coord.iter().map(|value| usize::from(*value)).collect::<Vec<_>>();
let path = wrapper_path.strip_prefix(&[2]).ok_or_else(|| {
format!(
"{source_label}{}: staged coordinate is outside attached source",
format_path(&wrapper_path)
)
})?;
if !source_path_is_zero_arg_call(source, path)? {
return Err(format!(
"{source_label}{}: staged value reference is not a zero-argument call",
format_path(path)
));
}
}
Ok(())
}
fn source_path_is_zero_arg_call(source: &Cirru, path: &[usize]) -> Result<bool, String> {
let Some((&child_index, parent_path)) = path.split_last() else {
return Ok(false);
};
let parent = navigate_to_path(source, parent_path)?;
Ok(matches!(parent, Cirru::List(items) if child_index == 0 && items.len() == 1))
}
fn validate_no_stale_attached_references(
snapshot: &Snapshot,
project_definitions: &[(String, String)],
target_ns: &str,
old_name: &str,
new_name: &str,
) -> Result<(), String> {
for (owner_ns, owner_def) in project_definitions {
let entry = snapshot
.files
.get(owner_ns)
.and_then(|file| file.defs.get(owner_def))
.ok_or_else(|| format!("Project definition `{owner_ns}/{owner_def}` is missing from the staged snapshot."))?;
for (index, test) in entry.tests.iter().enumerate() {
if !cirru_contains_target_reference(&test.code, owner_ns, target_ns, old_name) {
continue;
}
let source_label = format!("{owner_ns}/{owner_def}#{}", test.name);
if plan_attached_source_rewrite(
&test.code,
owner_ns,
&format!("&calcit:validate-rename-test:{owner_def}:{index}"),
&source_label,
target_ns,
old_name,
new_name,
)?
.is_some()
{
return Err(format!(
"{source_label}: staged semantic rename left a resolved reference to `{target_ns}/{old_name}`"
));
}
}
for (index, example) in entry.examples.iter().enumerate() {
if !cirru_contains_target_reference(example, owner_ns, target_ns, old_name) {
continue;
}
let source_label = format!("{owner_ns}/{owner_def} example {index}");
if plan_attached_source_rewrite(
example,
owner_ns,
&format!("&calcit:validate-rename-example:{owner_def}:{index}"),
&source_label,
target_ns,
old_name,
new_name,
)?
.is_some()
{
return Err(format!(
"{source_label}: staged semantic rename left a resolved reference to `{target_ns}/{old_name}`"
));
}
}
let (_, stale_count) = rewrite_loaded_schema_type_references(entry.schema.clone(), owner_ns, target_ns, old_name, new_name)?;
if stale_count > 0 {
return Err(format!(
"{owner_ns}/{owner_def} schema: staged semantic rename left a type reference to `{target_ns}/{old_name}`"
));
}
}
Ok(())
}
fn source_name_resolves_to_target(owner_ns: &str, source: &str, target_ns: &str, target_def: &str) -> bool {
if let Some((prefix, definition)) = source.rsplit_once('/') {
if definition != target_def {
return false;
}
if prefix == target_ns {
return true;
}
return program::lookup_ns_target_in_import(owner_ns, prefix).is_some_and(|namespace| namespace.as_ref() == target_ns);
}
source == target_def
&& (owner_ns == target_ns
|| imported_definition_target(owner_ns, source)
.is_some_and(|(namespace, definition)| namespace == target_ns && definition == target_def)
// Core names are implicitly visible after local definitions and imports.
// Lexical bindings are still checked by the compiler usage trace.
|| (target_ns == "calcit.core"
&& program::lookup_def_id(owner_ns, source).is_none()
&& imported_definition_target(owner_ns, source).is_none()
&& program::lookup_def_id("calcit.core", source).is_some()))
}
fn cirru_contains_target_reference(node: &Cirru, owner_ns: &str, target_ns: &str, target_def: &str) -> bool {
match node {
Cirru::Leaf(value) => source_name_resolves_to_target(owner_ns, value, target_ns, target_def),
Cirru::List(items) => items
.iter()
.any(|item| cirru_contains_target_reference(item, owner_ns, target_ns, target_def)),
}
}
fn quoted_region_contains_target_reference(node: &Cirru, owner_ns: &str, target_ns: &str, target_def: &str) -> bool {
let Cirru::List(items) = node else { return false };
if items
.first()
.is_some_and(|head| head.eq_leaf("quote") || head.eq_leaf("quasiquote"))
{
return items
.iter()
.skip(1)
.any(|item| cirru_contains_target_reference(item, owner_ns, target_ns, target_def));
}
items
.iter()
.any(|item| quoted_region_contains_target_reference(item, owner_ns, target_ns, target_def))
}
struct AttachedSourceRewrite {
code: Cirru,
origin_chain: Vec<Value>,
}
struct AttachedRewriteTarget<'a> {
namespace: &'a str,
definition: &'a str,
allow_preserving_macros: bool,
}
/// Resolve references inside one definition-attached executable source without guessing from leaf text.
fn plan_attached_source_rewrite(
source: &Cirru,
owner_ns: &str,
synthetic_def: &str,
source_label: &str,
target_ns: &str,
old_name: &str,
new_name: &str,
) -> Result<Option<AttachedSourceRewrite>, String> {
plan_attached_source_rewrite_with(
source,
owner_ns,
synthetic_def,
source_label,
AttachedRewriteTarget {
namespace: target_ns,
definition: old_name,
allow_preserving_macros: false,
},
&|source_leaf, _| semantic_rename_leaf_replacement(source_leaf, old_name, target_ns, new_name).map(Cirru::leaf),
)
}
fn plan_attached_value_call_rewrite(
source: &Cirru,
owner_ns: &str,
synthetic_def: &str,
source_label: &str,
target_ns: &str,
target_def: &str,
) -> Result<Option<AttachedSourceRewrite>, String> {
plan_attached_source_rewrite_with(
source,
owner_ns,
synthetic_def,
source_label,
AttachedRewriteTarget {
namespace: target_ns,
definition: target_def,
allow_preserving_macros: false,
},
&|source_leaf, _| Ok(Cirru::List(vec![Cirru::leaf(source_leaf)])),
)
}
fn plan_attached_source_rewrite_with<F>(
source: &Cirru,
owner_ns: &str,
synthetic_def: &str,
source_label: &str,
target: AttachedRewriteTarget<'_>,
rewrite_leaf: &F,
) -> Result<Option<AttachedSourceRewrite>, String>
where
F: Fn(&str, &[usize]) -> Result<Cirru, String>,
{
let AttachedRewriteTarget {
namespace: target_ns,
definition: target_def,
allow_preserving_macros,
} = target;
if quoted_region_contains_target_reference(source, owner_ns, target_ns, target_def) {
return Err(format!(
"{source_label}: quoted source contains `{target_ns}/{target_def}` and may be consumed dynamically"
));
}
let wrapper = Cirru::List(vec![Cirru::leaf("fn"), Cirru::List(vec![]), source.clone()]);
let parsed = code_to_calcit(&wrapper, owner_ns, synthetic_def, vec![])
.map_err(|error| format!("{source_label}: failed to parse attached source for semantic refactor: {error}"))?;
let warnings = RefCell::new(Vec::new());
let usages = runner::preprocess::trace_source_usages(&parsed, owner_ns, synthetic_def, &warnings, &CallStackList::default())
.map_err(|failure| {
format!(
"{source_label}: failed to preprocess attached source for semantic refactor: {}",
failure.msg
)
})?;
let mut rewrites = BTreeMap::<Vec<usize>, (String, Cirru, Vec<String>)>::new();
for usage in usages {
if usage.target_ns.as_ref() != target_ns || usage.target_def.as_ref() != target_def {
continue;
}
let macro_origin = usage
.macro_origin
.into_iter()
.filter(|origin| origin != "calcit.core/fn")
.collect::<Vec<_>>();
if !macro_origin.is_empty()
&& !(allow_preserving_macros
&& macro_origin
.iter()
.all(|origin| preserves_nominal_method_call_through_macro(origin)))
{
return Err(format!(
"{source_label}: target reference is produced across macro boundary {}",
macro_origin.join(" -> ")
));
}
let Some(location) = usage.location else {
return Err(format!(
"{source_label}: compiler resolved a target reference without a source coordinate"
));
};
if location.ns.as_ref() != owner_ns || location.def.as_ref() != synthetic_def {
return Err(format!(
"{source_label}: target reference points outside its editable attached source ({location})"
));
}
let wrapper_path = location.coord.iter().map(|value| usize::from(*value)).collect::<Vec<_>>();
let Some(path) = wrapper_path.strip_prefix(&[2]) else {
return Err(format!(
"{source_label}{}: compiler coordinate does not point into the attached expression",
format_path(&wrapper_path)
));
};
let node = navigate_to_path(source, path)?;
let Cirru::Leaf(source_leaf) = node else {
return Err(format!(
"{source_label}{}: resolved reference is not a source leaf",
format_path(path)
));
};
let replacement = rewrite_leaf(&source_leaf, path).map_err(|error| format!("{source_label}{}: {error}", format_path(path)))?;
rewrites.insert(path.to_vec(), (source_leaf.to_string(), replacement, macro_origin));
}
if rewrites.is_empty() {
return Ok(None);
}
let mut rewritten = source.clone();
let mut origin_chain = Vec::with_capacity(rewrites.len());
for (path, (original, replacement, macro_origin)) in rewrites {
replace_attached_source_node(&mut rewritten, &path, &original, &replacement)?;
origin_chain.push(serde_json::json!({
"kind": "resolved-attached-source",
"target": format!("{target_ns}/{target_def}"),
"path": format_path(&path),
"macro_origin": macro_origin,
}));
}
Ok(Some(AttachedSourceRewrite {
code: rewritten,
origin_chain,
}))
}
fn semantic_rename_leaf_replacement(source_leaf: &str, old_name: &str, target_ns: &str, new_name: &str) -> Result<String, String> {
if let Some((prefix, source_name)) = source_leaf.rsplit_once('/') {
if source_name != old_name {
return Err(format!("resolved leaf `{source_leaf}` does not name `{old_name}`"));
}
Ok(format!("{prefix}/{new_name}"))
} else if source_leaf == old_name {
Ok(format!("{target_ns}/{new_name}"))
} else {
Err(format!("resolved leaf `{source_leaf}` does not name `{old_name}`"))
}
}
fn replace_attached_source_node(node: &mut Cirru, path: &[usize], expected: &str, replacement: &Cirru) -> Result<(), String> {
replace_attached_source_tree(node, path, &Cirru::leaf(expected), replacement)
}
/// Replace a checked source subtree without interpreting its payload as executable code.
fn replace_attached_source_tree(node: &mut Cirru, path: &[usize], expected: &Cirru, replacement: &Cirru) -> Result<(), String> {
if path.is_empty() {
if node != expected {
return Err(format!(
"Attached source changed while planning rewrite: expected `{expected}`, got `{node}`"
));
}
*node = replacement.clone();
return Ok(());
}
let Cirru::List(items) = node else {
return Err(format!("Attached source path {} traverses a leaf", format_path(path)));
};
let index = path[0];
let child = items
.get_mut(index)
.ok_or_else(|| format!("Attached source path {} is out of range", format_path(path)))?;
replace_attached_source_tree(child, &path[1..], expected, replacement)
}
fn format_quoted_nodes(nodes: &[Cirru]) -> Result<String, String> {
let quoted = nodes
.iter()
.map(|node| Cirru::List(vec![Cirru::leaf("quote"), node.clone()]))
.collect::<Vec<_>>();
cirru_parser::format("ed, true.into()).map_err(|error| format!("Failed to encode attached source rewrite: {error}"))
}
/// `edit schema` only accepts the compact spelling, so a schema operation is
/// written as `quote $ Fn …` / `quote Name` whenever the node has one.
fn format_schema_operation(node: &Cirru) -> Result<String, String> {
let compact = match calcit_core::snapshot::parse_schema_annotation_for_write(node) {
Ok(annotation) => match calcit_core::snapshot::schema_annotation_to_storage_edn(annotation.as_ref()) {
cirru_edn::Edn::Quote(payload) => payload,
_ => node.clone(),
},
Err(_) => node.clone(),
};
format_quoted_nodes(std::slice::from_ref(&compact))
}
fn rewrite_loaded_schema_type_references(
schema: std::sync::Arc<CalcitTypeAnnotation>,
owner_ns: &str,
target_ns: &str,
old_name: &str,
new_name: &str,
) -> Result<(std::sync::Arc<CalcitTypeAnnotation>, usize), String> {
let replacements = Cell::new(0);
let rewritten = runner::preprocess::map_schema_references(
schema,
&|name, args| {
if source_name_resolves_to_target(owner_ns, name, target_ns, old_name) {
let replacement = semantic_rename_leaf_replacement(name, old_name, target_ns, new_name)
.expect("a compiler-loaded matching TypeRef must preserve the selected definition name");
replacements.set(replacements.get() + 1);
std::sync::Arc::new(CalcitTypeAnnotation::TypeRef(replacement.into(), args))
} else {
std::sync::Arc::new(CalcitTypeAnnotation::TypeRef(name.clone(), args))
}
},
&|trait_def| {
let source_name = trait_def.definition_ref.as_deref().unwrap_or_else(|| trait_def.name.ref_str());
if !source_name_resolves_to_target(owner_ns, source_name, target_ns, old_name) {
return trait_def;
}
let replacement = semantic_rename_leaf_replacement(source_name, old_name, target_ns, new_name)
.expect("a compiler-loaded matching trait bound must preserve the selected definition name");
let mut rewritten = trait_def.as_ref().clone();
rewritten.name = cirru_edn::EdnTag::new(new_name);
if rewritten.definition_ref.is_some() {
rewritten.definition_ref = Some(replacement.trim_start_matches('\'').into());
}
replacements.set(replacements.get() + 1);
std::sync::Arc::new(rewritten)
},
);
Ok((rewritten, replacements.get()))
}
fn schema_edn_to_source_node(schema: &cirru_edn::Edn) -> Result<Cirru, String> {
let rendered = cirru_edn::format(schema, true).map_err(|error| format!("Failed to format rewritten schema: {error}"))?;
let nodes = cirru_parser::parse(&rendered).map_err(|error| format!("Failed to parse rewritten schema source: {error}"))?;
match nodes.as_slice() {
[node] => Ok(node.clone()),
_ => Err(format!("Rewritten schema must render as one source node, got {}.", nodes.len())),
}
}
fn plan_referred_import_removals(
snapshot: &Snapshot,
snapshot_file: &str,
target_ns: &str,
old_name: &str,
new_name: &str,
) -> Result<Vec<FixSuggestion>, String> {
let mut suggestions = Vec::new();
let mut namespaces = snapshot.files.keys().cloned().collect::<Vec<_>>();
namespaces.sort();
for namespace in namespaces {
if namespace != snapshot.package && !namespace.starts_with(&format!("{}.", snapshot.package)) {
continue;
}
let file = &snapshot.files[&namespace];
let Cirru::List(ns_items) = &file.ns.code else { continue };
let Some(Cirru::List(require_items)) = ns_items.get(2) else {
continue;
};
if !require_items.first().is_some_and(|head| head.eq_leaf(":require")) {
continue;
}
let original_rule_nodes = require_items.iter().skip(1).cloned().collect::<Vec<_>>();
let mut rules = Vec::with_capacity(original_rule_nodes.len());
let mut changed = false;
for rule in &original_rule_nodes {
let Cirru::List(items) = rule else {
rules.push(rule.clone());
continue;
};
if items.len() != 3 || !items[0].eq_leaf(target_ns) || !items[1].eq_leaf(":refer") {
rules.push(rule.clone());
continue;
}
let Cirru::List(referred) = &items[2] else {
rules.push(rule.clone());
continue;
};
let next_referred = referred.iter().filter(|item| !item.eq_leaf(old_name)).cloned().collect::<Vec<_>>();
if next_referred.len() != referred.len() {
changed = true;
if next_referred.iter().any(|item| !item.eq_leaf("[]")) {
let mut next_items = items.clone();
next_items[2] = Cirru::List(next_referred);
rules.push(Cirru::List(next_items));
}
} else {
rules.push(rule.clone());
}
}
if !changed {
continue;
}
let original_rules = Cirru::List(original_rule_nodes);
let replacement_rules = Cirru::List(rules.clone());
let rules_json = Value::Array(rules.iter().map(cirru_to_json_value).collect());
suggestions.push(FixSuggestion {
rule_id: RENAME_DEFINITION_RULE,
diagnostic_code: RENAME_DEFINITION_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: namespace.clone(),
path: "ns.:require".to_owned(),
fingerprint: node_fingerprint(&original_rules),
origin_chain: vec![serde_json::json!({"kind": "refer-import", "target": format!("{target_ns}/{old_name}")})],
original: quoted_json(&original_rules),
replacement: Some(quoted_json(&replacement_rules)),
applicability: "machine-applicable",
message: format!(
"Remove the stale `:refer` binding for `{target_ns}/{old_name}`; rewritten usages name `{target_ns}/{new_name}` explicitly."
),
target_path: vec![],
operation: Some(FixOperation::ReplaceImports {
code: serde_json::to_string(&rules_json).map_err(|error| format!("Failed to encode import rewrite: {error}"))?,
}),
});
}
Ok(suggestions)
}
/// Convert removed-data diagnostics back to guarded source-leaf replacements.
fn plan_removed_data_api_fixes(
options: &FixCommand,
snapshot: &Snapshot,
snapshot_file: &str,
warnings: &[LocatedWarning],
) -> Result<Vec<FixSuggestion>, String> {
let mut suggestions = BTreeMap::new();
for warning in warnings {
if warning.code() != Some(REMOVED_DATA_API_DIAGNOSTIC) {
continue;
}
let location = warning.location();
if options.ns.as_deref().is_some_and(|filter| location.ns.as_ref() != filter)
|| options.definition.as_deref().is_some_and(|filter| location.def.as_ref() != filter)
{
continue;
}
let Some(file) = snapshot.files.get(location.ns.as_ref()) else {
continue;
};
let Some(entry) = file.defs.get(location.def.as_ref()) else {
continue;
};
let Some(suggestion) = removed_data_api_source_suggestion(snapshot_file, &entry.code, warning) else {
continue;
};
let key = (location.ns.to_string(), location.def.to_string(), suggestion.target_path.clone());
insert_fix_suggestion(&mut suggestions, key, suggestion)?;
}
Ok(suggestions.into_values().collect())
}
/// Map an existing compiler diagnostic back to its source leaf in any source region.
fn removed_data_api_source_suggestion(snapshot_file: &str, source: &Cirru, warning: &LocatedWarning) -> Option<FixSuggestion> {
let location = warning.location();
let coordinate = location.coord.iter().map(|value| usize::from(*value)).collect::<Vec<_>>();
let (target_path, original_leaf) = resolve_fix_target(source, &coordinate)?;
let (replacement_leaf, guidance) = migration_for_source_leaf(&original_leaf)?;
let original_node = Cirru::leaf(original_leaf.as_str());
let replacement = replacement_leaf.as_ref().map(|leaf| quoted_json(&Cirru::leaf(leaf.as_str())));
let applicability = if replacement.is_some() {
"machine-applicable"
} else {
"requires-review"
};
let message = if replacement.is_some() {
format!("Replace `{original_leaf}` with `{guidance}`.")
} else {
format!("Choose the value or definition predicate for `{original_leaf}`: {guidance}.")
};
Some(FixSuggestion {
rule_id: REMOVED_DATA_API_RULE,
diagnostic_code: REMOVED_DATA_API_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{}/{}", location.ns, location.def),
path: format!("code{}", format_path(&target_path)),
fingerprint: node_fingerprint(&original_node),
origin_chain: vec![],
original: quoted_json(&original_node),
replacement,
applicability,
message,
target_path,
operation: replacement_leaf.map(|replacement| FixOperation::ReplaceLeaf {
original: original_leaf,
replacement,
}),
})
}
fn plan_removed_data_api_source(
snapshot_file: &str,
namespace: &str,
definition: &str,
source: &Cirru,
) -> Result<Vec<FixSuggestion>, String> {
let parsed = code_to_calcit(source, namespace, definition, vec![])?;
let warnings = RefCell::new(Vec::new());
let usages = with_legacy_migration_mode(|| {
runner::preprocess::trace_source_usages(&parsed, namespace, definition, &warnings, &CallStackList::default())
.map_err(|failure| failure.msg)
})?;
let mut suggestions = BTreeMap::new();
for warning in warnings.borrow().iter() {
let location = warning.location();
if warning.code() != Some(REMOVED_DATA_API_DIAGNOSTIC) || location.ns.as_ref() != namespace || location.def.as_ref() != definition {
continue;
}
let Some(mut suggestion) = removed_data_api_source_suggestion(snapshot_file, source, warning) else {
continue;
};
let call_path = suggestion.target_path.strip_suffix(&[0]).unwrap_or(&suggestion.target_path);
if !method_source_context_is_stable(source, call_path, namespace, definition, &usages) {
suggestion.applicability = "requires-review";
suggestion.replacement = None;
suggestion.operation = None;
"The removed API reference crosses an unknown source context; review whether expansion observes its spelling."
.clone_into(&mut suggestion.message);
}
let key = (namespace.to_owned(), definition.to_owned(), suggestion.target_path.clone());
insert_fix_suggestion(&mut suggestions, key, suggestion)?;
}
Ok(suggestions.into_values().collect())
}
fn core_nominal_type_is_unshadowed(snapshot: &Snapshot, namespace: &str, nominal: &str, bindings: &HashSet<String>) -> bool {
let has_local_definition = snapshot.files.get(namespace).is_some_and(|file| file.defs.contains_key(nominal));
let has_import = program::PROGRAM_CODE_DATA
.read()
.ok()
.and_then(|data| data.get(namespace).map(|entry| entry.import_map.contains_key(nominal)))
.unwrap_or(false);
!bindings.contains(nominal) && !has_local_definition && !has_import
}
fn preserves_constructor_argument_through_macro(origin: &str) -> bool {
// Core bodies and validated Struct fields preserve one evaluation of each
// payload; none consumes nested call heads as data.
matches!(origin, "calcit.core/let" | "calcit.core/cond" | "calcit.core/%{}")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct CoreNominalMethod {
method: &'static str,
definition: &'static str,
arity: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CoreNominalMethodKind {
Option,
Result,
}
impl CoreNominalMethodKind {
fn rule_id(self) -> &'static str {
match self {
Self::Option => CORE_OPTION_METHOD_RULE,
Self::Result => CORE_RESULT_METHOD_RULE,
}
}
fn diagnostic(self) -> &'static str {
match self {
Self::Option => CORE_OPTION_METHOD_DIAGNOSTIC,
Self::Result => CORE_RESULT_METHOD_DIAGNOSTIC,
}
}
fn nominal(self) -> &'static str {
match self {
Self::Option => "Option",
Self::Result => "Result",
}
}
}
fn core_nominal_method(name: &str, kind: CoreNominalMethodKind) -> Option<CoreNominalMethod> {
match (kind, name.rsplit_once('/').map_or(name, |(_, definition)| definition)) {
(CoreNominalMethodKind::Option, "option:some?") => Some(CoreNominalMethod {
method: ".some?",
definition: "calcit.core/option:some?",
arity: 1,
}),
(CoreNominalMethodKind::Option, "option:none?") => Some(CoreNominalMethod {
method: ".none?",
definition: "calcit.core/option:none?",
arity: 1,
}),
(CoreNominalMethodKind::Option, "option:unwrap") => Some(CoreNominalMethod {
method: ".unwrap",
definition: "calcit.core/option:unwrap",
arity: 1,
}),
(CoreNominalMethodKind::Option, "option:unwrap-or") => Some(CoreNominalMethod {
method: ".unwrap-or",
definition: "calcit.core/option:unwrap-or",
arity: 2,
}),
(CoreNominalMethodKind::Option, "option:map") => Some(CoreNominalMethod {
method: ".map",
definition: "calcit.core/option:map",
arity: 2,
}),
(CoreNominalMethodKind::Option, "option:and-then") => Some(CoreNominalMethod {
method: ".and-then",
definition: "calcit.core/option:and-then",
arity: 2,
}),
(CoreNominalMethodKind::Option, "option:or-else") => Some(CoreNominalMethod {
method: ".or-else",
definition: "calcit.core/option:or-else",
arity: 2,
}),
(CoreNominalMethodKind::Option, "option:fold") => Some(CoreNominalMethod {
method: ".fold",
definition: "calcit.core/option:fold",
arity: 3,
}),
(CoreNominalMethodKind::Result, "result:unwrap-or") => Some(CoreNominalMethod {
method: ".unwrap-or",
definition: "calcit.core/result:unwrap-or",
arity: 2,
}),
(CoreNominalMethodKind::Result, "result:ok?") => Some(CoreNominalMethod {
method: ".ok?",
definition: "calcit.core/result:ok?",
arity: 1,
}),
(CoreNominalMethodKind::Result, "result:err?") => Some(CoreNominalMethod {
method: ".err?",
definition: "calcit.core/result:err?",
arity: 1,
}),
_ => None,
}
}
fn contains_core_nominal_method_candidate(node: &Cirru, kind: CoreNominalMethodKind) -> bool {
match node {
Cirru::Leaf(name) => core_nominal_method(name.as_ref(), kind).is_some(),
Cirru::List(items) => items.iter().any(|item| contains_core_nominal_method_candidate(item, kind)),
}
}
fn preserves_nominal_method_call_through_macro(origin: &str) -> bool {
// These core forms retain one executable evaluation of the nested call.
// assert= also quotes its source for diagnostics, but never evaluates that copy.
// loop splices its body into one generated defn and its initial values into one list.
preserves_constructor_argument_through_macro(origin)
|| matches!(
origin,
"calcit.core/def" | "calcit.core/do" | "calcit.core/fn" | "calcit.core/assert=" | "calcit.core/loop"
)
}
fn rewrite_core_nominal_method_tree(node: &Cirru, path: &mut Vec<usize>, selected: &BTreeMap<Vec<usize>, CoreNominalMethod>) -> Cirru {
let Cirru::List(items) = node else {
return node.clone();
};
let rewritten = items
.iter()
.enumerate()
.map(|(index, item)| {
path.push(index);
let rewritten = rewrite_core_nominal_method_tree(item, path, selected);
path.pop();
rewritten
})
.collect::<Vec<_>>();
if let Some(method) = selected.get(path) {
let mut direct = Vec::with_capacity(rewritten.len());
direct.push(rewritten[1].clone());
direct.push(Cirru::leaf(method.method));
direct.extend(rewritten.into_iter().skip(2));
Cirru::List(direct)
} else {
Cirru::List(rewritten)
}
}
/// Rewrite only core helper calls whose receiver resolves to the same proven nominal method.
fn plan_core_nominal_method_fixes(
snapshot: &Snapshot,
snapshot_file: &str,
selected_definitions: &[(String, String)],
kind: CoreNominalMethodKind,
) -> Result<Vec<FixSuggestion>, String> {
let mut suggestions = Vec::new();
for (namespace, definition) in selected_definitions {
select_definition_entry_context(namespace, definition);
let entry = snapshot
.files
.get(namespace)
.and_then(|file| file.defs.get(definition))
.ok_or_else(|| format!("Selected definition `{namespace}/{definition}` is missing from the source snapshot."))?;
suggestions.extend(plan_core_nominal_method_source(
snapshot,
snapshot_file,
namespace,
definition,
&entry.code,
kind,
)?);
}
Ok(suggestions)
}
/// Use the same nominal receiver proof for definition and attached executable source.
fn plan_core_nominal_method_source(
snapshot: &Snapshot,
snapshot_file: &str,
namespace: &str,
definition: &str,
source: &Cirru,
kind: CoreNominalMethodKind,
) -> Result<Vec<FixSuggestion>, String> {
let mut suggestions = Vec::new();
if list_head(source) == Some("defmacro") || !contains_core_nominal_method_candidate(source, kind) {
return Ok(suggestions);
}
let mut local_bindings = HashSet::new();
collect_potential_local_bindings(source, &mut local_bindings);
let compiled = program::lookup_compiled_def(namespace, definition);
let parsed = code_to_calcit(source, namespace, definition, vec![])?;
let mut safe_calls = BTreeMap::<Vec<usize>, CoreNominalMethod>::new();
let mut review_calls = BTreeMap::<Vec<usize>, String>::new();
let warnings = RefCell::new(Vec::new());
let usages = runner::preprocess::trace_source_usages(&parsed, namespace, definition, &warnings, &CallStackList::default())
.map_err(|failure| failure.msg)?;
let core_absent_heads = usages
.iter()
.filter(|usage| {
usage.target_ns.as_ref() == "calcit.core"
&& match kind {
CoreNominalMethodKind::Option => usage.target_def.as_ref() == "Option",
CoreNominalMethodKind::Result => usage.target_def.as_ref() == "Result",
}
})
.filter_map(|usage| usage.location.as_ref())
.filter(|location| location.ns.as_ref() == namespace && location.def.as_ref() == definition)
.map(|location| location.coord.iter().map(|value| usize::from(*value)).collect::<Vec<_>>())
.collect::<HashSet<_>>();
let (preprocessed, expressions) =
runner::preprocess::trace_source_expressions(&parsed, namespace, definition, &RefCell::new(Vec::new()), &CallStackList::default())
.map_err(|failure| failure.msg)?;
for usage in usages {
if usage.target_ns.as_ref() != "calcit.core" {
continue;
}
let Some(method) = core_nominal_method(usage.target_def.as_ref(), kind) else {
continue;
};
let Some(location) = usage.location else {
continue;
};
if location.ns.as_ref() != namespace || location.def.as_ref() != definition {
continue;
}
let leaf_path = location.coord.iter().map(|value| usize::from(*value)).collect::<Vec<_>>();
if leaf_path.last() != Some(&0) {
let node = navigate_to_path(source, &leaf_path)?;
if matches!(&node, Cirru::Leaf(name) if core_nominal_method(name.as_ref(), kind) == Some(method)) {
review_calls.insert(
leaf_path,
"The helper is referenced as a function value; a receiver method cannot replace it without changing its callable shape."
.to_owned(),
);
}
continue;
}
let Some((&0, call_path)) = leaf_path.split_last() else {
continue;
};
let source_leaf = navigate_to_path(source, &leaf_path)?;
if !matches!(&source_leaf, Cirru::Leaf(name) if core_nominal_method(name.as_ref(), kind) == Some(method)) {
continue;
}
let call = navigate_to_path(source, call_path)?;
let Cirru::List(items) = call else {
continue;
};
if !usage
.macro_origin
.iter()
.all(|origin| preserves_nominal_method_call_through_macro(origin))
{
review_calls.insert(
call_path.to_vec(),
format!(
"The reference crosses macro expansion {}; review the source call manually.",
usage.macro_origin.join(" -> ")
),
);
} else if items.len() != method.arity + 1 {
review_calls.insert(
call_path.to_vec(),
format!(
"The helper call does not have exactly {} argument(s); review this use manually.",
method.arity
),
);
} else {
let mut receiver_path = call_path.to_vec();
receiver_path.push(1);
let receiver = &items[1];
let short_constructor_is_shadowed = matches!(receiver, Cirru::List(parts)
if matches!(parts.first(), Some(Cirru::Leaf(name)) if name.as_ref() == kind.nominal()))
&& !core_nominal_type_is_unshadowed(snapshot, namespace, kind.nominal(), &local_bindings);
let source_receiver = code_to_calcit(receiver, namespace, definition, vec![])?;
// Reader shorthand is a call, not the located leaf inside that expansion.
let direct_source_shape = !matches!(receiver, Cirru::Leaf(_)) || !matches!(source_receiver, Calcit::List(_));
// Lowered children can inherit the source call's coordinates but not its result type.
let inferred = runner::preprocess::unique_source_expression_at_path(&expressions, namespace, definition, &receiver_path)
.and_then(|item| item.inferred_type.clone())
.or_else(|| {
compiled
.as_ref()
.filter(|_| direct_source_shape)
.and_then(|compiled| {
super::query::find_preprocessed_node_at_path(
&compiled.preprocessed_code,
source,
namespace,
definition,
&receiver_path,
matches!(receiver, Cirru::List(_)),
)
})
.and_then(runner::preprocess::infer_static_type_from_expr)
})
.or_else(|| {
if !direct_source_shape {
return None;
}
super::query::find_preprocessed_node_at_path(
&preprocessed,
source,
namespace,
definition,
&receiver_path,
matches!(receiver, Cirru::List(_)),
)
.and_then(runner::preprocess::infer_static_type_from_expr)
});
let proven = !short_constructor_is_shadowed
&& (inferred.as_ref().is_some_and(|receiver_type| {
let receiver_type = runner::preprocess::resolve_namespace_type_refs_for_body(receiver_type.clone(), namespace);
let expected = format!("calcit.core/{}", kind.nominal());
let arity = if kind == CoreNominalMethodKind::Option { 1 } else { 2 };
let is_core_nominal = match receiver_type.as_ref() {
CalcitTypeAnnotation::TypeRef(name, args) => name.as_ref() == expected && args.len() == arity,
CalcitTypeAnnotation::Enum(def, args) => {
def.definition_ref().is_some_and(|name| name.as_ref() == expected) && args.len() == arity
}
_ => false,
};
let contract = runner::preprocess::static_method_contract(receiver_type.as_ref(), method.method);
is_core_nominal && contract.status == "proven" && contract.definition.as_deref() == Some(method.definition)
}) || (method.method == ".unwrap-or"
&& matches!(receiver, Cirru::List(parts) if match kind {
CoreNominalMethodKind::Option =>
matches!(parts.as_slice(), [Cirru::Leaf(name), Cirru::Leaf(variant)]
if matches!(name.as_ref(), "Option" | "calcit.core/Option") && variant.as_ref() == ":none"),
CoreNominalMethodKind::Result =>
matches!(parts.as_slice(), [Cirru::Leaf(name), Cirru::Leaf(variant), _]
if matches!(name.as_ref(), "Result" | "calcit.core/Result") && variant.as_ref() == ":err"),
})
&& {
let mut constructor_head_path = receiver_path.clone();
constructor_head_path.push(0);
core_absent_heads.contains(&constructor_head_path)
}
&& {
let mut fallback_path = call_path.to_vec();
fallback_path.push(2);
runner::preprocess::unique_source_expression_at_path(&expressions, namespace, definition, &fallback_path)
.and_then(|item| item.inferred_type.clone())
.or_else(|| {
if matches!(&items[2], Cirru::Leaf(_)) {
code_to_calcit(&items[2], namespace, definition, vec![])
.ok()
.and_then(|value| runner::preprocess::infer_static_type_from_expr(&value))
} else {
None
}
})
.is_some_and(|fallback_type| {
let fallback_type = runner::preprocess::resolve_namespace_type_refs_for_body(fallback_type, namespace);
if matches!(
fallback_type.as_ref(),
CalcitTypeAnnotation::Dynamic | CalcitTypeAnnotation::TypeVar(_)
) {
return false;
}
let args = match kind {
CoreNominalMethodKind::Option => vec![fallback_type],
CoreNominalMethodKind::Result => {
let Some(error_type) = inferred.as_ref().and_then(|receiver_type| match receiver_type.as_ref() {
CalcitTypeAnnotation::TypeRef(name, args)
if name.as_ref() == "calcit.core/Result" && matches!(args.as_slice(), [_, _]) =>
{
Some(args[1].clone())
}
CalcitTypeAnnotation::Enum(def, args)
if def.definition_ref().is_some_and(|name| name.as_ref() == "calcit.core/Result")
&& matches!(args.as_slice(), [_, _]) =>
{
Some(args[1].clone())
}
_ => None,
}) else {
return false;
};
vec![fallback_type, error_type]
}
};
let narrowed = CalcitTypeAnnotation::TypeRef(Arc::from(format!("calcit.core/{}", kind.nominal())), Arc::new(args));
let contract = runner::preprocess::static_method_contract(&narrowed, method.method);
contract.status == "proven" && contract.definition.as_deref() == Some(method.definition)
})
}));
if proven {
safe_calls.insert(call_path.to_vec(), method);
} else {
review_calls.insert(
call_path.to_vec(),
format!(
"The receiver type {} is not proven to dispatch to the matching {} method; retain the helper until its type is explicit.",
inferred
.as_ref()
.map(|annotation| annotation.to_string())
.unwrap_or_else(|| "unknown".to_owned()),
kind.nominal()
),
);
}
}
}
for (path, message) in review_calls {
safe_calls.remove(&path);
let node = navigate_to_path(source, &path)?;
suggestions.push(FixSuggestion {
rule_id: kind.rule_id(),
diagnostic_code: kind.diagnostic(),
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{namespace}/{definition}"),
path: format!("code{}", format_path(&path)),
fingerprint: node_fingerprint(&node),
origin_chain: vec![],
original: quoted_json(&node),
replacement: None,
applicability: "requires-review",
message,
target_path: path,
operation: None,
});
}
let outermost = safe_calls
.keys()
.filter(|path| !safe_calls.keys().any(|other| other.len() < path.len() && path.starts_with(other)))
.cloned()
.collect::<Vec<_>>();
for path in outermost {
let original = navigate_to_path(source, &path)?;
let replacement = rewrite_core_nominal_method_tree(&original, &mut path.clone(), &safe_calls);
let original_code = original.format_one_liner().map_err(|error| {
format!(
"Failed to format {} helper source at {namespace}/{definition}: {error}",
kind.nominal()
)
})?;
let replacement_code = replacement.format_one_liner().map_err(|error| {
format!(
"Failed to format {} method replacement at {namespace}/{definition}: {error}",
kind.nominal()
)
})?;
suggestions.push(FixSuggestion {
rule_id: kind.rule_id(),
diagnostic_code: kind.diagnostic(),
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{namespace}/{definition}"),
path: format!("code{}", format_path(&path)),
fingerprint: node_fingerprint(&original),
origin_chain: vec![serde_json::json!({"kind":format!("compiler-proven-{}-method", kind.nominal().to_ascii_lowercase()),"calls":safe_calls.keys().filter(|candidate| candidate.starts_with(&path)).count()})],
original: quoted_json(&original),
replacement: Some(quoted_json(&replacement)),
applicability: "machine-applicable",
message: format!("Use the proven {} receiver method; receiver and fallback expressions stay in their original order and are evaluated once.", kind.nominal()),
target_path: path,
operation: Some(FixOperation::ReplaceNode {
original: original_code,
replacement: replacement_code,
}),
});
}
Ok(suggestions)
}
fn supports_attached_migrations(rule: &str) -> bool {
matches!(
rule,
REMOVED_DATA_API_RULE
| CORE_OPTION_METHOD_RULE
| CORE_RESULT_METHOD_RULE
| CORE_IDENTITY_CONVERSION_RULE
| CORE_ABSENCE_RULE
| NAMED_ENUM_CONSTRUCTOR_RULE
| NAMED_STRUCT_CONSTRUCTOR_RULE
| REDUNDANT_DO_RULE
| SINGLE_EXPRESSION_DO_RULE
)
}
/// Apply existing source proofs to one metadata region without registering synthetic definitions.
fn plan_attached_fixes(
snapshot: &Snapshot,
snapshot_file: &str,
selected_definitions: &[(String, String)],
selected_rules: &[&'static str],
) -> Result<Vec<FixSuggestion>, String> {
let mut suggestions = Vec::new();
for (namespace, definition) in selected_definitions {
select_definition_entry_context(namespace, definition);
let entry = &snapshot.files[namespace].defs[definition];
let mut regions = entry
.tests
.iter()
.map(|test| {
let mut tags = test.tags.iter().map(|tag| tag.ref_str()).collect::<Vec<_>>();
tags.sort_unstable();
(
format!("tests.{}", test.name),
vec![test.code.clone()],
Some((test.name.clone(), tags.join(","))),
)
})
.collect::<Vec<_>>();
if !entry.examples.is_empty() {
regions.push(("examples".to_owned(), entry.examples.clone(), None));
}
for (region, sources, test) in regions {
let original = if test.is_some() {
sources[0].clone()
} else {
Cirru::List(sources.clone())
};
let mut rewritten = sources;
let mut origins = Vec::new();
let mut blockers = Vec::new();
// Rules that rewrote or blocked this region; the merged suggestion is labelled from them,
// never from the preset's first rule.
let mut region_rules = Vec::<&'static str>::new();
for (index, source) in rewritten.iter_mut().enumerate() {
for rule in [REDUNDANT_DO_RULE, SINGLE_EXPRESSION_DO_RULE] {
if !selected_rules.contains(&rule) {
continue;
}
match plan_attached_do_rewrite(
source,
namespace,
&format!("&calcit:fix-attached:{definition}:{region}:{index}"),
rule,
) {
Ok(Some(rewrite)) => {
*source = rewrite.code;
origins.extend(rewrite.origin_chain);
region_rules.push(rule);
}
Ok(None) => {}
Err(error) => {
blockers.push(format!("{namespace}/{definition} {region}[{index}]: {error}"));
region_rules.push(rule);
}
}
}
// Re-prove each rule against the source produced by preceding rules.
// Subtree replacements may change coordinates or fingerprints of nested calls.
for selected_rule in selected_rules {
let blockers_before = blockers.len();
let selected_rules = std::slice::from_ref(selected_rule);
let wrapper = Cirru::List(vec![Cirru::leaf("fn"), Cirru::List(vec![]), source.clone()]);
let synthetic_def = format!("&calcit:fix-attached:{definition}:{region}:{index}");
let mut candidates = Vec::new();
if selected_rules.contains(&REMOVED_DATA_API_RULE) {
match plan_removed_data_api_source(snapshot_file, namespace, &synthetic_def, &wrapper) {
Ok(planned) => candidates.extend(planned),
Err(error) => blockers.push(format!("{namespace}/{definition} {region}[{index}]: {error}")),
}
}
let kinds = [NominalKind::Enum, NominalKind::Struct]
.into_iter()
.filter(|kind| selected_rules.contains(&kind.rule_id()))
.collect::<Vec<_>>();
if !kinds.is_empty() {
match plan_named_constructor_source(
snapshot,
snapshot_file,
(namespace, &synthetic_def),
&wrapper,
&kinds,
(false, false),
) {
Ok(planned) => candidates.extend(planned),
Err(error) => blockers.push(format!("{namespace}/{definition} {region}[{index}]: {error}")),
}
}
for kind in [CoreNominalMethodKind::Option, CoreNominalMethodKind::Result] {
if !selected_rules.contains(&kind.rule_id()) {
continue;
}
match plan_core_nominal_method_source(snapshot, snapshot_file, namespace, &synthetic_def, &wrapper, kind) {
Ok(planned) => candidates.extend(planned),
Err(error) => blockers.push(format!("{namespace}/{definition} {region}[{index}]: {error}")),
}
}
if selected_rules.contains(&CORE_IDENTITY_CONVERSION_RULE) {
match plan_core_identity_conversion_source(snapshot, snapshot_file, namespace, &synthetic_def, &wrapper) {
Ok(planned) => candidates.extend(planned),
Err(error) => blockers.push(format!("{namespace}/{definition} {region}[{index}]: {error}")),
}
}
if selected_rules.contains(&CORE_ABSENCE_RULE) {
match absence::plan_source(snapshot, snapshot_file, namespace, &synthetic_def, &wrapper) {
Ok(planned) => candidates.extend(planned),
Err(error) => blockers.push(format!("{namespace}/{definition} {region}[{index}]: {error}")),
}
}
if blockers.len() > blockers_before {
region_rules.push(selected_rule);
}
for candidate in candidates {
region_rules.push(candidate.rule_id);
let Some(path) = candidate.target_path.strip_prefix(&[2]) else {
blockers.push("Compiler suggestion points outside its attached source wrapper.".to_owned());
continue;
};
match candidate.operation {
Some(FixOperation::ReplaceNode { .. }) => {
let original = fix_source_json_to_cirru(&candidate.original)?;
let replacement =
fix_source_json_to_cirru(candidate.replacement.as_ref().ok_or("Missing attached subtree replacement")?)?;
replace_attached_source_tree(source, path, &original, &replacement)?;
origins.extend(candidate.origin_chain);
origins.push(
serde_json::json!({"kind": "resolved-attached-source", "path": format_path(path), "rule_id": candidate.rule_id}),
);
}
Some(FixOperation::ReplaceLeaf { original, replacement }) => {
replace_attached_source_node(source, path, &original, &Cirru::leaf(replacement))?;
origins.extend(candidate.origin_chain);
origins.push(
serde_json::json!({"kind": "resolved-attached-source", "path": format_path(path), "rule_id": candidate.rule_id}),
);
}
None => blockers.push(candidate.message),
_ => return Err("Attached source proof produced an unsupported operation.".to_owned()),
}
}
}
}
if origins.is_empty() && blockers.is_empty() {
continue;
}
// One region-level operation may merge several rules; report the earliest one in the
// selected (preset) order, while each origin entry keeps its own `rule_id`.
let Some(rule_id) = selected_rules
.iter()
.copied()
.find(|rule| region_rules.contains(rule))
.or_else(|| region_rules.first().copied())
else {
return Err(format!(
"{namespace}/{definition} {region}: attached rewrite has no contributing rule among the selected rules."
));
};
let metadata = fix_rule_metadata(rule_id);
// Merge all alias replacements in a metadata region into one operation.
// A blocked region is never partially rewritten or used as a test oracle.
let safe = blockers.is_empty();
let replacement = if test.is_some() {
rewritten[0].clone()
} else {
Cirru::List(rewritten.clone())
};
let operation = if safe {
let code = format_quoted_nodes(&rewritten)?;
Some(match test {
Some((name, tags)) => FixOperation::ReplaceTest { name, tags, code },
None => FixOperation::ReplaceExamples { code },
})
} else {
None
};
suggestions.push(FixSuggestion {
rule_id: metadata.rule_id,
diagnostic_code: metadata.diagnostic_code,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{namespace}/{definition}"),
path: region,
fingerprint: node_fingerprint(&original),
origin_chain: origins,
original: quoted_json(&original),
replacement: safe.then(|| quoted_json(&replacement)),
applicability: if safe { "machine-applicable" } else { "requires-review" },
message: if safe {
"Apply proven source rewrites without changing assertions, tags, or argument evaluation.".to_owned()
} else {
blockers.join("; ")
},
target_path: vec![],
operation,
});
}
}
Ok(suggestions)
}
/// Whether `name` is defined in, or imported into, the namespace. An unreadable
/// ns form counts as bound so that the caller asks for review.
fn namespace_binds_name(snapshot: &Snapshot, namespace: &str, name: &str) -> bool {
let Some(file) = snapshot.files.get(namespace) else {
return true;
};
file.defs.contains_key(name)
|| program::extract_import_map(&file.ns.code, namespace).map_or(true, |imports| imports.contains_key(name))
}
/// Collect complete built-in conversion calls without entering quoted source.
fn collect_identity_conversion_calls(node: &Cirru, path: &mut Vec<usize>, calls: &mut Vec<(Vec<usize>, Vec<usize>, Vec<usize>)>) {
let Cirru::List(items) = node else {
return;
};
if matches!(items.first(), Some(Cirru::Leaf(head)) if matches!(head.as_ref(), "quote" | "quasiquote")) {
return;
}
if items.len() == 2 && matches!(items.first(), Some(Cirru::Leaf(head)) if matches!(head.as_ref(), "turn-symbol" | "turn-tag")) {
let mut head_path = path.clone();
head_path.push(0);
let mut argument_path = path.clone();
argument_path.push(1);
calls.push((path.clone(), head_path, argument_path));
}
for (index, child) in items.iter().enumerate() {
path.push(index);
collect_identity_conversion_calls(child, path, calls);
path.pop();
}
}
/// Rename resolved core conversions only when the argument proves the same conversion.
fn plan_core_identity_conversion_fixes(
snapshot: &Snapshot,
snapshot_file: &str,
selected_definitions: &[(String, String)],
) -> Result<Vec<FixSuggestion>, String> {
let mut suggestions = Vec::new();
for (namespace, definition) in selected_definitions {
select_definition_entry_context(namespace, definition);
let file = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Selected namespace `{namespace}` is missing from the source snapshot."))?;
let entry = file
.defs
.get(definition)
.ok_or_else(|| format!("Selected definition `{namespace}/{definition}` is missing from the source snapshot."))?;
suggestions.extend(plan_core_identity_conversion_source(
snapshot,
snapshot_file,
namespace,
definition,
&entry.code,
)?);
}
Ok(suggestions)
}
/// Share the existing source and receiver proof with attached executable expressions.
fn plan_core_identity_conversion_source(
snapshot: &Snapshot,
snapshot_file: &str,
namespace: &str,
definition: &str,
source: &Cirru,
) -> Result<Vec<FixSuggestion>, String> {
let mut suggestions = Vec::new();
let file = snapshot
.files
.get(namespace)
.ok_or_else(|| format!("Selected namespace `{namespace}` is missing from the source snapshot."))?;
if list_head(source) == Some("defmacro") {
return Ok(suggestions);
}
let mut calls = Vec::new();
collect_identity_conversion_calls(source, &mut Vec::new(), &mut calls);
if calls.is_empty() {
return Ok(suggestions);
}
let mut local_bindings = HashSet::new();
collect_potential_local_bindings(source, &mut local_bindings);
let compiled = program::lookup_compiled_def(namespace, definition);
let parsed = code_to_calcit(source, namespace, definition, vec![])?;
let (preprocessed, expressions) =
runner::preprocess::trace_source_expressions(&parsed, namespace, definition, &RefCell::new(Vec::new()), &CallStackList::default())
.map_err(|failure| failure.msg)?;
let usages =
runner::preprocess::trace_source_usages(&parsed, namespace, definition, &RefCell::new(Vec::new()), &CallStackList::default())
.map_err(|failure| failure.msg)?;
for (call_path, head_path, argument_path) in calls {
let head = navigate_to_path(source, &head_path)?;
let Cirru::Leaf(old_name) = &head else {
continue;
};
if local_bindings.contains(old_name.as_ref()) || file.defs.contains_key(old_name.as_ref()) {
continue;
}
let expected_proc = match old_name.as_ref() {
"turn-symbol" => CalcitProc::TurnSymbol,
"turn-tag" => CalcitProc::TurnTag,
_ => continue,
};
let parsed_head = code_to_calcit(
&head,
namespace,
definition,
head_path
.iter()
.map(|index| u16::try_from(*index).map_err(|_| format!("Path index {index} exceeds Snapshot coordinate range")))
.collect::<Result<Vec<_>, _>>()?,
)?;
if !matches!(parsed_head, Calcit::Proc(proc) if proc == expected_proc) {
continue;
}
let argument = navigate_to_path(source, &argument_path)?;
let parsed_argument = code_to_calcit(
&argument,
namespace,
definition,
argument_path
.iter()
.map(|index| u16::try_from(*index).map_err(|_| format!("Path index {index} exceeds Snapshot coordinate range")))
.collect::<Result<Vec<_>, _>>()?,
)?;
let direct_source_shape = !matches!(argument, Cirru::Leaf(_)) || !matches!(parsed_argument, Calcit::List(_));
let inferred = compiled
.as_ref()
.filter(|_| direct_source_shape)
.and_then(|compiled| {
super::query::find_preprocessed_node_at_path(
&compiled.preprocessed_code,
source,
namespace,
definition,
&argument_path,
matches!(argument, Cirru::List(_)),
)
})
.and_then(runner::preprocess::infer_static_type_from_expr)
.or_else(|| {
if !direct_source_shape {
return None;
}
super::query::find_preprocessed_node_at_path(
&preprocessed,
source,
namespace,
definition,
&argument_path,
matches!(argument, Cirru::List(_)),
)
.and_then(runner::preprocess::infer_static_type_from_expr)
})
.or_else(|| {
runner::preprocess::unique_source_expression_at_path(&expressions, namespace, definition, &argument_path)
.and_then(|item| item.inferred_type.clone())
})
.or_else(|| super::query::infer_type_at_target(&parsed_argument, None));
let resolved = inferred
.as_ref()
.map(|annotation| runner::preprocess::resolve_namespace_type_refs_for_body(annotation.clone(), namespace));
let proven_argument = resolved
.as_ref()
.is_some_and(|annotation| matches!(annotation.as_ref(), CalcitTypeAnnotation::String));
if resolved.as_ref().is_some_and(|annotation| {
!proven_argument
&& !matches!(
annotation.as_ref(),
CalcitTypeAnnotation::Dynamic | CalcitTypeAnnotation::TypeVar(_)
)
}) {
continue;
}
let argument_crosses_macro = usages.iter().any(|usage| {
let Some(location) = &usage.location else {
return false;
};
location.ns.as_ref() == namespace
&& location.def.as_ref() == definition
&& location.coord.len() > argument_path.len()
&& location
.coord
.iter()
.map(|index| usize::from(*index))
.zip(argument_path.iter().copied())
.all(|(index, expected)| index == expected)
&& (!usage.macro_origin.is_empty()
|| matches!(
program::lookup_compiled_def(&usage.target_ns, &usage.target_def).map(|compiled| compiled.kind),
Some(program::CompiledDefKind::Macro)
))
});
let machine_applicable =
proven_argument && !argument_crosses_macro && method_source_context_is_stable(source, &call_path, namespace, definition, &usages);
let new_name = match expected_proc {
CalcitProc::TurnTag => "to-tag",
CalcitProc::TurnSymbol => "to-symbol",
_ => unreachable!("only supported conversions are collected"),
};
let replacement = format!("calcit.core/{new_name}");
let replacement_node = Cirru::leaf(replacement.as_str());
suggestions.push(FixSuggestion {
rule_id: CORE_IDENTITY_CONVERSION_RULE,
diagnostic_code: CORE_IDENTITY_CONVERSION_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{namespace}/{definition}"),
path: format!("code{}", format_path(&head_path)),
fingerprint: node_fingerprint(&head),
origin_chain: vec![serde_json::json!({
"kind": "resolved-core-conversion-and-argument-type",
"old_proc": old_name.as_ref(),
"argument_type": inferred.as_ref().map(|annotation| annotation.describe()),
"target": format!("calcit.core/{new_name}"),
})],
original: quoted_json(&head),
replacement: machine_applicable.then(|| quoted_json(&replacement_node)),
applicability: if machine_applicable {
"machine-applicable"
} else {
"requires-review"
},
message: if machine_applicable {
format!("Use `{new_name}` for a proven built-in argument; both paths call the same conversion once.")
} else if argument_crosses_macro {
format!("The argument to `{old_name}` crosses macro expansion; review this conversion manually.")
} else {
format!("Cannot prove an equivalent argument and stable source context for `{old_name}`; review this conversion manually.")
},
target_path: head_path,
operation: machine_applicable.then_some(FixOperation::ReplaceLeaf {
original: old_name.to_string(),
replacement,
}),
});
}
Ok(suggestions)
}
/// Allow evaluated call arguments only when the reader or resolver proves their enclosing call is not an unknown macro.
fn method_source_context_is_stable(
code: &Cirru,
call_path: &[usize],
namespace: &str,
definition: &str,
usages: &[runner::preprocess::ResolvedSourceUsage],
) -> bool {
(0..call_path.len()).all(|depth| {
let Ok(Cirru::List(items)) = navigate_to_path(code, &call_path[..depth]) else {
return false;
};
let Some(head) = items.first() else {
return false;
};
if matches!(head, Cirru::Leaf(head) if matches!(head.as_ref(), "defn" | "defwasm-export" | "fn" | "let" | "let[]" | "do" | "if" | "cond")) {
return true;
}
if matches!(
code_to_calcit(head, namespace, definition, Vec::new()),
Ok(Calcit::Proc(..) | Calcit::Method(..))
) {
return true;
}
let mut head_path = call_path[..depth].to_vec();
head_path.push(0);
let matching = usages
.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(head_path.iter().copied())
})
})
.collect::<Vec<_>>();
!matching.is_empty()
&& matching.iter().all(|usage| {
usage
.macro_origin
.iter()
.all(|origin| preserves_nominal_method_call_through_macro(origin))
&& (matches!(
program::lookup_compiled_def(&usage.target_ns, &usage.target_def).map(|compiled| compiled.kind),
Some(program::CompiledDefKind::Fn | program::CompiledDefKind::Proc)
) || preserves_nominal_method_call_through_macro(&format!("{}/{}", usage.target_ns, usage.target_def)))
})
})
}
/// Reuse structural body rules, checking actual attached coordinates rather than the synthetic function body.
fn plan_attached_do_rewrite(
source: &Cirru,
namespace: &str,
definition: &str,
rule: &str,
) -> Result<Option<AttachedSourceRewrite>, String> {
let mut paths = Vec::new();
if rule == REDUNDANT_DO_RULE {
collect_redundant_do_paths(source, &mut Vec::new(), &mut paths);
} else {
collect_single_expression_do_paths(source, &mut Vec::new(), &mut paths);
}
if paths.is_empty() {
return Ok(None);
}
let wrapper = Cirru::List(vec![Cirru::leaf("fn"), Cirru::List(vec![]), source.clone()]);
let parsed = code_to_calcit(&wrapper, namespace, definition, vec![])?;
let usages =
runner::preprocess::trace_source_usages(&parsed, namespace, definition, &RefCell::new(Vec::new()), &CallStackList::default())
.map_err(|error| error.msg)?;
for path in &paths {
let mut wrapper_path = vec![2];
wrapper_path.extend(path);
if !method_source_context_is_stable(&wrapper, &wrapper_path, namespace, definition, &usages) {
return Err(format!(
"Cannot prove stable executable context for `do` at {}; preserve the metadata region for review.",
format_path(path)
));
}
}
// Redundant wrappers are spliced by their actual enclosing body. A root multi-expression do has no such parent.
let mut targets = if rule == REDUNDANT_DO_RULE {
paths.iter().map(|path| path[..path.len() - 1].to_vec()).collect::<Vec<_>>()
} else {
paths.clone()
};
targets.sort_by(|left, right| right.cmp(left));
targets.dedup();
let mut rewritten = source.clone();
for path in targets {
let original = navigate_to_path(&rewritten, &path)?;
let replacement = if rule == REDUNDANT_DO_RULE {
splice_redundant_do_children(original.clone())
} else {
unwrap_single_expression_do(original.clone())
};
replace_attached_source_tree(&mut rewritten, &path, &original, &replacement)?;
}
Ok(Some(AttachedSourceRewrite {
code: rewritten,
origin_chain: paths
.into_iter()
.map(|path| serde_json::json!({"kind": "resolved-attached-source", "path": format_path(&path), "rule_id": rule}))
.collect(),
}))
}
/// Build structural splice suggestions for redundant `do` wrappers in proven variadic bodies.
fn plan_redundant_do_fixes(
snapshot: &Snapshot,
snapshot_file: &str,
selected_definitions: &[(String, String)],
excluded_regions: &[(String, Vec<usize>)],
) -> Result<Vec<FixSuggestion>, String> {
let mut suggestions = Vec::new();
for (namespace, definition) in selected_definitions {
select_definition_entry_context(namespace, definition);
let entry = snapshot
.files
.get(namespace)
.and_then(|file| file.defs.get(definition))
.ok_or_else(|| format!("Selected definition `{namespace}/{definition}` is missing from the source snapshot."))?;
let mut paths = Vec::new();
collect_redundant_do_paths(&entry.code, &mut Vec::new(), &mut paths);
let target_definition = format!("{namespace}/{definition}");
paths.retain(|path| {
!excluded_regions
.iter()
.any(|(region_definition, region_path)| region_definition == &target_definition && path.starts_with(region_path))
});
paths.sort_by(|left, right| right.cmp(left));
for target_path in paths {
let original_node = navigate_to_path(&entry.code, &target_path)?;
let Cirru::List(ref items) = original_node else {
continue;
};
let replacement_items = items.iter().skip(1).map(cirru_to_json_value).collect::<Vec<_>>();
suggestions.push(FixSuggestion {
rule_id: REDUNDANT_DO_RULE,
diagnostic_code: REDUNDANT_DO_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: target_definition.clone(),
path: format!("code{}", format_path(&target_path)),
fingerprint: node_fingerprint(&original_node),
origin_chain: vec![],
original: quoted_json(&original_node),
replacement: Some(serde_json::json!({
"$type": "splice",
"value": replacement_items,
})),
applicability: "machine-applicable",
message: "Splice a redundant `do` into the surrounding variadic body; sequencing and the final-value type are unchanged."
.to_owned(),
target_path,
operation: Some(FixOperation::SpliceDo),
});
}
}
Ok(suggestions)
}
/// Remove `hint-fn` forms the compiler found repeating their callback
/// context (#2636). The compiled selection records each site; a site counts
/// only when its source node still is that `hint-fn` list.
fn plan_redundant_hint_fn_fixes(
snapshot: &Snapshot,
snapshot_file: &str,
selected_definitions: &[(String, String)],
) -> Result<Vec<FixSuggestion>, String> {
let selected: HashSet<(&str, &str)> = selected_definitions
.iter()
.map(|(namespace, definition)| (namespace.as_str(), definition.as_str()))
.collect();
let mut sites = runner::preprocess::redundant_hint_sites();
// Later siblings first, so earlier deletions keep the remaining paths valid.
sites.sort_by(|left, right| (&left.ns, &left.def, &right.coord).cmp(&(&right.ns, &right.def, &left.coord)));
let mut suggestions = Vec::new();
for site in sites {
if !selected.contains(&(site.ns.as_str(), site.def.as_str())) {
continue;
}
let Some(entry) = snapshot.files.get(&site.ns).and_then(|file| file.defs.get(&site.def)) else {
continue;
};
let target_path: Vec<usize> = site.coord.iter().map(|index| usize::from(*index)).collect();
let Ok(node) = navigate_to_path(&entry.code, &target_path) else {
continue;
};
if list_head(&node) != Some("hint-fn") {
continue;
}
let original = node
.format_one_liner()
.map_err(|error| format!("Failed to format hint-fn source at {}/{}: {error}", site.ns, site.def))?;
suggestions.push(FixSuggestion {
rule_id: REDUNDANT_HINT_FN_RULE,
diagnostic_code: REDUNDANT_HINT_FN_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{}/{}", site.ns, site.def),
path: format!("code{}", format_path(&target_path)),
fingerprint: node_fingerprint(&node),
origin_chain: vec![serde_json::json!({"kind": "compiled-callback-context"})],
original: quoted_json(&node),
replacement: None,
applicability: "machine-applicable",
message: "Remove a `hint-fn` that repeats the signature the callback already receives from its call context; the checked types are unchanged."
.to_owned(),
target_path,
operation: Some(FixOperation::DeleteNode { original }),
});
}
Ok(suggestions)
}
/// Collect source paths in evaluation order while treating quoted trees as data.
fn collect_redundant_do_paths(node: &Cirru, path: &mut Vec<usize>, output: &mut Vec<Vec<usize>>) {
let Cirru::List(items) = node else {
return;
};
let head = items.first().and_then(|item| match item {
Cirru::Leaf(value) => Some(value.as_ref()),
Cirru::List(_) => None,
});
if matches!(head, Some("quote" | "quasiquote")) {
return;
}
let body_start = match head {
Some("defn") => Some(3),
Some("fn" | "let") => Some(2),
Some("let[]" | "let{}") => Some(3),
Some("do") => Some(1),
_ => None,
};
if let Some(body_start) = body_start {
for (index, child) in items.iter().enumerate().skip(body_start) {
if matches!(child, Cirru::List(children) if children.len() > 1 && matches!(children.first(), Some(Cirru::Leaf(head)) if head.as_ref() == "do"))
{
let mut target = path.clone();
target.push(index);
output.push(target);
}
}
}
for (index, child) in items.iter().enumerate() {
path.push(index);
collect_redundant_do_paths(child, path, output);
path.pop();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NilExprPosition {
Discarded,
UnitTail,
Value,
}
impl NilExprPosition {
fn allows_unit_rewrite(self) -> bool {
matches!(self, Self::Discarded | Self::UnitTail)
}
}
struct LegacyCommentNilCandidate {
path: Vec<usize>,
arg_count: usize,
position: NilExprPosition,
inside_unproven_macro: bool,
}
fn is_comment_form(node: &Cirru) -> bool {
matches!(
node,
Cirru::List(items) if matches!(items.first().and_then(leaf_value), Some(";" | "calcit.core/;"))
)
}
fn last_executable_index(items: &[Cirru], start: usize) -> Option<usize> {
(start..items.len()).rev().find(|&idx| !is_comment_form(&items[idx]))
}
fn collect_nil_fix_binding_names(node: &Cirru, target: &mut HashSet<String>) {
match node {
Cirru::Leaf(name) => {
let name = name.as_ref();
if !matches!(name, "&" | "?" | "[]" | "{}") && !name.starts_with([':', '|', '"', '\'']) {
target.insert(name.to_owned());
}
}
Cirru::List(items) => {
for item in items {
collect_nil_fix_binding_names(item, target);
}
}
}
}
fn resolve_fix_core_head<'a>(head: Option<&'a str>, shadowed: &HashSet<String>) -> Option<&'a str> {
let name = head?;
if let Some(qualified) = name.strip_prefix("calcit.core/") {
Some(qualified)
} else if name.contains('/') || shadowed.contains(name) {
None
} else {
Some(name)
}
}
fn namespace_shadowed_names(snapshot: &Snapshot, namespace: &str) -> Result<HashSet<String>, String> {
let mut shadowed = HashSet::new();
let Some(file) = snapshot.files.get(namespace) else {
return Ok(shadowed);
};
shadowed.extend(file.defs.keys().cloned());
let imports = program::extract_import_map(&file.ns.code, namespace)?;
for (local, rule) in imports {
let aliases_same_core = matches!(
rule.as_ref(),
program::ImportRule::NsReferDef(ns, def)
if ns.as_ref() == calcit_core::calcit::CORE_NS && def.as_ref() == local.as_ref()
);
if !aliases_same_core {
shadowed.insert(local.to_string());
}
}
Ok(shadowed)
}
#[allow(clippy::too_many_arguments)]
fn collect_legacy_comment_nil_paths(
node: &Cirru,
path: &mut Vec<usize>,
position: NilExprPosition,
root_returns_unit: bool,
allow_rewrite: bool,
shadowed: &HashSet<String>,
local_shadowed: &HashSet<String>,
is_macro_head: &mut impl FnMut(&str) -> bool,
output: &mut Vec<LegacyCommentNilCandidate>,
) {
let Cirru::List(items) = node else {
return;
};
let head = items.first().and_then(leaf_value);
let core_head = resolve_fix_core_head(head, shadowed);
match core_head {
Some("quote" | "quasiquote" | "cirru-quote" | "defmacro" | ";") => (),
Some(";nil") => {
output.push(LegacyCommentNilCandidate {
path: path.clone(),
arg_count: items.len().saturating_sub(1),
position,
inside_unproven_macro: !allow_rewrite,
});
}
Some("do") => {
let last_exec = last_executable_index(items, 1);
for (index, child) in items.iter().enumerate().skip(1) {
if is_comment_form(child) {
continue;
}
let child_pos = if Some(index) < last_exec {
NilExprPosition::Discarded
} else {
position
};
path.push(index);
collect_legacy_comment_nil_paths(
child,
path,
child_pos,
root_returns_unit,
allow_rewrite,
shadowed,
local_shadowed,
is_macro_head,
output,
);
path.pop();
}
}
Some("let") => {
let mut inner_shadowed = shadowed.clone();
let mut inner_local_shadowed = local_shadowed.clone();
if let Some(Cirru::List(bindings)) = items.get(1) {
for (bind_idx, binding) in bindings.iter().enumerate() {
if let Cirru::List(pair) = binding
&& let Some(value) = pair.get(1)
{
path.push(1);
path.push(bind_idx);
path.push(1);
collect_legacy_comment_nil_paths(
value,
path,
NilExprPosition::Value,
root_returns_unit,
allow_rewrite,
&inner_shadowed,
&inner_local_shadowed,
is_macro_head,
output,
);
path.pop();
path.pop();
path.pop();
}
if let Cirru::List(pair) = binding
&& let Some(binder) = pair.first()
{
collect_nil_fix_binding_names(binder, &mut inner_shadowed);
collect_nil_fix_binding_names(binder, &mut inner_local_shadowed);
}
}
}
let last_exec = last_executable_index(items, 2);
for (index, child) in items.iter().enumerate().skip(2) {
if is_comment_form(child) {
continue;
}
let child_pos = if Some(index) < last_exec {
NilExprPosition::Discarded
} else {
position
};
path.push(index);
collect_legacy_comment_nil_paths(
child,
path,
child_pos,
root_returns_unit,
allow_rewrite,
&inner_shadowed,
&inner_local_shadowed,
is_macro_head,
output,
);
path.pop();
}
}
Some("&let") => {
let mut inner_shadowed = shadowed.clone();
let mut inner_local_shadowed = local_shadowed.clone();
if let Some(Cirru::List(pair)) = items.get(1) {
if let Some(value) = pair.get(1) {
path.push(1);
path.push(1);
collect_legacy_comment_nil_paths(
value,
path,
NilExprPosition::Value,
root_returns_unit,
allow_rewrite,
shadowed,
local_shadowed,
is_macro_head,
output,
);
path.pop();
path.pop();
}
if let Some(binder) = pair.first() {
collect_nil_fix_binding_names(binder, &mut inner_shadowed);
collect_nil_fix_binding_names(binder, &mut inner_local_shadowed);
}
}
let last_exec = last_executable_index(items, 2);
for (index, child) in items.iter().enumerate().skip(2) {
if is_comment_form(child) {
continue;
}
let child_pos = if Some(index) < last_exec {
NilExprPosition::Discarded
} else {
position
};
path.push(index);
collect_legacy_comment_nil_paths(
child,
path,
child_pos,
root_returns_unit,
allow_rewrite,
&inner_shadowed,
&inner_local_shadowed,
is_macro_head,
output,
);
path.pop();
}
}
Some("let[]" | "let{}") => {
if let Some(value) = items.get(2)
&& !is_comment_form(value)
{
path.push(2);
collect_legacy_comment_nil_paths(
value,
path,
NilExprPosition::Value,
root_returns_unit,
allow_rewrite,
shadowed,
local_shadowed,
is_macro_head,
output,
);
path.pop();
}
let mut inner_shadowed = shadowed.clone();
let mut inner_local_shadowed = local_shadowed.clone();
if let Some(binding_pattern) = items.get(1) {
collect_nil_fix_binding_names(binding_pattern, &mut inner_shadowed);
collect_nil_fix_binding_names(binding_pattern, &mut inner_local_shadowed);
}
let last_exec = last_executable_index(items, 3);
for (index, child) in items.iter().enumerate().skip(3) {
if is_comment_form(child) {
continue;
}
let child_pos = if Some(index) < last_exec {
NilExprPosition::Discarded
} else {
position
};
path.push(index);
collect_legacy_comment_nil_paths(
child,
path,
child_pos,
root_returns_unit,
allow_rewrite,
&inner_shadowed,
&inner_local_shadowed,
is_macro_head,
output,
);
path.pop();
}
}
Some("defn") => {
let mut inner_shadowed = shadowed.clone();
let mut inner_local_shadowed = local_shadowed.clone();
if let Some(params) = items.get(2) {
collect_nil_fix_binding_names(params, &mut inner_shadowed);
collect_nil_fix_binding_names(params, &mut inner_local_shadowed);
}
let last_exec = last_executable_index(items, 3);
for (index, child) in items.iter().enumerate().skip(3) {
if is_comment_form(child) {
continue;
}
let child_pos = if Some(index) < last_exec {
NilExprPosition::Discarded
} else if path.is_empty() && root_returns_unit {
NilExprPosition::UnitTail
} else {
NilExprPosition::Value
};
path.push(index);
collect_legacy_comment_nil_paths(
child,
path,
child_pos,
root_returns_unit,
allow_rewrite,
&inner_shadowed,
&inner_local_shadowed,
is_macro_head,
output,
);
path.pop();
}
}
Some("fn") => {
let mut inner_shadowed = shadowed.clone();
let mut inner_local_shadowed = local_shadowed.clone();
if let Some(params) = items.get(1) {
collect_nil_fix_binding_names(params, &mut inner_shadowed);
collect_nil_fix_binding_names(params, &mut inner_local_shadowed);
}
let last_exec = last_executable_index(items, 2);
for (index, child) in items.iter().enumerate().skip(2) {
if is_comment_form(child) {
continue;
}
let child_pos = if Some(index) < last_exec {
NilExprPosition::Discarded
} else {
NilExprPosition::Value
};
path.push(index);
collect_legacy_comment_nil_paths(
child,
path,
child_pos,
root_returns_unit,
allow_rewrite,
&inner_shadowed,
&inner_local_shadowed,
is_macro_head,
output,
);
path.pop();
}
}
Some("when" | "when-not") => {
let mut args = items.iter().enumerate().skip(1).filter(|(_, child)| !is_comment_form(child));
if let Some((cond_idx, cond)) = args.next() {
path.push(cond_idx);
collect_legacy_comment_nil_paths(
cond,
path,
NilExprPosition::Value,
root_returns_unit,
allow_rewrite,
shadowed,
local_shadowed,
is_macro_head,
output,
);
path.pop();
}
for (index, child) in args {
path.push(index);
collect_legacy_comment_nil_paths(
child,
path,
NilExprPosition::Discarded,
root_returns_unit,
allow_rewrite,
shadowed,
local_shadowed,
is_macro_head,
output,
);
path.pop();
}
}
Some("if") => {
let exec_args: Vec<(usize, &Cirru)> = items
.iter()
.enumerate()
.skip(1)
.filter(|(_, child)| !is_comment_form(child))
.collect();
for (arg_pos, (index, branch)) in exec_args.into_iter().enumerate() {
let branch_pos = if arg_pos == 1 || arg_pos == 2 {
position
} else {
NilExprPosition::Value
};
path.push(index);
collect_legacy_comment_nil_paths(
branch,
path,
branch_pos,
root_returns_unit,
allow_rewrite,
shadowed,
local_shadowed,
is_macro_head,
output,
);
path.pop();
}
}
Some("if-not") => {
let exec_args: Vec<(usize, &Cirru)> = items
.iter()
.enumerate()
.skip(1)
.filter(|(_, child)| !is_comment_form(child))
.collect();
let two_arg = exec_args.len() == 2;
for (arg_pos, (index, branch)) in exec_args.into_iter().enumerate() {
let branch_pos = if arg_pos == 0 {
NilExprPosition::Value
} else if two_arg && arg_pos == 1 {
NilExprPosition::Discarded
} else if arg_pos <= 2 {
position
} else {
NilExprPosition::Value
};
path.push(index);
collect_legacy_comment_nil_paths(
branch,
path,
branch_pos,
root_returns_unit,
allow_rewrite,
shadowed,
local_shadowed,
is_macro_head,
output,
);
path.pop();
}
}
Some("if-let") => {
let mut then_shadowed = shadowed.clone();
let mut then_local_shadowed = local_shadowed.clone();
if let Some(Cirru::List(pair)) = items.get(1) {
if let Some(value) = pair.get(1) {
path.push(1);
path.push(1);
collect_legacy_comment_nil_paths(
value,
path,
NilExprPosition::Value,
root_returns_unit,
allow_rewrite,
shadowed,
local_shadowed,
is_macro_head,
output,
);
path.pop();
path.pop();
}
if let Some(binder) = pair.first() {
collect_nil_fix_binding_names(binder, &mut then_shadowed);
collect_nil_fix_binding_names(binder, &mut then_local_shadowed);
}
}
let exec_branches: Vec<(usize, &Cirru)> = items
.iter()
.enumerate()
.skip(2)
.filter(|(_, child)| !is_comment_form(child))
.collect();
let two_arg = exec_branches.len() == 1;
for (branch_idx, (index, branch)) in exec_branches.into_iter().enumerate() {
let (branch_pos, branch_shadowed, branch_local_shadowed) = if branch_idx == 0 {
(
if two_arg { NilExprPosition::Discarded } else { position },
&then_shadowed,
&then_local_shadowed,
)
} else if branch_idx == 1 {
(position, shadowed, local_shadowed)
} else {
(NilExprPosition::Value, shadowed, local_shadowed)
};
path.push(index);
collect_legacy_comment_nil_paths(
branch,
path,
branch_pos,
root_returns_unit,
allow_rewrite,
branch_shadowed,
branch_local_shadowed,
is_macro_head,
output,
);
path.pop();
}
}
Some("cond") => {
for (clause_idx, clause) in items.iter().enumerate().skip(1) {
if is_comment_form(clause) {
continue;
}
let Cirru::List(pair) = clause else {
continue;
};
path.push(clause_idx);
for (item_idx, item) in pair.iter().enumerate() {
if is_comment_form(item) {
continue;
}
let item_pos = if item_idx == 1 { position } else { NilExprPosition::Value };
path.push(item_idx);
collect_legacy_comment_nil_paths(
item,
path,
item_pos,
root_returns_unit,
allow_rewrite,
shadowed,
local_shadowed,
is_macro_head,
output,
);
path.pop();
}
path.pop();
}
}
Some("match") => {
if let Some(scrutinee) = items.get(1)
&& !is_comment_form(scrutinee)
{
path.push(1);
collect_legacy_comment_nil_paths(
scrutinee,
path,
NilExprPosition::Value,
root_returns_unit,
allow_rewrite,
shadowed,
local_shadowed,
is_macro_head,
output,
);
path.pop();
}
for (clause_idx, clause) in items.iter().enumerate().skip(2) {
if is_comment_form(clause) {
continue;
}
let Cirru::List(clause_items) = clause else {
continue;
};
let mut clause_shadowed = shadowed.clone();
let mut clause_local_shadowed = local_shadowed.clone();
if let Some(pattern) = clause_items.first() {
collect_nil_fix_binding_names(pattern, &mut clause_shadowed);
collect_nil_fix_binding_names(pattern, &mut clause_local_shadowed);
}
let last_exec = last_executable_index(clause_items, 1);
path.push(clause_idx);
for (expr_idx, expr) in clause_items.iter().enumerate().skip(1) {
if is_comment_form(expr) {
continue;
}
let expr_pos = if Some(expr_idx) < last_exec {
NilExprPosition::Discarded
} else {
position
};
path.push(expr_idx);
collect_legacy_comment_nil_paths(
expr,
path,
expr_pos,
root_returns_unit,
allow_rewrite,
&clause_shadowed,
&clause_local_shadowed,
is_macro_head,
output,
);
path.pop();
}
path.pop();
}
}
_ => {
// Unknown macros can rewrite or quote arguments such as `(capture (do (;nil) 1))`.
// Retain nested candidates for review instead of authorizing auto-rewrites across macro boundaries.
let child_allow_rewrite = if let Some(head_name) = head
&& !local_shadowed.contains(head_name)
&& is_macro_head(head_name)
{
false
} else {
allow_rewrite
};
for (index, child) in items.iter().enumerate() {
if is_comment_form(child) {
continue;
}
path.push(index);
collect_legacy_comment_nil_paths(
child,
path,
NilExprPosition::Value,
root_returns_unit,
child_allow_rewrite,
shadowed,
local_shadowed,
is_macro_head,
output,
);
path.pop();
}
}
}
}
/// Replace empty `(;nil)` forms with `&unit` only in provably discarded or `Unit`-tail positions.
fn plan_legacy_comment_nil_fixes(
snapshot: &Snapshot,
snapshot_file: &str,
selected_definitions: &[(String, String)],
) -> Result<Vec<FixSuggestion>, String> {
let mut suggestions = Vec::new();
let unit_leaf = Cirru::leaf("&unit");
let mut macro_head_cache = std::collections::HashMap::<(String, String), bool>::new();
for (namespace, definition) in selected_definitions {
select_definition_entry_context(namespace, definition);
let entry = snapshot
.files
.get(namespace)
.and_then(|file| file.defs.get(definition))
.ok_or_else(|| format!("Selected definition `{namespace}/{definition}` is missing from the source snapshot."))?;
let root_returns_unit = matches!(
entry.schema.as_ref(),
CalcitTypeAnnotation::Fn(fn_annot) if matches!(fn_annot.return_type.as_ref(), CalcitTypeAnnotation::Unit)
);
let namespace_shadowed = namespace_shadowed_names(snapshot, namespace)?;
let local_shadowed = HashSet::new();
let mut is_macro_head = |head: &str| {
let key = (namespace.clone(), head.to_owned());
*macro_head_cache
.entry(key)
.or_insert_with(|| super::edit::definition_head_is_macro(snapshot_file, snapshot, namespace, head).unwrap_or(true))
};
let mut candidates = Vec::new();
collect_legacy_comment_nil_paths(
&entry.code,
&mut Vec::new(),
NilExprPosition::Value,
root_returns_unit,
true,
&namespace_shadowed,
&local_shadowed,
&mut is_macro_head,
&mut candidates,
);
candidates.sort_by(|left, right| right.path.cmp(&left.path));
let target_definition = format!("{namespace}/{definition}");
for candidate in candidates {
let original_node = navigate_to_path(&entry.code, &candidate.path)?;
let safe_rewrite = !candidate.inside_unproven_macro && candidate.arg_count == 0 && candidate.position.allows_unit_rewrite();
let operation = if safe_rewrite {
Some(FixOperation::ReplaceNodeWithLeaf {
original_json_ast: cirru_to_json_value(&original_node).to_string(),
replacement_leaf: "&unit".to_owned(),
})
} else {
None
};
let message = if safe_rewrite {
match candidate.position {
NilExprPosition::Discarded => {
"Replace empty `(;nil)` in a discarded statement position with `&unit`; control flow and result values are unchanged."
.to_owned()
}
NilExprPosition::UnitTail => {
"Replace empty `(;nil)` in a `Fn ... (-> Unit)` tail position with `&unit` so the implementation satisfies its `Unit` contract."
.to_owned()
}
NilExprPosition::Value => unreachable!("checked allows_unit_rewrite"),
}
} else if candidate.inside_unproven_macro {
"Cannot auto-rewrite `(;nil)` inside a macro call boundary because macro expansion may quote or consume its form; review the macro expansion and migrate manually."
.to_owned()
} else if candidate.arg_count > 0 {
"Cannot auto-rewrite `(;nil …)` carrying ignored comment/expression arguments; review whether to convert arguments to `;` comments and use `&unit` or `Option :none`."
.to_owned()
} else {
"Cannot prove `(;nil)` return value is discarded; choose `&unit` (if unused) or `Option :none` (if modeling absence)."
.to_owned()
};
suggestions.push(FixSuggestion {
rule_id: LEGACY_COMMENT_NIL_RULE,
diagnostic_code: LEGACY_COMMENT_NIL_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: target_definition.clone(),
path: format!("code{}", format_path(&candidate.path)),
fingerprint: node_fingerprint(&original_node),
origin_chain: vec![serde_json::json!({
"kind": if safe_rewrite { "proven-discarded-comment-nil" } else { "unproven-comment-nil" },
"position": match candidate.position {
NilExprPosition::Discarded => "discarded",
NilExprPosition::UnitTail => "unit-tail",
NilExprPosition::Value => "value",
},
"arg_count": candidate.arg_count,
})],
original: quoted_json(&original_node),
replacement: safe_rewrite.then(|| quoted_json(&unit_leaf)),
applicability: if safe_rewrite { "machine-applicable" } else { "requires-review" },
message,
target_path: candidate.path,
operation,
});
}
}
Ok(suggestions)
}
/// Build unwrap suggestions for `do` forms whose single payload already is one expression.
fn plan_single_expression_do_fixes(
snapshot: &Snapshot,
snapshot_file: &str,
selected_definitions: &[(String, String)],
composed_regions: &[(String, Vec<usize>)],
redundant_do_regions: &[(String, Vec<usize>)],
) -> Result<Vec<FixSuggestion>, String> {
let mut suggestions = Vec::new();
for (namespace, definition) in selected_definitions {
select_definition_entry_context(namespace, definition);
let entry = snapshot
.files
.get(namespace)
.and_then(|file| file.defs.get(definition))
.ok_or_else(|| format!("Selected definition `{namespace}/{definition}` is missing from the source snapshot."))?;
let mut paths = Vec::new();
collect_single_expression_do_paths(&entry.code, &mut Vec::new(), &mut paths);
let target_definition = format!("{namespace}/{definition}");
paths.retain(|path| {
!composed_regions
.iter()
.any(|(region_definition, region_path)| region_definition == &target_definition && path.starts_with(region_path))
&& !redundant_do_regions
.iter()
.any(|(region_definition, region_path)| region_definition == &target_definition && path == region_path)
});
paths.sort_by(|left, right| right.cmp(left));
for target_path in paths {
let original_node = navigate_to_path(&entry.code, &target_path)?;
let Cirru::List(items) = &original_node else {
continue;
};
let Some(replacement_node) = items.get(1) else {
continue;
};
suggestions.push(FixSuggestion {
rule_id: SINGLE_EXPRESSION_DO_RULE,
diagnostic_code: SINGLE_EXPRESSION_DO_DIAGNOSTIC,
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: target_definition.clone(),
path: format!("code{}", format_path(&target_path)),
fingerprint: node_fingerprint(&original_node),
origin_chain: vec![],
original: quoted_json(&original_node),
replacement: Some(quoted_json(replacement_node)),
applicability: "machine-applicable",
message: "Unwrap a single-expression `do`; evaluation count, order, failure behavior, and result type are unchanged."
.to_owned(),
target_path,
operation: Some(FixOperation::SpliceDo),
});
}
}
Ok(suggestions)
}
/// Collect executable `(do expression)` paths while preserving macro and quoted data boundaries.
fn collect_single_expression_do_paths(node: &Cirru, path: &mut Vec<usize>, output: &mut Vec<Vec<usize>>) {
let Cirru::List(items) = node else {
return;
};
let head = items.first().and_then(leaf_value);
if matches!(head, Some("quote" | "quasiquote" | "defmacro")) {
return;
}
if head == Some("do") && items.len() == 2 {
output.push(path.clone());
}
for (index, child) in items.iter().enumerate() {
path.push(index);
collect_single_expression_do_paths(child, path, output);
path.pop();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NominalKind {
Enum,
Struct,
}
impl NominalKind {
fn definition_head(self) -> &'static str {
match self {
Self::Enum => "defenum",
Self::Struct => "defstruct",
}
}
fn legacy_head(self) -> &'static str {
match self {
Self::Enum => "%::",
Self::Struct => "%{}",
}
}
fn rule_id(self) -> &'static str {
match self {
Self::Enum => NAMED_ENUM_CONSTRUCTOR_RULE,
Self::Struct => NAMED_STRUCT_CONSTRUCTOR_RULE,
}
}
fn diagnostic_code(self) -> &'static str {
match self {
Self::Enum => NAMED_ENUM_CONSTRUCTOR_DIAGNOSTIC,
Self::Struct => NAMED_STRUCT_CONSTRUCTOR_DIAGNOSTIC,
}
}
fn display_name(self) -> &'static str {
match self {
Self::Enum => "enum",
Self::Struct => "struct",
}
}
}
/// Rewrite legacy prototype constructors only when the prototype resolves to a project nominal definition.
fn plan_named_constructor_fixes(
snapshot: &Snapshot,
snapshot_file: &str,
selected_definitions: &[(String, String)],
kinds: &[NominalKind],
compose_redundant_do: bool,
compose_single_expression_do: bool,
) -> Result<Vec<FixSuggestion>, String> {
let mut suggestions = Vec::new();
for (namespace, definition) in selected_definitions {
select_definition_entry_context(namespace, definition);
let entry = snapshot
.files
.get(namespace)
.and_then(|file| file.defs.get(definition))
.ok_or_else(|| format!("Selected definition `{namespace}/{definition}` is missing from the source snapshot."))?;
suggestions.extend(plan_named_constructor_source(
snapshot,
snapshot_file,
(namespace, definition),
&entry.code,
kinds,
(compose_redundant_do, compose_single_expression_do),
)?);
}
Ok(suggestions)
}
/// Share nominal resolution and field completeness with source-origin checks for attached constructors.
///
/// Constructors in executable code are proven by the compiler usage trace. A quasiquote template is
/// not compiled until each expansion, so a template constructor is proven statically instead: its
/// namespace-qualified prototype resolves through the macro namespace, the same way the expanded
/// symbol resolves at every expansion site. An unqualified template prototype can be captured by a
/// local at an expansion site, so it is reported for review.
fn plan_named_constructor_source(
snapshot: &Snapshot,
snapshot_file: &str,
owner: (&str, &str),
source: &Cirru,
kinds: &[NominalKind],
compose_do: (bool, bool),
) -> Result<Vec<FixSuggestion>, String> {
let (namespace, definition) = owner;
let (compose_redundant_do, compose_single_expression_do) = compose_do;
let mut suggestions = Vec::new();
let mut shadowed = HashSet::new();
collect_potential_local_bindings(source, &mut shadowed);
let scope = ConstructorScope {
snapshot,
namespace,
shadowed: &shadowed,
kinds,
macro_body: list_head(source) == Some("defmacro"),
};
let mut paths = Vec::new();
collect_named_constructor_paths(source, &mut Vec::new(), 0, &mut paths, &scope);
paths.sort();
if paths.is_empty() {
return Ok(suggestions);
}
let usages = if paths.iter().any(|(_, depth)| *depth == 0) {
let parsed = code_to_calcit(source, namespace, definition, vec![])?;
runner::preprocess::trace_source_usages(&parsed, namespace, definition, &RefCell::new(Vec::new()), &CallStackList::default())
.map_err(|error| error.msg)?
} else {
Vec::new()
};
let all_paths = paths;
let targets = all_paths
.iter()
.filter(|(path, _)| {
!all_paths
.iter()
.any(|(other, _)| other.len() < path.len() && path.starts_with(other))
})
.cloned()
.collect::<Vec<_>>();
for (target_path, target_depth) in targets {
let original_node = navigate_to_path(source, &target_path)?;
let Cirru::List(items) = &original_node else {
continue;
};
let Some(kind) = scope.legacy_kind(items) else {
continue;
};
let nested = all_paths
.iter()
.filter(|(path, _)| path.starts_with(&target_path))
.collect::<Vec<_>>();
let unqualified_template = nested.iter().any(|(path, depth)| {
*depth == 1
&& navigate_to_path(source, path)
.ok()
.and_then(|node| match node {
Cirru::List(parts) => parts.get(1).and_then(leaf_value).map(|prototype| !prototype.contains('/')),
Cirru::Leaf(_) => None,
})
.unwrap_or(true)
});
let proven = !unqualified_template
&& nested.iter().all(|(path, depth)| {
let Ok(Cirru::List(parts)) = navigate_to_path(source, path) else {
return false;
};
let Some(kind) = scope.legacy_kind(&parts) else {
return false;
};
if *depth == 1 {
// Resolution and field completeness were checked against the macro namespace.
return true;
}
let Some(prototype) = parts.get(1).and_then(leaf_value) else {
return false;
};
let Some((target_ns, target_def)) = resolve_nominal_target(snapshot, namespace, prototype, kind) else {
return false;
};
let mut prototype_path = path.clone();
prototype_path.push(1);
let matching = usages
.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(prototype_path.iter().copied())
})
})
.collect::<Vec<_>>();
!matching.is_empty()
&& matching.iter().all(|usage| {
usage.target_ns.as_ref() == target_ns
&& usage.target_def.as_ref() == target_def
&& usage
.macro_origin
.iter()
.all(|origin| preserves_nominal_method_call_through_macro(origin))
})
});
let replacement_node = rewrite_named_constructor_tree(
&original_node,
target_depth,
&scope,
compose_redundant_do,
compose_single_expression_do,
);
let original_code = original_node
.format_one_liner()
.map_err(|error| format!("Failed to format constructor source at {namespace}/{definition}: {error}"))?;
let replacement_code = replacement_node
.format_one_liner()
.map_err(|error| format!("Failed to format constructor replacement at {namespace}/{definition}: {error}"))?;
let prototype = items.get(1).and_then(leaf_value).unwrap_or("<unknown>");
let origin_kind = if target_depth == 1 {
"macro-namespace-resolved-template-constructor"
} else {
"compiler-resolved-nominal-constructor"
};
suggestions.push(FixSuggestion {
rule_id: kind.rule_id(),
diagnostic_code: kind.diagnostic_code(),
semantic_layer: "surface",
source_file: snapshot_file.to_owned(),
definition: format!("{namespace}/{definition}"),
path: format!("code{}", format_path(&target_path)),
fingerprint: node_fingerprint(&original_node),
origin_chain: vec![serde_json::json!({"kind": origin_kind, "proven": proven})],
original: quoted_json(&original_node),
replacement: proven.then(|| quoted_json(&replacement_node)),
applicability: if proven { "machine-applicable" } else { "requires-review" },
message: if proven {
format!(
"Replace legacy `{}` {} construction with the directly callable `{prototype}` constructor.",
kind.legacy_head(),
kind.display_name()
)
} else if unqualified_template {
"An unqualified prototype in a quasiquote template resolves at each expansion site, where a local may capture it; qualify the prototype with its namespace or review the macro users.".to_owned()
} else {
"Cannot prove the constructor prototype and executable macro origin; retain this source region for review.".to_owned()
},
target_path,
operation: proven.then_some(FixOperation::ReplaceNode {
original: original_code,
replacement: replacement_code,
}),
});
}
Ok(suggestions)
}
/// Resolution context shared by legacy nominal constructor collection and rewriting.
struct ConstructorScope<'a> {
snapshot: &'a Snapshot,
namespace: &'a str,
shadowed: &'a HashSet<String>,
kinds: &'a [NominalKind],
/// A `defmacro` body runs at expansion time; only its quasiquote templates are migrated.
macro_body: bool,
}
impl ConstructorScope<'_> {
fn legacy_kind(&self, items: &[Cirru]) -> Option<NominalKind> {
legacy_constructor_kind(items, self.snapshot, self.namespace, self.shadowed, self.kinds)
}
/// Depth 0 is executable code and depth 1 is a quasiquote template outside any unquote.
fn migrates_at(&self, depth: usize) -> bool {
depth == 1 || (depth == 0 && !self.macro_body)
}
/// Quasiquote depth of a list's children. `None` marks quoted data, nested templates and nested
/// macros, which stay unchanged.
fn child_depth(&self, items: &[Cirru], depth: usize, is_root: bool) -> Option<usize> {
match items.first().and_then(leaf_value) {
Some("quote" | "cirru-quote" | ";") => None,
Some("defmacro") if !(is_root && self.macro_body) => None,
Some("quasiquote") => (depth == 0).then_some(1),
Some("~" | "~@") => depth.checked_sub(1),
_ => Some(depth),
}
}
}
/// Collect legacy constructor calls in executable code and quasiquote templates while preserving
/// quoted data and rejecting unresolved or shadowed prototypes.
fn collect_named_constructor_paths(
node: &Cirru,
path: &mut Vec<usize>,
depth: usize,
output: &mut Vec<(Vec<usize>, usize)>,
scope: &ConstructorScope,
) {
let Cirru::List(items) = node else {
return;
};
let Some(child_depth) = scope.child_depth(items, depth, path.is_empty()) else {
return;
};
if scope.migrates_at(depth) && scope.legacy_kind(items).is_some() {
output.push((path.clone(), depth));
}
for (index, child) in items.iter().enumerate() {
path.push(index);
collect_named_constructor_paths(child, path, child_depth, output, scope);
path.pop();
}
}
fn legacy_constructor_kind(
items: &[Cirru],
snapshot: &Snapshot,
namespace: &str,
shadowed: &HashSet<String>,
kinds: &[NominalKind],
) -> Option<NominalKind> {
let head = items.first().and_then(leaf_value)?;
let prototype = items.get(1).and_then(leaf_value)?;
kinds.iter().copied().find(|kind| {
let target = resolve_nominal_target(snapshot, namespace, prototype, *kind);
head == kind.legacy_head()
&& !prototype.starts_with('_')
&& !prototype_is_shadowed(prototype, shadowed)
&& target.is_some()
&& (*kind != NominalKind::Struct
|| target.is_some_and(|(target_ns, target_def)| struct_fields_are_complete(snapshot, &target_ns, &target_def, items)))
&& legacy_constructor_replacement(items, *kind).is_some()
})
}
/// Recursively compose selected constructor and redundant-body rewrites inside one guarded replacement.
/// `depth` is the quasiquote depth of `node`; template code keeps its `do` structure.
fn rewrite_named_constructor_tree(
node: &Cirru,
depth: usize,
scope: &ConstructorScope,
compose_redundant_do: bool,
compose_single_expression_do: bool,
) -> Cirru {
let Cirru::List(items) = node else {
return node.clone();
};
let Some(child_depth) = scope.child_depth(items, depth, false) else {
return node.clone();
};
let rewritten_items = items
.iter()
.map(|item| rewrite_named_constructor_tree(item, child_depth, scope, compose_redundant_do, compose_single_expression_do))
.collect::<Vec<_>>();
let rewritten_node = match scope.legacy_kind(items) {
Some(kind) if scope.migrates_at(depth) => {
legacy_constructor_replacement(&rewritten_items, kind).unwrap_or(Cirru::List(rewritten_items))
}
_ => Cirru::List(rewritten_items),
};
if depth != 0 {
return rewritten_node;
}
let rewritten_node = if compose_redundant_do {
splice_redundant_do_children(rewritten_node)
} else {
rewritten_node
};
if compose_single_expression_do {
unwrap_single_expression_do(rewritten_node)
} else {
rewritten_node
}
}
/// Remove one single-expression `do` after recursively rewriting its payload.
fn unwrap_single_expression_do(node: Cirru) -> Cirru {
match node {
Cirru::List(items) if items.len() == 2 && items.first().and_then(leaf_value) == Some("do") => {
items.into_iter().nth(1).expect("single-expression do should contain one payload")
}
other => other,
}
}
/// Convert one validated legacy constructor node to direct surface syntax.
fn legacy_constructor_replacement(items: &[Cirru], kind: NominalKind) -> Option<Cirru> {
let prototype = items.get(1)?.clone();
match kind {
NominalKind::Enum => Some(Cirru::List(items.iter().skip(1).cloned().collect())),
NominalKind::Struct => {
let mut replacement = vec![prototype];
for field in items.iter().skip(2) {
let Cirru::List(pair) = field else {
return None;
};
if pair.len() != 2 || !pair.first().and_then(leaf_value).is_some_and(|key| key.starts_with(':')) {
return None;
}
replacement.extend(pair.iter().cloned());
}
Some(Cirru::List(replacement))
}
}
}
/// Splice direct `do` children only where the enclosing form accepts a variadic body.
fn splice_redundant_do_children(node: Cirru) -> Cirru {
let Cirru::List(items) = node else {
return node;
};
let body_start = match items.first().and_then(leaf_value) {
Some("defn") => Some(3),
Some("fn" | "let") => Some(2),
Some("let[]" | "let{}") => Some(3),
Some("do") => Some(1),
_ => None,
};
let Some(body_start) = body_start else {
return Cirru::List(items);
};
let mut output = Vec::with_capacity(items.len());
for (index, item) in items.into_iter().enumerate() {
if index >= body_start
&& let Cirru::List(children) = &item
&& children.len() > 1
&& children.first().and_then(leaf_value) == Some("do")
{
output.extend(children.iter().skip(1).cloned());
} else {
output.push(item);
}
}
Cirru::List(output)
}
/// Read the leaf head of one source list.
fn list_head(node: &Cirru) -> Option<&str> {
match node {
Cirru::List(items) => items.first().and_then(leaf_value),
Cirru::Leaf(_) => None,
}
}
/// Borrow a source leaf value without accepting nested forms.
fn leaf_value(node: &Cirru) -> Option<&str> {
match node {
Cirru::Leaf(value) => Some(value.as_ref()),
Cirru::List(_) => None,
}
}
/// Treat common lexical binders conservatively: one matching local name suppresses migration in the whole definition.
fn collect_potential_local_bindings(node: &Cirru, output: &mut HashSet<String>) {
let Cirru::List(items) = node else {
return;
};
if matches!(items.first().and_then(leaf_value), Some("quote" | "quasiquote")) {
return;
}
match items.first().and_then(leaf_value) {
Some("defn" | "defmacro") => collect_binding_tree(items.get(2), output),
Some("fn") => collect_binding_tree(items.get(1), output),
Some("let" | "loop") => collect_binding_positions(items.get(1), true, output),
Some("&let" | "doseq" | "if-let" | "when-let") => collect_binding_positions(items.get(1), false, output),
_ => {}
}
for child in items {
collect_potential_local_bindings(child, output);
}
}
/// Collect only binding patterns, never leaves from initializer expressions.
fn collect_binding_positions(node: Option<&Cirru>, paired: bool, output: &mut HashSet<String>) {
let Some(Cirru::List(items)) = node else {
return;
};
if paired {
for binding in items {
if let Cirru::List(pair) = binding {
collect_binding_tree(pair.first(), output);
}
}
} else {
for binding in items.iter().step_by(2) {
collect_binding_tree(Some(binding), output);
}
}
}
/// Conservatively collect leaves from one supported binding pattern.
fn collect_binding_tree(node: Option<&Cirru>, output: &mut HashSet<String>) {
match node {
Some(Cirru::Leaf(value)) if !value.starts_with('&') => {
output.insert(value.to_string());
}
Some(Cirru::List(items)) => {
for item in items {
collect_binding_tree(Some(item), output);
}
}
_ => {}
}
}
/// Reject bare nominal names that may resolve to a local binding instead of a definition.
fn prototype_is_shadowed(prototype: &str, shadowed: &HashSet<String>) -> bool {
if prototype.contains('/') {
false
} else {
shadowed.contains(prototype)
}
}
/// Resolve a nominal prototype to its exact editable project definition, or to a `calcit.core`
/// enum that no local definition or import shadows.
fn resolve_nominal_target(snapshot: &Snapshot, at_ns: &str, prototype: &str, kind: NominalKind) -> Option<(String, String)> {
let target = if let Some((prefix, definition)) = prototype.rsplit_once('/') {
let namespace = if snapshot.files.contains_key(prefix) || prefix == CORE_NS {
prefix.to_owned()
} else {
let namespace =
program::lookup_ns_target_in_import(at_ns, prefix).or_else(|| program::lookup_default_target_in_import(at_ns, prefix))?;
namespace.to_string()
};
(namespace, definition.to_owned())
} else if nominal_definition_matches(snapshot, at_ns, prototype, kind) {
return Some((at_ns.to_owned(), prototype.to_owned()));
} else if let Some(target) = imported_definition_target(at_ns, prototype) {
target
} else if core_nominal_type_is_unshadowed(snapshot, at_ns, prototype, &HashSet::new()) {
(CORE_NS.to_owned(), prototype.to_owned())
} else {
return None;
};
if target.0 == CORE_NS && !snapshot.files.contains_key(CORE_NS) {
return (kind == NominalKind::Enum && core_enum_names().contains(&target.1)).then_some(target);
}
nominal_definition_matches(snapshot, &target.0, &target.1, kind).then_some(target)
}
const CORE_NS: &str = "calcit.core";
/// Enums that `calcit.core` declares with `defenum`, read once from the embedded core snapshot.
/// Core wraps most of them as `def Name (impl-traits (defenum Name ...) ...)`.
fn core_enum_names() -> &'static HashSet<String> {
static NAMES: std::sync::LazyLock<HashSet<String>> = std::sync::LazyLock::new(|| {
calcit_core::core_snapshot()
.ok()
.and_then(|core| {
core.files.get(CORE_NS).map(|file| {
file
.defs
.iter()
.filter(|(name, entry)| declares_enum(&entry.code, name))
.map(|(name, _)| name.to_owned())
.collect()
})
})
.unwrap_or_default()
});
&NAMES
}
/// Whether a definition body evaluates `defenum <name>`, looking through wrapping forms but not quoted data.
fn declares_enum(code: &Cirru, name: &str) -> bool {
let Cirru::List(items) = code else {
return false;
};
match items.first().and_then(leaf_value) {
Some("quote" | "quasiquote" | "defmacro" | "defn" | "fn") => false,
Some("defenum") => items.get(1).and_then(leaf_value) == Some(name),
_ => items.iter().any(|item| declares_enum(item, name)),
}
}
/// Resolve a referred local import name without losing a renamed target definition.
fn imported_definition_target(at_ns: &str, local_name: &str) -> Option<(String, String)> {
let program_data = program::PROGRAM_CODE_DATA.read().ok()?;
let rule = program_data.get(at_ns)?.import_map.get(local_name)?;
match rule.as_ref() {
program::ImportRule::NsReferDef(namespace, definition) => Some((namespace.to_string(), definition.to_string())),
program::ImportRule::NsAs(_) | program::ImportRule::NsDefault(_) => None,
}
}
/// Check that a project definition has the expected nominal declaration kind.
fn nominal_definition_matches(snapshot: &Snapshot, namespace: &str, definition: &str, kind: NominalKind) -> bool {
snapshot
.files
.get(namespace)
.and_then(|file| file.defs.get(definition))
.is_some_and(|entry| list_head(&entry.code) == Some(kind.definition_head()))
}
/// Require every declared Struct field exactly once before flattening legacy field pairs.
fn struct_fields_are_complete(snapshot: &Snapshot, namespace: &str, definition: &str, constructor: &[Cirru]) -> bool {
let Some(Cirru::List(definition_items)) = snapshot
.files
.get(namespace)
.and_then(|file| file.defs.get(definition))
.map(|entry| &entry.code)
else {
return false;
};
let declared = definition_items
.iter()
.skip(2)
.filter_map(|field| match field {
Cirru::List(pair) if pair.len() >= 2 => pair.first().and_then(leaf_value).filter(|name| name.starts_with(':')),
_ => None,
})
.collect::<HashSet<_>>();
let mut provided = HashSet::new();
for field in constructor.iter().skip(2) {
let Some(name) = (match field {
Cirru::List(pair) if pair.len() == 2 => pair.first().and_then(leaf_value).filter(|name| name.starts_with(':')),
_ => None,
}) else {
return false;
};
if !provided.insert(name) {
return false;
}
}
provided == declared
}
/// Deduplicate identical compiler suggestions and fail closed on conflicting replacements.
fn insert_fix_suggestion(
suggestions: &mut BTreeMap<(String, String, Vec<usize>), FixSuggestion>,
key: (String, String, Vec<usize>),
suggestion: FixSuggestion,
) -> Result<(), String> {
if let Some(existing) = suggestions.get(&key) {
if existing != &suggestion {
return Err(format!(
"Fix suggestions overlap at {}/{} {}; refusing to choose between different replacements.",
key.0,
key.1,
format_path(&key.2)
));
}
} else {
suggestions.insert(key, suggestion);
}
Ok(())
}
/// Resolve a diagnostic coordinate to the exact source leaf that owns the migration.
fn resolve_fix_target(code: &Cirru, coordinate: &[usize]) -> Option<(Vec<usize>, String)> {
let node = navigate_to_path(code, coordinate).ok()?;
match node {
Cirru::Leaf(value) => Some((coordinate.to_vec(), value.to_string())),
Cirru::List(items) => match items.first() {
Some(Cirru::Leaf(value)) => {
let mut head_path = coordinate.to_vec();
head_path.push(0);
Some((head_path, value.to_string()))
}
_ => None,
},
}
}
/// Preserve namespace qualification while resolving a removed data API migration.
fn migration_for_source_leaf(source: &str) -> Option<(Option<String>, String)> {
let (prefix, name) = source.rsplit_once('/').map_or(("", source), |(prefix, name)| (prefix, name));
let migration = runner::preprocess::removed_data_api_migration(name)?;
let replacement = migration.replacement.map(|replacement| {
if prefix.is_empty() {
replacement
} else {
format!("{prefix}/{replacement}")
}
});
let guidance = replacement.clone().unwrap_or(migration.guidance);
Some((replacement, guidance))
}
/// Lower one typed suggestion into guarded tree commands for the staged transaction.
fn suggestion_operations(suggestion: &FixSuggestion) -> Vec<Vec<String>> {
match &suggestion.operation {
Some(FixOperation::ReplaceLeaf { original, replacement }) => vec![vec![
"tree".to_owned(),
"replace".to_owned(),
suggestion.definition.clone(),
"--path".to_owned(),
format_path(&suggestion.target_path),
"--expect".to_owned(),
format!("quote {original}"),
"--code".to_owned(),
format!("quote {replacement}"),
]],
Some(FixOperation::WrapLeafCall { original }) => vec![vec![
"tree".to_owned(),
"replace".to_owned(),
suggestion.definition.clone(),
"--path".to_owned(),
format_path(&suggestion.target_path),
"--expect".to_owned(),
format!("quote {original}"),
"--code".to_owned(),
format!("quote $ {original}"),
]],
Some(FixOperation::ReplaceNode { original, replacement }) => vec![vec![
"tree".to_owned(),
"replace".to_owned(),
suggestion.definition.clone(),
"--path".to_owned(),
format_path(&suggestion.target_path),
"--expect".to_owned(),
format!("quote $ {original}"),
"--code".to_owned(),
format!("quote $ {replacement}"),
]],
Some(FixOperation::ReplaceNodeWithLeaf {
original_json_ast,
replacement_leaf,
}) => vec![vec![
"tree".to_owned(),
"replace".to_owned(),
suggestion.definition.clone(),
"--path".to_owned(),
format_path(&suggestion.target_path),
"--expect".to_owned(),
original_json_ast.clone(),
"--code".to_owned(),
format!("quote {replacement_leaf}"),
]],
Some(FixOperation::SpliceDo) => {
let mut head_path = suggestion.target_path.clone();
head_path.push(0);
vec![
vec![
"tree".to_owned(),
"delete".to_owned(),
suggestion.definition.clone(),
"--path".to_owned(),
format_path(&head_path),
"--expect".to_owned(),
"quote do".to_owned(),
],
vec![
"tree".to_owned(),
"unwrap".to_owned(),
suggestion.definition.clone(),
"--path".to_owned(),
format_path(&suggestion.target_path),
],
]
}
Some(FixOperation::DeleteNode { original }) => vec![vec![
"tree".to_owned(),
"delete".to_owned(),
suggestion.definition.clone(),
"--path".to_owned(),
format_path(&suggestion.target_path),
"--expect".to_owned(),
format!("quote $ {original}"),
]],
Some(FixOperation::ReplaceImports { code }) => vec![vec![
"edit".to_owned(),
"imports".to_owned(),
suggestion.definition.clone(),
"--code".to_owned(),
code.clone(),
]],
Some(FixOperation::ReplaceExamples { code }) => vec![vec![
"edit".to_owned(),
"meta".to_owned(),
suggestion.definition.clone(),
"--examples".to_owned(),
"--code".to_owned(),
code.clone(),
]],
Some(FixOperation::ReplaceTest { name, tags, code }) => {
let mut args = vec![
"edit".to_owned(),
"add-test".to_owned(),
suggestion.definition.clone(),
name.clone(),
"--code".to_owned(),
code.clone(),
"--overwrite".to_owned(),
];
if !tags.is_empty() {
args.push("--tags".to_owned());
args.push(tags.clone());
}
vec![args]
}
Some(FixOperation::ReplaceSchema { code }) => vec![vec![
"edit".to_owned(),
"schema".to_owned(),
suggestion.definition.clone(),
"--code".to_owned(),
code.clone(),
]],
Some(FixOperation::ReplaceDefinition { code }) => vec![vec![
"edit".to_owned(),
"def".to_owned(),
suggestion.definition.clone(),
"--code".to_owned(),
code.clone(),
"--overwrite".to_owned(),
]],
Some(FixOperation::RenameDefinition { new_name }) => vec![vec![
"edit".to_owned(),
"rename".to_owned(),
suggestion.definition.clone(),
new_name.clone(),
]],
None => vec![],
}
}
/// Encode one Cirru node as the public quoted-AST JSON envelope.
fn quoted_json(node: &Cirru) -> Value {
serde_json::json!({
"$type": "quote",
"value": cirru_to_json_value(node),
})
}
/// Decode a public quote or splice envelope for a human source preview.
fn fix_source_json_to_cirru(value: &Value) -> Result<Cirru, String> {
let Value::Object(fields) = value else {
return Err("expected a source AST object".to_owned());
};
if !matches!(fields.get("$type").and_then(Value::as_str), Some("quote" | "splice")) {
return Err("expected `$type: quote` or `$type: splice` in source preview".to_owned());
}
let node = fields
.get("value")
.ok_or_else(|| "quoted AST source preview is missing `value`".to_owned())?;
json_value_to_cirru(node)
}
/// Fingerprint the canonical JSON shape used in machine-readable fix plans.
fn node_fingerprint(node: &Cirru) -> String {
let mut hasher = Md5::new();
hasher.update(cirru_to_json_value(node).to_string().as_bytes());
format!("md5:{}", hex::encode(hasher.finalize()))
}
/// Require an inspectable, clean VCS boundary unless the caller explicitly opts out.
fn guard_git_worktree(snapshot_file: &str, allow_dirty: bool, allow_no_vcs: bool) -> Result<(), String> {
let project_dir = Path::new(snapshot_file).parent().unwrap_or_else(|| Path::new("."));
let probe = Command::new("git")
.arg("-C")
.arg(project_dir)
.args(["rev-parse", "--show-toplevel"])
.output();
let Ok(probe) = probe else {
if allow_no_vcs {
return Ok(());
}
return Err("Cannot verify a Git worktree. Re-run with `--allow-no-vcs` only after reviewing the preview.".to_owned());
};
if !probe.status.success() {
if allow_no_vcs {
return Ok(());
}
return Err("Snapshot is not inside a Git worktree. Re-run with `--allow-no-vcs` only after reviewing the preview.".to_owned());
}
if allow_dirty {
return Ok(());
}
let status = Command::new("git")
.arg("-C")
.arg(project_dir)
.args(["status", "--porcelain", "--untracked-files=normal"])
.output()
.map_err(|error| format!("Failed to inspect Git worktree: {error}"))?;
if !status.status.success() {
return Err(format!(
"Failed to inspect Git worktree: {}",
String::from_utf8_lossy(&status.stderr).trim_end()
));
}
if !status.stdout.is_empty() {
return Err("Git worktree is dirty. Commit/stash changes, or re-run with `--allow-dirty` after reviewing the preview.".to_owned());
}
Ok(())
}
/// Render the compact human view without changing the JSON protocol.
fn print_human_report(report: &FixReport<'_>) {
println!(
"# {}\n",
if report.data.filters.rule_id == "pattern" {
"Reviewed structural source rewrites"
} else {
"Compiler-guided source fixes"
}
);
println!("- mode: `{}`", report.data.mode);
println!("- revision: `{}`", report.revision);
if let Some(preset) = report.data.filters.preset_id {
println!("- preset: `{preset}`");
}
if let Some(coverage) = &report.data.filters.source_coverage {
println!("- scanned source regions: `{}`", coverage.scanned_regions.join(", "));
println!("- manual review source regions: `{}`", coverage.manual_review_regions.join(", "));
}
if let Some(replacement) = report.data.filters.replacement_name {
println!("- replacement definition: `{replacement}`");
}
println!("- rules: `{}`", report.data.filters.expanded_rule_ids.join(", "));
println!("- suggestions: `{}`", report.data.suggestions.len());
println!("- changed: `{}`", report.data.changed);
if let Some(workflow) = &report.data.workflow {
println!("- workflow: `{}`", workflow.workflow);
println!("- workflow status: `{}`", workflow.status);
println!("- entries: `{}`", workflow.entries.len());
println!("- review-required source fixes: `{}`", workflow.review_required.source_fixes.len());
println!(
"- review-required type findings: `{}`",
workflow.review_required.type_findings.len()
);
println!("- retained type boundaries: `{}`", workflow.retained_type_boundaries.len());
println!("- FFI boundaries: `{}`", workflow.review_required.ffi_boundaries.len());
println!("- verification results: `{}`", workflow.verification.results.len());
}
for (index, suggestion) in report.data.suggestions.iter().enumerate() {
println!("\n## Suggestion {}\n", index + 1);
println!("- applicability: `{}`", suggestion.applicability);
println!("- rule: `{}`", suggestion.rule_id);
println!("- definition: `{}`", suggestion.definition);
println!("- path: `{}`", suggestion.path);
println!("- message: {}\n", suggestion.message);
match fix_source_json_to_cirru(&suggestion.original).and_then(|node| markdown_cirru_section(3, "Before", &node, 0)) {
Ok(section) => println!("{section}"),
Err(error) => println!("### Before\n\n_Unable to render source preview: {error}_"),
}
if let Some(replacement) = &suggestion.replacement {
match fix_source_json_to_cirru(replacement).and_then(|node| markdown_cirru_section(3, "After", &node, 0)) {
Ok(section) => println!("\n{section}"),
Err(error) => println!("\n### After\n\n_Unable to render source preview: {error}_"),
}
}
}
if report.data.mode == "preview" && report.data.changed {
println!("\n## Next step\n\nRun `calcit fix --apply` after reviewing this plan.");
}
if report.data.mode == "preview" && report.data.filters.rule_id == "pattern" && !report.data.suggestions.is_empty() {
println!(
"\n## Next step\n\nReview the pattern/template and every candidate, then repeat the same selection with `--apply --expect-revision '{}'`. Type validation runs before publishing; it does not prove semantic equivalence.",
report.revision
);
}
}
#[cfg(test)]
mod tests {
use super::{
ConstructorScope, FixOperation, FixSuggestion, NominalKind, REMOVED_DATA_API_RULE, collect_potential_local_bindings,
collect_redundant_do_paths, fix_rule_metadata, fix_source_json_to_cirru, insert_fix_suggestion, legacy_constructor_replacement,
migration_for_source_leaf, prototype_is_shadowed, resolve_fix_target, rewrite_loaded_schema_type_references,
rewrite_named_constructor_tree, struct_fields_are_complete, suggestion_operations,
};
use calcit_core::calcit::{CalcitFnTypeAnnotation, CalcitGenericBound, CalcitTrait, CalcitTypeAnnotation, SchemaKind};
use cirru_parser::Cirru;
use serde_json::Value;
use std::collections::BTreeMap;
use std::sync::Arc;
use super::super::common::markdown_cirru_section;
fn leaf(value: &str) -> Cirru {
Cirru::leaf(value)
}
#[test]
fn strict_verification_requires_both_process_and_report_success() {
// This is a transport invariant; no Calcit test can inject a child report.
let passed = serde_json::json!({"data":{"status":"passed"},"diagnostics":[]});
for (succeeded, report, expected) in [
(true, passed.clone(), "passed"),
(false, passed, "failed"),
(true, serde_json::json!({"data":{"status":"failed"},"diagnostics":[]}), "failed"),
(
true,
serde_json::json!({"data":{"status":"passed"},"diagnostics":[{"severity":"error"}]}),
"failed",
),
] {
let bytes = serde_json::to_vec(&report).unwrap();
let result = super::strict_workflow_verification_result("entry:default", succeeded, &bytes, b"");
assert_eq!(result.status, expected);
assert_eq!(result.report, report, "valid child reports retain their details");
}
for stdout in [
b"".as_slice(),
b"macro-log\n{}",
b"{}{}",
b"null",
b"{}",
b"{\"data\":null,\"diagnostics\":[]}",
] {
let result = super::strict_workflow_verification_result("entry:default", true, stdout, b"child-stderr");
assert_eq!(result.status, "failed", "zero exit cannot authorize invalid output");
assert_eq!(result.report["diagnostics"][0]["code"], "E_WORKFLOW_OUTPUT");
assert_eq!(result.report["diagnostics"][0]["severity"], "error");
assert_eq!(result.report["diagnostics"][0]["stderr"], "child-stderr");
assert!(
result.report["diagnostics"][0]["message"]
.as_str()
.unwrap()
.contains("entry:default")
);
}
}
#[test]
fn splice_fix_source_decodes_the_replacement_sequence() {
let replacement = serde_json::json!({
"$type": "splice",
"value": [["println", "working"], ["finish", "value"]],
});
let node = fix_source_json_to_cirru(&replacement).expect("splice replacement should decode");
assert_eq!(
node,
Cirru::List(vec![
Cirru::List(vec![leaf("println"), leaf("working")]),
Cirru::List(vec![leaf("finish"), leaf("value")]),
])
);
let section = markdown_cirru_section(3, "After", &node, 0).expect("splice replacement should render");
assert!(section.contains("### After\n"));
assert!(section.contains("```cirru\n"));
assert!(section.contains("println working"));
assert!(section.contains("finish value"));
}
#[test]
fn preserves_source_qualifier_for_exact_removed_api_migration() {
assert_eq!(
migration_for_source_leaf("core/&tuple:enum"),
Some((Some("core/&enum:definition".to_owned()), "core/&enum:definition".to_owned()))
);
}
#[test]
fn removed_data_fix_is_derived_from_the_current_diagnostic() {
let metadata = fix_rule_metadata(REMOVED_DATA_API_RULE);
assert_eq!(metadata.diagnostic_code, "E_REMOVED_DATA_API");
assert_eq!(metadata.evidence_source, "current-diagnostic");
assert_eq!(metadata.lifecycle, "current-semantics");
assert!(!metadata.source_version_required);
}
#[test]
fn retired_enum_predicates_are_not_data_api_migrations() {
assert_eq!(migration_for_source_leaf("tuple?"), None);
assert_eq!(migration_for_source_leaf("tuple-enum"), None);
}
#[test]
fn warning_coordinate_can_identify_a_call_or_a_leaf() {
let code = Cirru::List(vec![leaf("do"), Cirru::List(vec![leaf("tuple-enum"), leaf("value")])]);
assert_eq!(resolve_fix_target(&code, &[1]), Some((vec![1, 0], "tuple-enum".to_owned())));
assert_eq!(resolve_fix_target(&code, &[1, 0]), Some((vec![1, 0], "tuple-enum".to_owned())));
}
#[test]
fn generated_operation_carries_path_and_expected_leaf() {
let suggestion = FixSuggestion {
rule_id: "removed-data-api-v1",
diagnostic_code: "E_REMOVED_DATA_API",
semantic_layer: "surface",
source_file: "calcit.cirru".to_owned(),
definition: "app.main/main!".to_owned(),
path: "code@3.0".to_owned(),
fingerprint: "md5:test".to_owned(),
origin_chain: vec![],
original: Value::Null,
replacement: Value::Null.into(),
applicability: "machine-applicable",
message: String::new(),
target_path: vec![3, 0],
operation: Some(FixOperation::ReplaceLeaf {
original: "tuple-enum".to_owned(),
replacement: "enum-definition".to_owned(),
}),
};
let operations = suggestion_operations(&suggestion);
assert_eq!(
operations,
vec![vec![
"tree",
"replace",
"app.main/main!",
"--path",
"@3.0",
"--expect",
"quote tuple-enum",
"--code",
"quote enum-definition",
]]
);
}
#[test]
fn redundant_do_is_found_only_in_variadic_sequence_positions() {
let code = Cirru::List(vec![
leaf("defn"),
leaf("demo"),
Cirru::List(vec![]),
Cirru::List(vec![leaf("do"), leaf("a"), leaf("b")]),
Cirru::List(vec![
leaf("if"),
leaf("ready?"),
Cirru::List(vec![leaf("do"), leaf("c"), leaf("d")]),
leaf("e"),
]),
Cirru::List(vec![
leaf("let"),
Cirru::List(vec![]),
Cirru::List(vec![leaf("do"), leaf("f"), leaf("g")]),
]),
Cirru::List(vec![
leaf("quote"),
Cirru::List(vec![leaf("fn"), Cirru::List(vec![]), Cirru::List(vec![leaf("do"), leaf("h")])]),
]),
Cirru::List(vec![
leaf("defmacro"),
leaf("pack"),
Cirru::List(vec![]),
Cirru::List(vec![leaf("do"), leaf("i"), leaf("j")]),
]),
Cirru::List(vec![
leaf("let[]"),
Cirru::List(vec![]),
Cirru::List(vec![]),
Cirru::List(vec![leaf("do"), leaf("k"), leaf("l")]),
]),
]);
let mut paths = Vec::new();
collect_redundant_do_paths(&code, &mut Vec::new(), &mut paths);
assert_eq!(paths, vec![vec![3], vec![5, 2], vec![8, 3]]);
}
#[test]
fn redundant_do_operation_deletes_the_head_then_splices_the_body() {
let suggestion = FixSuggestion {
rule_id: "redundant-do-v1",
diagnostic_code: "FIX_REDUNDANT_DO",
semantic_layer: "surface",
source_file: "calcit.cirru".to_owned(),
definition: "app.main/demo".to_owned(),
path: "code@3".to_owned(),
fingerprint: "md5:test".to_owned(),
origin_chain: vec![],
original: Value::Null,
replacement: Some(Value::Null),
applicability: "machine-applicable",
message: String::new(),
target_path: vec![3],
operation: Some(FixOperation::SpliceDo),
};
assert_eq!(
suggestion_operations(&suggestion),
vec![
vec!["tree", "delete", "app.main/demo", "--path", "@3.0", "--expect", "quote do"],
vec!["tree", "unwrap", "app.main/demo", "--path", "@3"],
]
);
}
#[test]
fn constructor_replacement_keeps_argument_order() {
let suggestion = FixSuggestion {
rule_id: "named-enum-constructor-v1",
diagnostic_code: "FIX_NAMED_ENUM_CONSTRUCTOR",
semantic_layer: "surface",
source_file: "calcit.cirru".to_owned(),
definition: "app.main/demo".to_owned(),
path: "code@3".to_owned(),
fingerprint: "md5:test".to_owned(),
origin_chain: vec![],
original: Value::Null,
replacement: Some(Value::Null),
applicability: "machine-applicable",
message: String::new(),
target_path: vec![3],
operation: Some(FixOperation::ReplaceNode {
original: "%:: Result :ok value".to_owned(),
replacement: "Result :ok value".to_owned(),
}),
};
assert_eq!(
suggestion_operations(&suggestion),
vec![vec![
"tree",
"replace",
"app.main/demo",
"--path",
"@3",
"--expect",
"quote $ %:: Result :ok value",
"--code",
"quote $ Result :ok value",
]]
);
}
#[test]
fn local_nominal_name_is_treated_as_shadowed() {
let code = Cirru::List(vec![
leaf("defn"),
leaf("demo"),
Cirru::List(vec![leaf("Result")]),
Cirru::List(vec![leaf("%::"), leaf("Result"), leaf(":ok")]),
]);
let mut shadowed = std::collections::HashSet::new();
collect_potential_local_bindings(&code, &mut shadowed);
assert!(prototype_is_shadowed("Result", &shadowed));
assert!(!prototype_is_shadowed("app.schema/Result", &shadowed));
}
#[test]
fn legacy_struct_pairs_are_flattened_for_direct_construction() {
let items = vec![
leaf("%{}"),
leaf("Person"),
Cirru::List(vec![leaf(":name"), leaf("name")]),
Cirru::List(vec![leaf(":age"), leaf("age")]),
];
assert_eq!(
legacy_constructor_replacement(&items, NominalKind::Struct),
Some(Cirru::List(vec![
leaf("Person"),
leaf(":name"),
leaf("name"),
leaf(":age"),
leaf("age")
]))
);
assert_eq!(
legacy_constructor_replacement(&[leaf("%{}"), leaf("Person"), leaf("dynamic-fields")], NominalKind::Struct),
None
);
}
#[test]
fn equivalent_readable_constructors_converge_to_the_same_current_tree() {
let snapshot = super::load_snapshot(concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/fixtures/fix-command.cirru"))
.expect("fix fixture should load");
let legacy = Cirru::List(vec![leaf("%::"), leaf("FixPersonChoice"), leaf(":none")]);
let current = Cirru::List(vec![leaf("FixPersonChoice"), leaf(":none")]);
let shadowed = std::collections::HashSet::new();
let kinds = [NominalKind::Enum];
let scope = ConstructorScope {
snapshot: &snapshot,
namespace: "fix-command.main",
shadowed: &shadowed,
kinds: &kinds,
macro_body: false,
};
let normalized_legacy = rewrite_named_constructor_tree(&legacy, 0, &scope, false, false);
let normalized_current = rewrite_named_constructor_tree(¤t, 0, &scope, false, false);
assert_eq!(normalized_legacy, current);
assert_eq!(normalized_current, current);
}
#[test]
fn legacy_struct_requires_complete_unique_declared_fields() {
let snapshot = super::load_snapshot(concat!(env!("CARGO_MANIFEST_DIR"), "/../../tests/fixtures/fix-command.cirru"))
.expect("fix fixture should load");
let complete = vec![
leaf("%{}"),
leaf("FixPerson"),
Cirru::List(vec![leaf(":name"), leaf("name")]),
Cirru::List(vec![leaf(":age"), leaf("age")]),
];
assert!(struct_fields_are_complete(&snapshot, "fix-command.main", "FixPerson", &complete));
assert!(!struct_fields_are_complete(
&snapshot,
"fix-command.main",
"FixPerson",
&complete[..3]
));
let duplicate = vec![
leaf("%{}"),
leaf("FixPerson"),
Cirru::List(vec![leaf(":name"), leaf("first")]),
Cirru::List(vec![leaf(":name"), leaf("second")]),
Cirru::List(vec![leaf(":age"), leaf("age")]),
];
assert!(!struct_fields_are_complete(&snapshot, "fix-command.main", "FixPerson", &duplicate));
}
#[test]
fn quoted_binding_shapes_do_not_suppress_real_migrations() {
let code = Cirru::List(vec![
leaf("defn"),
leaf("demo"),
Cirru::List(vec![]),
Cirru::List(vec![
leaf("quote"),
Cirru::List(vec![leaf("fn"), Cirru::List(vec![leaf("Result")]), leaf("Result")]),
]),
]);
let mut shadowed = std::collections::HashSet::new();
collect_potential_local_bindings(&code, &mut shadowed);
assert!(!shadowed.contains("Result"));
}
#[test]
fn conflicting_suggestions_for_one_source_node_are_rejected() {
let mut suggestions = BTreeMap::new();
let key = ("app.main".to_owned(), "main!".to_owned(), vec![3, 0]);
let first = FixSuggestion {
rule_id: "removed-data-api-v1",
diagnostic_code: "E_REMOVED_DATA_API",
semantic_layer: "surface",
source_file: "calcit.cirru".to_owned(),
definition: "app.main/main!".to_owned(),
path: "code@3.0".to_owned(),
fingerprint: "md5:test".to_owned(),
origin_chain: vec![],
original: Value::Null,
replacement: Some(Value::String("enum-definition".to_owned())),
applicability: "machine-applicable",
message: String::new(),
target_path: vec![3, 0],
operation: Some(FixOperation::ReplaceLeaf {
original: "tuple-enum".to_owned(),
replacement: "enum-definition".to_owned(),
}),
};
insert_fix_suggestion(&mut suggestions, key.clone(), first.clone()).expect("first suggestion should insert");
insert_fix_suggestion(&mut suggestions, key.clone(), first.clone()).expect("identical duplicate should be idempotent");
let mut conflicting = first;
conflicting.operation = Some(FixOperation::ReplaceLeaf {
original: "tuple-enum".to_owned(),
replacement: "enum?".to_owned(),
});
let error = insert_fix_suggestion(&mut suggestions, key, conflicting).expect_err("conflicting overlap should fail");
assert!(error.contains("overlap at app.main/main! @3.0"), "error: {error}");
assert_eq!(suggestions.len(), 1);
}
#[test]
fn schema_reference_rewrite_only_changes_loaded_type_refs() {
let schema = Arc::new(CalcitTypeAnnotation::TypeRef(Arc::from("app.schema/Order"), Arc::new(vec![])));
let (rewritten, count) =
rewrite_loaded_schema_type_references(schema, "app.main", "app.schema", "Order", "Purchase").expect("rewrite TypeRef");
assert_eq!(count, 1);
assert!(matches!(
rewritten.as_ref(),
CalcitTypeAnnotation::TypeRef(name, args) if name.as_ref() == "app.schema/Purchase" && args.is_empty()
));
let generic = Arc::new(CalcitTypeAnnotation::TypeVar(Arc::from("Order")));
let (unchanged, count) = rewrite_loaded_schema_type_references(generic.clone(), "app.schema", "app.schema", "Order", "Purchase")
.expect("preserve TypeVar");
assert_eq!(count, 0);
assert_eq!(unchanged, generic);
}
#[test]
fn schema_reference_rewrite_changes_resolved_trait_bounds() {
let direct_trait = Arc::new(CalcitTrait::new_reference("app.schema/Show"));
let schema = Arc::new(CalcitTypeAnnotation::Fn(Arc::new(CalcitFnTypeAnnotation {
open_reason: Default::default(),
cases: Default::default(),
guard: None,
runtime_arity: None,
generics: Arc::new(vec![Arc::from("T")]),
where_bounds: Arc::new(vec![CalcitGenericBound {
name: Arc::from("T"),
traits: Arc::new(vec![Arc::new(CalcitTrait::new_reference("app.schema/Show"))]),
}]),
arg_types: vec![
Arc::new(CalcitTypeAnnotation::TypeVar(Arc::from("T"))),
Arc::new(CalcitTypeAnnotation::Trait(direct_trait)),
],
return_type: Arc::new(CalcitTypeAnnotation::TypeVar(Arc::from("T"))),
fn_kind: SchemaKind::Fn,
rest_type: None,
features: Arc::new(std::collections::HashSet::new()),
})));
let (rewritten, count) =
rewrite_loaded_schema_type_references(schema, "app.main", "app.schema", "Show", "Display").expect("rewrite trait bound");
let CalcitTypeAnnotation::Fn(signature) = rewritten.as_ref() else {
panic!("rewritten schema should remain a function");
};
let trait_def = &signature.where_bounds[0].traits[0];
assert_eq!(count, 2);
assert_eq!(trait_def.name.ref_str(), "Display");
assert_eq!(trait_def.definition_ref.as_deref(), Some("app.schema/Display"));
assert!(matches!(signature.arg_types[0].as_ref(), CalcitTypeAnnotation::TypeVar(name) if name.as_ref() == "T"));
assert!(matches!(
signature.arg_types[1].as_ref(),
CalcitTypeAnnotation::Trait(trait_def)
if trait_def.name.ref_str() == "Display" && trait_def.definition_ref.as_deref() == Some("app.schema/Display")
));
}
#[test]
fn legacy_comment_nil_collector_respects_quotes_comments_shadowing_and_macro_boundaries() {
let source = cirru_parser::parse(
r#"
defn demo (when)
cirru-quote (do (;nil) 1)
when true (;nil)
capture (do (;nil) 1)
&let (x 1)
;nil
, 2
;nil
; trailing-comment
"#,
)
.expect("valid cirru");
let mut candidates = Vec::new();
let shadowed = std::collections::HashSet::new();
let local_shadowed = std::collections::HashSet::new();
let mut is_macro = |head: &str| head == "capture";
super::collect_legacy_comment_nil_paths(
&source[0],
&mut Vec::new(),
super::NilExprPosition::Value,
false,
true,
&shadowed,
&local_shadowed,
&mut is_macro,
&mut candidates,
);
// 1) cirru-quote is skipped
// 2) `when true (;nil)` with shadowed `when` -> Value (unsafe)
// 3) `capture (do (;nil) 1)` -> inside_unproven_macro = true (unsafe)
// 4) `&let (x 1) (;nil) (, 2)` -> Discarded (safe)
// 5) trailing `;nil` before `; trailing-comment` when root returns Value -> Value (unsafe)
assert_eq!(candidates.len(), 4);
assert!(!candidates[0].position.allows_unit_rewrite(), "shadowed when must be Value");
assert!(candidates[1].inside_unproven_macro, "capture macro arg must stay guarded");
assert!(candidates[2].position.allows_unit_rewrite(), "&let non-tail is Discarded");
assert!(!candidates[3].position.allows_unit_rewrite(), "tail before comment is Value");
}
#[test]
fn macro_diagnostic_capture_distinguishes_project_compile_time_logs_and_deduplicates_by_source() {
use calcit_core::calcit::{Calcit, GENERATED_DEF, NodeLocation};
use calcit_core::call_stack::CallStackList;
use calcit_core::runner::macro_capability::{with_compile_time_macro_context, with_macro_context};
use calcit_core::runner::preprocess::set_project_namespaces;
use std::collections::HashSet;
let _lock = crate::GLOBAL_TEST_LOCK.lock().unwrap_or_else(|error| error.into_inner());
set_project_namespaces(&HashSet::from(["app.main".to_owned()]));
let loc_a = NodeLocation::new(Arc::from("app.main"), Arc::from("caller-a"), Arc::from(vec![1_u16]));
let loc_b = NodeLocation::new(Arc::from("app.main"), Arc::from("caller-b"), Arc::from(vec![2_u16]));
let loc_generated = NodeLocation::new(Arc::from("app.main"), Arc::from(GENERATED_DEF), Arc::from(vec![0_u16]));
let declared = Arc::new(HashSet::new());
let _output_guard = crate::ProgramOutputGuard::new(true, true);
let _capture_guard = crate::injection::MacroDiagnosticCaptureGuard::new();
// 1. General program output outside any macro is silenced, not captured.
crate::injection::stdout_println(vec![Calcit::Str("general-output".into())], &CallStackList::default()).unwrap();
// 2. Runtime macro fallback (compile_time = false) is not captured.
with_macro_context(Arc::from("app.main/m"), declared.clone(), Some(loc_a.clone()), || {
crate::injection::stdout_println(vec![Calcit::Str("runtime-macro".into())], &CallStackList::default())
})
.unwrap();
// 3. Non-project macro (dependency or core) is not captured.
with_compile_time_macro_context(Arc::from("dep.macros/m"), declared.clone(), Some(loc_a.clone()), || {
crate::injection::stderr_println(vec![Calcit::Str("dep-macro".into())], &CallStackList::default())
})
.unwrap();
// 4. Unlocatable macro (None or GENERATED_DEF) is not captured.
with_compile_time_macro_context(Arc::from("app.main/m"), declared.clone(), None, || {
crate::injection::stdout_println(vec![Calcit::Str("no-loc".into())], &CallStackList::default())
})
.unwrap();
with_compile_time_macro_context(Arc::from("app.main/m"), declared.clone(), Some(loc_generated), || {
crate::injection::stdout_println(vec![Calcit::Str("gen-loc".into())], &CallStackList::default())
})
.unwrap();
// 5. Locatable compile-time project macro diagnostics are captured and deduplicated by (macro, location, message).
for _ in 0..3 {
with_compile_time_macro_context(Arc::from("app.main/m1"), declared.clone(), Some(loc_a.clone()), || {
crate::injection::stdout_println(vec![Calcit::Str("same-msg".into())], &CallStackList::default())
})
.unwrap();
}
with_compile_time_macro_context(Arc::from("app.main/m1"), declared.clone(), Some(loc_b), || {
crate::injection::stderr_println(vec![Calcit::Str("same-msg".into())], &CallStackList::default())
})
.unwrap();
with_compile_time_macro_context(Arc::from("app.main/m2"), declared, Some(loc_a), || {
crate::injection::stdout_println(vec![Calcit::Str("same-msg".into())], &CallStackList::default())
})
.unwrap();
let summary = super::summarize_macro_diagnostics(crate::injection::take_captured_macro_diagnostics());
assert_eq!(summary.len(), 3);
assert_eq!(summary[0].r#macro, "app.main/m1");
assert_eq!(summary[0].definition, "app.main/caller-a");
assert_eq!(summary[0].path, "code@1");
assert_eq!(summary[0].message, "same-msg");
assert_eq!(summary[0].count, 3);
assert_eq!(summary[1].definition, "app.main/caller-b");
assert_eq!(summary[1].count, 1);
assert_eq!(summary[2].r#macro, "app.main/m2");
assert_eq!(summary[2].definition, "app.main/caller-a");
assert_eq!(summary[2].count, 1);
}
}