Skip to main content

logicaffeine_language/
formatter.rs

1//! Output formatters for logical expressions.
2//!
3//! This module defines the [`LogicFormatter`] trait and its implementations for
4//! rendering logical expressions in different notations:
5//!
6//! - **Unicode**: Standard FOL symbols (∀, ∃, ∧, ∨, ¬, →)
7//! - **LaTeX**: TeX math mode notation (\\forall, \\exists, \\land, etc.)
8//! - **ASCII**: Plain text fallback (ALL, EXISTS, AND, OR, NOT)
9//!
10//! Formatters handle quantifiers, connectives, modal operators, temporal operators,
11//! and special constructs like plurals and possessives.
12
13use std::fmt::Write;
14
15use crate::ast::{
16    AspectOperator, BinaryTemporalOp, ModalDomain, QuantifierKind, TemporalOperator, Term,
17    VoiceOperator,
18};
19use crate::registry::SymbolRegistry;
20use crate::token::TokenType;
21use logicaffeine_base::Interner;
22
23/// Trait for formatting logical expressions in various notations.
24/// The connectives a formula joins its parts with, whatever token the parser read each from:
25/// `If`, `Then` and `Implies` are all the implication. Every printer asks this one mapping, so the
26/// Logic Output, the Syntax Tree and the generated Rust can never draw a connective differently.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub enum Connective {
29    And,
30    Or,
31    Implies,
32    Iff,
33    Not,
34}
35
36impl Connective {
37    pub fn of(op: &TokenType) -> Option<Connective> {
38        match op {
39            TokenType::And => Some(Connective::And),
40            TokenType::Or => Some(Connective::Or),
41            TokenType::If | TokenType::Then | TokenType::Implies => Some(Connective::Implies),
42            TokenType::Iff => Some(Connective::Iff),
43            TokenType::Not => Some(Connective::Not),
44            _ => None,
45        }
46    }
47}
48
49pub trait LogicFormatter {
50    // Quantifiers
51    fn quantifier(&self, kind: &QuantifierKind, var: &str, body: &str) -> String {
52        let sym = match kind {
53            QuantifierKind::Universal => self.universal(),
54            QuantifierKind::Existential => self.existential(),
55            QuantifierKind::Most => "MOST ".to_string(),
56            QuantifierKind::Few => "FEW ".to_string(),
57            QuantifierKind::Many => "MANY ".to_string(),
58            QuantifierKind::Cardinal(n) => self.cardinal(*n),
59            QuantifierKind::AtLeast(n) => self.at_least(*n),
60            QuantifierKind::AtMost(n) => self.at_most(*n),
61            QuantifierKind::Generic => "Gen ".to_string(),
62            QuantifierKind::InfinitelyMany => self.infinitely_many(),
63            QuantifierKind::FinitelyMany => self.finitely_many(),
64            QuantifierKind::AllButFinitelyMany => self.all_but_finitely_many(),
65        };
66        format!("{}{}({})", sym, var, body)
67    }
68
69    fn universal(&self) -> String;
70    fn existential(&self) -> String;
71    fn cardinal(&self, n: u32) -> String;
72    fn at_least(&self, n: u32) -> String;
73    fn at_most(&self, n: u32) -> String;
74    /// ∃^∞
75    fn infinitely_many(&self) -> String;
76    /// ∃^<∞
77    fn finitely_many(&self) -> String;
78    /// ∀^∞
79    fn all_but_finitely_many(&self) -> String;
80
81    // Binary operators
82    fn binary_op(&self, op: &TokenType, left: &str, right: &str) -> String {
83        match Connective::of(op) {
84            Some(Connective::And) => format!("({} {} {})", left, self.and(), right),
85            Some(Connective::Or) => format!("({} {} {})", left, self.or(), right),
86            Some(Connective::Implies) => format!("({} {} {})", left, self.implies(), right),
87            Some(Connective::Iff) => format!("({} {} {})", left, self.iff(), right),
88            Some(Connective::Not) | None => String::new(),
89        }
90    }
91
92    fn and(&self) -> &'static str;
93    fn or(&self) -> &'static str;
94    fn implies(&self) -> &'static str;
95    fn iff(&self) -> &'static str;
96
97    // Unary operators
98    fn unary_op(&self, op: &TokenType, operand: &str) -> String {
99        match Connective::of(op) {
100            Some(Connective::Not) => format!("{}{}", self.not(), operand),
101            Some(Connective::And | Connective::Or | Connective::Implies | Connective::Iff)
102            | None => String::new(),
103        }
104    }
105
106    fn not(&self) -> &'static str;
107
108    // Identity operator (used in Identity expressions)
109    fn identity(&self) -> &'static str {
110        " = "
111    }
112
113    // Whether to wrap identity expressions in parentheses
114    fn wrap_identity(&self) -> bool {
115        false
116    }
117
118    // Modal operators
119    fn modal(&self, domain: ModalDomain, force: f32, body: &str) -> String {
120        let sym = match domain {
121            ModalDomain::Alethic if force <= 0.5 => self.possibility(),
122            ModalDomain::Alethic => self.necessity(),
123            ModalDomain::Deontic if force <= 0.5 => "P",
124            ModalDomain::Deontic => "O",
125            ModalDomain::Temporal => "Temporal",
126        };
127        format!("{}_{{{:.1}}} {}", sym, force, body)
128    }
129
130    fn necessity(&self) -> &'static str;
131    fn possibility(&self) -> &'static str;
132
133    // Temporal operators
134    fn temporal(&self, op: &TemporalOperator, body: &str) -> String {
135        let sym = match op {
136            TemporalOperator::Past => self.past(),
137            TemporalOperator::Future => self.future(),
138            TemporalOperator::Always => "G",
139            TemporalOperator::Eventually => "F",
140            TemporalOperator::BoundedEventually(n) => return format!("F≤{}({})", n, body),
141            TemporalOperator::Next => "X",
142        };
143        format!("{}({})", sym, body)
144    }
145
146    fn past(&self) -> &'static str;
147    fn future(&self) -> &'static str;
148
149    // Binary temporal operators
150    fn temporal_binary(&self, op: &BinaryTemporalOp, left: &str, right: &str) -> String {
151        let sym = match op {
152            BinaryTemporalOp::Until => "U",
153            BinaryTemporalOp::Release => "R",
154            BinaryTemporalOp::WeakUntil => "W",
155        };
156        format!("({} {} {})", left, sym, right)
157    }
158
159    // Aspectual operators
160    fn aspectual(&self, op: &AspectOperator, body: &str) -> String {
161        let sym = match op {
162            AspectOperator::Progressive => self.progressive(),
163            AspectOperator::Perfect => self.perfect(),
164            AspectOperator::Habitual => self.habitual(),
165            AspectOperator::Iterative => self.iterative(),
166        };
167        format!("{}({})", sym, body)
168    }
169
170    fn progressive(&self) -> &'static str;
171    fn perfect(&self) -> &'static str;
172    fn habitual(&self) -> &'static str;
173    fn iterative(&self) -> &'static str;
174
175    // Voice operators
176    fn voice(&self, op: &VoiceOperator, body: &str) -> String {
177        let sym = match op {
178            VoiceOperator::Passive => self.passive(),
179        };
180        format!("{}({})", sym, body)
181    }
182
183    fn passive(&self) -> &'static str;
184
185    // Lambda
186    fn lambda(&self, var: &str, body: &str) -> String;
187
188    // Counterfactual
189    fn counterfactual(&self, antecedent: &str, consequent: &str) -> String;
190
191    // Superlative expansion
192    fn superlative(&self, comp: &str, domain: &str, subject: &str) -> String;
193
194    // Event quantification (uses existential + and)
195    fn event_quantifier(&self, pred: &str, adverbs: &[String]) -> String {
196        if adverbs.is_empty() {
197            format!("{}e({})", self.existential(), pred)
198        } else {
199            let conj = self.and();
200            format!(
201                "{}e({} {} {})",
202                self.existential(),
203                pred,
204                conj,
205                adverbs.join(&format!(" {} ", conj))
206            )
207        }
208    }
209
210    // Categorical (legacy)
211    fn categorical_all(&self) -> &'static str;
212    fn categorical_no(&self) -> &'static str;
213    fn categorical_some(&self) -> &'static str;
214    fn categorical_not(&self) -> &'static str;
215
216    // Sanitization hook for LaTeX special characters
217    fn sanitize(&self, s: &str) -> String {
218        s.to_string()
219    }
220
221    // Whether to use simple predicate form instead of event semantics
222    fn use_simple_events(&self) -> bool {
223        false
224    }
225
226    // Whether to use full predicate names instead of abbreviations
227    fn use_full_names(&self) -> bool {
228        false
229    }
230
231    // Whether to preserve original case (for code generation)
232    fn preserve_case(&self) -> bool {
233        false
234    }
235
236    // Whether to include world arguments in predicates (for Kripke semantics)
237    fn include_world_arguments(&self) -> bool {
238        false
239    }
240
241    /// Hook for customizing how comparatives are rendered.
242    /// Default implementation uses standard logic notation: tallER(subj, obj) or tallER(subj, obj, diff)
243    fn write_comparative<W: Write>(
244        &self,
245        w: &mut W,
246        adjective: &str,
247        subject: &str,
248        object: &str,
249        difference: Option<&str>,
250    ) -> std::fmt::Result {
251        if let Some(diff) = difference {
252            write!(w, "{}er({}, {}, {})", adjective, subject, object, diff)
253        } else {
254            write!(w, "{}er({}, {})", adjective, subject, object)
255        }
256    }
257
258    /// Hook for customizing how predicates are rendered.
259    /// Default implementation uses standard logic notation: Name(Arg1, Arg2)
260    fn write_predicate<W: Write>(
261        &self,
262        w: &mut W,
263        name: &str,
264        args: &[Term],
265        registry: &mut SymbolRegistry,
266        interner: &Interner,
267    ) -> std::fmt::Result {
268        write!(w, "{}(", self.sanitize(name))?;
269        for (i, arg) in args.iter().enumerate() {
270            if i > 0 {
271                write!(w, ", ")?;
272            }
273            if self.use_full_names() {
274                arg.write_to_full(w, registry, interner)?;
275            } else {
276                arg.write_to(w, registry, interner)?;
277            }
278        }
279        write!(w, ")")
280    }
281}
282
283pub struct UnicodeFormatter;
284
285impl LogicFormatter for UnicodeFormatter {
286    fn universal(&self) -> String {
287        "∀".to_string()
288    }
289    fn existential(&self) -> String {
290        "∃".to_string()
291    }
292    fn cardinal(&self, n: u32) -> String {
293        format!("∃={}.", n)
294    }
295    fn at_least(&self, n: u32) -> String {
296        format!("∃≥{}", n)
297    }
298    fn at_most(&self, n: u32) -> String {
299        format!("∃≤{}", n)
300    }
301    fn infinitely_many(&self) -> String {
302        "∃^∞".to_string()
303    }
304    fn finitely_many(&self) -> String {
305        "∃^<∞".to_string()
306    }
307    fn all_but_finitely_many(&self) -> String {
308        "∀^∞".to_string()
309    }
310
311    fn and(&self) -> &'static str {
312        "∧"
313    }
314    fn or(&self) -> &'static str {
315        "∨"
316    }
317    fn implies(&self) -> &'static str {
318        "→"
319    }
320    fn iff(&self) -> &'static str {
321        "↔"
322    }
323    fn not(&self) -> &'static str {
324        "¬"
325    }
326
327    fn necessity(&self) -> &'static str {
328        "□"
329    }
330    fn possibility(&self) -> &'static str {
331        "◇"
332    }
333
334    fn past(&self) -> &'static str {
335        "P"
336    }
337    fn future(&self) -> &'static str {
338        "F"
339    }
340
341    fn progressive(&self) -> &'static str {
342        "Prog"
343    }
344    fn perfect(&self) -> &'static str {
345        "Perf"
346    }
347    fn habitual(&self) -> &'static str {
348        "HAB"
349    }
350    fn iterative(&self) -> &'static str {
351        "ITER"
352    }
353    fn passive(&self) -> &'static str {
354        "Pass"
355    }
356
357    fn lambda(&self, var: &str, body: &str) -> String {
358        format!("λ{}.{}", var, body)
359    }
360
361    fn counterfactual(&self, antecedent: &str, consequent: &str) -> String {
362        format!("({} □→ {})", antecedent, consequent)
363    }
364
365    fn superlative(&self, comp: &str, domain: &str, subject: &str) -> String {
366        format!(
367            "∀x(({}(x) ∧ x ≠ {}) → {}({}, x))",
368            domain, subject, comp, subject
369        )
370    }
371
372    fn categorical_all(&self) -> &'static str {
373        "∀"
374    }
375    fn categorical_no(&self) -> &'static str {
376        "∀¬"
377    }
378    fn categorical_some(&self) -> &'static str {
379        "∃"
380    }
381    fn categorical_not(&self) -> &'static str {
382        "¬"
383    }
384
385    // Use full predicate names (e.g., "Wet" not "W")
386    fn use_full_names(&self) -> bool {
387        true
388    }
389}
390
391pub struct LatexFormatter;
392
393impl LogicFormatter for LatexFormatter {
394    fn universal(&self) -> String {
395        "\\forall ".to_string()
396    }
397    fn existential(&self) -> String {
398        "\\exists ".to_string()
399    }
400    fn cardinal(&self, n: u32) -> String {
401        format!("\\exists_{{={}}} ", n)
402    }
403    fn at_least(&self, n: u32) -> String {
404        format!("\\exists_{{\\geq {}}} ", n)
405    }
406    fn at_most(&self, n: u32) -> String {
407        format!("\\exists_{{\\leq {}}} ", n)
408    }
409    fn infinitely_many(&self) -> String {
410        "\\exists^{\\infty} ".to_string()
411    }
412    fn finitely_many(&self) -> String {
413        "\\exists^{<\\infty} ".to_string()
414    }
415    fn all_but_finitely_many(&self) -> String {
416        "\\forall^{\\infty} ".to_string()
417    }
418
419    fn and(&self) -> &'static str {
420        "\\cdot"
421    }
422    fn or(&self) -> &'static str {
423        "\\vee"
424    }
425    fn implies(&self) -> &'static str {
426        "\\supset"
427    }
428    fn iff(&self) -> &'static str {
429        "\\equiv"
430    }
431    fn not(&self) -> &'static str {
432        "\\sim "
433    }
434
435    fn necessity(&self) -> &'static str {
436        "\\Box"
437    }
438    fn possibility(&self) -> &'static str {
439        "\\Diamond"
440    }
441
442    fn past(&self) -> &'static str {
443        "\\mathsf{P}"
444    }
445    fn future(&self) -> &'static str {
446        "\\mathsf{F}"
447    }
448
449    fn progressive(&self) -> &'static str {
450        "\\mathsf{Prog}"
451    }
452    fn perfect(&self) -> &'static str {
453        "\\mathsf{Perf}"
454    }
455    fn habitual(&self) -> &'static str {
456        "\\mathsf{HAB}"
457    }
458    fn iterative(&self) -> &'static str {
459        "\\mathsf{ITER}"
460    }
461    fn passive(&self) -> &'static str {
462        "\\mathsf{Pass}"
463    }
464
465    fn lambda(&self, var: &str, body: &str) -> String {
466        format!("\\lambda {}.{}", var, body)
467    }
468
469    fn counterfactual(&self, antecedent: &str, consequent: &str) -> String {
470        format!("({} \\boxright {})", antecedent, consequent)
471    }
472
473    fn superlative(&self, comp: &str, domain: &str, subject: &str) -> String {
474        format!(
475            "\\forall x(({}(x) \\land x \\neq {}) \\supset {}({}, x))",
476            domain, subject, comp, subject
477        )
478    }
479
480    fn categorical_all(&self) -> &'static str {
481        "All"
482    }
483    fn categorical_no(&self) -> &'static str {
484        "No"
485    }
486    fn categorical_some(&self) -> &'static str {
487        "Some"
488    }
489    fn categorical_not(&self) -> &'static str {
490        "not"
491    }
492
493    fn sanitize(&self, s: &str) -> String {
494        s.replace('_', r"\_")
495            .replace('^', r"\^{}")
496            .replace('&', r"\&")
497            .replace('%', r"\%")
498            .replace('#', r"\#")
499            .replace('$', r"\$")
500    }
501}
502
503pub struct SimpleFOLFormatter;
504
505impl LogicFormatter for SimpleFOLFormatter {
506    fn universal(&self) -> String {
507        "∀".to_string()
508    }
509    fn existential(&self) -> String {
510        "∃".to_string()
511    }
512    fn cardinal(&self, n: u32) -> String {
513        format!("∃={}", n)
514    }
515    fn at_least(&self, n: u32) -> String {
516        format!("∃≥{}", n)
517    }
518    fn at_most(&self, n: u32) -> String {
519        format!("∃≤{}", n)
520    }
521    fn infinitely_many(&self) -> String {
522        "∃^∞".to_string()
523    }
524    fn finitely_many(&self) -> String {
525        "∃^<∞".to_string()
526    }
527    fn all_but_finitely_many(&self) -> String {
528        "∀^∞".to_string()
529    }
530
531    fn and(&self) -> &'static str {
532        "∧"
533    }
534    fn or(&self) -> &'static str {
535        "∨"
536    }
537    fn implies(&self) -> &'static str {
538        "→"
539    }
540    fn iff(&self) -> &'static str {
541        "↔"
542    }
543    fn not(&self) -> &'static str {
544        "¬"
545    }
546
547    fn necessity(&self) -> &'static str {
548        "□"
549    }
550    fn possibility(&self) -> &'static str {
551        "◇"
552    }
553
554    fn past(&self) -> &'static str {
555        "Past"
556    }
557    fn future(&self) -> &'static str {
558        "Future"
559    }
560
561    fn progressive(&self) -> &'static str {
562        ""
563    }
564    fn perfect(&self) -> &'static str {
565        ""
566    }
567    fn habitual(&self) -> &'static str {
568        ""
569    }
570    fn iterative(&self) -> &'static str {
571        ""
572    }
573    fn passive(&self) -> &'static str {
574        ""
575    }
576
577    fn lambda(&self, var: &str, body: &str) -> String {
578        format!("λ{}.{}", var, body)
579    }
580
581    fn counterfactual(&self, antecedent: &str, consequent: &str) -> String {
582        format!("({} □→ {})", antecedent, consequent)
583    }
584
585    fn superlative(&self, comp: &str, domain: &str, subject: &str) -> String {
586        format!(
587            "∀x(({}(x) ∧ x ≠ {}) → {}({}, x))",
588            domain, subject, comp, subject
589        )
590    }
591
592    fn categorical_all(&self) -> &'static str {
593        "∀"
594    }
595    fn categorical_no(&self) -> &'static str {
596        "∀¬"
597    }
598    fn categorical_some(&self) -> &'static str {
599        "∃"
600    }
601    fn categorical_not(&self) -> &'static str {
602        "¬"
603    }
604
605    fn modal(&self, _domain: ModalDomain, _force: f32, body: &str) -> String {
606        body.to_string()
607    }
608
609    fn aspectual(&self, _op: &AspectOperator, body: &str) -> String {
610        body.to_string()
611    }
612
613    fn use_simple_events(&self) -> bool {
614        true
615    }
616
617    fn use_full_names(&self) -> bool {
618        true
619    }
620}
621
622/// Formatter for Kripke lowered output with explicit world arguments.
623/// Modals are already lowered to quantifiers; this formatter just renders
624/// the result with world arguments appended to predicates.
625pub struct KripkeFormatter;
626
627impl LogicFormatter for KripkeFormatter {
628    fn universal(&self) -> String {
629        "ForAll ".to_string()
630    }
631    fn existential(&self) -> String {
632        "Exists ".to_string()
633    }
634    fn cardinal(&self, n: u32) -> String {
635        format!("Exists={} ", n)
636    }
637    fn at_least(&self, n: u32) -> String {
638        format!("Exists>={} ", n)
639    }
640    fn at_most(&self, n: u32) -> String {
641        format!("Exists<={} ", n)
642    }
643    fn infinitely_many(&self) -> String {
644        "Exists^inf ".to_string()
645    }
646    fn finitely_many(&self) -> String {
647        "Exists^<inf ".to_string()
648    }
649    fn all_but_finitely_many(&self) -> String {
650        "ForAll^inf ".to_string()
651    }
652
653    fn and(&self) -> &'static str {
654        " And "
655    }
656    fn or(&self) -> &'static str {
657        " Or "
658    }
659    fn implies(&self) -> &'static str {
660        " Implies "
661    }
662    fn iff(&self) -> &'static str {
663        " Iff "
664    }
665    fn not(&self) -> &'static str {
666        "Not "
667    }
668
669    fn necessity(&self) -> &'static str {
670        "Box"
671    }
672    fn possibility(&self) -> &'static str {
673        "Diamond"
674    }
675
676    fn past(&self) -> &'static str {
677        "Past"
678    }
679    fn future(&self) -> &'static str {
680        "Future"
681    }
682
683    fn progressive(&self) -> &'static str {
684        "Prog"
685    }
686    fn perfect(&self) -> &'static str {
687        "Perf"
688    }
689    fn habitual(&self) -> &'static str {
690        "HAB"
691    }
692    fn iterative(&self) -> &'static str {
693        "ITER"
694    }
695    fn passive(&self) -> &'static str {
696        "Pass"
697    }
698
699    fn lambda(&self, var: &str, body: &str) -> String {
700        format!("Lambda {}.{}", var, body)
701    }
702
703    fn counterfactual(&self, antecedent: &str, consequent: &str) -> String {
704        format!("({} Counterfactual {})", antecedent, consequent)
705    }
706
707    fn superlative(&self, comp: &str, domain: &str, subject: &str) -> String {
708        format!(
709            "ForAll x(({}(x) And x != {}) Implies {}({}, x))",
710            domain, subject, comp, subject
711        )
712    }
713
714    fn categorical_all(&self) -> &'static str {
715        "ForAll"
716    }
717    fn categorical_no(&self) -> &'static str {
718        "ForAll Not"
719    }
720    fn categorical_some(&self) -> &'static str {
721        "Exists"
722    }
723    fn categorical_not(&self) -> &'static str {
724        "Not"
725    }
726
727    fn modal(&self, _domain: ModalDomain, _force: f32, body: &str) -> String {
728        // Modals already lowered to quantifiers - just pass through
729        body.to_string()
730    }
731
732    fn use_full_names(&self) -> bool {
733        true
734    }
735
736    fn include_world_arguments(&self) -> bool {
737        true
738    }
739}
740
741/// Formatter that produces Rust boolean expressions for runtime assertions.
742/// Used by codegen to convert LogicExpr into debug_assert!() compatible code.
743pub struct RustFormatter;
744
745impl LogicFormatter for RustFormatter {
746    // Operators map to Rust boolean operators
747    fn and(&self) -> &'static str {
748        "&&"
749    }
750    fn or(&self) -> &'static str {
751        "||"
752    }
753    fn not(&self) -> &'static str {
754        "!"
755    }
756    fn implies(&self) -> &'static str {
757        "||"
758    } // Handled via binary_op override
759    fn iff(&self) -> &'static str {
760        "=="
761    }
762    fn identity(&self) -> &'static str {
763        " == "
764    } // Rust equality
765    fn wrap_identity(&self) -> bool {
766        true
767    } // Wrap in parens for valid Rust
768
769    // Use full variable names, not abbreviations
770    fn use_full_names(&self) -> bool {
771        true
772    }
773    fn preserve_case(&self) -> bool {
774        true
775    } // Keep original variable case
776
777    // Quantifiers: runtime can't check universal quantification, emit comments
778    fn universal(&self) -> String {
779        "/* ∀ */".to_string()
780    }
781    fn existential(&self) -> String {
782        "/* ∃ */".to_string()
783    }
784    fn cardinal(&self, n: u32) -> String {
785        format!("/* ∃={} */", n)
786    }
787    fn at_least(&self, n: u32) -> String {
788        format!("/* ∃≥{} */", n)
789    }
790    fn at_most(&self, n: u32) -> String {
791        format!("/* ∃≤{} */", n)
792    }
793    fn infinitely_many(&self) -> String {
794        "/* ∃^∞ */".to_string()
795    }
796    fn finitely_many(&self) -> String {
797        "/* ∃^<∞ */".to_string()
798    }
799    fn all_but_finitely_many(&self) -> String {
800        "/* ∀^∞ */".to_string()
801    }
802
803    // Modal/Temporal operators are stripped for runtime (not checkable)
804    fn necessity(&self) -> &'static str {
805        ""
806    }
807    fn possibility(&self) -> &'static str {
808        ""
809    }
810    fn past(&self) -> &'static str {
811        ""
812    }
813    fn future(&self) -> &'static str {
814        ""
815    }
816    fn progressive(&self) -> &'static str {
817        ""
818    }
819    fn perfect(&self) -> &'static str {
820        ""
821    }
822    fn habitual(&self) -> &'static str {
823        ""
824    }
825    fn iterative(&self) -> &'static str {
826        ""
827    }
828    fn passive(&self) -> &'static str {
829        ""
830    }
831    fn categorical_all(&self) -> &'static str {
832        ""
833    }
834    fn categorical_no(&self) -> &'static str {
835        ""
836    }
837    fn categorical_some(&self) -> &'static str {
838        ""
839    }
840    fn categorical_not(&self) -> &'static str {
841        ""
842    }
843
844    fn lambda(&self, var: &str, body: &str) -> String {
845        format!("|{}| {{ {} }}", var, body)
846    }
847
848    fn counterfactual(&self, a: &str, c: &str) -> String {
849        format!("/* if {} then {} */", a, c)
850    }
851
852    fn superlative(&self, _: &str, _: &str, _: &str) -> String {
853        "/* superlative */".to_string()
854    }
855
856    // Override comparative for Rust: map adjectives to comparison operators
857    fn write_comparative<W: Write>(
858        &self,
859        w: &mut W,
860        adjective: &str,
861        subject: &str,
862        object: &str,
863        _difference: Option<&str>,
864    ) -> std::fmt::Result {
865        let adj_lower = adjective.to_lowercase();
866        match adj_lower.as_str() {
867            "great" | "big" | "large" | "tall" | "old" | "high" | "more" | "greater" => {
868                write!(w, "({} > {})", subject, object)
869            }
870            "small" | "little" | "short" | "young" | "low" | "less" | "fewer" => {
871                write!(w, "({} < {})", subject, object)
872            }
873            _ => write!(w, "({} > {})", subject, object), // default to greater-than
874        }
875    }
876
877    // Override unary_op to wrap in parens for valid Rust
878    fn unary_op(&self, op: &TokenType, operand: &str) -> String {
879        match op {
880            TokenType::Not => format!("(!{})", operand),
881            _ => format!("/* unknown unary */({})", operand),
882        }
883    }
884
885    // Override binary_op for implication desugaring: A → B = !A || B
886    fn binary_op(&self, op: &TokenType, left: &str, right: &str) -> String {
887        match Connective::of(op) {
888            Some(Connective::Implies) => format!("(!({}) || ({}))", left, right),
889            Some(Connective::And) => format!("({} && {})", left, right),
890            Some(Connective::Or) => format!("({} || {})", left, right),
891            Some(Connective::Iff) => format!("({} == {})", left, right),
892            Some(Connective::Not) | None => "/* unknown op */".to_string(),
893        }
894    }
895
896    // Core predicate mapping: semantic interpretation of predicates to Rust operators
897    fn write_predicate<W: Write>(
898        &self,
899        w: &mut W,
900        name: &str,
901        args: &[Term],
902        _registry: &mut SymbolRegistry,
903        interner: &Interner,
904    ) -> std::fmt::Result {
905        // Helper to render a term at given index to a string, preserving original case
906        let render = |idx: usize| -> String {
907            let mut buf = String::new();
908            if let Some(arg) = args.get(idx) {
909                let _ = arg.write_to_raw(&mut buf, interner);
910            }
911            buf
912        };
913
914        match name.to_lowercase().as_str() {
915            // Comparisons
916            "greater" if args.len() == 2 => write!(w, "({} > {})", render(0), render(1)),
917            "less" if args.len() == 2 => write!(w, "({} < {})", render(0), render(1)),
918            "equal" | "equals" if args.len() == 2 => write!(w, "({} == {})", render(0), render(1)),
919            "notequal" | "not_equal" if args.len() == 2 => {
920                write!(w, "({} != {})", render(0), render(1))
921            }
922            "greaterequal" | "atleast" | "at_least" if args.len() == 2 => {
923                write!(w, "({} >= {})", render(0), render(1))
924            }
925            "lessequal" | "atmost" | "at_most" if args.len() == 2 => {
926                write!(w, "({} <= {})", render(0), render(1))
927            }
928
929            // Unary checks
930            "positive" if args.len() == 1 => write!(w, "({} > 0)", render(0)),
931            "negative" if args.len() == 1 => write!(w, "({} < 0)", render(0)),
932            "zero" if args.len() == 1 => write!(w, "({} == 0)", render(0)),
933            "empty" if args.len() == 1 => write!(w, "{}.is_empty()", render(0)),
934
935            // Collection membership
936            "in" if args.len() == 2 => write!(w, "{}.contains(&{})", render(1), render(0)),
937            "contains" if args.len() == 2 => write!(w, "{}.contains(&{})", render(0), render(1)),
938
939            // Fallback: method call for 1 arg, function call for N args
940            _ if args.len() == 1 => write!(w, "{}.is_{}()", render(0), name.to_lowercase()),
941            _ => {
942                write!(w, "{}(", name.to_lowercase())?;
943                for i in 0..args.len() {
944                    if i > 0 {
945                        write!(w, ", ")?;
946                    }
947                    write!(w, "{}", render(i))?;
948                }
949                write!(w, ")")
950            }
951        }
952    }
953}
954
955#[cfg(test)]
956#[path = "../../logicaffeine_tests/unit/logicaffeine_language/formatter/tests.rs"]
957mod tests;