Skip to main content

logicaffeine_language/
compile.rs

1//! # Compilation API
2//!
3//! This module provides the public entry points for natural language to first-order
4//! logic translation.
5//!
6//! ## Compilation Functions
7//!
8//! | Function | Use Case |
9//! |----------|----------|
10//! | [`compile`] | Single sentence, Unicode output |
11//! | [`compile_simple`] | Single sentence, ASCII output |
12//! | [`compile_kripke`] | Modal logic with world quantification |
13//! | [`compile_with_discourse`] | Multi-sentence with anaphora resolution |
14//! | [`compile_forest`] | Ambiguous sentences, all readings |
15//! | [`compile_all_scopes`] | All quantifier scope permutations |
16//! | [`compile_discourse`] | Multi-sentence with temporal ordering |
17//! | [`compile_theorem`] | Theorem proving with backward chaining |
18//!
19//! ## Example
20//!
21//! ```rust
22//! use logicaffeine_language::{compile, compile_forest};
23//!
24//! // Simple compilation
25//! let fol = compile("John loves Mary.").unwrap();
26//! assert!(fol.contains("Love"));
27//!
28//! // Handle ambiguity
29//! let readings = compile_forest("Every woman loves a man.");
30//! assert!(readings.len() >= 1); // Surface and possibly inverse scope
31//! ```
32
33use crate::{
34    analysis,
35    arena_ctx::AstContext,
36    drs, lambda, lexicon, mwe,
37    parser::{ModalPreference, NegativeScopeMode, QuantifierParsing},
38    pragmatics, semantics, token, Arena, CompileOptions, Interner, Lexer, OutputFormat, ParseError,
39    Parser, SymbolRegistry,
40};
41
42/// Maximum number of readings in a parse forest.
43/// Prevents exponential blowup from ambiguous sentences.
44pub const MAX_FOREST_READINGS: usize = 12;
45
46/// Compile natural language input to first-order logic with default options.
47pub fn compile(input: &str) -> Result<String, ParseError> {
48    compile_with_options(input, CompileOptions::default())
49}
50
51/// Compile with conversational (scalar) implicature enrichment (§8.7). The literal
52/// `compile` output is unchanged; this adds the `+> Implicature(…)` line.
53pub fn compile_pragmatic(input: &str) -> Result<String, ParseError> {
54    compile_with_options(
55        input,
56        CompileOptions {
57            format: OutputFormat::Unicode,
58            pragmatic: true,
59        },
60    )
61}
62
63/// Compile with simple FOL format.
64pub fn compile_simple(input: &str) -> Result<String, ParseError> {
65    compile_with_options(
66        input,
67        CompileOptions {
68            format: OutputFormat::SimpleFOL,
69            pragmatic: false,
70        },
71    )
72}
73
74/// Compile with Kripke semantics lowering.
75/// Modal operators are transformed into explicit possible world quantification.
76pub fn compile_kripke(input: &str) -> Result<String, ParseError> {
77    compile_with_options(
78        input,
79        CompileOptions {
80            format: OutputFormat::Kripke,
81            pragmatic: false,
82        },
83    )
84}
85
86/// Compile to Kripke-lowered FOL and pass the AST to a callback.
87///
88/// The callback receives the Kripke-lowered LogicExpr and the Interner
89/// for symbol resolution. This avoids lifetime issues with arena-allocated ASTs.
90pub fn compile_kripke_with<F, R>(input: &str, f: F) -> Result<R, ParseError>
91where
92    F: FnOnce(&crate::ast::logic::LogicExpr<'_>, &Interner) -> R,
93{
94    if input.trim().is_empty() {
95        return Err(ParseError {
96            kind: crate::error::ParseErrorKind::Custom("Empty input".to_string()),
97            span: crate::token::Span { start: 0, end: 0 },
98        });
99    }
100    let mut interner = Interner::new();
101    let mut lexer = Lexer::new(input, &mut interner);
102    let tokens = lexer.tokenize();
103
104    let mwe_trie = mwe::build_mwe_trie();
105    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
106
107    let type_registry = {
108        let mut discovery = analysis::DiscoveryPass::new(&tokens, &mut interner);
109        discovery.run()
110    };
111
112    let expr_arena = Arena::new();
113    let term_arena = Arena::new();
114    let np_arena = Arena::new();
115    let sym_arena = Arena::new();
116    let role_arena = Arena::new();
117    let pp_arena = Arena::new();
118
119    let ctx = AstContext::new(
120        &expr_arena,
121        &term_arena,
122        &np_arena,
123        &sym_arena,
124        &role_arena,
125        &pp_arena,
126    );
127
128    let mut world_state = drs::WorldState::new();
129    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
130    let ast = parser.parse()?;
131    let ast = semantics::apply_axioms(ast, ctx.exprs, ctx.terms, &mut interner);
132    let ast = semantics::apply_kripke_lowering(ast, ctx.exprs, ctx.terms, &mut interner);
133
134    Ok(f(ast, &interner))
135}
136
137/// Compile natural language input to first-order logic with specified options.
138pub fn compile_with_options(input: &str, options: CompileOptions) -> Result<String, ParseError> {
139    if input.trim().is_empty() {
140        return Err(ParseError {
141            kind: crate::error::ParseErrorKind::Custom("Empty input".to_string()),
142            span: crate::token::Span { start: 0, end: 0 },
143        });
144    }
145    let mut interner = Interner::new();
146    let mut lexer = Lexer::new(input, &mut interner);
147    let tokens = lexer.tokenize();
148
149    // Apply MWE collapsing
150    let mwe_trie = mwe::build_mwe_trie();
151    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
152
153    // Pass 1: Discovery - scan for type definitions
154    let type_registry = {
155        let mut discovery = analysis::DiscoveryPass::new(&tokens, &mut interner);
156        discovery.run()
157    };
158
159    let expr_arena = Arena::new();
160    let term_arena = Arena::new();
161    let np_arena = Arena::new();
162    let sym_arena = Arena::new();
163    let role_arena = Arena::new();
164    let pp_arena = Arena::new();
165
166    let ctx = AstContext::new(
167        &expr_arena,
168        &term_arena,
169        &np_arena,
170        &sym_arena,
171        &role_arena,
172        &pp_arena,
173    );
174
175    // Pass 2: Parse with type context
176    let mut world_state = drs::WorldState::new();
177    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
178    let ast = if options.pragmatic {
179        parser.parse_pragmatic()?
180    } else {
181        parser.parse()?
182    };
183    let ast = semantics::apply_axioms(ast, ctx.exprs, ctx.terms, &mut interner);
184
185    // Apply Kripke lowering for Kripke format (before pragmatics to preserve modal structure)
186    let ast = if options.format == OutputFormat::Kripke {
187        semantics::apply_kripke_lowering(ast, ctx.exprs, ctx.terms, &mut interner)
188    } else {
189        ast
190    };
191
192    let ast = pragmatics::apply_pragmatics(ast, ctx.exprs, &interner);
193    let mut registry = SymbolRegistry::new();
194    // Use transpile_discourse to format multiple sentences as numbered formulas
195    let main_output = ast.transpile_discourse(&mut registry, &interner, options.format);
196
197    // Append Reichenbach temporal constraints
198    let constraints = world_state.time_constraints();
199    if constraints.is_empty() {
200        Ok(main_output)
201    } else {
202        let constraint_strs: Vec<String> = constraints
203            .iter()
204            .map(|c| match c.relation {
205                drs::TimeRelation::Precedes => format!("Precedes({}, {})", c.left, c.right),
206                drs::TimeRelation::Equals => format!("{}={}", c.left, c.right),
207            })
208            .collect();
209        Ok(format!("{} ∧ {}", main_output, constraint_strs.join(" ∧ ")))
210    }
211}
212
213/// Compile with shared WorldState for cross-sentence discourse.
214pub fn compile_with_world_state(
215    input: &str,
216    world_state: &mut drs::WorldState,
217) -> Result<String, ParseError> {
218    compile_with_world_state_options(input, world_state, CompileOptions::default())
219}
220
221/// Compile with shared WorldState and options.
222pub fn compile_with_world_state_options(
223    input: &str,
224    world_state: &mut drs::WorldState,
225    options: CompileOptions,
226) -> Result<String, ParseError> {
227    let mut interner = Interner::new();
228    compile_with_world_state_interner_options(input, world_state, &mut interner, options)
229}
230
231/// Compile with shared WorldState AND Interner for proper cross-sentence discourse.
232/// Use this when you need pronouns to resolve across multiple sentences.
233pub fn compile_with_discourse(
234    input: &str,
235    world_state: &mut drs::WorldState,
236    interner: &mut Interner,
237) -> Result<String, ParseError> {
238    compile_with_world_state_interner_options(
239        input,
240        world_state,
241        interner,
242        CompileOptions::default(),
243    )
244}
245
246/// Compile with full control over WorldState, Interner, and options.
247pub fn compile_with_world_state_interner_options(
248    input: &str,
249    world_state: &mut drs::WorldState,
250    interner: &mut Interner,
251    options: CompileOptions,
252) -> Result<String, ParseError> {
253    let mut lexer = Lexer::new(input, interner);
254    let tokens = lexer.tokenize();
255
256    // Apply MWE collapsing
257    let mwe_trie = mwe::build_mwe_trie();
258    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, interner);
259
260    // Pass 1: Discovery
261    let type_registry = {
262        let mut discovery = analysis::DiscoveryPass::new(&tokens, interner);
263        discovery.run()
264    };
265
266    let expr_arena = Arena::new();
267    let term_arena = Arena::new();
268    let np_arena = Arena::new();
269    let sym_arena = Arena::new();
270    let role_arena = Arena::new();
271    let pp_arena = Arena::new();
272
273    let ctx = AstContext::new(
274        &expr_arena,
275        &term_arena,
276        &np_arena,
277        &sym_arena,
278        &role_arena,
279        &pp_arena,
280    );
281
282    let mut parser = Parser::new(tokens, world_state, interner, ctx, type_registry);
283    // Swap DRS from WorldState into Parser at start
284    parser.swap_drs_with_world_state();
285    let ast = parser.parse()?;
286    // Swap DRS back to WorldState at end
287    parser.swap_drs_with_world_state();
288    let ast = semantics::apply_axioms(ast, ctx.exprs, ctx.terms, interner);
289
290    // Mark sentence boundary for telescoping support
291    world_state.end_sentence();
292
293    let ast = if options.format == OutputFormat::Kripke {
294        semantics::apply_kripke_lowering(ast, ctx.exprs, ctx.terms, interner)
295    } else {
296        ast
297    };
298
299    let ast = pragmatics::apply_pragmatics(ast, ctx.exprs, interner);
300    let mut registry = SymbolRegistry::new();
301    let main_output = ast.transpile_discourse(&mut registry, interner, options.format);
302
303    let constraints = world_state.time_constraints();
304    if constraints.is_empty() {
305        Ok(main_output)
306    } else {
307        let constraint_strs: Vec<String> = constraints
308            .iter()
309            .map(|c| match c.relation {
310                drs::TimeRelation::Precedes => format!("Precedes({}, {})", c.left, c.right),
311                drs::TimeRelation::Equals => format!("{}={}", c.left, c.right),
312            })
313            .collect();
314        Ok(format!("{} ∧ {}", main_output, constraint_strs.join(" ∧ ")))
315    }
316}
317
318/// Returns all possible scope readings for a sentence.
319/// For sentences with multiple quantifiers, this returns all permutations.
320/// Example: "Every woman loves a man" returns both:
321///   - Surface: ∀x(Woman(x) → ∃y(Man(y) ∧ Loves(x, y)))
322///   - Inverse: ∃y(Man(y) ∧ ∀x(Woman(x) → Loves(x, y)))
323pub fn compile_all_scopes(input: &str) -> Result<Vec<String>, ParseError> {
324    compile_all_scopes_with_options(input, CompileOptions::default())
325}
326
327/// Returns all scope readings with specified output format.
328pub fn compile_all_scopes_with_options(
329    input: &str,
330    options: CompileOptions,
331) -> Result<Vec<String>, ParseError> {
332    let mut interner = Interner::new();
333    let mut lexer = Lexer::new(input, &mut interner);
334    let tokens = lexer.tokenize();
335
336    // Apply MWE collapsing
337    let mwe_trie = mwe::build_mwe_trie();
338    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
339
340    // Pass 1: Discovery - scan for type definitions
341    let type_registry = {
342        let mut discovery = analysis::DiscoveryPass::new(&tokens, &mut interner);
343        discovery.run()
344    };
345
346    let expr_arena = Arena::new();
347    let term_arena = Arena::new();
348    let np_arena = Arena::new();
349    let sym_arena = Arena::new();
350    let role_arena = Arena::new();
351    let pp_arena = Arena::new();
352
353    let ctx = AstContext::new(
354        &expr_arena,
355        &term_arena,
356        &np_arena,
357        &sym_arena,
358        &role_arena,
359        &pp_arena,
360    );
361
362    // Pass 2: Parse with type context
363    let mut world_state = drs::WorldState::new();
364    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
365    let ast = parser.parse()?;
366
367    let scope_arena = Arena::new();
368    let scope_term_arena = Arena::new();
369    let scopings = lambda::enumerate_scopings(ast, &mut interner, &scope_arena, &scope_term_arena);
370
371    let intensional_arena = Arena::new();
372    let intensional_term_arena = Arena::new();
373    let intensional_role_arena: Arena<(crate::ast::ThematicRole, crate::ast::Term)> = Arena::new();
374
375    let mut results = Vec::new();
376    for scoped_expr in scopings {
377        let intensional_readings = lambda::enumerate_intensional_readings(
378            scoped_expr,
379            &mut interner,
380            &intensional_arena,
381            &intensional_term_arena,
382            &intensional_role_arena,
383        );
384        for reading in intensional_readings {
385            let reading = semantics::apply_axioms(
386                reading,
387                &intensional_arena,
388                &intensional_term_arena,
389                &mut interner,
390            );
391            let mut registry = SymbolRegistry::new();
392            results.push(reading.transpile(&mut registry, &interner, options.format));
393        }
394    }
395
396    // Cumulative reading (Scha) — irreducible to either nesting — for two-cardinal
397    // transitive sentences ("Three boys lifted five boxes.").
398    if let Some(cumulative) = lambda::cumulative_reading(ast, &mut interner, &scope_arena) {
399        let cumulative =
400            semantics::apply_axioms(cumulative, &scope_arena, &scope_term_arena, &mut interner);
401        let mut registry = SymbolRegistry::new();
402        let rendered = cumulative.transpile(&mut registry, &interner, options.format);
403        if !results.contains(&rendered) {
404            results.push(rendered);
405        }
406    }
407
408    Ok(results)
409}
410
411// ═══════════════════════════════════════════════════════════════════
412// Parse Forest Compilation (Ambiguity Resolution)
413// ═══════════════════════════════════════════════════════════════════
414
415/// Compile natural language input, producing all valid parse readings.
416/// Handles lexical ambiguity (Noun/Verb) and structural ambiguity (PP attachment).
417pub fn compile_forest(input: &str) -> Vec<String> {
418    compile_forest_with_options(input, CompileOptions::default())
419}
420
421/// Compile natural language input with options, producing all valid parse readings.
422pub fn compile_forest_with_options(input: &str, options: CompileOptions) -> Vec<String> {
423    let mut interner = Interner::new();
424    let mut lexer = Lexer::new(input, &mut interner);
425    let tokens = lexer.tokenize();
426
427    // Apply MWE collapsing
428    let mwe_trie = mwe::build_mwe_trie();
429    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
430
431    // Pass 1: Discovery - scan for type definitions
432    let type_registry = {
433        let mut discovery = analysis::DiscoveryPass::new(&tokens, &mut interner);
434        discovery.run()
435    };
436
437    let has_lexical_ambiguity = tokens
438        .iter()
439        .any(|t| matches!(t.kind, token::TokenType::Ambiguous { .. }));
440
441    let has_pp_ambiguity = tokens.iter().any(|t| {
442        if let token::TokenType::Preposition(sym) = &t.kind {
443            let prep = interner.resolve(*sym);
444            prep == "with" || prep == "by" || prep == "for"
445        } else {
446            false
447        }
448    });
449
450    // Detect plurality ambiguity (mixed verb + plural subject)
451    let has_mixed_verb = tokens.iter().any(|t| {
452        if let token::TokenType::Verb { lemma, .. } = &t.kind {
453            Lexer::is_mixed_verb(interner.resolve(*lemma))
454        } else {
455            false
456        }
457    });
458
459    // Detect collective verbs (always require group reading with cardinals)
460    let has_collective_verb = tokens.iter().any(|t| {
461        if let token::TokenType::Verb { lemma, .. } = &t.kind {
462            Lexer::is_collective_verb(interner.resolve(*lemma))
463        } else {
464            false
465        }
466    });
467
468    let has_plural_subject = tokens.iter().any(|t| {
469        matches!(t.kind, token::TokenType::Cardinal(_))
470            || matches!(&t.kind, token::TokenType::Article(def) if matches!(def, lexicon::Definiteness::Definite))
471    });
472
473    let has_plurality_ambiguity = (has_mixed_verb || has_collective_verb) && has_plural_subject;
474
475    // Detect event adjective + agentive noun ambiguity
476    let has_event_adjective_ambiguity = {
477        let mut has_event_adj = false;
478        let mut has_agentive_noun = false;
479        for token in &tokens {
480            if let token::TokenType::Adjective(sym) = &token.kind {
481                if lexicon::is_event_modifier_adjective(interner.resolve(*sym)) {
482                    has_event_adj = true;
483                }
484            }
485            if let token::TokenType::Noun(sym) = &token.kind {
486                if lexicon::lookup_agentive_noun(interner.resolve(*sym)).is_some() {
487                    has_agentive_noun = true;
488                }
489            }
490        }
491        has_event_adj && has_agentive_noun
492    };
493
494    // Detect lexically negative verbs (e.g., "lacks", "miss") for scope ambiguity
495    let has_negative_verb = tokens.iter().any(|t| {
496        if let token::TokenType::Verb { lemma, .. } = &t.kind {
497            lexicon::get_canonical_verb(&interner.resolve(*lemma).to_lowercase())
498                .map(|(_, is_neg)| is_neg)
499                .unwrap_or(false)
500        } else {
501            false
502        }
503    });
504
505    // Detect modal polysemy (may, can, could)
506    let has_may = tokens
507        .iter()
508        .any(|t| matches!(t.kind, token::TokenType::May));
509    let has_can = tokens
510        .iter()
511        .any(|t| matches!(t.kind, token::TokenType::Can));
512    let has_could = tokens
513        .iter()
514        .any(|t| matches!(t.kind, token::TokenType::Could));
515
516    let mut results: Vec<String> = Vec::new();
517
518    // Reading 1: Default mode (verb priority for Ambiguous tokens)
519    {
520        let expr_arena = Arena::new();
521        let term_arena = Arena::new();
522        let np_arena = Arena::new();
523        let sym_arena = Arena::new();
524        let role_arena = Arena::new();
525        let pp_arena = Arena::new();
526
527        let ast_ctx = AstContext::new(
528            &expr_arena,
529            &term_arena,
530            &np_arena,
531            &sym_arena,
532            &role_arena,
533            &pp_arena,
534        );
535
536        let mut world_state = drs::WorldState::new();
537        let mut parser = Parser::new(
538            tokens.clone(),
539            &mut world_state,
540            &mut interner,
541            ast_ctx,
542            type_registry.clone(),
543        );
544        parser.set_noun_priority_mode(false);
545
546        if let Ok(ast) = parser.parse() {
547            let ast = semantics::apply_axioms(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner);
548            let ast = if options.format == OutputFormat::Kripke {
549                semantics::apply_kripke_lowering(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner)
550            } else {
551                ast
552            };
553            let mut registry = SymbolRegistry::new();
554            results.push(ast.transpile_discourse(&mut registry, &interner, options.format));
555        }
556    }
557
558    // Reading set 2: PER-TOKEN resolution of lexical ambiguity. Each
559    // Ambiguous token contributes its primary and alternative readings;
560    // every combination is parsed STRICTLY, so exactly the grammatical
561    // readings survive ("I saw her duck." → perception event AND
562    // possessed-bird object; "time flies" → N+V and compound-N+V).
563    if has_lexical_ambiguity {
564        let amb_positions: Vec<usize> = tokens
565            .iter()
566            .enumerate()
567            .filter(|(_, t)| matches!(t.kind, token::TokenType::Ambiguous { .. }))
568            .map(|(i, _)| i)
569            .collect();
570        let option_counts: Vec<usize> = amb_positions
571            .iter()
572            .map(|&i| {
573                if let token::TokenType::Ambiguous { alternatives, .. } = &tokens[i].kind {
574                    1 + alternatives.len()
575                } else {
576                    1
577                }
578            })
579            .collect();
580        let total: usize = option_counts.iter().product();
581
582        if total <= MAX_FOREST_READINGS {
583            for combo in 0..total {
584                let mut variant = tokens.clone();
585                let mut rem = combo;
586                for (slot, &i) in amb_positions.iter().enumerate() {
587                    let pick = rem % option_counts[slot];
588                    rem /= option_counts[slot];
589                    if let token::TokenType::Ambiguous {
590                        primary,
591                        alternatives,
592                    } = &tokens[i].kind
593                    {
594                        variant[i].kind = if pick == 0 {
595                            (**primary).clone()
596                        } else {
597                            alternatives[pick - 1].clone()
598                        };
599                    }
600                }
601
602                let expr_arena = Arena::new();
603                let term_arena = Arena::new();
604                let np_arena = Arena::new();
605                let sym_arena = Arena::new();
606                let role_arena = Arena::new();
607                let pp_arena = Arena::new();
608
609                let ast_ctx = AstContext::new(
610                    &expr_arena,
611                    &term_arena,
612                    &np_arena,
613                    &sym_arena,
614                    &role_arena,
615                    &pp_arena,
616                );
617
618                let mut world_state = drs::WorldState::new();
619                let mut parser = Parser::new(
620                    variant,
621                    &mut world_state,
622                    &mut interner,
623                    ast_ctx,
624                    type_registry.clone(),
625                );
626
627                if let Ok(ast) = parser.parse() {
628                    let ast =
629                        semantics::apply_axioms(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner);
630                    let ast = if options.format == OutputFormat::Kripke {
631                        semantics::apply_kripke_lowering(
632                            ast,
633                            ast_ctx.exprs,
634                            ast_ctx.terms,
635                            &mut interner,
636                        )
637                    } else {
638                        ast
639                    };
640                    let mut registry = SymbolRegistry::new();
641                    let reading = ast.transpile_discourse(&mut registry, &interner, options.format);
642                    if !results.contains(&reading) {
643                        results.push(reading);
644                    }
645                }
646            }
647        }
648    }
649
650    // Reading 3: PP attachment mode (for structural ambiguity)
651    if has_pp_ambiguity {
652        let expr_arena = Arena::new();
653        let term_arena = Arena::new();
654        let np_arena = Arena::new();
655        let sym_arena = Arena::new();
656        let role_arena = Arena::new();
657        let pp_arena = Arena::new();
658
659        let ast_ctx = AstContext::new(
660            &expr_arena,
661            &term_arena,
662            &np_arena,
663            &sym_arena,
664            &role_arena,
665            &pp_arena,
666        );
667
668        let mut world_state = drs::WorldState::new();
669        let mut parser = Parser::new(
670            tokens.clone(),
671            &mut world_state,
672            &mut interner,
673            ast_ctx,
674            type_registry.clone(),
675        );
676        parser.set_pp_attachment_mode(true);
677
678        if let Ok(ast) = parser.parse() {
679            let ast = semantics::apply_axioms(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner);
680            let ast = if options.format == OutputFormat::Kripke {
681                semantics::apply_kripke_lowering(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner)
682            } else {
683                ast
684            };
685            let mut registry = SymbolRegistry::new();
686            let reading = ast.transpile_discourse(&mut registry, &interner, options.format);
687            if !results.contains(&reading) {
688                results.push(reading);
689            }
690        }
691    }
692
693    // Reading 4: Collective mode (for plurality ambiguity with mixed verbs)
694    if has_plurality_ambiguity {
695        let expr_arena = Arena::new();
696        let term_arena = Arena::new();
697        let np_arena = Arena::new();
698        let sym_arena = Arena::new();
699        let role_arena = Arena::new();
700        let pp_arena = Arena::new();
701
702        let ast_ctx = AstContext::new(
703            &expr_arena,
704            &term_arena,
705            &np_arena,
706            &sym_arena,
707            &role_arena,
708            &pp_arena,
709        );
710
711        let mut world_state = drs::WorldState::new();
712        let mut parser = Parser::new(
713            tokens.clone(),
714            &mut world_state,
715            &mut interner,
716            ast_ctx,
717            type_registry.clone(),
718        );
719        parser.set_collective_mode(true);
720
721        if let Ok(ast) = parser.parse() {
722            if let Ok(transformed) = parser.transform_cardinal_to_group(ast) {
723                let transformed = semantics::apply_axioms(
724                    transformed,
725                    ast_ctx.exprs,
726                    ast_ctx.terms,
727                    &mut interner,
728                );
729                let mut registry = SymbolRegistry::new();
730                let reading = transformed.transpile(&mut registry, &interner, options.format);
731                if !results.contains(&reading) {
732                    results.push(reading);
733                }
734            }
735        }
736    }
737
738    // Reading 4b: Distributive mode — a mixed verb with a definite plural
739    // defaults to the collective reading, so the per-member reading is the
740    // OTHER half of the ambiguity ("the boys lifted the piano" — each alone).
741    if has_plurality_ambiguity {
742        let expr_arena = Arena::new();
743        let term_arena = Arena::new();
744        let np_arena = Arena::new();
745        let sym_arena = Arena::new();
746        let role_arena = Arena::new();
747        let pp_arena = Arena::new();
748
749        let ast_ctx = AstContext::new(
750            &expr_arena,
751            &term_arena,
752            &np_arena,
753            &sym_arena,
754            &role_arena,
755            &pp_arena,
756        );
757
758        let mut world_state = drs::WorldState::new();
759        let mut parser = Parser::new(
760            tokens.clone(),
761            &mut world_state,
762            &mut interner,
763            ast_ctx,
764            type_registry.clone(),
765        );
766        parser.set_distributive_marker(true);
767
768        if let Ok(ast) = parser.parse() {
769            let ast = semantics::apply_axioms(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner);
770            let mut registry = SymbolRegistry::new();
771            let reading = ast.transpile(&mut registry, &interner, options.format);
772            if !results.contains(&reading) {
773                results.push(reading);
774            }
775        }
776    }
777
778    // Reading 5: Event adjective mode (for event-modifying adjectives with agentive nouns)
779    if has_event_adjective_ambiguity {
780        let expr_arena = Arena::new();
781        let term_arena = Arena::new();
782        let np_arena = Arena::new();
783        let sym_arena = Arena::new();
784        let role_arena = Arena::new();
785        let pp_arena = Arena::new();
786
787        let ast_ctx = AstContext::new(
788            &expr_arena,
789            &term_arena,
790            &np_arena,
791            &sym_arena,
792            &role_arena,
793            &pp_arena,
794        );
795
796        let mut world_state = drs::WorldState::new();
797        let mut parser = Parser::new(
798            tokens.clone(),
799            &mut world_state,
800            &mut interner,
801            ast_ctx,
802            type_registry.clone(),
803        );
804        parser.set_event_reading_mode(true);
805
806        if let Ok(ast) = parser.parse() {
807            let ast = semantics::apply_axioms(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner);
808            let ast = if options.format == OutputFormat::Kripke {
809                semantics::apply_kripke_lowering(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner)
810            } else {
811                ast
812            };
813            let mut registry = SymbolRegistry::new();
814            let reading = ast.transpile_discourse(&mut registry, &interner, options.format);
815            if !results.contains(&reading) {
816                results.push(reading);
817            }
818        }
819    }
820
821    // Reading 6: Wide scope negation mode (for lexically negative verbs like "lacks")
822    if has_negative_verb {
823        let expr_arena = Arena::new();
824        let term_arena = Arena::new();
825        let np_arena = Arena::new();
826        let sym_arena = Arena::new();
827        let role_arena = Arena::new();
828        let pp_arena = Arena::new();
829
830        let ast_ctx = AstContext::new(
831            &expr_arena,
832            &term_arena,
833            &np_arena,
834            &sym_arena,
835            &role_arena,
836            &pp_arena,
837        );
838
839        let mut world_state = drs::WorldState::new();
840        let mut parser = Parser::new(
841            tokens.clone(),
842            &mut world_state,
843            &mut interner,
844            ast_ctx,
845            type_registry.clone(),
846        );
847        parser.set_negative_scope_mode(NegativeScopeMode::Wide);
848
849        if let Ok(ast) = parser.parse() {
850            let ast = semantics::apply_axioms(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner);
851            let ast = if options.format == OutputFormat::Kripke {
852                semantics::apply_kripke_lowering(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner)
853            } else {
854                ast
855            };
856            let mut registry = SymbolRegistry::new();
857            let reading = ast.transpile_discourse(&mut registry, &interner, options.format);
858            if !results.contains(&reading) {
859                results.push(reading);
860            }
861        }
862    }
863
864    // Reading 7: Epistemic modal preference (May=Possibility, Could=Possibility)
865    if has_may || has_could {
866        let expr_arena = Arena::new();
867        let term_arena = Arena::new();
868        let np_arena = Arena::new();
869        let sym_arena = Arena::new();
870        let role_arena = Arena::new();
871        let pp_arena = Arena::new();
872
873        let ast_ctx = AstContext::new(
874            &expr_arena,
875            &term_arena,
876            &np_arena,
877            &sym_arena,
878            &role_arena,
879            &pp_arena,
880        );
881
882        let mut world_state = drs::WorldState::new();
883        let mut parser = Parser::new(
884            tokens.clone(),
885            &mut world_state,
886            &mut interner,
887            ast_ctx,
888            type_registry.clone(),
889        );
890        parser.set_modal_preference(ModalPreference::Epistemic);
891
892        if let Ok(ast) = parser.parse() {
893            let ast = semantics::apply_axioms(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner);
894            let ast = if options.format == OutputFormat::Kripke {
895                semantics::apply_kripke_lowering(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner)
896            } else {
897                ast
898            };
899            let mut registry = SymbolRegistry::new();
900            let reading = ast.transpile_discourse(&mut registry, &interner, options.format);
901            if !results.contains(&reading) {
902                results.push(reading);
903            }
904        }
905    }
906
907    // Reading 8: Deontic modal preference (Can=Permission)
908    if has_can {
909        let expr_arena = Arena::new();
910        let term_arena = Arena::new();
911        let np_arena = Arena::new();
912        let sym_arena = Arena::new();
913        let role_arena = Arena::new();
914        let pp_arena = Arena::new();
915
916        let ast_ctx = AstContext::new(
917            &expr_arena,
918            &term_arena,
919            &np_arena,
920            &sym_arena,
921            &role_arena,
922            &pp_arena,
923        );
924
925        let mut world_state = drs::WorldState::new();
926        let mut parser = Parser::new(
927            tokens.clone(),
928            &mut world_state,
929            &mut interner,
930            ast_ctx,
931            type_registry.clone(),
932        );
933        parser.set_modal_preference(ModalPreference::Deontic);
934
935        if let Ok(ast) = parser.parse() {
936            let ast = semantics::apply_axioms(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner);
937            let ast = if options.format == OutputFormat::Kripke {
938                semantics::apply_kripke_lowering(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner)
939            } else {
940                ast
941            };
942            let mut registry = SymbolRegistry::new();
943            let reading = ast.transpile_discourse(&mut registry, &interner, options.format);
944            if !results.contains(&reading) {
945                results.push(reading);
946            }
947        }
948    }
949
950    // Reading 9: Wide scope negation + Deontic modal preference
951    if has_negative_verb && has_can {
952        let expr_arena = Arena::new();
953        let term_arena = Arena::new();
954        let np_arena = Arena::new();
955        let sym_arena = Arena::new();
956        let role_arena = Arena::new();
957        let pp_arena = Arena::new();
958
959        let ast_ctx = AstContext::new(
960            &expr_arena,
961            &term_arena,
962            &np_arena,
963            &sym_arena,
964            &role_arena,
965            &pp_arena,
966        );
967
968        let mut world_state = drs::WorldState::new();
969        let mut parser = Parser::new(
970            tokens.clone(),
971            &mut world_state,
972            &mut interner,
973            ast_ctx,
974            type_registry,
975        );
976        parser.set_negative_scope_mode(NegativeScopeMode::Wide);
977        parser.set_modal_preference(ModalPreference::Deontic);
978
979        if let Ok(ast) = parser.parse() {
980            let ast = semantics::apply_axioms(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner);
981            let ast = if options.format == OutputFormat::Kripke {
982                semantics::apply_kripke_lowering(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner)
983            } else {
984                ast
985            };
986            let mut registry = SymbolRegistry::new();
987            let reading = ast.transpile_discourse(&mut registry, &interner, options.format);
988            if !results.contains(&reading) {
989                results.push(reading);
990            }
991        }
992    }
993
994    // Enforce MAX_FOREST_READINGS limit
995    results.truncate(MAX_FOREST_READINGS);
996
997    results
998}
999
1000// ═══════════════════════════════════════════════════════════════════
1001// Discourse Compilation
1002// ═══════════════════════════════════════════════════════════════════
1003
1004/// Compile multiple sentences as a discourse, tracking temporal ordering.
1005pub fn compile_discourse(sentences: &[&str]) -> Result<String, ParseError> {
1006    compile_discourse_with_options(sentences, CompileOptions::default())
1007}
1008
1009/// Compile multiple sentences as a discourse with specified options.
1010pub fn compile_discourse_with_options(
1011    sentences: &[&str],
1012    options: CompileOptions,
1013) -> Result<String, ParseError> {
1014    let mut interner = Interner::new();
1015    let mut world_state = drs::WorldState::new();
1016    let mut results = Vec::new();
1017    let mut registry = SymbolRegistry::new();
1018    let mwe_trie = mwe::build_mwe_trie();
1019
1020    for sentence in sentences {
1021        let event_var_name = world_state.next_event_var();
1022        let event_var_symbol = interner.intern(&event_var_name);
1023
1024        let mut lexer = Lexer::new(sentence, &mut interner);
1025        let tokens = lexer.tokenize();
1026
1027        // Apply MWE collapsing
1028        let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
1029
1030        // Pass 1: Discovery - scan for type definitions
1031        let type_registry = {
1032            let mut discovery = analysis::DiscoveryPass::new(&tokens, &mut interner);
1033            discovery.run()
1034        };
1035
1036        let expr_arena = Arena::new();
1037        let term_arena = Arena::new();
1038        let np_arena = Arena::new();
1039        let sym_arena = Arena::new();
1040        let role_arena = Arena::new();
1041        let pp_arena = Arena::new();
1042
1043        let ast_ctx = AstContext::new(
1044            &expr_arena,
1045            &term_arena,
1046            &np_arena,
1047            &sym_arena,
1048            &role_arena,
1049            &pp_arena,
1050        );
1051
1052        // Pass 2: Parse with WorldState (DRS persists across sentences)
1053        let mut parser = Parser::new(
1054            tokens,
1055            &mut world_state,
1056            &mut interner,
1057            ast_ctx,
1058            type_registry,
1059        );
1060        parser.set_discourse_event_var(event_var_symbol);
1061        // Swap DRS from WorldState into Parser at start
1062        parser.swap_drs_with_world_state();
1063        let ast = parser.parse()?;
1064        // Swap DRS back to WorldState at end
1065        parser.swap_drs_with_world_state();
1066
1067        // Mark sentence boundary - collect telescope candidates for cross-sentence anaphora
1068        world_state.end_sentence();
1069
1070        let ast = semantics::apply_axioms(ast, ast_ctx.exprs, ast_ctx.terms, &mut interner);
1071        results.push(ast.transpile_discourse(&mut registry, &interner, options.format));
1072    }
1073
1074    let event_history = world_state.event_history();
1075    let mut precedes = Vec::new();
1076    for i in 0..event_history.len().saturating_sub(1) {
1077        precedes.push(format!(
1078            "Precedes({}, {})",
1079            event_history[i],
1080            event_history[i + 1]
1081        ));
1082    }
1083
1084    if precedes.is_empty() {
1085        Ok(results.join(" ∧ "))
1086    } else {
1087        Ok(format!(
1088            "{} ∧ {}",
1089            results.join(" ∧ "),
1090            precedes.join(" ∧ ")
1091        ))
1092    }
1093}
1094
1095// ═══════════════════════════════════════════════════════════════════
1096// Ambiguity Handling
1097// ═══════════════════════════════════════════════════════════════════
1098
1099/// Compile with PP attachment ambiguity detection.
1100/// Returns multiple readings if structural ambiguity exists.
1101pub fn compile_ambiguous(input: &str) -> Result<Vec<String>, ParseError> {
1102    compile_ambiguous_with_options(input, CompileOptions::default())
1103}
1104
1105/// Compile with PP attachment ambiguity detection and specified options.
1106pub fn compile_ambiguous_with_options(
1107    input: &str,
1108    options: CompileOptions,
1109) -> Result<Vec<String>, ParseError> {
1110    let mut interner = Interner::new();
1111    let mut lexer = Lexer::new(input, &mut interner);
1112    let tokens = lexer.tokenize();
1113
1114    // Apply MWE collapsing
1115    let mwe_trie = mwe::build_mwe_trie();
1116    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
1117
1118    // Pass 1: Discovery - scan for type definitions
1119    let type_registry = {
1120        let mut discovery = analysis::DiscoveryPass::new(&tokens, &mut interner);
1121        discovery.run()
1122    };
1123
1124    let expr_arena = Arena::new();
1125    let term_arena = Arena::new();
1126    let np_arena = Arena::new();
1127    let sym_arena = Arena::new();
1128    let role_arena = Arena::new();
1129    let pp_arena = Arena::new();
1130
1131    let ctx = AstContext::new(
1132        &expr_arena,
1133        &term_arena,
1134        &np_arena,
1135        &sym_arena,
1136        &role_arena,
1137        &pp_arena,
1138    );
1139
1140    // Pass 2: Parse with type context
1141    let mut world_state = drs::WorldState::new();
1142    let mut parser = Parser::new(
1143        tokens.clone(),
1144        &mut world_state,
1145        &mut interner,
1146        ctx,
1147        type_registry.clone(),
1148    );
1149    let ast = parser.parse()?;
1150    let ast = semantics::apply_axioms(ast, ctx.exprs, ctx.terms, &mut interner);
1151    let mut registry = SymbolRegistry::new();
1152    let reading1 = ast.transpile(&mut registry, &interner, options.format);
1153
1154    let has_pp_ambiguity = tokens.iter().any(|t| {
1155        if let token::TokenType::Preposition(sym) = &t.kind {
1156            let prep = interner.resolve(*sym);
1157            prep == "with" || prep == "by" || prep == "for"
1158        } else {
1159            false
1160        }
1161    });
1162
1163    if has_pp_ambiguity {
1164        let expr_arena2 = Arena::new();
1165        let term_arena2 = Arena::new();
1166        let np_arena2 = Arena::new();
1167        let sym_arena2 = Arena::new();
1168        let role_arena2 = Arena::new();
1169        let pp_arena2 = Arena::new();
1170
1171        let ctx2 = AstContext::new(
1172            &expr_arena2,
1173            &term_arena2,
1174            &np_arena2,
1175            &sym_arena2,
1176            &role_arena2,
1177            &pp_arena2,
1178        );
1179
1180        let mut world_state2 = drs::WorldState::new();
1181        let mut parser2 = Parser::new(
1182            tokens,
1183            &mut world_state2,
1184            &mut interner,
1185            ctx2,
1186            type_registry,
1187        );
1188        parser2.set_pp_attachment_mode(true);
1189        let ast2 = parser2.parse()?;
1190        let ast2 = semantics::apply_axioms(ast2, ctx2.exprs, ctx2.terms, &mut interner);
1191        let mut registry2 = SymbolRegistry::new();
1192        let reading2 = ast2.transpile(&mut registry2, &interner, options.format);
1193
1194        if reading1 != reading2 {
1195            return Ok(vec![reading1, reading2]);
1196        }
1197    }
1198
1199    Ok(vec![reading1])
1200}
1201
1202// ═══════════════════════════════════════════════════════════════════
1203// Theorem Compilation
1204// ═══════════════════════════════════════════════════════════════════
1205
1206use crate::ast::Stmt;
1207use crate::error::ParseErrorKind;
1208use crate::proof_convert::logic_expr_to_proof_expr;
1209use crate::token::Span;
1210
1211/// Compile and prove a theorem block.
1212pub fn compile_theorem(input: &str) -> Result<String, ParseError> {
1213    let mut interner = Interner::new();
1214    let mut lexer = Lexer::new(input, &mut interner);
1215    let tokens = lexer.tokenize();
1216
1217    // Apply MWE collapsing
1218    let mwe_trie = mwe::build_mwe_trie();
1219    let tokens = mwe::apply_mwe_pipeline(tokens, &mwe_trie, &mut interner);
1220
1221    // Pass 1: Discovery
1222    let type_registry = {
1223        let mut discovery = analysis::DiscoveryPass::new(&tokens, &mut interner);
1224        discovery.run()
1225    };
1226
1227    let expr_arena = Arena::new();
1228    let term_arena = Arena::new();
1229    let np_arena = Arena::new();
1230    let sym_arena = Arena::new();
1231    let role_arena = Arena::new();
1232    let pp_arena = Arena::new();
1233
1234    let ctx = AstContext::new(
1235        &expr_arena,
1236        &term_arena,
1237        &np_arena,
1238        &sym_arena,
1239        &role_arena,
1240        &pp_arena,
1241    );
1242
1243    // Parse as program to get statements including Theorem blocks
1244    let mut world_state = drs::WorldState::new();
1245    let mut parser = Parser::new(tokens, &mut world_state, &mut interner, ctx, type_registry);
1246    let statements = parser.parse_program()?;
1247
1248    // Find the first Theorem statement
1249    let theorem = statements
1250        .iter()
1251        .find_map(|stmt| {
1252            if let Stmt::Theorem(t) = stmt {
1253                Some(t)
1254            } else {
1255                None
1256            }
1257        })
1258        .ok_or_else(|| ParseError {
1259            kind: ParseErrorKind::Custom("No theorem block found in input".to_string()),
1260            span: Span::default(),
1261        })?;
1262
1263    // Convert premises and goal from LogicExpr to ProofExpr
1264    let premises: Vec<_> = theorem
1265        .premises
1266        .iter()
1267        .map(|premise| logic_expr_to_proof_expr(premise, &interner))
1268        .collect();
1269    let goal = logic_expr_to_proof_expr(theorem.goal, &interner);
1270
1271    // Route through the one canonical pipeline (prove → certify → kernel check),
1272    // so every theorem entry point shares a single engine. This door reports a
1273    // proof when a derivation is found, annotating whether the kernel certified
1274    // it; the strong (kernel-checked) guarantee is exposed by `verify_theorem`
1275    // and the `verified` flag on `TheoremCompileResult`. An explicit `Proof:` tactic
1276    // SCRIPT (English-esque vernacular) is run through the tactic framework instead,
1277    // then certified through the SAME kernel door (`qed` → `check_derivation`).
1278    use crate::ast::theorem::ProofStrategy;
1279    let (outcome, discharged) = match &theorem.strategy {
1280        ProofStrategy::Auto => (
1281            logicaffeine_proof::verify::prove_certify_check(&premises, &goal),
1282            0,
1283        ),
1284        ProofStrategy::Script(src) => {
1285            run_proof_sketch(&premises, &theorem.premise_names, &goal, src, None)
1286        }
1287        // A one-word `Proof:` line names a SINGLE step. It runs through the same engine —
1288        // there is one proof-step namespace — and the only difference is the diagnostic
1289        // when the word is not a step at all.
1290        ProofStrategy::ByRule(rule) => {
1291            run_proof_sketch(&premises, &theorem.premise_names, &goal, rule, Some(rule))
1292        }
1293        // `Proof: Induction on n.` in its structured form. Lowering it to the script the
1294        // tactic engine already speaks keeps ONE driver rather than a second, divergent one.
1295        ProofStrategy::Induction(variable) => run_proof_sketch(
1296            &premises,
1297            &theorem.premise_names,
1298            &goal,
1299            &format!("induction {variable}"),
1300            None,
1301        ),
1302    };
1303    match outcome.derivation {
1304        Some(derivation) if outcome.verified => Ok(format!(
1305            "Theorem '{}' Proved! [kernel-verified]{}\n{}",
1306            theorem.name,
1307            discharged_note(discharged),
1308            derivation.display_tree()
1309        )),
1310        Some(derivation) => Ok(format!(
1311            "Theorem '{}' — derivation found but NOT kernel-certified (this is not a proof)\n{}",
1312            theorem.name,
1313            derivation.display_tree()
1314        )),
1315        None => Err(ParseError {
1316            kind: ParseErrorKind::Custom(format!(
1317                "Theorem '{}' failed.\n  Goal: {}\n  Premises: {}\n  Error: {}",
1318                theorem.name,
1319                goal,
1320                theorem.premises.len(),
1321                outcome
1322                    .verification_error
1323                    .unwrap_or_else(|| "no derivation found".to_string())
1324            )),
1325            span: Span::default(),
1326        }),
1327    }
1328}
1329
1330/// The vernacular `Proof:` line is an English proof SKETCH, not a Lean tactic block.
1331///
1332/// It names the METHOD; the routine obligations the method leaves are discharged by the
1333/// same certified automation `Proof: Auto.` uses, and the count comes back so the answer can
1334/// SAY how much the author left to the machine (see `discharged_note`). Nothing about the
1335/// trust door moves: every step, sketched or swept, is assembled into one derivation and
1336/// certified through `qed` → `check_derivation` → the kernel. The engine-level script API
1337/// (`ProofState::run_script` + `qed`) keeps Lean's strict "close every goal" discipline
1338/// untouched — the sketch reading belongs to the vernacular surface, not to the engine.
1339///
1340/// A step that ERRORS is never swept: the sweep runs only after the sketch itself ran
1341/// clean, so a misspelt tactic, a missing hypothesis or an inapplicable rule still fails
1342/// loudly instead of being proved around.
1343///
1344/// `rule_name` is `Some` for a [`ProofStrategy::ByRule`](crate::ast::theorem::ProofStrategy::ByRule)
1345/// line — a one-word proof. It changes only the DIAGNOSTIC: a word the tactic namespace does
1346/// not carry is reported as what it is (a kernel inference-rule name) rather than leaving the
1347/// author to read "unknown tactic" and guess.
1348pub fn run_proof_sketch(
1349    premises: &[logicaffeine_proof::ProofExpr],
1350    premise_names: &[Option<String>],
1351    goal: &logicaffeine_proof::ProofExpr,
1352    script: &str,
1353    rule_name: Option<&str>,
1354) -> (logicaffeine_proof::verify::VerifiedProof, usize) {
1355    use logicaffeine_proof::tactic::{ProofState, TacticError};
1356
1357    /// A sketch cannot leave more obligations than this and still be a sketch; the bound
1358    /// keeps a pathological script from turning one theorem into an unbounded proof search.
1359    const MAX_RESIDUAL_OBLIGATIONS: usize = 64;
1360
1361    let fail = |err: String| logicaffeine_proof::verify::VerifiedProof {
1362        derivation: None,
1363        proof_term: None,
1364        kernel_ctx: Default::default(),
1365        verified: false,
1366        verification_error: Some(err),
1367    };
1368
1369    let mut st = ProofState::start_with_names(premises.to_vec(), premise_names, goal.clone());
1370    if let Err(e) = st.run_script(script) {
1371        let mut message = e.to_string();
1372        if let Some(rule) = rule_name {
1373            if message.contains("unknown tactic") {
1374                // The word is one of TWO things, and saying the wrong one is worse than
1375                // saying nothing: a rule name is answered with the spelling that applies it,
1376                // and a word that is neither is told it is neither. Asking
1377                // `InferenceRule::from_name` is what separates them — the message used to
1378                // call every unknown one-word proof line an inference rule, which was a
1379                // FALSE statement about `Proof: Frobnicate.`
1380                message.push_str(
1381                    &if logicaffeine_proof::InferenceRule::from_name(rule).is_some() {
1382                        format!(
1383                            " — `{rule}` names a kernel INFERENCE RULE, not a proof step. \
1384                         The vernacular has one proof-step namespace (the tactics); write \
1385                         `Proof: By {rule}.` to apply that rule to the facts in scope in one \
1386                         kernel-certified step, `Proof: Auto.` to let the prover select the \
1387                         rule that applies, or name a tactic (assumption, intro, cases, \
1388                         induction, simp, …)"
1389                        )
1390                    } else {
1391                        format!(
1392                            " — `{rule}` is neither a proof step nor a kernel inference rule. \
1393                         Write `Proof: Auto.` to let the prover search, name a tactic \
1394                         (assumption, intro, cases, induction, simp, …), or name a rule with \
1395                         `Proof: By <Rule>.`"
1396                        )
1397                    },
1398                );
1399            }
1400        }
1401        return (fail(message), 0);
1402    }
1403
1404    let mut discharged = 0usize;
1405    let mut remaining = usize::MAX;
1406    loop {
1407        match st.qed() {
1408            Ok(vp) => return (vp, discharged),
1409            Err(TacticError::GoalsRemain(open)) => {
1410                // Strict decrease OR stop: `auto` closes the focused goal or fails, so a
1411                // count that did not shrink means the sweep is spinning.
1412                if open >= remaining || discharged >= MAX_RESIDUAL_OBLIGATIONS {
1413                    return (
1414                        fail(format!(
1415                            "the proof sketch left {open} obligation(s) the automation could \
1416                             not discharge"
1417                        )),
1418                        discharged,
1419                    );
1420                }
1421                remaining = open;
1422                if let Err(e) = st.run_script("auto") {
1423                    return (
1424                        fail(format!(
1425                            "the proof sketch left {open} obligation(s) the automation could \
1426                             not discharge: {e}"
1427                        )),
1428                        discharged,
1429                    );
1430                }
1431                discharged += 1;
1432            }
1433            Err(e) => return (fail(format!("{e:?}")), discharged),
1434        }
1435    }
1436}
1437
1438/// How the certified answer reports obligations the AUTHOR did not write and the automation
1439/// closed. Empty when the sketch was a complete proof, so a full tactic script reads exactly
1440/// as it did before.
1441fn discharged_note(discharged: usize) -> String {
1442    match discharged {
1443        0 => String::new(),
1444        1 => " (1 residual obligation discharged by automation)".to_string(),
1445        n => format!(" ({n} residual obligations discharged by automation)"),
1446    }
1447}
1448
1449#[cfg(test)]
1450#[path = "../../logicaffeine_tests/unit/logicaffeine_language/compile/tests.rs"]
1451mod tests;