Skip to main content

logicaffeine_compile/extraction/
collector.rs

1//! Dependency collection for program extraction.
2//!
3//! Collects all transitive dependencies needed to extract a definition.
4
5use crate::kernel::{Context, Term};
6use std::collections::{HashMap, HashSet};
7
8/// Whether `name` extracts to self-contained Rust: a constructor of an emittable
9/// inductive, an emittable inductive (has constructors) or mapped primitive, or a
10/// definition whose body only references extractable things. Axioms / declarations
11/// / tactics (no extractable body, e.g. `syn_diag`, `try_auto`) are NOT extractable
12/// — extracting them would emit Rust referencing undefined symbols.
13pub fn is_extractable(ctx: &Context, name: &str) -> bool {
14    extractable(ctx, name, &mut HashMap::new())
15}
16
17fn extractable(ctx: &Context, name: &str, memo: &mut HashMap<String, bool>) -> bool {
18    // `_` is a placeholder (e.g. a match-motive binder) that surfaces as a Global
19    // but is never emitted — treat it as benign.
20    if name == "_" {
21        return true;
22    }
23    if let Some(&b) = memo.get(name) {
24        return b;
25    }
26    // Optimistic for recursive/cyclic references (a fixpoint that can't lower).
27    memo.insert(name.to_string(), true);
28    // The prelude's arithmetic (`add`/`sub`/… at `Int -> Int -> Int`) is OPAQUE to extraction:
29    // it lowers to a Rust operator, so it extracts without emitting anything and without
30    // pulling in what implements it. Since `Int` became a real inductive these names have
31    // bodies (`Int_add`, …), and following one drags the whole structural integer tower into
32    // the output — where `Int` is `i64` and none of it type-checks. Asked before the body.
33    let result = if super::codegen::arith_builtin_operator(ctx, name).is_some() {
34        true
35    } else if ctx.is_constructor(name) {
36        ctx.constructor_inductive(name)
37            .map(|ind| !ctx.get_constructors(ind).is_empty())
38            .unwrap_or(false)
39    } else if ctx.is_inductive(name) {
40        (!ctx.get_constructors(name).is_empty() && !is_logical_type(name))
41            || is_mapped_primitive(name)
42    } else if let Some(body) = ctx.get_definition_body(name) {
43        let mut refs = Vec::new();
44        collect_globals(body, &mut refs);
45        refs.iter().all(|g| extractable(ctx, g, memo))
46            && matches_inferable(ctx, body)
47            // Arithmetic builtins must be fully (binary) applied — a bare/partial
48            // `add` has no Rust function to call.
49            && super::codegen::arith_uses_well_formed(ctx, body)
50    } else {
51        // A declaration / axiom / primitive op with no body. The mapped primitives
52        // and the arithmetic builtins (`add`/`sub`/… → Rust operators) are the only
53        // bodyless globals that extract to real Rust; everything else (tactics,
54        // reflection axioms) would emit references to undefined symbols.
55        is_mapped_primitive(name) || super::codegen::arith_operator(name).is_some()
56    };
57    memo.insert(name.to_string(), result);
58    result
59}
60
61/// Whether every `match` in a term has an inductive the extractor can recognize
62/// (from the motive or the discriminant). Literate-generated matches sometimes
63/// lack a readable motive, which would extract to an empty (non-exhaustive) match;
64/// such definitions are not cleanly extractable.
65fn matches_inferable(ctx: &Context, term: &Term) -> bool {
66    match term {
67        Term::Match {
68            discriminant,
69            motive,
70            cases,
71        } => {
72            if motive_inductive(ctx, motive)
73                .or_else(|| disc_inductive(ctx, discriminant))
74                .is_none()
75            {
76                return false;
77            }
78            matches_inferable(ctx, discriminant)
79                && matches_inferable(ctx, motive)
80                && cases.iter().all(|c| matches_inferable(ctx, c))
81        }
82        Term::Lambda {
83            param_type, body, ..
84        } => matches_inferable(ctx, param_type) && matches_inferable(ctx, body),
85        Term::Pi {
86            param_type,
87            body_type,
88            ..
89        } => matches_inferable(ctx, param_type) && matches_inferable(ctx, body_type),
90        Term::App(f, a) => matches_inferable(ctx, f) && matches_inferable(ctx, a),
91        Term::Fix { body, .. } => matches_inferable(ctx, body),
92        _ => true,
93    }
94}
95
96fn motive_inductive(ctx: &Context, motive: &Term) -> Option<String> {
97    if let Term::Lambda { param_type, .. } = motive {
98        if let Term::Global(name) = param_type.as_ref() {
99            if ctx.is_inductive(name) {
100                return Some(name.clone());
101            }
102        }
103    }
104    None
105}
106
107fn disc_inductive(ctx: &Context, term: &Term) -> Option<String> {
108    match term {
109        Term::Global(name) => {
110            if ctx.is_constructor(name) {
111                ctx.constructor_inductive(name).map(|s| s.to_string())
112            } else if ctx.is_inductive(name) {
113                Some(name.clone())
114            } else {
115                None
116            }
117        }
118        Term::App(f, _) => disc_inductive(ctx, f),
119        _ => None,
120    }
121}
122
123fn is_mapped_primitive(name: &str) -> bool {
124    matches!(
125        name,
126        "Int" | "Float" | "Text" | "Bool" | "Duration" | "Date" | "Moment"
127    )
128}
129
130/// StandardLibrary types that encode logic/proof/reflection rather than user data
131/// (`Syntax` ASTs, `Eq`/`And`/`Ex` propositions, `Derivation` proofs, …). Values of
132/// these are not the "compile my data to Rust" use case and don't extract cleanly,
133/// so definitions over them are left as a note instead of emitting broken Rust.
134pub fn is_logical_type(name: &str) -> bool {
135    matches!(
136        name,
137        "Syntax"
138            | "Derivation"
139            | "Eq"
140            | "And"
141            | "Or"
142            | "Iff"
143            | "Ex"
144            | "Not"
145            | "True"
146            | "False"
147            | "Entity"
148            | "Univ"
149            | "Prop"
150    )
151}
152
153/// Collect all dependencies of a definition.
154///
155/// Starting from an entry point, recursively collects all global names
156/// that are referenced, including inductives, constructors, and definitions.
157pub fn collect_dependencies(ctx: &Context, entry: &str) -> HashSet<String> {
158    let mut visited = HashSet::new();
159    let mut to_visit = vec![entry.to_string()];
160
161    while let Some(name) = to_visit.pop() {
162        if visited.contains(&name) {
163            continue;
164        }
165        visited.insert(name.clone());
166
167        // The prelude's arithmetic lowers to an operator, so it depends on NOTHING — see
168        // `extractable`. Following `add` into `Int_add` would pull the structural integer
169        // tower (and `Nat`) into every module that adds two numbers.
170        if super::codegen::arith_builtin_operator(ctx, &name).is_some() {
171            continue;
172        }
173
174        // Get the term to analyze based on what kind of global it is
175        if let Some(body) = ctx.get_definition_body(&name) {
176            collect_globals(body, &mut to_visit);
177            // Also collect from the type
178            if let Some(ty) = ctx.get_definition_type(&name) {
179                collect_globals(ty, &mut to_visit);
180            }
181        }
182
183        if ctx.is_inductive(&name) {
184            // Add constructors and their types
185            for (ctor_name, ctor_ty) in ctx.get_constructors(&name) {
186                collect_globals(ctor_ty, &mut to_visit);
187                to_visit.push(ctor_name.to_string());
188            }
189        }
190
191        if ctx.is_constructor(&name) {
192            // Add the inductive type
193            if let Some(ind) = ctx.constructor_inductive(&name) {
194                to_visit.push(ind.to_string());
195            }
196        }
197    }
198
199    visited
200}
201
202/// Recursively collect all Global references from a term.
203pub(crate) fn collect_globals(term: &Term, deps: &mut Vec<String>) {
204    match term {
205        Term::Global(name) => deps.push(name.clone()),
206        Term::Const { name, .. } => deps.push(name.clone()),
207        Term::App(f, a) => {
208            collect_globals(f, deps);
209            collect_globals(a, deps);
210        }
211        Term::Lambda {
212            param_type, body, ..
213        } => {
214            collect_globals(param_type, deps);
215            collect_globals(body, deps);
216        }
217        Term::Pi {
218            param_type,
219            body_type,
220            ..
221        } => {
222            collect_globals(param_type, deps);
223            collect_globals(body_type, deps);
224        }
225        Term::Fix { body, .. } => collect_globals(body, deps),
226        Term::Match {
227            discriminant,
228            motive,
229            cases,
230        } => {
231            collect_globals(discriminant, deps);
232            collect_globals(motive, deps);
233            for case in cases {
234                collect_globals(case, deps);
235            }
236        }
237        Term::Let {
238            ty, value, body, ..
239        } => {
240            collect_globals(ty, deps);
241            collect_globals(value, deps);
242            collect_globals(body, deps);
243        }
244        Term::MutualFix { defs, .. } => {
245            for (_, body) in defs {
246                collect_globals(body, deps);
247            }
248        }
249        Term::Annotated { term, .. } => collect_globals(term, deps),
250        // Base cases: no dependencies
251        Term::Sort(_) | Term::Var(_) | Term::Lit(_) | Term::Hole => {}
252    }
253}