Skip to main content

logicaffeine_language/
proof_convert.rs

1//! Conversion from parser AST to proof engine representation.
2//!
3//! This module bridges the parser's arena-allocated AST ([`LogicExpr<'a>`]) to the
4//! proof engine's owned representation ([`ProofExpr`]).
5//!
6//! The conversion clones all data into owned Strings, enabling proof trees
7//! to persist beyond the arena's lifetime. Symbols are resolved using the
8//! interner at conversion time.
9//!
10//! # Key Function
11//!
12//! [`logic_expr_to_proof_expr`] is the main entry point for converting
13//! parsed expressions to the format expected by the proof search engine.
14
15use crate::ast::logic::{
16    LogicExpr, ModalDomain, ModalFlavor, QuantifierKind, TemporalOperator, Term,
17};
18use crate::intern::Interner;
19use crate::lexicon::get_canonical_noun;
20
21/// "John and Mary left": a distributive verb says of a group what it says of each member —
22/// `leave(John ⊕ Mary)` holds as `leave(John) ∧ leave(Mary)`. A collective verb (meet, gather)
23/// or one that may be collective (carry, lift) keeps the group, and so does anything that is
24/// not a verb at all ("a is part of a ⊕ b").
25fn distributes_over_its_subject(verb: &str) -> bool {
26    let lemma = verb.to_lowercase();
27    crate::lexicon::lookup_verb_db(&lemma).is_some()
28        && !crate::lexicon::is_collective_verb(&lemma)
29        && !crate::lexicon::is_mixed_verb(&lemma)
30}
31
32/// The conjunction of `parts`, left to right.
33fn conjoin(parts: impl IntoIterator<Item = ProofExpr>) -> ProofExpr {
34    let mut parts = parts.into_iter();
35    let first = parts.next().expect("a group has members");
36    parts.fold(first, |so_far, next| {
37        ProofExpr::And(Box::new(so_far), Box::new(next))
38    })
39}
40use crate::token::TokenType;
41use logicaffeine_proof::{ProofExpr, ProofTerm};
42
43// =============================================================================
44// PUBLIC API
45// =============================================================================
46
47/// Map the parser's comparison-predicate names onto the proof oracle's canonical,
48/// case-sensitive vocabulary (`Gt`/`Lt`/`Gte`/`Lte`/`Eq`/`Neq`; see oracle.rs:879
49/// and modal_translation.rs:124). Returns `None` for any non-comparison name,
50/// which then falls through to ordinary noun normalization. The parser only ever
51/// emits these names for binary degree comparisons, so the caller gates on arity 2.
52fn canonical_comparison_name(name: &str) -> Option<&'static str> {
53    match name {
54        "Greater" | "Gt" => Some("Gt"),
55        "Less" | "Lt" => Some("Lt"),
56        "GreaterEqual" | "Gte" => Some("Gte"),
57        "LessEqual" | "Lte" => Some("Lte"),
58        "Equal" | "Eq" => Some("Eq"),
59        "NotEqual" | "Neq" => Some("Neq"),
60        _ => None,
61    }
62}
63
64/// Map the parser's arithmetic-function names onto the oracle's canonical,
65/// case-sensitive `Add`/`Sub`/`Mul`/`Div` (see oracle.rs:1034). Returns `None`
66/// for every other function name so measure functions (`Score`, `Ord`, …) stay
67/// verbatim as uninterpreted integer functions.
68fn canonical_arithmetic_fn(name: &str) -> Option<&'static str> {
69    match name {
70        "add" | "Add" => Some("Add"),
71        "sub" | "Sub" => Some("Sub"),
72        "mul" | "Mul" => Some("Mul"),
73        "div" | "Div" => Some("Div"),
74        _ => None,
75    }
76}
77
78/// Rename a free variable `from` → `to` inside a [`ProofTerm`].
79fn subst_proof_term(t: &ProofTerm, from: &str, to: &str) -> ProofTerm {
80    match t {
81        ProofTerm::Variable(v) if v == from => ProofTerm::Variable(to.to_string()),
82        ProofTerm::BoundVarRef(v) if v == from => ProofTerm::BoundVarRef(to.to_string()),
83        ProofTerm::Function(name, args) => ProofTerm::Function(
84            name.clone(),
85            args.iter().map(|a| subst_proof_term(a, from, to)).collect(),
86        ),
87        ProofTerm::Group(args) => {
88            ProofTerm::Group(args.iter().map(|a| subst_proof_term(a, from, to)).collect())
89        }
90        other => other.clone(),
91    }
92}
93
94/// Rename a free variable `from` → `to` inside a [`ProofExpr`], stopping at a
95/// quantifier that re-binds `from` (capture avoidance). Used to build the
96/// uniqueness clause of an "exactly one" expansion.
97fn subst_proof_var(e: &ProofExpr, from: &str, to: &str) -> ProofExpr {
98    match e {
99        ProofExpr::Predicate { name, args, world } => ProofExpr::Predicate {
100            name: name.clone(),
101            args: args.iter().map(|a| subst_proof_term(a, from, to)).collect(),
102            world: world.clone(),
103        },
104        ProofExpr::Identity(a, b) => {
105            ProofExpr::Identity(subst_proof_term(a, from, to), subst_proof_term(b, from, to))
106        }
107        ProofExpr::And(l, r) => ProofExpr::And(
108            Box::new(subst_proof_var(l, from, to)),
109            Box::new(subst_proof_var(r, from, to)),
110        ),
111        ProofExpr::Or(l, r) => ProofExpr::Or(
112            Box::new(subst_proof_var(l, from, to)),
113            Box::new(subst_proof_var(r, from, to)),
114        ),
115        ProofExpr::Implies(l, r) => ProofExpr::Implies(
116            Box::new(subst_proof_var(l, from, to)),
117            Box::new(subst_proof_var(r, from, to)),
118        ),
119        ProofExpr::Iff(l, r) => ProofExpr::Iff(
120            Box::new(subst_proof_var(l, from, to)),
121            Box::new(subst_proof_var(r, from, to)),
122        ),
123        ProofExpr::Not(x) => ProofExpr::Not(Box::new(subst_proof_var(x, from, to))),
124        ProofExpr::ForAll { variable, body } if variable != from => ProofExpr::ForAll {
125            variable: variable.clone(),
126            body: Box::new(subst_proof_var(body, from, to)),
127        },
128        ProofExpr::Exists { variable, body } if variable != from => ProofExpr::Exists {
129            variable: variable.clone(),
130            body: Box::new(subst_proof_var(body, from, to)),
131        },
132        ProofExpr::Temporal { operator, body } => ProofExpr::Temporal {
133            operator: operator.clone(),
134            body: Box::new(subst_proof_var(body, from, to)),
135        },
136        ProofExpr::Term(t) => ProofExpr::Term(subst_proof_term(t, from, to)),
137        other => other.clone(),
138    }
139}
140
141fn subst_term_with(t: &ProofTerm, from: &str, to: &ProofTerm) -> ProofTerm {
142    match t {
143        ProofTerm::Variable(v) if v == from => to.clone(),
144        ProofTerm::BoundVarRef(v) if v == from => to.clone(),
145        ProofTerm::Function(name, args) => ProofTerm::Function(
146            name.clone(),
147            args.iter().map(|a| subst_term_with(a, from, to)).collect(),
148        ),
149        ProofTerm::Group(args) => {
150            ProofTerm::Group(args.iter().map(|a| subst_term_with(a, from, to)).collect())
151        }
152        other => other.clone(),
153    }
154}
155
156/// Substitute a free variable `from` with the CONSTANT `to` inside a [`ProofExpr`]
157/// — the operation that turns a wh-question body φ(x) into a candidate goal φ(c),
158/// so "who/what is …?" is answered by enumerating domain individuals and proving
159/// each candidate. Stops at a quantifier that re-binds `from` (capture avoidance).
160pub fn instantiate_var_with_constant(e: &ProofExpr, from: &str, to: &str) -> ProofExpr {
161    let c = ProofTerm::Constant(to.to_string());
162    subst_expr_with(e, from, &c)
163}
164
165fn subst_expr_with(e: &ProofExpr, from: &str, to: &ProofTerm) -> ProofExpr {
166    match e {
167        ProofExpr::Predicate { name, args, world } => ProofExpr::Predicate {
168            name: name.clone(),
169            args: args.iter().map(|a| subst_term_with(a, from, to)).collect(),
170            world: world.clone(),
171        },
172        ProofExpr::Identity(a, b) => {
173            ProofExpr::Identity(subst_term_with(a, from, to), subst_term_with(b, from, to))
174        }
175        ProofExpr::And(l, r) => ProofExpr::And(
176            Box::new(subst_expr_with(l, from, to)),
177            Box::new(subst_expr_with(r, from, to)),
178        ),
179        ProofExpr::Or(l, r) => ProofExpr::Or(
180            Box::new(subst_expr_with(l, from, to)),
181            Box::new(subst_expr_with(r, from, to)),
182        ),
183        ProofExpr::Implies(l, r) => ProofExpr::Implies(
184            Box::new(subst_expr_with(l, from, to)),
185            Box::new(subst_expr_with(r, from, to)),
186        ),
187        ProofExpr::Iff(l, r) => ProofExpr::Iff(
188            Box::new(subst_expr_with(l, from, to)),
189            Box::new(subst_expr_with(r, from, to)),
190        ),
191        ProofExpr::Not(x) => ProofExpr::Not(Box::new(subst_expr_with(x, from, to))),
192        ProofExpr::ForAll { variable, body } if variable != from => ProofExpr::ForAll {
193            variable: variable.clone(),
194            body: Box::new(subst_expr_with(body, from, to)),
195        },
196        ProofExpr::Exists { variable, body } if variable != from => ProofExpr::Exists {
197            variable: variable.clone(),
198            body: Box::new(subst_expr_with(body, from, to)),
199        },
200        ProofExpr::Temporal { operator, body } => ProofExpr::Temporal {
201            operator: operator.clone(),
202            body: Box::new(subst_expr_with(body, from, to)),
203        },
204        ProofExpr::Term(t) => ProofExpr::Term(subst_term_with(t, from, to)),
205        other => other.clone(),
206    }
207}
208
209/// Convert a LogicExpr to ProofExpr.
210///
211/// This is the main entry point for bridging the parser to the proof engine.
212/// All Symbols are resolved to owned Strings using the interner.
213pub fn logic_expr_to_proof_expr<'a>(expr: &LogicExpr<'a>, interner: &Interner) -> ProofExpr {
214    match expr {
215        // --- Core FOL ---
216        LogicExpr::Predicate { name, args, world } => {
217            // Semantic Normalization:
218            // 1. Lemmatize: "cats" → "Cat", "men" → "Man" (canonical noun form)
219            // 2. Lowercase: "Cat" → "cat", "Mortal" → "mortal"
220            // This ensures "Mortal" (noun) == "mortal" (adj) == "mortals" (plural noun)
221            let name_str = interner.resolve(*name);
222            // A binary comparison predicate carries arithmetic meaning the oracle
223            // recognises only under its canonical name; it bypasses noun
224            // normalization (which would lowercase "Greater" → "greater" and strand
225            // the comparison as an uninterpreted function the solver cannot use).
226            let normalized = match (args.len() == 2)
227                .then(|| canonical_comparison_name(name_str))
228                .flatten()
229            {
230                Some(canon) => canon.to_string(),
231                None => get_canonical_noun(&name_str.to_lowercase())
232                    .map(|lemma| lemma.to_lowercase())
233                    .unwrap_or_else(|| name_str.to_lowercase()),
234            };
235
236            let lowered: Vec<ProofTerm> = args
237                .iter()
238                .map(|t| term_to_proof_term(t, interner))
239                .collect();
240
241            // An equality whose sides are ARITHMETIC is a ring identity — lower `Eq(e1, e2)` to
242            // `Identity(e1, e2)` so the arithmetic oracle (the engine's `try_arithmetic`) can decide it,
243            // rather than leaving it as an uninterpreted binary relation. Gated on a side actually being
244            // arithmetic, so a general `Eq(x, y)` over entities stays a `Predicate` and existing FOL
245            // equality handling is untouched.
246            let is_arith_term = |t: &ProofTerm| {
247                matches!(
248                    t,
249                    ProofTerm::Function(n, _)
250                        if matches!(
251                            n.as_str(),
252                            "Add" | "Sub" | "Mul" | "Div" | "add" | "sub" | "mul" | "div" | "mod"
253                        )
254                )
255            };
256            if normalized == "Eq"
257                && lowered.len() == 2
258                && (is_arith_term(&lowered[0]) || is_arith_term(&lowered[1]))
259            {
260                let mut it = lowered.into_iter();
261                return ProofExpr::Identity(it.next().unwrap(), it.next().unwrap());
262            }
263
264            let world = world.map(|w| interner.resolve(w).to_string());
265            if let Some(ProofTerm::Group(members)) = lowered
266                .first()
267                .filter(|_| distributes_over_its_subject(&normalized))
268            {
269                return conjoin(members.iter().map(|member| {
270                    let mut args = lowered.clone();
271                    args[0] = member.clone();
272                    ProofExpr::Predicate {
273                        name: normalized.clone(),
274                        args,
275                        world: world.clone(),
276                    }
277                }));
278            }
279            ProofExpr::Predicate {
280                name: normalized,
281                args: lowered,
282                world,
283            }
284        }
285
286        LogicExpr::Identity { left, right } => ProofExpr::Identity(
287            term_to_proof_term(left, interner),
288            term_to_proof_term(right, interner),
289        ),
290
291        LogicExpr::Atom(s) => ProofExpr::Atom(interner.resolve(*s).to_string()),
292
293        // --- Quantifiers ---
294        LogicExpr::Quantifier {
295            kind,
296            variable,
297            body,
298            ..
299        } => {
300            let var_name = interner.resolve(*variable).to_string();
301            let body_expr = Box::new(logic_expr_to_proof_expr(body, interner));
302
303            match kind {
304                QuantifierKind::Universal => ProofExpr::ForAll {
305                    variable: var_name,
306                    body: body_expr,
307                },
308                QuantifierKind::Existential => ProofExpr::Exists {
309                    variable: var_name,
310                    body: body_expr,
311                },
312                // Map other quantifiers to existential with a note
313                QuantifierKind::Most => ProofExpr::Unsupported("Most quantifier".into()),
314                QuantifierKind::Few => ProofExpr::Unsupported("Few quantifier".into()),
315                QuantifierKind::Many => ProofExpr::Unsupported("Many quantifier".into()),
316                QuantifierKind::Generic => ProofExpr::ForAll {
317                    variable: var_name,
318                    body: body_expr,
319                },
320                QuantifierKind::Cardinal(1) => {
321                    // "Exactly one x: φ(x)" = ∃x(φ(x) ∧ ∀y(φ(y) → y = x)) — existence
322                    // PLUS uniqueness, the form the entailment oracle reasons over.
323                    // Dropping the count (plain ∃) loses the constraint a logic-grid
324                    // bijection depends on.
325                    let x = var_name;
326                    let y = format!("{x}_uniq");
327                    let phi_y = Box::new(subst_proof_var(&body_expr, &x, &y));
328                    let uniqueness = ProofExpr::ForAll {
329                        variable: y.clone(),
330                        body: Box::new(ProofExpr::Implies(
331                            phi_y,
332                            Box::new(ProofExpr::Identity(
333                                ProofTerm::Variable(y),
334                                ProofTerm::Variable(x.clone()),
335                            )),
336                        )),
337                    };
338                    ProofExpr::Exists {
339                        variable: x,
340                        body: Box::new(ProofExpr::And(body_expr, Box::new(uniqueness))),
341                    }
342                }
343                QuantifierKind::Cardinal(n) => {
344                    // n ≥ 2: existence is a sound (if incomplete) weakening of the
345                    // exact count for the proof path.
346                    ProofExpr::Exists {
347                        variable: format!("{}_{}", var_name, n),
348                        body: body_expr,
349                    }
350                }
351                QuantifierKind::AtLeast(_) | QuantifierKind::AtMost(_) => {
352                    ProofExpr::Unsupported("Counting quantifier".into())
353                }
354                // The infinitary quantifiers read over the order of the naturals, where a set is
355                // infinite exactly when it is unbounded: ∃^∞x φ is ∀b ∃x (x > b ∧ φ), ∀^∞x φ is
356                // ∃b ∀x (x > b → φ), and ∃^<∞x φ is ∃b ∀x (x > b → ¬φ).
357                QuantifierKind::InfinitelyMany
358                | QuantifierKind::FinitelyMany
359                | QuantifierKind::AllButFinitelyMany => {
360                    let bound = format!("{var_name}_bound");
361                    let past_bound = Box::new(ProofExpr::Predicate {
362                        name: "Gt".to_string(),
363                        args: vec![
364                            ProofTerm::Variable(var_name.clone()),
365                            ProofTerm::Variable(bound.clone()),
366                        ],
367                        world: None,
368                    });
369                    match kind {
370                        QuantifierKind::InfinitelyMany => ProofExpr::ForAll {
371                            variable: bound,
372                            body: Box::new(ProofExpr::Exists {
373                                variable: var_name,
374                                body: Box::new(ProofExpr::And(past_bound, body_expr)),
375                            }),
376                        },
377                        QuantifierKind::FinitelyMany => ProofExpr::Exists {
378                            variable: bound,
379                            body: Box::new(ProofExpr::ForAll {
380                                variable: var_name,
381                                body: Box::new(ProofExpr::Implies(
382                                    past_bound,
383                                    Box::new(ProofExpr::Not(body_expr)),
384                                )),
385                            }),
386                        },
387                        _ => ProofExpr::Exists {
388                            variable: bound,
389                            body: Box::new(ProofExpr::ForAll {
390                                variable: var_name,
391                                body: Box::new(ProofExpr::Implies(past_bound, body_expr)),
392                            }),
393                        },
394                    }
395                }
396            }
397        }
398
399        // --- Logical Connectives ---
400        LogicExpr::BinaryOp { left, op, right } => {
401            let l = Box::new(logic_expr_to_proof_expr(left, interner));
402            let r = Box::new(logic_expr_to_proof_expr(right, interner));
403
404            match op {
405                TokenType::And => ProofExpr::And(l, r),
406                TokenType::Or => ProofExpr::Or(l, r),
407                TokenType::If | TokenType::Implies | TokenType::Then => ProofExpr::Implies(l, r),
408                TokenType::Iff => ProofExpr::Iff(l, r),
409                _ => ProofExpr::Unsupported(format!("Binary operator {:?}", op)),
410            }
411        }
412
413        LogicExpr::UnaryOp { op, operand } => {
414            let inner = Box::new(logic_expr_to_proof_expr(operand, interner));
415            match op {
416                TokenType::Not => ProofExpr::Not(inner),
417                _ => ProofExpr::Unsupported(format!("Unary operator {:?}", op)),
418            }
419        }
420
421        // --- Modal Logic ---
422        LogicExpr::Modal { vector, operand } => {
423            let body = Box::new(logic_expr_to_proof_expr(operand, interner));
424            let domain = match vector.domain {
425                ModalDomain::Alethic => "Alethic",
426                ModalDomain::Deontic => "Deontic",
427                ModalDomain::Temporal => "Temporal",
428            };
429            let flavor = match vector.flavor {
430                ModalFlavor::Root => "Root",
431                ModalFlavor::Epistemic => "Epistemic",
432                ModalFlavor::Evidential => "Evidential",
433                ModalFlavor::Bouletic => "Bouletic",
434            };
435            ProofExpr::Modal {
436                domain: domain.to_string(),
437                force: vector.force,
438                flavor: flavor.to_string(),
439                body,
440            }
441        }
442
443        // --- Temporal Logic ---
444        LogicExpr::Temporal { operator, body } => {
445            let body_expr = logic_expr_to_proof_expr(body, interner);
446            let op_name = match operator {
447                TemporalOperator::Past => "Past",
448                TemporalOperator::Future => "Future",
449                TemporalOperator::Always => "Always",
450                TemporalOperator::Eventually | TemporalOperator::BoundedEventually(_) => {
451                    "Eventually"
452                }
453                TemporalOperator::Next => "Next",
454            };
455            // A single predicate or event that converted to a conjunction is a group's
456            // distribution: each member's share is that member's own event, stated as the
457            // member's own sentence states it — and an event reaches the prover tenselessly (a
458            // NeoEvent carries no tense), so "John and Mary left" gives it leave(John) and
459            // leave(Mary) exactly as "John left" gives it leave(John).
460            if matches!(body, LogicExpr::Predicate { .. } | LogicExpr::NeoEvent(_))
461                && matches!(body_expr, ProofExpr::And(..))
462            {
463                return body_expr;
464            }
465            ProofExpr::Temporal {
466                operator: op_name.to_string(),
467                body: Box::new(body_expr),
468            }
469        }
470
471        LogicExpr::TemporalBinary {
472            operator,
473            left,
474            right,
475        } => ProofExpr::TemporalBinary {
476            operator: format!("{:?}", operator),
477            left: Box::new(logic_expr_to_proof_expr(left, interner)),
478            right: Box::new(logic_expr_to_proof_expr(right, interner)),
479        },
480
481        // --- Lambda Calculus ---
482        LogicExpr::Lambda { variable, body } => ProofExpr::Lambda {
483            variable: interner.resolve(*variable).to_string(),
484            body: Box::new(logic_expr_to_proof_expr(body, interner)),
485        },
486
487        LogicExpr::App { function, argument } => ProofExpr::App(
488            Box::new(logic_expr_to_proof_expr(function, interner)),
489            Box::new(logic_expr_to_proof_expr(argument, interner)),
490        ),
491
492        // --- Event Semantics ---
493        LogicExpr::NeoEvent(data) => {
494            let roles: Vec<(String, ProofTerm)> = data
495                .roles
496                .iter()
497                .map(|(role, term)| {
498                    let role_name = role.name();
499                    (role_name.to_string(), term_to_proof_term(term, interner))
500                })
501                .collect();
502
503            let event_var = interner.resolve(data.event_var).to_string();
504            let verb = interner.resolve(data.verb).to_string();
505            let agent_group = roles
506                .iter()
507                .position(|(role, term)| role == "Agent" && matches!(term, ProofTerm::Group(_)));
508            if let Some(at) = agent_group.filter(|_| distributes_over_its_subject(&verb)) {
509                let ProofTerm::Group(members) = roles[at].1.clone() else {
510                    unreachable!("matched a group")
511                };
512                return conjoin(members.into_iter().map(|member| {
513                    let mut own = roles.clone();
514                    own[at].1 = member;
515                    ProofExpr::NeoEvent {
516                        event_var: event_var.clone(),
517                        verb: verb.clone(),
518                        roles: own,
519                    }
520                }));
521            }
522            ProofExpr::NeoEvent {
523                event_var,
524                verb,
525                roles,
526            }
527        }
528
529        // --- Counterfactual ---
530        LogicExpr::Counterfactual {
531            antecedent,
532            consequent,
533        } => {
534            // □→ keeps closest-world semantics: the consequent is quantified
535            // over the similarity-closest antecedent-worlds, never lowered to
536            // material implication (§4.5).
537            ProofExpr::Counterfactual {
538                antecedent: Box::new(logic_expr_to_proof_expr(antecedent, interner)),
539                consequent: Box::new(logic_expr_to_proof_expr(consequent, interner)),
540            }
541        }
542
543        // --- Unsupported constructs (return Unsupported variant) ---
544        LogicExpr::Categorical(_) => ProofExpr::Unsupported("Categorical (legacy)".into()),
545        LogicExpr::Relation(_) => ProofExpr::Unsupported("Relation (legacy)".into()),
546        LogicExpr::Metaphor { .. } => ProofExpr::Unsupported("Metaphor".into()),
547        // A wh-question "Who is a lawyer?" is the GOAL ∃x.φ(x): proving it means
548        // SOMEONE satisfies φ; the ANSWER is the witness (extracted by enumerating
549        // the domain in `answer_question`). Carrying the variable + body lets the
550        // answer layer recover both.
551        LogicExpr::Question { wh_variable, body } => ProofExpr::Exists {
552            variable: interner.resolve(*wh_variable).to_string(),
553            body: Box::new(logic_expr_to_proof_expr(body, interner)),
554        },
555        LogicExpr::YesNoQuestion { .. } => ProofExpr::Unsupported("YesNoQuestion".into()),
556        LogicExpr::Intensional { .. } => ProofExpr::Unsupported("Intensional".into()),
557        LogicExpr::Event { .. } => ProofExpr::Unsupported("Event (legacy)".into()),
558        LogicExpr::Imperative { action } => {
559            // Directive(h, p) → O_g p: the commanded action becomes a bouletic
560            // obligation over the addressee's action worlds (§1.4). The action
561            // itself is NOT asserted — commanding is not doing.
562            ProofExpr::Modal {
563                domain: "Deontic".to_string(),
564                force: 1.0,
565                flavor: "Bouletic".to_string(),
566                body: Box::new(logic_expr_to_proof_expr(action, interner)),
567            }
568        }
569        LogicExpr::Exclamative { body, .. } => {
570            // The presupposed/asserted content is the body predication.
571            logic_expr_to_proof_expr(body, interner)
572        }
573        LogicExpr::Optative { wish } => {
574            // Wish(speaker, ⟨p⟩): a bouletic necessity over the speaker's
575            // preference-ideal worlds (§1.2); the complement is not entailed.
576            ProofExpr::Modal {
577                domain: "Deontic".to_string(),
578                force: 1.0,
579                flavor: "Bouletic".to_string(),
580                body: Box::new(logic_expr_to_proof_expr(wish, interner)),
581            }
582        }
583        LogicExpr::Implicature { assertion, .. } => {
584            // Truth-conditional content is the literal assertion; the implicature is
585            // defeasible/cancellable and not part of the entailment core.
586            logic_expr_to_proof_expr(assertion, interner)
587        }
588        LogicExpr::SpeechAct {
589            performer,
590            act_type,
591            ..
592        } => {
593            // A performative asserts that the act is performed at the utterance
594            // world (the saying is the doing): `act_type(performer)`. The
595            // propositional content is NOT asserted — promising to φ does not make
596            // φ true — so it is deliberately not conjoined here.
597            ProofExpr::Predicate {
598                name: interner.resolve(*act_type).to_lowercase(),
599                args: vec![term_to_proof_term(&Term::Constant(*performer), interner)],
600                world: None,
601            }
602        }
603        LogicExpr::Causal { .. } => ProofExpr::Unsupported("Causal".into()),
604        LogicExpr::Concessive { main, .. } => {
605            // The main clause is asserted; the concession is backgrounded (a defeated
606            // expectation), so the truth-conditional content reduces to the main.
607            logic_expr_to_proof_expr(main, interner)
608        }
609        LogicExpr::Comparative { .. } => ProofExpr::Unsupported("Comparative".into()),
610        LogicExpr::Superlative { .. } => ProofExpr::Unsupported("Superlative".into()),
611        LogicExpr::Scopal { .. } => ProofExpr::Unsupported("Scopal".into()),
612        LogicExpr::Control { .. } => ProofExpr::Unsupported("Control".into()),
613        LogicExpr::Presupposition {
614            assertion,
615            presupposition,
616        } => {
617            // A surviving (projected/accommodated) presupposition is real
618            // content: "Mary doesn't regret lying" carries both ¬Regret and
619            // the projected Lied(mary). Bound/filtered presuppositions are
620            // rewritten away before this point (Van der Sandt pass), so the
621            // conjunction is monotonically sound.
622            ProofExpr::And(
623                Box::new(logic_expr_to_proof_expr(assertion, interner)),
624                Box::new(logic_expr_to_proof_expr(presupposition, interner)),
625            )
626        }
627        LogicExpr::Focus { scope, .. } => {
628            // Focus marking is information structure; the truth-conditional
629            // content is the scope. Cleft exhaustivity is already a separate
630            // conjunct built by the parser.
631            logic_expr_to_proof_expr(scope, interner)
632        }
633        LogicExpr::TemporalAnchor { .. } => ProofExpr::Unsupported("TemporalAnchor".into()),
634        LogicExpr::Distributive { predicate } => {
635            // *P(σN) — atomic distribution over the plural sum. Members of
636            // σN are exactly the Ns (Link lattice atoms), so the first-order
637            // form is ∀x(N(x) → P(x)).
638            let base = logic_expr_to_proof_expr(predicate, interner);
639            match find_sigma_symbol(predicate) {
640                Some(noun) => {
641                    let noun_str = interner.resolve(noun).to_string();
642                    let noun_pred = get_canonical_noun(&noun_str.to_lowercase())
643                        .map(|lemma| lemma.to_lowercase())
644                        .unwrap_or_else(|| noun_str.to_lowercase());
645                    let var = format!("each_{}", noun_pred);
646                    let sigma_term = ProofTerm::Variable(noun_str);
647                    let member = ProofTerm::Variable(var.clone());
648                    let body = replace_proof_term(&base, &sigma_term, &member);
649                    ProofExpr::ForAll {
650                        variable: var.clone(),
651                        body: Box::new(ProofExpr::Implies(
652                            Box::new(ProofExpr::Predicate {
653                                name: noun_pred,
654                                args: vec![ProofTerm::Variable(var)],
655                                world: None,
656                            }),
657                            Box::new(body),
658                        )),
659                    }
660                }
661                None => base,
662            }
663        }
664        LogicExpr::GroupQuantifier {
665            group_var,
666            count,
667            member_var,
668            restriction,
669            body,
670        } => {
671            // ∃g(group(g) ∧ count(g, n) ∧ ∀x(member(x, g) → R(x)) ∧ B(g))
672            let g = interner.resolve(*group_var).to_string();
673            let x = interner.resolve(*member_var).to_string();
674            let group_pred = ProofExpr::Predicate {
675                name: "group".to_string(),
676                args: vec![ProofTerm::Variable(g.clone())],
677                world: None,
678            };
679            let count_pred = ProofExpr::Predicate {
680                name: "count".to_string(),
681                args: vec![
682                    ProofTerm::Variable(g.clone()),
683                    ProofTerm::Constant(count.to_string()),
684                ],
685                world: None,
686            };
687            let member_pred = ProofExpr::Predicate {
688                name: "member".to_string(),
689                args: vec![
690                    ProofTerm::Variable(x.clone()),
691                    ProofTerm::Variable(g.clone()),
692                ],
693                world: None,
694            };
695            let members = ProofExpr::ForAll {
696                variable: x,
697                body: Box::new(ProofExpr::Implies(
698                    Box::new(member_pred),
699                    Box::new(logic_expr_to_proof_expr(restriction, interner)),
700                )),
701            };
702            ProofExpr::Exists {
703                variable: g,
704                body: Box::new(ProofExpr::And(
705                    Box::new(ProofExpr::And(
706                        Box::new(ProofExpr::And(Box::new(group_pred), Box::new(count_pred))),
707                        Box::new(members),
708                    )),
709                    Box::new(logic_expr_to_proof_expr(body, interner)),
710                )),
711            }
712        }
713        // Aspectual wrappers (Imperfective, Perfective, etc.) are transparent to proof.
714        // "John runs" -> Aspectual(Imperfective, ∃e(Run(e) ∧ Agent(e, John)))
715        // We pass through to the inner event structure.
716        LogicExpr::Aspectual { body, .. } => logic_expr_to_proof_expr(body, interner),
717        LogicExpr::Voice { .. } => ProofExpr::Unsupported("Voice".into()),
718    }
719}
720
721/// Convert a Term to ProofTerm.
722/// A defeasible default extracted by [`logic_expr_to_proof_expr_defeasible`]:
723/// the abnormality predicate guarding one GEN rule or implicature.
724#[derive(Debug, Clone)]
725pub struct DefaultRule {
726    /// The abnormality predicate name (`ab_1`, `ab_2`, …).
727    pub ab_name: String,
728    /// The generic's restrictor predicate ("penguin" in GEN x(Penguin → …)),
729    /// used for specificity ordering. `None` for implicatures.
730    pub restriction_pred: Option<String>,
731    /// Unary (per-individual, generics) vs propositional (implicatures).
732    pub unary: bool,
733}
734
735/// Convert with DEFEASIBLE semantics: a generic `GEN x(R(x) → N(x))` becomes
736/// the abnormality-guarded `∀x((R(x) ∧ ¬ab_k(x)) → N(x))`, and an implicature
737/// is asserted under its own guard (`assertion ∧ (¬ab_k → implicature)`).
738/// The circumscription itself — minimizing each `ab_k` — happens in the
739/// defeasible reasoner; this conversion only preserves what the strict
740/// export (`Generic → ∀`, implicature dropped) erases.
741pub fn logic_expr_to_proof_expr_defeasible<'a>(
742    expr: &LogicExpr<'a>,
743    interner: &Interner,
744    defaults: &mut Vec<DefaultRule>,
745) -> ProofExpr {
746    match expr {
747        LogicExpr::Quantifier {
748            kind: QuantifierKind::Generic,
749            variable,
750            body,
751            ..
752        } => {
753            let var = interner.resolve(*variable).to_string();
754            if let LogicExpr::BinaryOp {
755                left: restriction,
756                op: TokenType::Implies | TokenType::If,
757                right: nucleus,
758            } = body
759            {
760                let ab_name = format!("ab_{}", defaults.len() + 1);
761                let restriction_pred = match restriction {
762                    LogicExpr::Predicate { name, .. } => {
763                        let s = interner.resolve(*name);
764                        Some(
765                            get_canonical_noun(&s.to_lowercase())
766                                .map(|l| l.to_lowercase())
767                                .unwrap_or_else(|| s.to_lowercase()),
768                        )
769                    }
770                    _ => None,
771                };
772                defaults.push(DefaultRule {
773                    ab_name: ab_name.clone(),
774                    restriction_pred,
775                    unary: true,
776                });
777                let guarded = ProofExpr::And(
778                    Box::new(logic_expr_to_proof_expr(restriction, interner)),
779                    Box::new(ProofExpr::Not(Box::new(ProofExpr::Predicate {
780                        name: ab_name,
781                        args: vec![ProofTerm::Variable(var.clone())],
782                        world: None,
783                    }))),
784                );
785                return ProofExpr::ForAll {
786                    variable: var,
787                    body: Box::new(ProofExpr::Implies(
788                        Box::new(guarded),
789                        Box::new(logic_expr_to_proof_expr(nucleus, interner)),
790                    )),
791                };
792            }
793            logic_expr_to_proof_expr(expr, interner)
794        }
795        LogicExpr::Implicature {
796            assertion,
797            implicature,
798        } => {
799            let ab_name = format!("ab_{}", defaults.len() + 1);
800            defaults.push(DefaultRule {
801                ab_name: ab_name.clone(),
802                restriction_pred: None,
803                unary: false,
804            });
805            ProofExpr::And(
806                Box::new(logic_expr_to_proof_expr(assertion, interner)),
807                Box::new(ProofExpr::Implies(
808                    Box::new(ProofExpr::Not(Box::new(ProofExpr::Atom(ab_name)))),
809                    Box::new(logic_expr_to_proof_expr(implicature, interner)),
810                )),
811            )
812        }
813        // Containers recurse so defaults nested under connectives or
814        // presuppositions are still found.
815        LogicExpr::BinaryOp { left, op, right } => {
816            let l = logic_expr_to_proof_expr_defeasible(left, interner, defaults);
817            let r = logic_expr_to_proof_expr_defeasible(right, interner, defaults);
818            match op {
819                TokenType::And => ProofExpr::And(Box::new(l), Box::new(r)),
820                TokenType::Or => ProofExpr::Or(Box::new(l), Box::new(r)),
821                TokenType::If | TokenType::Implies => ProofExpr::Implies(Box::new(l), Box::new(r)),
822                TokenType::Iff => ProofExpr::Iff(Box::new(l), Box::new(r)),
823                _ => logic_expr_to_proof_expr(expr, interner),
824            }
825        }
826        LogicExpr::UnaryOp {
827            op: TokenType::Not,
828            operand,
829        } => ProofExpr::Not(Box::new(logic_expr_to_proof_expr_defeasible(
830            operand, interner, defaults,
831        ))),
832        LogicExpr::Presupposition {
833            assertion,
834            presupposition,
835        } => ProofExpr::And(
836            Box::new(logic_expr_to_proof_expr_defeasible(
837                assertion, interner, defaults,
838            )),
839            Box::new(logic_expr_to_proof_expr_defeasible(
840                presupposition,
841                interner,
842                defaults,
843            )),
844        ),
845        _ => logic_expr_to_proof_expr(expr, interner),
846    }
847}
848
849/// Find the first `Term::Sigma` symbol in an expression (the plural sum a
850/// `Distributive` operator ranges over).
851fn find_sigma_symbol<'a>(expr: &LogicExpr<'a>) -> Option<crate::Symbol> {
852    fn in_term<'a>(term: &Term<'a>) -> Option<crate::Symbol> {
853        match term {
854            Term::Sigma(s) => Some(*s),
855            Term::Function(_, args) | Term::Group(args) => args.iter().find_map(in_term),
856            Term::Possessed { possessor, .. } => in_term(possessor),
857            _ => None,
858        }
859    }
860    match expr {
861        LogicExpr::Predicate { args, .. } => args.iter().find_map(in_term),
862        LogicExpr::NeoEvent(data) => data.roles.iter().find_map(|(_, t)| in_term(t)),
863        LogicExpr::Quantifier { body, .. } => find_sigma_symbol(body),
864        LogicExpr::BinaryOp { left, right, .. } => {
865            find_sigma_symbol(left).or_else(|| find_sigma_symbol(right))
866        }
867        LogicExpr::UnaryOp { operand, .. } => find_sigma_symbol(operand),
868        LogicExpr::Modal { operand, .. } => find_sigma_symbol(operand),
869        LogicExpr::Temporal { body, .. } => find_sigma_symbol(body),
870        LogicExpr::Aspectual { body, .. } => find_sigma_symbol(body),
871        LogicExpr::Distributive { predicate } => find_sigma_symbol(predicate),
872        LogicExpr::Presupposition { assertion, .. } => find_sigma_symbol(assertion),
873        _ => None,
874    }
875}
876
877/// Replace every occurrence of `from` with `to` in the term positions of a
878/// proof expression (used to instantiate a plural sum by its members).
879fn replace_proof_term(expr: &ProofExpr, from: &ProofTerm, to: &ProofTerm) -> ProofExpr {
880    fn in_term(term: &ProofTerm, from: &ProofTerm, to: &ProofTerm) -> ProofTerm {
881        if term == from {
882            return to.clone();
883        }
884        match term {
885            ProofTerm::Function(name, args) => ProofTerm::Function(
886                name.clone(),
887                args.iter().map(|t| in_term(t, from, to)).collect(),
888            ),
889            ProofTerm::Group(terms) => {
890                ProofTerm::Group(terms.iter().map(|t| in_term(t, from, to)).collect())
891            }
892            other => other.clone(),
893        }
894    }
895    match expr {
896        ProofExpr::Predicate { name, args, world } => ProofExpr::Predicate {
897            name: name.clone(),
898            args: args.iter().map(|t| in_term(t, from, to)).collect(),
899            world: world.clone(),
900        },
901        ProofExpr::Identity(l, r) => {
902            ProofExpr::Identity(in_term(l, from, to), in_term(r, from, to))
903        }
904        ProofExpr::And(l, r) => ProofExpr::And(
905            Box::new(replace_proof_term(l, from, to)),
906            Box::new(replace_proof_term(r, from, to)),
907        ),
908        ProofExpr::Or(l, r) => ProofExpr::Or(
909            Box::new(replace_proof_term(l, from, to)),
910            Box::new(replace_proof_term(r, from, to)),
911        ),
912        ProofExpr::Implies(l, r) => ProofExpr::Implies(
913            Box::new(replace_proof_term(l, from, to)),
914            Box::new(replace_proof_term(r, from, to)),
915        ),
916        ProofExpr::Iff(l, r) => ProofExpr::Iff(
917            Box::new(replace_proof_term(l, from, to)),
918            Box::new(replace_proof_term(r, from, to)),
919        ),
920        ProofExpr::Not(inner) => ProofExpr::Not(Box::new(replace_proof_term(inner, from, to))),
921        ProofExpr::ForAll { variable, body } => ProofExpr::ForAll {
922            variable: variable.clone(),
923            body: Box::new(replace_proof_term(body, from, to)),
924        },
925        ProofExpr::Exists { variable, body } => ProofExpr::Exists {
926            variable: variable.clone(),
927            body: Box::new(replace_proof_term(body, from, to)),
928        },
929        ProofExpr::Modal {
930            domain,
931            force,
932            flavor,
933            body,
934        } => ProofExpr::Modal {
935            domain: domain.clone(),
936            force: *force,
937            flavor: flavor.clone(),
938            body: Box::new(replace_proof_term(body, from, to)),
939        },
940        ProofExpr::Counterfactual {
941            antecedent,
942            consequent,
943        } => ProofExpr::Counterfactual {
944            antecedent: Box::new(replace_proof_term(antecedent, from, to)),
945            consequent: Box::new(replace_proof_term(consequent, from, to)),
946        },
947        ProofExpr::Temporal { operator, body } => ProofExpr::Temporal {
948            operator: operator.clone(),
949            body: Box::new(replace_proof_term(body, from, to)),
950        },
951        ProofExpr::NeoEvent {
952            event_var,
953            verb,
954            roles,
955        } => ProofExpr::NeoEvent {
956            event_var: event_var.clone(),
957            verb: verb.clone(),
958            roles: roles
959                .iter()
960                .map(|(r, t)| (r.clone(), in_term(t, from, to)))
961                .collect(),
962        },
963        other => other.clone(),
964    }
965}
966
967pub fn term_to_proof_term<'a>(term: &Term<'a>, interner: &Interner) -> ProofTerm {
968    match term {
969        Term::Constant(s) => ProofTerm::Constant(interner.resolve(*s).to_string()),
970
971        Term::Variable(s) => ProofTerm::Variable(interner.resolve(*s).to_string()),
972
973        Term::Function(name, args) => {
974            // An arithmetic offset ("add"/"sub") must reach the oracle under its
975            // canonical name (`Add`/`Sub`) or the equality degrades to an
976            // uninterpreted function and the offset never forces a value. Measure
977            // functions (Score, Ord, …) are left verbatim as uninterpreted ints.
978            let name_str = interner.resolve(*name);
979            let canon = (args.len() == 2)
980                .then(|| canonical_arithmetic_fn(name_str))
981                .flatten()
982                .map(|s| s.to_string())
983                .unwrap_or_else(|| name_str.to_string());
984            ProofTerm::Function(
985                canon,
986                args.iter()
987                    .map(|t| term_to_proof_term(t, interner))
988                    .collect(),
989            )
990        }
991
992        // A group of one is that one individual (a ⊕ nothing = a).
993        Term::Group([only]) => term_to_proof_term(only, interner),
994        Term::Group(terms) => ProofTerm::Group(
995            terms
996                .iter()
997                .map(|t| term_to_proof_term(t, interner))
998                .collect(),
999        ),
1000
1001        Term::Possessed {
1002            possessor,
1003            possessed,
1004        } => {
1005            // Convert possession to function application: has(possessor, possessed)
1006            ProofTerm::Function(
1007                "has".to_string(),
1008                vec![
1009                    term_to_proof_term(possessor, interner),
1010                    ProofTerm::Constant(interner.resolve(*possessed).to_string()),
1011                ],
1012            )
1013        }
1014
1015        Term::Sigma(s) => {
1016            // Sigma variables become regular variables
1017            ProofTerm::Variable(interner.resolve(*s).to_string())
1018        }
1019
1020        Term::Intension(s) => {
1021            // Intensions become constants with ^ prefix
1022            ProofTerm::Constant(format!("^{}", interner.resolve(*s)))
1023        }
1024
1025        Term::Kind(s) => {
1026            // Kind terms are reified entities; like intensions they become a
1027            // ^-prefixed constant so kind predication reasons over a fixed object.
1028            ProofTerm::Constant(format!("^{}", interner.resolve(*s)))
1029        }
1030
1031        Term::Proposition(expr) => {
1032            // Embedded propositions - convert recursively but wrap as constant
1033            // This is a simplification; full handling would need reification
1034            let proof_expr = logic_expr_to_proof_expr(expr, interner);
1035            ProofTerm::Constant(format!("[{}]", proof_expr))
1036        }
1037
1038        Term::Value { kind, unit, .. } => {
1039            // Convert numeric values to constants
1040            use crate::ast::logic::NumberKind;
1041            match kind {
1042                NumberKind::Integer(n) => {
1043                    if let Some(u) = unit {
1044                        ProofTerm::Constant(format!("{}{}", n, interner.resolve(*u)))
1045                    } else {
1046                        ProofTerm::Constant(n.to_string())
1047                    }
1048                }
1049                NumberKind::Real(f) => {
1050                    if let Some(u) = unit {
1051                        ProofTerm::Constant(format!("{}{}", f, interner.resolve(*u)))
1052                    } else {
1053                        ProofTerm::Constant(f.to_string())
1054                    }
1055                }
1056                // A number we could not VALUE still has a UNIT, and the unit is part of
1057                // the term's identity exactly as it is for the two arms above. Dropping it
1058                // would let `99999999999999999999 dollars` and the same numeral in euros
1059                // reach the kernel as one constant.
1060                NumberKind::Symbolic(s) => {
1061                    let text = interner.resolve(*s);
1062                    match unit {
1063                        Some(u) => ProofTerm::Constant(format!("{}{}", text, interner.resolve(*u))),
1064                        None => ProofTerm::Constant(text.to_string()),
1065                    }
1066                }
1067            }
1068        }
1069    }
1070}
1071
1072#[cfg(test)]
1073#[path = "../../logicaffeine_tests/unit/logicaffeine_language/proof_convert/tests.rs"]
1074mod tests;