Skip to main content

logicaffeine_language/parser/
clause.rs

1//! Clause-level parsing: sentences, conditionals, conjunctions, and relative clauses.
2//!
3//! This module handles the top-level sentence structures including:
4//!
5//! - **Simple sentences**: Subject-verb-object patterns
6//! - **Conditionals**: "If P then Q" with DRS scope handling
7//! - **Counterfactuals**: "If P were/had, Q would" (subjunctive)
8//! - **Disjunctions**: "Either P or Q", "P or Q"
9//! - **Conjunctions**: "P and Q"
10//! - **Relative clauses**: "who/that/which" attaching to noun phrases
11//! - **VP ellipsis**: "John ran and Mary did too"
12//!
13//! The [`ClauseParsing`] trait defines the interface implemented by [`Parser`].
14
15use super::math::MathParsing;
16use super::modal::ModalParsing;
17use super::noun::NounParsing;
18use super::pragmatics::PragmaticsParsing;
19use super::quantifier::QuantifierParsing;
20use super::question::QuestionParsing;
21use super::verb::LogicVerbParsing;
22use super::ParserMode;
23use super::{EventTemplate, ParseResult, Parser};
24use crate::ast::{
25    AspectOperator, LogicExpr, NeoEventData, NounPhrase, QuantifierKind, TemporalOperator, Term,
26    ThematicRole,
27};
28use crate::drs::{BoxType, Gender, Number};
29use crate::error::{ParseError, ParseErrorKind};
30use crate::lexer::Lexer;
31use crate::lexicon::Definiteness;
32use crate::lexicon::Time;
33use crate::token::{Token, TokenType};
34use logicaffeine_base::Symbol;
35
36/// Whether `kind` can BEGIN a clause subject (an NP head/determiner), as opposed to
37/// a copula or verb. Used to tell a fronted temporal adjunct ("Every year SIMON
38/// takes …") from a temporal SUBJECT ("Every year IS long").
39fn starts_clause_subject(kind: &TokenType) -> bool {
40    kind.is_generalized_quantifier()
41        || matches!(
42            kind,
43            TokenType::ProperName(_)
44                | TokenType::Noun(_)
45                | TokenType::Article(_)
46                | TokenType::Pronoun { .. }
47                | TokenType::All
48                | TokenType::No
49                | TokenType::Some
50                | TokenType::Any
51                | TokenType::Cardinal(_)
52                | TokenType::Number(_)
53        )
54}
55
56/// One side of an "Of A and B, …" pair. A bare proper name is a referring
57/// CONSTANT (`is_var == false`); anything with a determiner, adjective,
58/// possessor, PP, or relative clause is a DESCRIPTION carried by a fresh
59/// existential VARIABLE plus a `restrictor` predicate over it — so two NPs that
60/// share a head noun ("the red stamp" / "the blue stamp") stay distinct instead
61/// of collapsing to one constant.
62struct OfEntity<'a> {
63    sym: Symbol,
64    is_var: bool,
65    term: Term<'a>,
66    restrictor: Option<&'a LogicExpr<'a>>,
67}
68
69/// Trait for parsing clause-level structures.
70///
71/// Defines methods for parsing sentences, conditionals, conjunctions,
72/// and other clause-level constructs.
73pub trait ClauseParsing<'a, 'ctx, 'int> {
74    /// Parses a complete sentence, handling imperatives, ellipsis, and questions.
75    /// Depth-guarded wrapper (the parse-time half of the AST depth gate for the
76    /// LOGIC descent): a parenthesized / nested sentence recurses back through
77    /// here once per level, so a nesting tower becomes a graceful `AstTooDeep`
78    /// instead of a parser stack overflow. The body lives in `parse_sentence_inner`.
79    fn parse_sentence(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
80    /// The real body of [`Self::parse_sentence`]; call the guarded wrapper, never this.
81    fn parse_sentence_inner(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
82    /// Parses "if P then Q" conditionals with DRS scope handling.
83    fn parse_conditional(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
84    /// Parses "either P or Q" exclusive disjunctions.
85    fn parse_either_or(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
86    /// Parses "P or Q" disjunctions.
87    fn parse_disjunction(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
88    /// Parses "P and Q" conjunctions with scope coordination.
89    fn parse_conjunction(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
90    /// Extracts the subject of a copular predication, for non-parallel coordination.
91    fn extract_copular_subject(&self, expr: &'a LogicExpr<'a>) -> Option<Symbol>;
92    /// Parses a bare copular-predicate remnant ("wealthy" / "a philanthropist").
93    fn try_parse_copular_predicate(
94        &mut self,
95        subject: Symbol,
96    ) -> ParseResult<Option<&'a LogicExpr<'a>>>;
97    /// Parses "who/that/which" relative clauses attaching to noun phrases.
98    fn parse_relative_clause(&mut self, gap_var: Symbol) -> ParseResult<&'a LogicExpr<'a>>;
99    /// Parses a clause with a gap filled by borrowed verb (for VP coordination).
100    fn parse_gapped_clause(&mut self, borrowed_verb: Symbol) -> ParseResult<&'a LogicExpr<'a>>;
101    /// Parses "if P were/had" counterfactual antecedent (subjunctive).
102    fn parse_counterfactual_antecedent(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
103    /// Parses "Q would" counterfactual consequent.
104    fn parse_counterfactual_consequent(&mut self) -> ParseResult<&'a LogicExpr<'a>>;
105    /// Checks if current token is a wh-word (who, what, which, etc.).
106    fn check_wh_word(&self) -> bool;
107    /// Returns true if parsing a counterfactual context.
108    fn is_counterfactual_context(&self) -> bool;
109    /// Returns true if expression is a complete clause.
110    fn is_complete_clause(&self, expr: &LogicExpr<'a>) -> bool;
111    /// Extracts the main verb from an expression.
112    fn extract_verb_from_expr(&self, expr: &LogicExpr<'a>) -> Option<Symbol>;
113    /// Attempts to parse an English imperative ("Close the door.", "Don't touch
114    /// that.", "Let's leave."). Returns `None` (restoring position) when the input
115    /// is not verb-initial / not a hortative or negative command.
116    fn try_parse_imperative(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>>;
117    /// True if a finite verb (Verb/Auxiliary/copula/have/modal) appears at or after
118    /// `from`, before the clause terminator. Used to distinguish an imperative
119    /// (command verb is the only finite verb) from a declarative whose initial word
120    /// is a subject ("Set A has cardinality 5.").
121    fn clause_has_later_finite_verb(&self, from: usize) -> bool;
122    /// True when the verb at `vp` heads a reduced object relative (its overt subject
123    /// sits at `vp - 1`, the relativized head is the determiner-headed noun before
124    /// it), so it is NOT the clause's main verb.
125    fn is_reduced_relative_verb(&self, vp: usize) -> bool;
126    /// Attempts to parse an it-cleft "It was X who/that VP." → focus on X plus
127    /// exhaustivity (only X did it). Returns `None` (restoring position) otherwise.
128    fn try_parse_cleft(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>>;
129    /// Attempts to parse an exclamative "How tall she is!" / "What a fool he is!"
130    /// (how/what, no subject-aux inversion, "!"-terminated). Returns `None` otherwise.
131    fn try_parse_exclamative(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>>;
132    /// Attempts to parse an optative wish "May you prosper!", "Long live the king!",
133    /// "If only it were Friday!". Returns `None` (restoring position) otherwise.
134    fn try_parse_optative(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>>;
135    /// Attempts to parse correlative coordination "Neither X nor Y VP" / "Either X
136    /// or Y VP" — a shared predicate scoped over two subjects. `None` otherwise.
137    fn try_parse_correlative(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>>;
138    /// Attempts to parse "Of NP₁ and NP₂, one VP₁ and the other VP₂" →
139    /// (VP₁(NP₁) ∧ VP₂(NP₂)) ∨ (VP₁(NP₂) ∧ VP₂(NP₁)). Returns `None` otherwise.
140    fn try_parse_of_pair_xor(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>>;
141    /// Attempts to parse a sentence-initial temporal NP that FRAMES the clause
142    /// ("Every year Simon takes a holiday" → HAB), not its subject. `None` otherwise.
143    fn try_parse_fronted_temporal_adjunct(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>>;
144    /// Attempts to parse an inverted conditional "Had/Were/Should SUBJECT …, …" by
145    /// un-inverting to the canonical "If SUBJECT aux …" form and reusing the conditional
146    /// parser. Handles multi-word subjects and `Should`-fronting. `None` otherwise.
147    fn try_parse_inverted_conditional(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>>;
148    /// Attempts to parse VP ellipsis ("Mary did too").
149    fn try_parse_ellipsis(&mut self) -> Option<ParseResult<&'a LogicExpr<'a>>>;
150    /// Checks for ellipsis auxiliary (did, does, can, etc.).
151    fn check_ellipsis_auxiliary(&self) -> bool;
152    /// Checks for ellipsis terminator (too, also, as well).
153    fn check_ellipsis_terminator(&self) -> bool;
154}
155
156impl<'a, 'ctx, 'int> ClauseParsing<'a, 'ctx, 'int> for Parser<'a, 'ctx, 'int> {
157    fn try_parse_imperative(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>> {
158        let start = self.backtrack_point();
159        let mut negated = false;
160        // The covert subject of an imperative is the addressee (the hearer); the
161        // hortative "let's" makes it the inclusive group (speaker + addressee).
162        let mut agent_name = "Addressee";
163
164        if self.check(&TokenType::Let) {
165            // Hortative: "Let's leave." / "Let us leave." (Let + 's|us + verb)
166            let n1 = self.current + 1;
167            if n1 >= self.tokens.len() {
168                return Ok(None);
169            }
170            let next = &self.tokens[n1];
171            let next_text = self.interner.resolve(next.lexeme);
172            let is_lets = matches!(next.kind, TokenType::Possessive)
173                || next_text.eq_ignore_ascii_case("us")
174                || next_text.eq_ignore_ascii_case("'s")
175                || next_text.eq_ignore_ascii_case("s");
176            if !is_lets {
177                return Ok(None);
178            }
179            self.advance(); // Let
180            self.advance(); // 's / us
181            agent_name = "Us";
182        } else if self.check(&TokenType::Do) {
183            // Negative imperative: "Don't touch that." → Do + Not + verb
184            let n1 = self.current + 1;
185            if n1 < self.tokens.len() && matches!(self.tokens[n1].kind, TokenType::Not) {
186                self.advance(); // Do
187                self.advance(); // Not
188                negated = true;
189            } else {
190                // "Do you ...?" is a yes/no question, handled elsewhere.
191                return Ok(None);
192            }
193        }
194
195        // Sentence-initial imperatives capitalize the command verb, so the lexer
196        // may have tagged it as a ProperName ("Close" in "Close the door."). Retag
197        // a capitalized known base verb as a Verb — but ONLY when no other finite
198        // verb appears later in the clause. A real imperative has the command verb
199        // as its only finite verb; a later finite verb means the initial capitalized
200        // word is actually a subject ("Bill ran.", "Set A has cardinality 5.").
201        if let TokenType::ProperName(sym) = self.peek().kind {
202            let lemma = self.interner.resolve(sym).to_lowercase();
203            if crate::lexicon::is_base_verb(&lemma)
204                && !self.clause_has_later_finite_verb(self.current + 1)
205            {
206                let class = crate::lexicon::lookup_verb_class(&lemma);
207                self.tokens[self.current].kind = TokenType::Verb {
208                    lemma: sym,
209                    time: Time::Present,
210                    aspect: crate::lexicon::Aspect::Simple,
211                    class,
212                };
213            }
214        }
215
216        // An imperative is verb-initial. English has no bare-verb declaratives, and
217        // yes/no questions begin with an auxiliary (Do/Is/...) rather than a Verb
218        // token, so a Verb in initial position is the command verb.
219        if !self.check_verb() {
220            self.backtrack_to(&start);
221            return Ok(None);
222        }
223
224        // Even when the initial word is a Verb token, a later finite verb means it is
225        // really a subject (e.g. "Set" in "Set A has cardinality 5."), not a command.
226        if self.clause_has_later_finite_verb(self.current + 1) {
227            self.backtrack_to(&start);
228            return Ok(None);
229        }
230
231        let agent = self.interner.intern(agent_name);
232        let core = self.parse_predicate_with_subject(agent)?;
233        let action = if negated {
234            self.ctx.exprs.alloc(LogicExpr::UnaryOp {
235                op: TokenType::Not,
236                operand: core,
237            })
238        } else {
239            core
240        };
241        Ok(Some(self.ctx.exprs.alloc(LogicExpr::Imperative { action })))
242    }
243
244    fn clause_has_later_finite_verb(&self, from: usize) -> bool {
245        let mut j = from;
246        while j < self.tokens.len() {
247            // A finite verb that heads a REDUCED OBJECT RELATIVE ("the friend Simon
248            // WENT with", "the waterfall Derrick PHOTOGRAPHED") is not the clause's
249            // main verb — its presence must NOT veto the imperative reading of a
250            // sentence-initial command verb. The relative's signature is a
251            // determiner-headed noun head followed by a fresh subject (ProperName /
252            // Pronoun) and then this verb. Skip past such a verb (and a trailing
253            // stranded preposition) and keep scanning for a genuine main verb.
254            if matches!(self.tokens[j].kind, TokenType::Verb { .. })
255                && self.is_reduced_relative_verb(j)
256            {
257                let after = j + 1;
258                if matches!(
259                    self.tokens.get(after).map(|t| &t.kind),
260                    Some(TokenType::Preposition(_))
261                ) {
262                    j = after + 1;
263                } else {
264                    j = after;
265                }
266                continue;
267            }
268            match self.tokens[j].kind {
269                TokenType::Period | TokenType::EOF | TokenType::Exclamation => return false,
270                TokenType::Verb { .. }
271                | TokenType::Auxiliary(_)
272                | TokenType::Is
273                | TokenType::Are
274                | TokenType::Was
275                | TokenType::Were
276                | TokenType::Do
277                | TokenType::Does => return true,
278                _ => {
279                    // Some finite verbs (have/has/had, modals) are lexed as other
280                    // token kinds; catch them by lexeme.
281                    let lex = self.interner.resolve(self.tokens[j].lexeme).to_lowercase();
282                    if matches!(
283                        lex.as_str(),
284                        "has"
285                            | "have"
286                            | "had"
287                            | "is"
288                            | "are"
289                            | "was"
290                            | "were"
291                            | "do"
292                            | "does"
293                            | "did"
294                            | "will"
295                            | "would"
296                            | "can"
297                            | "could"
298                            | "should"
299                            | "shall"
300                            | "may"
301                            | "might"
302                            | "must"
303                    ) {
304                        return true;
305                    }
306                }
307            }
308            j += 1;
309        }
310        false
311    }
312
313    /// True when the verb at `vp` heads a reduced object relative — i.e. it is the
314    /// finite verb of a relativizer-dropped clause modifying a preceding noun head,
315    /// not a main-clause verb. The relative's overt subject (a ProperName or
316    /// Pronoun) sits at `vp - 1`, and the relativized head is the determiner-headed
317    /// common noun that immediately precedes that subject ("the friend \[Simon\] went",
318    /// "the waterfall \[Derrick\] photographed"). The determiner requirement is what
319    /// distinguishes this from a true main clause whose initial word is a subject
320    /// ("Set A has …" — "A" has no determiner-headed noun before it).
321    fn is_reduced_relative_verb(&self, vp: usize) -> bool {
322        if vp == 0 {
323            return false;
324        }
325        let subj = vp - 1;
326        if !matches!(
327            self.tokens[subj].kind,
328            TokenType::ProperName(_) | TokenType::Pronoun { .. }
329        ) {
330            return false;
331        }
332        if subj == 0 {
333            return false;
334        }
335        // The relativized head must be a common noun (the gap filler).
336        let head = subj - 1;
337        if !matches!(
338            self.tokens[head].kind,
339            TokenType::Noun(_) | TokenType::CalendarUnit(_) | TokenType::Ambiguous { .. }
340        ) {
341            return false;
342        }
343        // Walk back across nouns/adjectives in the head NP to find a determiner —
344        // an article, possessive, or quantifier opening the NP that the relative
345        // modifies. Without one, "X Y verb" is a bare main clause, not a relative.
346        let mut k = head;
347        loop {
348            match self.tokens[k].kind {
349                ref determiner if determiner.is_generalized_quantifier() => return true,
350                TokenType::Article(_)
351                | TokenType::Possessive
352                | TokenType::All
353                | TokenType::Some
354                | TokenType::No
355                | TokenType::Any => return true,
356                TokenType::Noun(_)
357                | TokenType::CalendarUnit(_)
358                | TokenType::Adjective(_)
359                | TokenType::Ambiguous { .. } => {
360                    if k == 0 {
361                        return false;
362                    }
363                    k -= 1;
364                }
365                _ => return false,
366            }
367        }
368    }
369
370    fn try_parse_cleft(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>> {
371        let start = self.backtrack_point();
372        // "It was/is X who/that VP." — the expletive "it" + copula + focus + relative.
373        if !self
374            .interner
375            .resolve(self.peek().lexeme)
376            .eq_ignore_ascii_case("it")
377        {
378            return Ok(None);
379        }
380        if self.current + 1 >= self.tokens.len()
381            || !matches!(
382                self.tokens[self.current + 1].kind,
383                TokenType::Is | TokenType::Was
384            )
385        {
386            return Ok(None);
387        }
388        self.advance(); // it
389        self.advance(); // is/was
390
391        // The focused constituent (a proper name or NP).
392        let focus_np = match self.parse_noun_phrase(false) {
393            Ok(np) => np,
394            Err(_) => {
395                self.backtrack_to(&start);
396                return Ok(None);
397            }
398        };
399        if !self.check(&TokenType::Who) && !self.check(&TokenType::That) {
400            self.backtrack_to(&start);
401            return Ok(None);
402        }
403        self.advance(); // who/that
404
405        let focus_sym = focus_np.noun;
406        // The cleft clause "broke the vase" with the focus as subject — the core
407        // predication.
408        let core = self.parse_predicate_with_subject(focus_sym)?;
409
410        // Exhaustivity: ∀z( core[focus→z] → z = focus ) — no one but the focus did it.
411        let z = self.next_var_name();
412        let core_z = self.substitute_constant_with_var_sym(core, focus_sym, z)?;
413        let identity = self.ctx.exprs.alloc(LogicExpr::Identity {
414            left: self.ctx.terms.alloc(Term::Variable(z)),
415            right: self.ctx.terms.alloc(Term::Constant(focus_sym)),
416        });
417        let implies = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
418            left: core_z,
419            op: TokenType::Implies,
420            right: identity,
421        });
422        let exhaustivity = self.ctx.exprs.alloc(LogicExpr::Quantifier {
423            kind: QuantifierKind::Universal,
424            variable: z,
425            body: implies,
426            island_id: self.current_island,
427        });
428
429        // Focus marker over the core, conjoined with the exhaustivity claim.
430        let focused_term = self.ctx.terms.alloc(Term::Constant(focus_sym));
431        let focus_expr = self.ctx.exprs.alloc(LogicExpr::Focus {
432            kind: crate::token::FocusKind::Cleft,
433            focused: focused_term,
434            scope: core,
435        });
436        Ok(Some(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
437            left: focus_expr,
438            op: TokenType::And,
439            right: exhaustivity,
440        })))
441    }
442
443    fn try_parse_exclamative(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>> {
444        let start = self.backtrack_point();
445        let lead = self.interner.resolve(self.peek().lexeme).to_lowercase();
446        if lead != "how" && lead != "what" {
447            return Ok(None);
448        }
449        // An exclamative is "!"-terminated and has NO subject-aux inversion. A
450        // wh-question ("How tall is she?") inverts and ends with "?"; require "!".
451        let ends_with_exclamation = self.tokens[start.pos..]
452            .iter()
453            .take_while(|t| !matches!(t.kind, TokenType::EOF))
454            .any(|t| matches!(t.kind, TokenType::Exclamation));
455        if !ends_with_exclamation {
456            return Ok(None);
457        }
458        let is_what = lead == "what";
459        self.advance(); // How / What
460                        // optional "a"/"an"
461        if self.check_article() {
462            self.advance();
463        }
464        // The gradable adjective (How) or the noun (What).
465        let pred_sym = match self.consume_content_word() {
466            Ok(s) => s,
467            Err(_) => {
468                self.backtrack_to(&start);
469                return Ok(None);
470            }
471        };
472        // The subject (a pronoun or proper name).
473        let subj_sym = if let TokenType::ProperName(s) = self.peek().kind {
474            self.advance();
475            s
476        } else if self.check_pronoun() {
477            let lx = self.interner.resolve(self.peek().lexeme).to_string();
478            self.advance();
479            let cap = lx
480                .chars()
481                .next()
482                .map(|c| c.to_uppercase().collect::<String>() + &lx[1..])
483                .unwrap_or(lx);
484            self.interner.intern(&cap)
485        } else {
486            match self.consume_content_word() {
487                Ok(s) => s,
488                Err(_) => {
489                    self.backtrack_to(&start);
490                    return Ok(None);
491                }
492            }
493        };
494        // optional copula + "!"
495        if matches!(
496            self.peek().kind,
497            TokenType::Is | TokenType::Are | TokenType::Was | TokenType::Were
498        ) {
499            self.advance();
500        }
501        if self.check(&TokenType::Exclamation) {
502            self.advance();
503        }
504
505        let degree_var = self.next_var_name();
506        // "How tall she is!" → Tall(she, d); "What a fool he is!" → Fool(he).
507        let body = if is_what {
508            self.ctx.exprs.alloc(LogicExpr::Predicate {
509                name: pred_sym,
510                args: self.ctx.terms.alloc_slice([Term::Constant(subj_sym)]),
511                world: None,
512            })
513        } else {
514            self.ctx.exprs.alloc(LogicExpr::Predicate {
515                name: pred_sym,
516                args: self
517                    .ctx
518                    .terms
519                    .alloc_slice([Term::Constant(subj_sym), Term::Variable(degree_var)]),
520                world: None,
521            })
522        };
523        Ok(Some(
524            self.ctx
525                .exprs
526                .alloc(LogicExpr::Exclamative { degree_var, body }),
527        ))
528    }
529
530    fn try_parse_optative(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>> {
531        let start = self.backtrack_point();
532        // Optatives are "!"-terminated wishes.
533        let ends_with_exclamation = self.tokens[start.pos..]
534            .iter()
535            .take_while(|t| !matches!(t.kind, TokenType::EOF))
536            .any(|t| matches!(t.kind, TokenType::Exclamation));
537        if !ends_with_exclamation {
538            return Ok(None);
539        }
540
541        // "May SUBJ VP!" — may-fronting (a wish, not the deontic modal). "May"
542        // collides with the month proper-name; in some contexts (e.g. theorem
543        // premises) the lexer emits it as a `ProperName("May")`, so accept that
544        // spelling too — the `!` terminator and the SUBJ-VP shape below keep a
545        // genuine month reading ("May 3 is a holiday.") from matching.
546        let is_may_fronting = self.check(&TokenType::May)
547            || matches!(self.peek().kind, TokenType::ProperName(_))
548                && self
549                    .interner
550                    .resolve(self.peek().lexeme)
551                    .eq_ignore_ascii_case("may");
552        if is_may_fronting {
553            self.advance(); // May
554            let subj_sym = if let TokenType::ProperName(s) = self.peek().kind {
555                self.advance();
556                s
557            } else if self.check_pronoun() {
558                let lx = self.interner.resolve(self.peek().lexeme).to_lowercase();
559                self.advance();
560                match lx.as_str() {
561                    "you" => self.interner.intern("Addressee"),
562                    "i" | "me" => self.interner.intern("Speaker"),
563                    other => self.interner.intern(
564                        &(other
565                            .chars()
566                            .next()
567                            .map(|c| c.to_uppercase().collect::<String>() + &other[1..])
568                            .unwrap_or_default()),
569                    ),
570                }
571            } else {
572                match self.parse_noun_phrase(false) {
573                    Ok(np) => np.noun,
574                    Err(_) => {
575                        self.backtrack_to(&start);
576                        return Ok(None);
577                    }
578                }
579            };
580            // The wish verb may be a rare/unlisted word ("prosper"), so capture it
581            // by lexeme rather than requiring a recognized verb token.
582            if self.is_at_end() || self.check(&TokenType::Exclamation) {
583                self.backtrack_to(&start);
584                return Ok(None);
585            }
586            let vlex = self.interner.resolve(self.peek().lexeme).to_string();
587            let vname = vlex
588                .chars()
589                .next()
590                .map(|c| c.to_uppercase().collect::<String>() + &vlex[1..])
591                .unwrap_or(vlex);
592            let verb_sym = self.interner.intern(&vname);
593            self.advance(); // consume the wish verb
594                            // Optional object (a pronoun / proper name).
595            let wish = if let TokenType::ProperName(o) = self.peek().kind {
596                self.advance();
597                self.ctx.exprs.alloc(LogicExpr::Predicate {
598                    name: verb_sym,
599                    args: self
600                        .ctx
601                        .terms
602                        .alloc_slice([Term::Constant(subj_sym), Term::Constant(o)]),
603                    world: None,
604                })
605            } else {
606                self.ctx.exprs.alloc(LogicExpr::Predicate {
607                    name: verb_sym,
608                    args: self.ctx.terms.alloc_slice([Term::Constant(subj_sym)]),
609                    world: None,
610                })
611            };
612            return Ok(Some(self.ctx.exprs.alloc(LogicExpr::Optative { wish })));
613        }
614
615        // "Long live NP!" — fixed optative construction.
616        let lead = self.interner.resolve(self.peek().lexeme).to_lowercase();
617        if lead == "long"
618            && self.current + 1 < self.tokens.len()
619            && self
620                .interner
621                .resolve(self.tokens[self.current + 1].lexeme)
622                .eq_ignore_ascii_case("live")
623        {
624            self.advance(); // Long
625            self.advance(); // live
626            let np = self.parse_noun_phrase(false)?;
627            let live_sym = self.interner.intern("Live");
628            let wish = self.ctx.exprs.alloc(LogicExpr::Predicate {
629                name: live_sym,
630                args: self.ctx.terms.alloc_slice([Term::Constant(np.noun)]),
631                world: None,
632            });
633            return Ok(Some(self.ctx.exprs.alloc(LogicExpr::Optative { wish })));
634        }
635
636        // "If only S!" — counterfactual wish.
637        if self.check(&TokenType::If)
638            && self.current + 1 < self.tokens.len()
639            && self
640                .interner
641                .resolve(self.tokens[self.current + 1].lexeme)
642                .eq_ignore_ascii_case("only")
643        {
644            self.advance(); // If
645            self.advance(); // only
646            let wish = self.parse_sentence()?;
647            return Ok(Some(self.ctx.exprs.alloc(LogicExpr::Optative { wish })));
648        }
649
650        Ok(None)
651    }
652
653    fn try_parse_correlative(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>> {
654        let start = self.backtrack_point();
655        let lead = self.interner.resolve(self.peek().lexeme).to_lowercase();
656        let is_neither = lead == "neither";
657        let is_either = lead == "either";
658        if !is_neither && !is_either {
659            return Ok(None);
660        }
661        self.advance(); // Neither / Either
662
663        // Parse each disjunct as a FULL noun phrase so multi-word proper names
664        // ("Belle Grove"), possessives ("Pam's client"), and descriptive NPs with
665        // PPs / relative clauses ("the person who paid $150") are preserved with
666        // ZERO meaning loss. A bare proper name OR a bare definite (head only,
667        // nothing to lose) stays a referring CONSTANT; a description carrying
668        // RESTRICTIONS (adjectives / possessor / PPs / relative clause) becomes a
669        // fresh existential VARIABLE with a restrictor, so the shared predicate
670        // distributes over the right entity.
671        fn build_disjunct<'a, 'ctx, 'int>(
672            p: &mut Parser<'a, 'ctx, 'int>,
673        ) -> ParseResult<OfEntity<'a>> {
674            let np = p.parse_noun_phrase(true)?;
675            let has_rel = p.check(&TokenType::Who)
676                || p.check(&TokenType::That)
677                || p.check(&TokenType::Where)
678                || p.check(&TokenType::Whose);
679            let is_desc = !np.adjectives.is_empty()
680                || np.possessor.is_some()
681                || !np.pps.is_empty()
682                || has_rel;
683            let (sym, is_var) = if is_desc {
684                (p.next_var_name(), true)
685            } else {
686                (np.noun, false)
687            };
688            let term = if is_var {
689                Term::Variable(sym)
690            } else {
691                Term::Constant(sym)
692            };
693            let rel = p.try_attach_relative(term)?;
694            let restrictor = if is_var {
695                let mut r = p.nominal_predication(term, &np);
696                for pp in np.pps {
697                    let pp_sub = p.substitute_pp_placeholder(pp, sym);
698                    r = p.ctx.exprs.alloc(LogicExpr::BinaryOp {
699                        left: r,
700                        op: TokenType::And,
701                        right: pp_sub,
702                    });
703                }
704                if let Some(rc) = rel {
705                    r = p.ctx.exprs.alloc(LogicExpr::BinaryOp {
706                        left: r,
707                        op: TokenType::And,
708                        right: rc,
709                    });
710                }
711                Some(r)
712            } else {
713                None
714            };
715            Ok(OfEntity {
716                sym,
717                is_var,
718                term,
719                restrictor,
720            })
721        }
722
723        // A disjunct's predicate becomes its branch: a description asserts its
724        // restrictor and binds the predicate under a fresh existential; a bare
725        // constant predicates directly. (For a constant this is exactly the old
726        // ¬pred / pred form, so proper-name correlatives are byte-identical.)
727        fn wrap_branch<'a, 'ctx, 'int>(
728            p: &mut Parser<'a, 'ctx, 'int>,
729            e: &OfEntity<'a>,
730            body: &'a LogicExpr<'a>,
731        ) -> &'a LogicExpr<'a> {
732            if !e.is_var {
733                return body;
734            }
735            let inner = match e.restrictor {
736                Some(r) => p.ctx.exprs.alloc(LogicExpr::BinaryOp {
737                    left: r,
738                    op: TokenType::And,
739                    right: body,
740                }),
741                None => body,
742            };
743            p.ctx.exprs.alloc(LogicExpr::Quantifier {
744                kind: QuantifierKind::Existential,
745                variable: e.sym,
746                body: inner,
747                island_id: p.current_island,
748            })
749        }
750
751        let e1 = match self.try_parse(|p| build_disjunct(p)) {
752            Some(e) => e,
753            None => {
754                self.backtrack_to(&start);
755                return Ok(None);
756            }
757        };
758
759        let conj = self.interner.resolve(self.peek().lexeme).to_lowercase();
760        if conj != "nor" && conj != "or" {
761            self.backtrack_to(&start);
762            return Ok(None);
763        }
764        self.advance(); // nor / or
765
766        let e2 = match self.try_parse(|p| build_disjunct(p)) {
767            Some(e) => e,
768            None => {
769                self.backtrack_to(&start);
770                return Ok(None);
771            }
772        };
773
774        // The shared predicate is parsed once per subject by re-parsing from the
775        // same position (parallel structure), so "Neither X nor Y VP" distributes VP.
776        let vp_start = self.backtrack_point();
777        let pred1 = if e1.is_var {
778            self.parse_predicate_with_subject_as_var(e1.sym)?
779        } else {
780            self.parse_predicate_with_subject(e1.sym)?
781        };
782        self.backtrack_to(&vp_start);
783        let pred2 = if e2.is_var {
784            self.parse_predicate_with_subject_as_var(e2.sym)?
785        } else {
786            self.parse_predicate_with_subject(e2.sym)?
787        };
788
789        let result = if is_neither {
790            // ¬pred1 ∧ ¬pred2 — a description binds its (asserted) restrictor and
791            // the negated predicate under its own existential.
792            let n1 = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
793                op: TokenType::Not,
794                operand: pred1,
795            });
796            let b1 = wrap_branch(self, &e1, n1);
797            let n2 = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
798                op: TokenType::Not,
799                operand: pred2,
800            });
801            let b2 = wrap_branch(self, &e2, n2);
802            self.ctx.exprs.alloc(LogicExpr::BinaryOp {
803                left: b1,
804                op: TokenType::And,
805                right: b2,
806            })
807        } else {
808            // "either…or" is the inclusive disjunction by default (so the proof engine
809            // and existing tests see a plain ∨); its EXCLUSIVITY implicature
810            // `∧ ¬(branch1 ∧ branch2)` is a pragmatic enrichment, added only in that mode.
811            let b1 = wrap_branch(self, &e1, pred1);
812            let b2 = wrap_branch(self, &e2, pred2);
813            let disj = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
814                left: b1,
815                op: TokenType::Or,
816                right: b2,
817            });
818            if self.pragmatic {
819                let both = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
820                    left: b1,
821                    op: TokenType::And,
822                    right: b2,
823                });
824                let not_both = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
825                    op: TokenType::Not,
826                    operand: both,
827                });
828                self.ctx.exprs.alloc(LogicExpr::BinaryOp {
829                    left: disj,
830                    op: TokenType::And,
831                    right: not_both,
832                })
833            } else {
834                disj
835            }
836        };
837        Ok(Some(result))
838    }
839
840    fn try_parse_inverted_conditional(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>> {
841        // A fronted auxiliary (Had / Were / Should) stands in for "if".
842        if !matches!(
843            self.peek().kind,
844            TokenType::Had | TokenType::Were | TokenType::Should
845        ) {
846            return Ok(None);
847        }
848
849        // Require "antecedent, consequent" — a comma before the clause terminator — so an
850        // inverted yes/no question ("Had you eaten?") is not mistaken for a conditional.
851        let has_comma = self.tokens[self.current..]
852            .iter()
853            .take_while(|t| !matches!(t.kind, TokenType::EOF | TokenType::Period))
854            .any(|t| matches!(t.kind, TokenType::Comma));
855        if !has_comma {
856            return Ok(None);
857        }
858
859        // Where the fronted aux un-inverts to: before the antecedent's first verb when
860        // there is one ("Had the soldiers KNOWN" → "the soldiers had known"), else after
861        // the subject-NP head (copular "Were I rich" → "I were rich"). Scanning stops at
862        // the clause comma so the aux never lands in the consequent.
863        let start = self.current + 1;
864        let comma_at = self.tokens[start..]
865            .iter()
866            .position(|t| matches!(t.kind, TokenType::Comma))
867            .map(|p| start + p)
868            .unwrap_or(self.tokens.len());
869
870        let first_verb =
871            (start..comma_at).find(|&j| matches!(self.tokens[j].kind, TokenType::Verb { .. }));
872
873        // Subject-NP head: optional determiners/adjectives then a nominal head (or, after
874        // a determiner, any content word — "soldiers" is verb/noun-ambiguous here).
875        let mut i = start;
876        while i < comma_at
877            && matches!(
878                self.tokens[i].kind,
879                TokenType::Article(_)
880                    | TokenType::Adjective(_)
881                    | TokenType::Cardinal(_)
882                    | TokenType::Possessive
883            )
884        {
885            i += 1;
886        }
887        let head_is_nominal = i < comma_at
888            && matches!(
889                self.tokens[i].kind,
890                TokenType::Noun(_) | TokenType::ProperName(_) | TokenType::Pronoun { .. }
891            );
892        let head_after_determiner =
893            i > start && i < comma_at && Self::is_content_word_type(&self.tokens[i].kind);
894
895        let insert_at = match first_verb {
896            Some(v) => v,
897            None if head_is_nominal || head_after_determiner => i + 1,
898            None => return Ok(None), // no subject NP / no predicate — not a conditional
899        };
900
901        // Un-invert to canonical order: lift the fronted aux to just after the subject NP
902        // and prepend a synthesized "If", then reuse the conditional parser. Reusing it
903        // keeps one antecedent grammar (weather verbs, conjunction, counterfactual
904        // detection) rather than duplicating it for the inverted word order.
905        let aux = self.tokens.remove(self.current);
906        self.tokens.insert(insert_at - 1, aux);
907        let mut if_tok = self.tokens[self.current].clone();
908        if_tok.kind = TokenType::If;
909        if_tok.lexeme = self.interner.intern("if");
910        self.tokens.insert(self.current, if_tok);
911        self.advance(); // consume the synthesized "If"
912        Ok(Some(self.parse_conditional()?))
913    }
914
915    /// A sentence-initial temporal NP that FRAMES the clause rather than serving as
916    /// its subject: "Every year Simon takes a holiday" → HAB over the whole clause.
917    /// Fires only for "Every/All <calendar-unit>" FOLLOWED BY a clause subject; a
918    /// time NP that is itself the subject ("Every year is long") has a copula/verb
919    /// next and is left to the ordinary quantifier path.
920    fn try_parse_fronted_temporal_adjunct(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>> {
921        let is_universal_det = matches!(self.peek().kind, TokenType::All);
922        let unit_next = matches!(
923            self.tokens.get(self.current + 1).map(|t| &t.kind),
924            Some(TokenType::CalendarUnit(_))
925        );
926        let subject_after = self
927            .tokens
928            .get(self.current + 2)
929            .map_or(false, |t| starts_clause_subject(&t.kind));
930        if !(is_universal_det && unit_next && subject_after) {
931            return Ok(None);
932        }
933        self.advance(); // Every / All
934        self.advance(); // <calendar-unit>
935        if self.check(&TokenType::Comma) {
936            self.advance();
937        }
938        let clause = self.parse_sentence()?;
939        // A present-tense clause ("Simon takes …") already carries HAB; the fronted
940        // "every <unit>" then adds nothing — don't double-wrap.
941        if matches!(
942            clause,
943            LogicExpr::Aspectual {
944                operator: AspectOperator::Habitual,
945                ..
946            }
947        ) {
948            return Ok(Some(clause));
949        }
950        Ok(Some(self.ctx.exprs.alloc(LogicExpr::Aspectual {
951            operator: AspectOperator::Habitual,
952            body: clause,
953        })))
954    }
955
956    fn parse_sentence(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
957        self.enter_recursion()?;
958        let result = self.parse_sentence_inner();
959        self.leave_recursion();
960        let sentence = result?;
961        // A sentence-final "infinitely often" scopes over the sentence it ends: G F.
962        if self.check(&TokenType::InfinitelyOften) {
963            self.advance();
964            return Ok(self.infinitely_often(sentence));
965        }
966        Ok(sentence)
967    }
968
969    fn parse_sentence_inner(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
970        // In imperative mode, handle Let statements by converting to LogicExpr
971        // This supports declarative parser being called after process_block_headers()
972        // Let x is/= value -> returns the value expression (the test just checks parsing succeeds)
973        if self.mode == ParserMode::Imperative && self.check(&TokenType::Let) {
974            self.advance(); // consume "Let"
975            let _var = self.expect_identifier()?;
976            // Accept "is", "be", "=" as assignment operators
977            if self.check(&TokenType::Is)
978                || self.check(&TokenType::Be)
979                || self.check(&TokenType::Equals)
980                || self.check(&TokenType::Identity)
981                || self.check(&TokenType::Assign)
982            {
983                self.advance(); // consume the operator
984            }
985            // Parse the value and return it (test just checks parsing succeeds)
986            return self.parse_disjunction();
987        }
988
989        // The MATH layer: a quantified arithmetic proposition ("For all n, n plus 0
990        // equals n."). Tried first because it is the one production whose vocabulary
991        // (`plus`, `equals`) the English parser reads as ordinary words; it self-rewinds
992        // unless it consumes the whole sentence, so everything else is untouched.
993        if self.mode != ParserMode::Imperative {
994            if let Some(math) = self.try_parse_math_sentence() {
995                return math;
996            }
997        }
998
999        // Check for ellipsis pattern: "Mary does too." / "Mary can too."
1000        if let Some(result) = self.try_parse_ellipsis() {
1001            return result;
1002        }
1003
1004        // Optatives: "May you prosper!", "Long live the king!", "If only …!".
1005        if self.mode != ParserMode::Imperative {
1006            if let Some(opt) = self.try_parse_optative()? {
1007                return Ok(opt);
1008            }
1009        }
1010
1011        // Correlative coordination: "Neither X nor Y VP" / "Either X or Y VP".
1012        if self.mode != ParserMode::Imperative {
1013            if let Some(corr) = self.try_parse_correlative()? {
1014                return Ok(corr);
1015            }
1016        }
1017
1018        // "Of NP₁ and NP₂, one VP₁ and the other VP₂" binary XOR partition.
1019        if self.mode != ParserMode::Imperative {
1020            if let Some(xor) = self.try_parse_of_pair_xor()? {
1021                return Ok(xor);
1022            }
1023        }
1024
1025        // Sentence-initial temporal adjunct: "Every year Simon takes a holiday"
1026        // (habitual) — the fronted time NP frames the whole clause.
1027        if self.mode != ParserMode::Imperative {
1028            if let Some(framed) = self.try_parse_fronted_temporal_adjunct()? {
1029                return Ok(framed);
1030            }
1031        }
1032
1033        // "Whoever VP₁ VP₂" → ∀x(VP₁(x) → VP₂(x)).
1034        // "Whoever" is not in the lexicon so it arrives as Noun/ProperName; detect by text.
1035        if self.mode != ParserMode::Imperative {
1036            let lead_text = self.interner.resolve(self.peek().lexeme).to_lowercase();
1037            if lead_text == "whoever" {
1038                self.advance(); // consume "whoever"
1039                let var = self.next_var_name();
1040                let restrictor = self.parse_predicate_with_subject(var)?;
1041                let scope = self.parse_predicate_with_subject(var)?;
1042                let body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1043                    left: restrictor,
1044                    op: TokenType::Implies,
1045                    right: scope,
1046                });
1047                return Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
1048                    kind: QuantifierKind::Universal,
1049                    variable: var,
1050                    body,
1051                    island_id: self.current_island,
1052                }));
1053            }
1054        }
1055
1056        // Exclamatives: "How tall she is!" / "What a fool he is!" — before the
1057        // wh-question path, since they share how/what but are "!"-terminated.
1058        if self.mode != ParserMode::Imperative {
1059            if let Some(excl) = self.try_parse_exclamative()? {
1060                return Ok(excl);
1061            }
1062        }
1063
1064        // it-clefts: "It was John who broke the vase." → focus + exhaustivity.
1065        if self.mode != ParserMode::Imperative {
1066            if let Some(cleft) = self.try_parse_cleft()? {
1067                return Ok(cleft);
1068            }
1069        }
1070
1071        // English imperatives: bare-verb-initial commands ("Close the door."),
1072        // negatives ("Don't touch that."), and hortatives ("Let's leave."). Only in
1073        // declarative (English) mode — code mode has its own verb-initial handling.
1074        if self.mode != ParserMode::Imperative {
1075            if let Some(imp) = self.try_parse_imperative()? {
1076                return Ok(imp);
1077            }
1078        }
1079
1080        // "Although/Though X, Y" concessive subordinator: Y holds despite X (a
1081        // defeated expectation). → Concessive{ main: Y, concession: X }.
1082        if self.check(&TokenType::Although) {
1083            self.advance(); // consume "Although"/"Though"
1084            let concession = self.parse_sentence()?;
1085            if self.check(&TokenType::Comma) {
1086                self.advance();
1087            }
1088            let main = self.parse_sentence()?;
1089            return Ok(self
1090                .ctx
1091                .exprs
1092                .alloc(LogicExpr::Concessive { main, concession }));
1093        }
1094
1095        // "While X, Y" as temporal duration subordinator
1096        // Duration semantics: Y holds for the entire interval where X is true.
1097        // Lowered as implication checked globally: G(X → Y)
1098        if self.check(&TokenType::While) {
1099            self.advance(); // consume "While"
1100            let condition = self.parse_sentence()?;
1101            if self.check(&TokenType::Comma) {
1102                self.advance();
1103            }
1104            let consequent = self.parse_sentence()?;
1105            return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1106                left: condition,
1107                op: TokenType::Implies,
1108                right: consequent,
1109            }));
1110        }
1111
1112        // "When X, Y" as temporal subordinator (before wh-question check)
1113        // Disambiguate: subordinator has comma-separated clauses, question does not
1114        if self.check(&TokenType::When) {
1115            let saved = self.backtrack_point();
1116            let mut found_comma = false;
1117            for i in (self.current + 1)..self.tokens.len() {
1118                match &self.tokens[i].kind {
1119                    TokenType::Comma => {
1120                        found_comma = true;
1121                        break;
1122                    }
1123                    TokenType::Period => break,
1124                    _ => {}
1125                }
1126            }
1127            if found_comma {
1128                self.advance(); // consume "When"
1129                let condition = self.parse_sentence()?;
1130                if self.check(&TokenType::Comma) {
1131                    self.advance();
1132                }
1133                let consequent = self.parse_sentence()?;
1134                return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1135                    left: condition,
1136                    op: TokenType::Implies,
1137                    right: consequent,
1138                }));
1139            }
1140            self.backtrack_to(&saved);
1141        }
1142
1143        // "Whenever X, Y" → same as "When X, Y"
1144        if self.check_content_word() {
1145            let word = self.interner.resolve(self.peek().lexeme).to_string();
1146            if word == "Whenever" || word == "whenever" {
1147                self.advance(); // consume "Whenever"
1148                let condition = self.parse_sentence()?;
1149                if self.check(&TokenType::Comma) {
1150                    self.advance();
1151                }
1152                let consequent = self.parse_sentence()?;
1153                return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1154                    left: condition,
1155                    op: TokenType::Implies,
1156                    right: consequent,
1157                }));
1158            }
1159        }
1160
1161        if self.check_wh_word() {
1162            return self.parse_wh_question();
1163        }
1164
1165        if self.check(&TokenType::Does)
1166            || self.check(&TokenType::Do)
1167            || self.check(&TokenType::Is)
1168            || self.check(&TokenType::Are)
1169            || self.check(&TokenType::Was)
1170            || self.check(&TokenType::Were)
1171            || self.check(&TokenType::Would)
1172            || self.check(&TokenType::Could)
1173            || self.check(&TokenType::Can)
1174        {
1175            return self.parse_yes_no_question();
1176        }
1177
1178        // Inverted conditional (§4.1): "Had I known, …" / "Were I rich, …" /
1179        // "Should it rain, …" — subject-aux inversion stands in for "if".
1180        if let Some(expr) = self.try_parse_inverted_conditional()? {
1181            return Ok(expr);
1182        }
1183
1184        if self.match_token(&[TokenType::If]) {
1185            return self.parse_conditional();
1186        }
1187
1188        // Handle "Either X or Y" disjunction
1189        // Special case: "Either NP1 or NP2 is/are PRED" should apply PRED to both
1190        if self.match_token(&[TokenType::Either]) {
1191            return self.parse_either_or();
1192        }
1193
1194        if self.check_modal() {
1195            self.advance();
1196            return self.parse_modal();
1197        }
1198
1199        if self.match_token(&[TokenType::Not]) {
1200            self.negative_depth += 1;
1201            let inner = self.parse_sentence()?;
1202            self.negative_depth -= 1;
1203            return Ok(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
1204                op: TokenType::Not,
1205                operand: inner,
1206            }));
1207        }
1208
1209        // "not both every request is valid and every grant is valid" → ¬(X ∧ Y)
1210        // Only triggers for clausal conjunction: "both" + quantifier/determiner
1211        // NOT for conjoined NP: "both Socrates and Plato are men"
1212        if self.check(&TokenType::Both) {
1213            // Peek at token after "both" — if it's a quantifier, this is clausal
1214            let next_is_clausal = if self.current + 1 < self.tokens.len() {
1215                let next = &self.tokens[self.current + 1].kind;
1216                matches!(next, TokenType::Any | TokenType::Article(_))
1217                    || QuantifierKind::of_determiner(next).is_some()
1218            } else {
1219                false
1220            };
1221            if next_is_clausal {
1222                self.advance(); // consume "both"
1223                let first = self.parse_atom()?;
1224                if self.check(&TokenType::And) {
1225                    self.advance(); // consume "and"
1226                }
1227                let second = self.parse_atom()?;
1228                return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1229                    left: first,
1230                    op: TokenType::And,
1231                    right: second,
1232                }));
1233            }
1234        }
1235
1236        // Sentence-initial temporal operators for hardware verification:
1237        // "Always, P" → Temporal { Always, P }
1238        // "Eventually, P" → Temporal { Eventually, P }
1239        // "Next, P" → Temporal { Next, P }
1240        // "Never P" → Temporal { Always, ¬P }
1241        {
1242            let temporal_op = match &self.peek().kind {
1243                TokenType::Adverb(sym)
1244                | TokenType::ScopalAdverb(sym)
1245                | TokenType::TemporalAdverb(sym) => {
1246                    let resolved = self.interner.resolve(*sym).to_string();
1247                    match resolved.as_str() {
1248                        "Always" => Some(crate::ast::logic::TemporalOperator::Always),
1249                        "Eventually" => Some(crate::ast::logic::TemporalOperator::Eventually),
1250                        "Next" => Some(crate::ast::logic::TemporalOperator::Next),
1251                        _ => None,
1252                    }
1253                }
1254                // Handle "next" as an adjective token (common fallback)
1255                TokenType::Adjective(sym) => {
1256                    let resolved = self.interner.resolve(*sym).to_string();
1257                    if resolved == "Next" {
1258                        Some(crate::ast::logic::TemporalOperator::Next)
1259                    } else {
1260                        None
1261                    }
1262                }
1263                _ => None,
1264            };
1265            if let Some(op) = temporal_op {
1266                self.advance(); // consume the token
1267                                // Optionally consume comma: "Always, P"
1268                if self.check(&TokenType::Comma) {
1269                    self.advance();
1270                }
1271                let body = self.parse_sentence()?;
1272                return Ok(self
1273                    .ctx
1274                    .exprs
1275                    .alloc(LogicExpr::Temporal { operator: op, body }));
1276            }
1277        }
1278        // "Infinitely often, P" → G(F(P))
1279        if self.check(&TokenType::InfinitelyOften) {
1280            self.advance();
1281            if self.check(&TokenType::Comma) {
1282                self.advance();
1283            }
1284            let body = self.parse_sentence()?;
1285            return Ok(self.infinitely_often(body));
1286        }
1287        // "Never P" → G(¬P): Always { Not { P } }
1288        if self.check(&TokenType::Never) {
1289            self.advance(); // consume "Never"
1290                            // Optionally consume comma
1291            if self.check(&TokenType::Comma) {
1292                self.advance();
1293            }
1294            let body = self.parse_sentence()?;
1295            let negated = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
1296                op: TokenType::Not,
1297                operand: body,
1298            });
1299            return Ok(self.ctx.exprs.alloc(LogicExpr::Temporal {
1300                operator: crate::ast::logic::TemporalOperator::Always,
1301                body: negated,
1302            }));
1303        }
1304
1305        // "After X, Y" → X → Y (temporal sequence)
1306        // "Before X, Y" → Y → X
1307        // Handles both "After reset is deasserted, ..." (full clause)
1308        // and "After request, ..." (bare signal/event noun)
1309        if self.check_preposition_is("after") || self.check_preposition_is("After") {
1310            self.advance(); // consume "after"
1311
1312            // Check for bare noun/signal + comma pattern: "After request, ..."
1313            // Also handle Performative tokens (e.g., "request" when not after determiner)
1314            let is_bare_noun_comma = self.current + 1 < self.tokens.len()
1315                && matches!(self.tokens[self.current + 1].kind, TokenType::Comma)
1316                && (self.check_content_word()
1317                    || matches!(self.peek().kind, TokenType::Performative(_)));
1318            let antecedent = if is_bare_noun_comma {
1319                let noun = match self.advance().kind.clone() {
1320                    TokenType::Performative(s) => s,
1321                    TokenType::Noun(s) | TokenType::Adjective(s) | TokenType::ProperName(s) => s,
1322                    TokenType::Verb { lemma, .. } => lemma,
1323                    _ => {
1324                        return Err(crate::error::ParseError {
1325                            kind: crate::error::ParseErrorKind::ExpectedContentWord {
1326                                found: self.peek().kind.clone(),
1327                            },
1328                            span: self.current_span(),
1329                        })
1330                    }
1331                };
1332                self.ctx.exprs.alloc(LogicExpr::Atom(noun))
1333            } else {
1334                self.parse_sentence()?
1335            };
1336
1337            if self.check(&TokenType::Comma) {
1338                self.advance();
1339            }
1340            let consequent = self.parse_sentence()?;
1341            let consequent = self.try_wrap_bounded_delay(consequent);
1342            return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1343                left: antecedent,
1344                op: TokenType::Implies,
1345                right: consequent,
1346            }));
1347        }
1348        if self.check_preposition_is("before") || self.check_preposition_is("Before") {
1349            self.advance(); // consume "before"
1350            let first_clause = self.parse_sentence()?;
1351            if self.check(&TokenType::Comma) {
1352                self.advance();
1353            }
1354            let second_clause = self.parse_sentence()?;
1355            return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1356                left: second_clause,
1357                op: TokenType::Implies,
1358                right: first_clause,
1359            }));
1360        }
1361
1362        self.parse_disjunction()
1363    }
1364
1365    fn check_wh_word(&self) -> bool {
1366        if matches!(
1367            self.peek().kind,
1368            TokenType::Who | TokenType::What | TokenType::Where | TokenType::When | TokenType::Why
1369        ) {
1370            return true;
1371        }
1372        if self.check_preposition() && self.current + 1 < self.tokens.len() {
1373            matches!(
1374                self.tokens[self.current + 1].kind,
1375                TokenType::Who
1376                    | TokenType::What
1377                    | TokenType::Where
1378                    | TokenType::When
1379                    | TokenType::Why
1380            )
1381        } else {
1382            false
1383        }
1384    }
1385
1386    fn parse_conditional(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
1387        let is_counterfactual = self.is_counterfactual_context();
1388
1389        // Biscuit / relevance conditional (§4.2): "If you WANT tea, the kettle is
1390        // hot." — an "if you <relevance-verb> …" antecedent restricts RELEVANCE, not
1391        // truth; the consequent is asserted unconditionally.
1392        let is_biscuit = self.check_pronoun()
1393            && self
1394                .interner
1395                .resolve(self.peek().lexeme)
1396                .eq_ignore_ascii_case("you")
1397            && self
1398                .tokens
1399                .get(self.current + 1)
1400                .map(|t| {
1401                    crate::lexicon::is_relevance_verb(
1402                        &self.interner.resolve(t.lexeme).to_lowercase(),
1403                    )
1404                })
1405                .unwrap_or(false);
1406
1407        self.retag_antecedent_any();
1408
1409        // Enter DRS antecedent box - indefinites here get universal force
1410        self.drs.enter_box(BoxType::ConditionalAntecedent);
1411        let mut antecedent = self.parse_counterfactual_antecedent()?;
1412
1413        // Handle conjunction of clauses in antecedent: "If X is Y and Z is W, ..."
1414        while self.check(&TokenType::And) {
1415            self.advance(); // consume "and"
1416            let second = self.parse_counterfactual_antecedent()?;
1417            antecedent = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1418                left: antecedent,
1419                op: TokenType::And,
1420                right: second,
1421            });
1422        }
1423        self.drs.exit_box();
1424
1425        if self.check(&TokenType::Comma) {
1426            self.advance();
1427        }
1428
1429        if self.check(&TokenType::Then) {
1430            self.advance();
1431        }
1432
1433        // Enter DRS consequent box - can access antecedent referents
1434        self.drs.enter_box(BoxType::ConditionalConsequent);
1435        let mut consequent = self.parse_counterfactual_consequent()?;
1436
1437        // Conjunction of consequent clauses: "…, he would have passed and he
1438        // would have celebrated." A non-clausal "and" (NP coordination left
1439        // unconsumed) rolls back and is left for the caller.
1440        while self.check(&TokenType::And) {
1441            let cp = self.checkpoint();
1442            self.advance(); // consume "and"
1443            match self.parse_counterfactual_consequent() {
1444                Ok(second) => {
1445                    consequent = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1446                        left: consequent,
1447                        op: TokenType::And,
1448                        right: second,
1449                    });
1450                }
1451                Err(_) => {
1452                    self.restore(cp);
1453                    break;
1454                }
1455            }
1456        }
1457
1458        // Trailing temporal operators on the consequent — the conditional's
1459        // consequent path does not route through parse_disjunction, so the
1460        // same handlers apply here: "…, P until Q." / "…, P in the next
1461        // cycle." / "…, P within N cycles."
1462        if self.check(&TokenType::Until)
1463            || self.check(&TokenType::Release)
1464            || self.check(&TokenType::WeakUntil)
1465        {
1466            let op = match self.peek().kind {
1467                TokenType::Release => crate::ast::logic::BinaryTemporalOp::Release,
1468                TokenType::WeakUntil => crate::ast::logic::BinaryTemporalOp::WeakUntil,
1469                _ => crate::ast::logic::BinaryTemporalOp::Until,
1470            };
1471            self.advance();
1472            let right = self.parse_counterfactual_consequent()?;
1473            consequent = self.ctx.exprs.alloc(LogicExpr::TemporalBinary {
1474                operator: op,
1475                left: consequent,
1476                right,
1477            });
1478        }
1479        consequent = self.try_wrap_next_cycle(consequent);
1480        consequent = self.try_wrap_bounded_delay(consequent);
1481        self.drs.exit_box();
1482
1483        // Biscuit conditional: assert the consequent and mark the antecedent as a
1484        // relevance condition — `consequent ∧ Relevance(⟨antecedent⟩)`.
1485        if is_biscuit {
1486            let relevance = self.ctx.exprs.alloc(LogicExpr::Predicate {
1487                name: self.interner.intern("Relevance"),
1488                args: self.ctx.terms.alloc_slice([Term::Proposition(antecedent)]),
1489                world: None,
1490            });
1491            return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1492                left: consequent,
1493                op: TokenType::And,
1494                right: relevance,
1495            }));
1496        }
1497
1498        // Get DRS referents that need universal quantification
1499        let universal_refs = self.drs.get_universal_referents();
1500
1501        // Build the conditional expression
1502        let conditional = if is_counterfactual {
1503            self.ctx.exprs.alloc(LogicExpr::Counterfactual {
1504                antecedent,
1505                consequent,
1506            })
1507        } else {
1508            self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1509                left: antecedent,
1510                op: TokenType::If,
1511                right: consequent,
1512            })
1513        };
1514
1515        // Wrap with universal quantifiers for DRS referents
1516        let mut result = conditional;
1517        for var in universal_refs.into_iter().rev() {
1518            result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
1519                kind: QuantifierKind::Universal,
1520                variable: var,
1521                body: result,
1522                island_id: self.current_island,
1523            });
1524        }
1525
1526        Ok(result)
1527    }
1528
1529    /// Parse "Either NP1 or NP2 is/are PRED" or "Either S1 or S2"
1530    ///
1531    /// Handles coordination: "Either Alice or Bob is guilty" should become
1532    /// guilty(Alice) ∨ guilty(Bob), not Alice ∨ guilty(Bob)
1533    fn parse_either_or(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
1534        // Save position for potential backtracking
1535        let start_pos = self.backtrack_point();
1536
1537        // Try to parse as "Either NP1 or NP2 VP"
1538        // First, try to parse just a proper name (not a full clause)
1539        if let TokenType::ProperName(name1) = self.peek().kind {
1540            self.advance(); // consume first proper name
1541
1542            if self.check(&TokenType::Or) {
1543                self.advance(); // consume "or"
1544
1545                if let TokenType::ProperName(name2) = self.peek().kind {
1546                    self.advance(); // consume second proper name
1547
1548                    // Check for shared predicate: "is/are ADJECTIVE"
1549                    let is_copula = matches!(
1550                        self.peek().kind,
1551                        TokenType::Is | TokenType::Are | TokenType::Was | TokenType::Were
1552                    );
1553                    if is_copula {
1554                        self.advance(); // consume copula
1555
1556                        // Check for negation: "is not"
1557                        let is_negated = self.match_token(&[TokenType::Not]);
1558
1559                        // Try to get an adjective
1560                        if let TokenType::Adjective(adj) = self.peek().kind {
1561                            self.advance(); // consume adjective
1562
1563                            // Create predicate for each NP
1564                            let pred1 = self.ctx.exprs.alloc(LogicExpr::Predicate {
1565                                name: adj,
1566                                args: self.ctx.terms.alloc_slice(vec![Term::Constant(name1)]),
1567                                world: None,
1568                            });
1569                            let pred2 = self.ctx.exprs.alloc(LogicExpr::Predicate {
1570                                name: adj,
1571                                args: self.ctx.terms.alloc_slice(vec![Term::Constant(name2)]),
1572                                world: None,
1573                            });
1574
1575                            // Apply negation if needed
1576                            let left = if is_negated {
1577                                self.ctx.exprs.alloc(LogicExpr::UnaryOp {
1578                                    op: TokenType::Not,
1579                                    operand: pred1,
1580                                })
1581                            } else {
1582                                pred1
1583                            };
1584                            let right = if is_negated {
1585                                self.ctx.exprs.alloc(LogicExpr::UnaryOp {
1586                                    op: TokenType::Not,
1587                                    operand: pred2,
1588                                })
1589                            } else {
1590                                pred2
1591                            };
1592
1593                            return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1594                                left,
1595                                op: TokenType::Or,
1596                                right,
1597                            }));
1598                        }
1599                    }
1600                }
1601            }
1602
1603            // Backtrack if the special case didn't match
1604            self.backtrack_to(&start_pos);
1605        }
1606
1607        // Fall back to general disjunction parsing
1608        // Enter disjunct box for left side - referents here are inaccessible outward
1609        self.drs.enter_box(BoxType::Disjunct);
1610        let left = self.parse_conjunction()?;
1611        self.drs.exit_box();
1612
1613        if !self.check(&TokenType::Or) {
1614            return Err(ParseError {
1615                kind: ParseErrorKind::ExpectedKeyword {
1616                    keyword: "or".to_string(),
1617                },
1618                span: self.current_span(),
1619            });
1620        }
1621        self.advance(); // consume "or"
1622
1623        // Enter disjunct box for right side - referents here are also inaccessible outward
1624        self.drs.enter_box(BoxType::Disjunct);
1625        let right = self.parse_conjunction()?;
1626        self.drs.exit_box();
1627
1628        Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1629            left,
1630            op: TokenType::Or,
1631            right,
1632        }))
1633    }
1634
1635    fn is_counterfactual_context(&self) -> bool {
1636        for i in 0..5 {
1637            if self.current + i >= self.tokens.len() {
1638                break;
1639            }
1640            let token = &self.tokens[self.current + i];
1641            if matches!(token.kind, TokenType::Were | TokenType::Had) {
1642                return true;
1643            }
1644            if matches!(token.kind, TokenType::Comma | TokenType::Period) {
1645                break;
1646            }
1647        }
1648        false
1649    }
1650
1651    fn parse_counterfactual_antecedent(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
1652        let unknown = self.interner.intern("?");
1653        if self.check_content_word() || self.check_pronoun() || self.check_article() {
1654            // Weather verb detection: "if it rains" → ∃e(Rain(e))
1655            // Must check BEFORE pronoun resolution since "it" would resolve to "?"
1656            if self.check_pronoun() {
1657                let token = self.peek();
1658                let token_text = self.interner.resolve(token.lexeme);
1659                if token_text.eq_ignore_ascii_case("it") {
1660                    // Look ahead for weather verb: "it rains" or "it is raining"
1661                    if self.current + 1 < self.tokens.len() {
1662                        // Check for "it + verb" pattern
1663                        if let TokenType::Verb { lemma, time, .. } =
1664                            &self.tokens[self.current + 1].kind
1665                        {
1666                            let lemma_str = self.interner.resolve(*lemma);
1667                            if Lexer::is_weather_verb(lemma_str) {
1668                                let verb = *lemma;
1669                                let verb_time = *time;
1670                                self.advance(); // consume "it"
1671                                self.advance(); // consume weather verb
1672
1673                                let event_var = self.get_event_var();
1674
1675                                // Weather verbs are impersonal - no pronoun resolution needed
1676                                // Event var gets universal force from transpiler when suppress_existential=true
1677                                let suppress_existential = self.drs.in_conditional_antecedent();
1678
1679                                let mut result: &'a LogicExpr<'a> = self.ctx.exprs.alloc(
1680                                    LogicExpr::NeoEvent(Box::new(NeoEventData {
1681                                        event_var,
1682                                        verb,
1683                                        roles: self.ctx.roles.alloc_slice(vec![]),
1684                                        modifiers: self.ctx.syms.alloc_slice(vec![]),
1685                                        suppress_existential,
1686                                        world: None,
1687                                    })),
1688                                );
1689
1690                                // Handle coordinated weather verbs: "rains and thunders" or "rains or thunders"
1691                                // SHARE the same event_var for all coordinated verbs
1692                                while self.check(&TokenType::And) || self.check(&TokenType::Or) {
1693                                    let is_disjunction = self.check(&TokenType::Or);
1694                                    self.advance(); // consume "and" or "or"
1695
1696                                    if let TokenType::Verb { lemma: lemma2, .. } =
1697                                        &self.peek().kind.clone()
1698                                    {
1699                                        let lemma2_str = self.interner.resolve(*lemma2);
1700                                        if Lexer::is_weather_verb(lemma2_str) {
1701                                            let verb2 = *lemma2;
1702                                            self.advance(); // consume second weather verb
1703
1704                                            // REUSE same event_var - no new variable, no DRS registration
1705                                            let neo_event2 = self.ctx.exprs.alloc(
1706                                                LogicExpr::NeoEvent(Box::new(NeoEventData {
1707                                                    event_var, // Same variable as first weather verb
1708                                                    verb: verb2,
1709                                                    roles: self.ctx.roles.alloc_slice(vec![]),
1710                                                    modifiers: self.ctx.syms.alloc_slice(vec![]),
1711                                                    suppress_existential,
1712                                                    world: None,
1713                                                })),
1714                                            );
1715
1716                                            let op = if is_disjunction {
1717                                                TokenType::Or
1718                                            } else {
1719                                                TokenType::And
1720                                            };
1721                                            result = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1722                                                left: result,
1723                                                op,
1724                                                right: neo_event2,
1725                                            });
1726                                        } else {
1727                                            break; // Not a weather verb, stop coordination
1728                                        }
1729                                    } else {
1730                                        break;
1731                                    }
1732                                }
1733
1734                                return Ok(match verb_time {
1735                                    Time::Past => self.ctx.exprs.alloc(LogicExpr::Temporal {
1736                                        operator: TemporalOperator::Past,
1737                                        body: result,
1738                                    }),
1739                                    Time::Future => self.ctx.exprs.alloc(LogicExpr::Temporal {
1740                                        operator: TemporalOperator::Future,
1741                                        body: result,
1742                                    }),
1743                                    _ => result,
1744                                });
1745                            }
1746                        }
1747                        // Check for "it + is/are + verb" pattern: "it is raining"
1748                        else if self.current + 2 < self.tokens.len() {
1749                            let is_copula = matches!(
1750                                self.tokens[self.current + 1].kind,
1751                                TokenType::Is | TokenType::Are | TokenType::Was | TokenType::Were
1752                            );
1753                            if is_copula {
1754                                if let TokenType::Verb { lemma, .. } =
1755                                    &self.tokens[self.current + 2].kind
1756                                {
1757                                    let lemma_str = self.interner.resolve(*lemma);
1758                                    if Lexer::is_weather_verb(lemma_str) {
1759                                        let verb = *lemma;
1760                                        let verb_time = if matches!(
1761                                            self.tokens[self.current + 1].kind,
1762                                            TokenType::Was | TokenType::Were
1763                                        ) {
1764                                            Time::Past
1765                                        } else {
1766                                            Time::Present
1767                                        };
1768                                        self.advance(); // consume "it"
1769                                        self.advance(); // consume "is/are/was/were"
1770                                        self.advance(); // consume weather verb
1771
1772                                        let event_var = self.get_event_var();
1773                                        // Weather verbs are impersonal - no pronoun resolution needed
1774                                        // Event var gets universal force from transpiler when suppress_existential=true
1775                                        let suppress_existential =
1776                                            self.drs.in_conditional_antecedent();
1777
1778                                        let neo_event = self.ctx.exprs.alloc(LogicExpr::NeoEvent(
1779                                            Box::new(NeoEventData {
1780                                                event_var,
1781                                                verb,
1782                                                roles: self.ctx.roles.alloc_slice(vec![]),
1783                                                modifiers: self.ctx.syms.alloc_slice(vec![]),
1784                                                suppress_existential,
1785                                                world: None,
1786                                            }),
1787                                        ));
1788
1789                                        // Progressive aspect for "is raining"
1790                                        let with_aspect =
1791                                            self.ctx.exprs.alloc(LogicExpr::Aspectual {
1792                                                operator: AspectOperator::Progressive,
1793                                                body: neo_event,
1794                                            });
1795
1796                                        return Ok(match verb_time {
1797                                            Time::Past => {
1798                                                self.ctx.exprs.alloc(LogicExpr::Temporal {
1799                                                    operator: TemporalOperator::Past,
1800                                                    body: with_aspect,
1801                                                })
1802                                            }
1803                                            _ => with_aspect,
1804                                        });
1805                                    }
1806                                }
1807                            }
1808                        }
1809                    }
1810                }
1811            }
1812
1813            // Track if subject is an indefinite that needs DRS registration. A pronoun that
1814            // resolves to a bound referent is that referent's variable, not a constant.
1815            let mut bound = false;
1816            let (subject, subject_type_pred) = if self.check_pronoun() {
1817                let token = self.advance().clone();
1818                let token_text = self.interner.resolve(token.lexeme);
1819                // Handle first/second person pronouns as constants (deictic reference)
1820                let resolved = if token_text.eq_ignore_ascii_case("i") {
1821                    self.interner.intern("Speaker")
1822                } else if token_text.eq_ignore_ascii_case("you") {
1823                    self.interner.intern("Addressee")
1824                } else if let TokenType::Pronoun { gender, number, .. } = token.kind {
1825                    match self.resolve_pronoun(gender, number)? {
1826                        super::ResolvedPronoun::Variable(s) => {
1827                            bound = true;
1828                            s
1829                        }
1830                        super::ResolvedPronoun::Constant(s) => s,
1831                    }
1832                } else {
1833                    unknown
1834                };
1835                (resolved, None)
1836            } else {
1837                let np = self.parse_noun_phrase(true)?;
1838
1839                // Check if this NP should introduce a DRS referent
1840                // Both indefinites ("a dog") and definites ("the dog") introduce referents
1841                // For definites without antecedent, this implements "global accommodation"
1842                if np.definiteness == Some(Definiteness::Definite)
1843                    || np.definiteness == Some(Definiteness::Distal)
1844                {
1845                    // A definite description ("the butler") denotes a UNIQUE
1846                    // individual: like a proper name it is a RIGID constant, and
1847                    // every co-referring pronoun ("…he…") must resolve to that
1848                    // SAME constant. Register the referent as rigid (so anaphora
1849                    // binds to the constant, not a fresh variable) but emit NO
1850                    // type predicate and NO variable subject — a `Variable` here
1851                    // would take universal force in the antecedent and diverge
1852                    // from the constant its pronoun and the goal resolve to,
1853                    // which the kernel certifier cannot reconcile.
1854                    let gender = Self::infer_noun_gender(self.interner.resolve(np.noun));
1855                    let number = if Self::is_plural_noun(self.interner.resolve(np.noun)) {
1856                        Number::Plural
1857                    } else {
1858                        Number::Singular
1859                    };
1860                    self.drs.introduce_referent_with_source(
1861                        np.noun,
1862                        np.noun,
1863                        gender,
1864                        number,
1865                        crate::drs::ReferentSource::ProperName,
1866                    );
1867                    (np.noun, None)
1868                } else if np.definiteness == Some(Definiteness::Indefinite) {
1869                    let gender = Self::infer_noun_gender(self.interner.resolve(np.noun));
1870                    let number = if Self::is_plural_noun(self.interner.resolve(np.noun)) {
1871                        Number::Plural
1872                    } else {
1873                        Number::Singular
1874                    };
1875
1876                    // An indefinite ("a farmer") introduces a fresh variable, like every other
1877                    // indefinite, and registers it in the DRS for the consequent's pronouns; the
1878                    // antecedent box gives it universal force over the whole conditional.
1879                    let var = self.next_var_name();
1880                    self.drs.introduce_referent(var, np.noun, gender, number);
1881
1882                    let type_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
1883                        name: np.noun,
1884                        args: self.ctx.terms.alloc_slice([Term::Variable(var)]),
1885                        world: None,
1886                    });
1887
1888                    (var, Some(type_pred))
1889                } else {
1890                    // Proper name - use as constant (proper names have their own registration)
1891                    (np.noun, None)
1892                }
1893            };
1894
1895            // Determine the subject term type
1896            let subject_is_var = bound || subject_type_pred.is_some();
1897            let subject_term = if subject_is_var {
1898                Term::Variable(subject)
1899            } else {
1900                Term::Constant(subject)
1901            };
1902
1903            // Handle presupposition triggers in antecedent: "If John stopped smoking, ..."
1904            // Only trigger if followed by gerund complement
1905            if self.check_presup_trigger() && self.is_followed_by_gerund() {
1906                let presup_kind = match self.advance().kind {
1907                    TokenType::PresupTrigger(kind) => kind,
1908                    TokenType::Verb { lemma, .. } => {
1909                        let s = self.interner.resolve(lemma).to_lowercase();
1910                        crate::lexicon::lookup_presup_trigger(&s)
1911                            .expect("Lexicon mismatch: Verb flagged as trigger but lookup failed")
1912                    }
1913                    _ => panic!("Expected presupposition trigger"),
1914                };
1915                let presupposition =
1916                    self.parse_presupposition_for_term(subject_term, presup_kind, false)?;
1917                return Ok(match subject_type_pred {
1918                    Some(type_pred) => self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1919                        left: type_pred,
1920                        op: TokenType::And,
1921                        right: presupposition,
1922                    }),
1923                    None => presupposition,
1924                });
1925            }
1926
1927            if self.check(&TokenType::Were) {
1928                self.advance();
1929                let predicate = if self.check_pronoun() {
1930                    let token = self.advance().clone();
1931                    if let TokenType::Pronoun { gender, number, .. } = token.kind {
1932                        let token_text = self.interner.resolve(token.lexeme);
1933                        if token_text.eq_ignore_ascii_case("i") {
1934                            self.interner.intern("Speaker")
1935                        } else if token_text.eq_ignore_ascii_case("you") {
1936                            self.interner.intern("Addressee")
1937                        } else {
1938                            let resolved_pronoun = self.resolve_pronoun(gender, number)?;
1939                            match resolved_pronoun {
1940                                super::ResolvedPronoun::Variable(s)
1941                                | super::ResolvedPronoun::Constant(s) => s,
1942                            }
1943                        }
1944                    } else {
1945                        unknown
1946                    }
1947                } else {
1948                    self.consume_content_word()?
1949                };
1950                let be = self.interner.intern("Be");
1951                let be_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
1952                    name: be,
1953                    args: self
1954                        .ctx
1955                        .terms
1956                        .alloc_slice([subject_term, Term::Constant(predicate)]),
1957                    world: None,
1958                });
1959                // Combine with type predicate if indefinite subject
1960                return Ok(if let Some(type_pred) = subject_type_pred {
1961                    self.ctx.exprs.alloc(LogicExpr::BinaryOp {
1962                        left: type_pred,
1963                        op: TokenType::And,
1964                        right: be_pred,
1965                    })
1966                } else {
1967                    be_pred
1968                });
1969            }
1970
1971            if self.check(&TokenType::Had) {
1972                self.advance();
1973                // "If John had NOT studied, …" — negated antecedent.
1974                let negated = self.check(&TokenType::Not);
1975                if negated {
1976                    self.advance();
1977                }
1978                let verb = self.consume_content_word()?;
1979                let mut main_pred: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::Predicate {
1980                    name: verb,
1981                    args: self.ctx.terms.alloc_slice([subject_term]),
1982                    world: None,
1983                });
1984                if negated {
1985                    main_pred = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
1986                        op: TokenType::Not,
1987                        operand: main_pred,
1988                    });
1989                }
1990
1991                // Handle "because" causal clause in antecedent
1992                // Phase 35: Do NOT consume if followed by string literal (Trust justification)
1993                if self.check(&TokenType::Because) && !self.peek_next_is_string_literal() {
1994                    self.advance();
1995                    let cause = self.parse_atom()?;
1996                    let causal = self.ctx.exprs.alloc(LogicExpr::Causal {
1997                        effect: main_pred,
1998                        cause,
1999                    });
2000                    // Combine with type predicate if indefinite subject
2001                    return Ok(if let Some(type_pred) = subject_type_pred {
2002                        self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2003                            left: type_pred,
2004                            op: TokenType::And,
2005                            right: causal,
2006                        })
2007                    } else {
2008                        causal
2009                    });
2010                }
2011
2012                // Combine with type predicate if indefinite subject
2013                return Ok(if let Some(type_pred) = subject_type_pred {
2014                    self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2015                        left: type_pred,
2016                        op: TokenType::And,
2017                        right: main_pred,
2018                    })
2019                } else {
2020                    main_pred
2021                });
2022            }
2023
2024            // Parse verb phrase with subject
2025            // Use variable term for indefinite subjects, constant for definites/proper names
2026            let verb_phrase = if subject_is_var {
2027                self.parse_predicate_with_subject_as_var(subject)?
2028            } else {
2029                self.parse_predicate_with_subject(subject)?
2030            };
2031
2032            // Combine with type predicate if indefinite subject
2033            return Ok(if let Some(type_pred) = subject_type_pred {
2034                self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2035                    left: type_pred,
2036                    op: TokenType::And,
2037                    right: verb_phrase,
2038                })
2039            } else {
2040                verb_phrase
2041            });
2042        }
2043
2044        self.parse_sentence()
2045    }
2046
2047    fn parse_counterfactual_consequent(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
2048        let unknown = self.interner.intern("?");
2049        if self.check_content_word() || self.check_pronoun() {
2050            // Check for grammatically incorrect "its" + weather adjective
2051            // "its" is possessive, "it's" is contraction - common typo
2052            if self.check_pronoun() {
2053                let token = self.peek();
2054                let token_text = self.interner.resolve(token.lexeme).to_lowercase();
2055                if token_text == "its" {
2056                    // Check if followed by weather adjective
2057                    if self.current + 1 < self.tokens.len() {
2058                        let next_token = &self.tokens[self.current + 1];
2059                        let next_str = self.interner.resolve(next_token.lexeme).to_lowercase();
2060                        if let Some(meta) = crate::lexicon::lookup_adjective_db(&next_str) {
2061                            if meta.features.contains(&crate::lexicon::Feature::Weather) {
2062                                return Err(ParseError {
2063                                    kind: ParseErrorKind::GrammarError(
2064                                        "Did you mean 'it's' (it is)? 'its' is a possessive pronoun.".to_string()
2065                                    ),
2066                                    span: self.current_span(),
2067                                });
2068                            }
2069                        }
2070                    }
2071                }
2072            }
2073
2074            // Check for expletive "it" + copula + weather adjective: "it's wet" → Wet
2075            if self.check_pronoun() {
2076                let token_text = self.interner.resolve(self.peek().lexeme).to_lowercase();
2077                if token_text == "it" {
2078                    // Look ahead for copula + weather adjective
2079                    // Handle both "it is wet" and "it's wet" (where 's is Possessive token)
2080                    if self.current + 2 < self.tokens.len() {
2081                        let next = &self.tokens[self.current + 1].kind;
2082                        if matches!(next, TokenType::Is | TokenType::Was | TokenType::Possessive) {
2083                            // Check if followed by weather adjective
2084                            let adj_token = &self.tokens[self.current + 2];
2085                            let adj_sym = adj_token.lexeme;
2086                            let adj_str = self.interner.resolve(adj_sym).to_lowercase();
2087                            if let Some(meta) = crate::lexicon::lookup_adjective_db(&adj_str) {
2088                                if meta.features.contains(&crate::lexicon::Feature::Weather) {
2089                                    self.advance(); // consume "it"
2090                                    self.advance(); // consume copula
2091                                    self.advance(); // consume adjective token
2092
2093                                    // Use the canonical lemma from lexicon (e.g., "Wet" not "wet")
2094                                    let adj_lemma = self.interner.intern(meta.lemma);
2095
2096                                    // Get event variable from DRS (introduced in antecedent)
2097                                    let event_var = self
2098                                        .drs
2099                                        .get_last_event_referent(self.interner)
2100                                        .unwrap_or_else(|| self.interner.intern("e"));
2101
2102                                    // First weather adjective predicate
2103                                    let mut result: &'a LogicExpr<'a> =
2104                                        self.ctx.exprs.alloc(LogicExpr::Predicate {
2105                                            name: adj_lemma,
2106                                            args: self
2107                                                .ctx
2108                                                .terms
2109                                                .alloc_slice([Term::Variable(event_var)]),
2110                                            world: None,
2111                                        });
2112
2113                                    // Handle coordinated adjectives: "wet and cold"
2114                                    while self.check(&TokenType::And) {
2115                                        self.advance(); // consume "and"
2116                                        if self.check_content_word() {
2117                                            let adj2_lexeme = self.peek().lexeme;
2118                                            let adj2_str =
2119                                                self.interner.resolve(adj2_lexeme).to_lowercase();
2120
2121                                            // Check if it's also a weather adjective
2122                                            if let Some(meta2) =
2123                                                crate::lexicon::lookup_adjective_db(&adj2_str)
2124                                            {
2125                                                if meta2
2126                                                    .features
2127                                                    .contains(&crate::lexicon::Feature::Weather)
2128                                                {
2129                                                    self.advance(); // consume adjective token
2130                                                                    // Use the canonical lemma from lexicon (e.g., "Cold" not "cold")
2131                                                    let adj2_lemma =
2132                                                        self.interner.intern(meta2.lemma);
2133                                                    let pred2 = self.ctx.exprs.alloc(
2134                                                        LogicExpr::Predicate {
2135                                                            name: adj2_lemma,
2136                                                            args: self.ctx.terms.alloc_slice([
2137                                                                Term::Variable(event_var),
2138                                                            ]),
2139                                                            world: None,
2140                                                        },
2141                                                    );
2142                                                    result =
2143                                                        self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2144                                                            left: result,
2145                                                            op: TokenType::And,
2146                                                            right: pred2,
2147                                                        });
2148                                                    continue;
2149                                                }
2150                                            }
2151                                        }
2152                                        break;
2153                                    }
2154
2155                                    return Ok(result);
2156                                }
2157                            }
2158                        }
2159                    }
2160                }
2161            }
2162
2163            // A pronoun that resolves to a referent of the antecedent ("If a farmer owns a
2164            // donkey, HE beats it") is that referent's bound variable, not a constant.
2165            let mut bound = false;
2166            let subject = if self.check_pronoun() {
2167                let token = self.advance().clone();
2168                let token_text = self.interner.resolve(token.lexeme);
2169                // Handle first/second person pronouns as constants (deictic reference)
2170                if token_text.eq_ignore_ascii_case("i") {
2171                    self.interner.intern("Speaker")
2172                } else if token_text.eq_ignore_ascii_case("you") {
2173                    self.interner.intern("Addressee")
2174                } else if let TokenType::Pronoun { gender, number, .. } = token.kind {
2175                    match self.resolve_pronoun(gender, number)? {
2176                        super::ResolvedPronoun::Variable(s) => {
2177                            bound = true;
2178                            s
2179                        }
2180                        super::ResolvedPronoun::Constant(s) => s,
2181                    }
2182                } else {
2183                    unknown
2184                }
2185            } else {
2186                let np = self.parse_noun_phrase(true)?;
2187                if np.definiteness == Some(crate::lexicon::Definiteness::Definite) {
2188                    // A definite presupposes existence: accommodate the
2189                    // referent GLOBALLY (highest box) so later mentions BIND
2190                    // to it ("…, the kettle is hot." then "The kettle is
2191                    // hot." reuses the same individual).
2192                    self.drs.introduce_referent_global(
2193                        np.noun,
2194                        np.noun,
2195                        Gender::Unknown,
2196                        Number::Singular,
2197                        crate::drs::ReferentSource::MainClause,
2198                    );
2199                }
2200                np.noun
2201            };
2202
2203            if self.check(&TokenType::Would) {
2204                self.advance();
2205                // "…, he would NOT have failed." — negated consequent.
2206                let negated = self.check(&TokenType::Not);
2207                if negated {
2208                    self.advance();
2209                }
2210                if self.check_content_word() {
2211                    let next_word = self.interner.resolve(self.peek().lexeme).to_lowercase();
2212                    if next_word == "have" {
2213                        self.advance();
2214                    }
2215                }
2216                // A bare verb keeps the simple predication shape; anything
2217                // after it ("would buy a boat") takes the full VP grammar.
2218                let clause_ends_after_verb = matches!(
2219                    self.tokens.get(self.current + 1).map(|t| t.kind.clone()),
2220                    Some(
2221                        TokenType::Period
2222                            | TokenType::Exclamation
2223                            | TokenType::EOF
2224                            | TokenType::And
2225                            | TokenType::Comma
2226                    ) | None
2227                );
2228                let mut pred: &'a LogicExpr<'a> = if clause_ends_after_verb {
2229                    let verb = self.consume_content_word()?;
2230                    let subject_term = if bound {
2231                        Term::Variable(subject)
2232                    } else {
2233                        Term::Constant(subject)
2234                    };
2235                    self.ctx.exprs.alloc(LogicExpr::Predicate {
2236                        name: verb,
2237                        args: self.ctx.terms.alloc_slice([subject_term]),
2238                        world: None,
2239                    })
2240                } else if bound {
2241                    self.parse_predicate_with_subject_as_var(subject)?
2242                } else {
2243                    self.parse_predicate_with_subject(subject)?
2244                };
2245                if negated {
2246                    pred = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2247                        op: TokenType::Not,
2248                        operand: pred,
2249                    });
2250                }
2251                return Ok(pred);
2252            }
2253
2254            return if bound {
2255                self.parse_predicate_with_subject_as_var(subject)
2256            } else {
2257                self.parse_predicate_with_subject(subject)
2258            };
2259        }
2260
2261        self.parse_sentence()
2262    }
2263
2264    fn extract_verb_from_expr(&self, expr: &LogicExpr<'a>) -> Option<Symbol> {
2265        match expr {
2266            // NeoEvent directly contains the verb
2267            LogicExpr::NeoEvent(data) => Some(data.verb),
2268            // Control structures directly contain the verb
2269            LogicExpr::Control { verb, .. } => Some(*verb),
2270            // Phase 46: For BinaryOp, try to find NeoEvent first (either side),
2271            // then fall back to Predicate. This handles both:
2272            // - Transitive: Apple(x) ∧ ∃e(Eat(e)...) - NeoEvent on right
2273            // - Motion PP: ∃e(Walk(e)...) ∧ To(e, Park) - NeoEvent on left
2274            LogicExpr::BinaryOp { left, right, .. } => {
2275                // First check if left contains a NeoEvent (motion PP case)
2276                if let Some(verb) = self.extract_neo_event_verb(left) {
2277                    return Some(verb);
2278                }
2279                // Then check right (transitive case with type predicate on left)
2280                if let Some(verb) = self.extract_neo_event_verb(right) {
2281                    return Some(verb);
2282                }
2283                // Fall back to any extractable verb
2284                self.extract_verb_from_expr(left)
2285                    .or_else(|| self.extract_verb_from_expr(right))
2286            }
2287            // Plain predicate - last resort (might be type predicate or PP)
2288            LogicExpr::Predicate { name, .. } => Some(*name),
2289            LogicExpr::Modal { operand, .. } => self.extract_verb_from_expr(operand),
2290            LogicExpr::Presupposition { assertion, .. } => self.extract_verb_from_expr(assertion),
2291            LogicExpr::Temporal { body, .. } => self.extract_verb_from_expr(body),
2292            LogicExpr::TemporalAnchor { body, .. } => self.extract_verb_from_expr(body),
2293            LogicExpr::Aspectual { body, .. } => self.extract_verb_from_expr(body),
2294            LogicExpr::Quantifier { body, .. } => self.extract_verb_from_expr(body),
2295            _ => None,
2296        }
2297    }
2298
2299    /// Phase 46: Generalized gapping with template-guided reconstruction.
2300    /// Handles NPs, PPs, temporal adverbs, and preserves roles from EventTemplate.
2301    fn parse_gapped_clause(&mut self, borrowed_verb: Symbol) -> ParseResult<&'a LogicExpr<'a>> {
2302        let subject = if self.remnant_names_two_people() {
2303            let name = self.consume_content_word()?;
2304            NounPhrase {
2305                definiteness: None,
2306                adjectives: &[],
2307                noun: name,
2308                possessor: None,
2309                pps: &[],
2310                superlative: None,
2311            }
2312        } else {
2313            self.parse_noun_phrase(true)?
2314        };
2315
2316        if self.check(&TokenType::Comma) {
2317            self.advance();
2318        }
2319
2320        let subject_term = self.noun_phrase_to_term(&subject);
2321        let event_var = self.get_event_var();
2322        let suppress_existential = self.drs.in_conditional_antecedent();
2323
2324        // Get template for role guidance
2325        let template = self.last_event_template.clone();
2326
2327        // Collect arguments (NPs, PPs, temporal adverbs) from gapped clause
2328        let mut np_args: Vec<Term<'a>> = Vec::new();
2329        let mut pp_args: Vec<(Symbol, Term<'a>)> = Vec::new();
2330        let mut override_adverb: Option<Symbol> = None;
2331
2332        loop {
2333            if self.check_temporal_adverb() {
2334                // Temporal adverb: override template modifier
2335                if let TokenType::TemporalAdverb(sym) = self.advance().kind {
2336                    override_adverb = Some(sym);
2337                }
2338            } else if self.check_preposition() {
2339                // PP argument: "to the school", "on the table"
2340                let prep = if let TokenType::Preposition(sym) = self.advance().kind {
2341                    sym
2342                } else {
2343                    continue;
2344                };
2345                let np = self.parse_noun_phrase(false)?;
2346                pp_args.push((prep, self.noun_phrase_to_term(&np)));
2347            } else if self.check_content_word() || self.check_article() {
2348                // NP argument
2349                let np = self.parse_noun_phrase(false)?;
2350                np_args.push(self.noun_phrase_to_term(&np));
2351                if self.check(&TokenType::Comma) {
2352                    self.advance();
2353                }
2354            } else {
2355                break;
2356            }
2357        }
2358
2359        // Build roles using template guidance
2360        let roles = self.build_gapped_roles(subject_term, &np_args, &pp_args, &template);
2361
2362        // Handle modifiers: override if adverb provided, else inherit from template
2363        let modifiers = match (override_adverb, &template) {
2364            (Some(adv), Some(tmpl)) => {
2365                // Filter out temporal modifiers from template, add new one
2366                let mut mods: Vec<Symbol> = tmpl
2367                    .modifiers
2368                    .iter()
2369                    .filter(|m| !self.is_temporal_modifier(**m))
2370                    .cloned()
2371                    .collect();
2372                mods.push(adv);
2373                mods
2374            }
2375            (Some(adv), None) => vec![adv],
2376            (None, Some(tmpl)) => tmpl.modifiers.clone(),
2377            (None, None) => vec![],
2378        };
2379
2380        Ok(self
2381            .ctx
2382            .exprs
2383            .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
2384                event_var,
2385                verb: borrowed_verb,
2386                roles: self.ctx.roles.alloc_slice(roles),
2387                modifiers: self.ctx.syms.alloc_slice(modifiers),
2388                suppress_existential,
2389                world: None,
2390            }))))
2391    }
2392
2393    fn is_complete_clause(&self, expr: &LogicExpr<'a>) -> bool {
2394        match expr {
2395            LogicExpr::Atom(_) => false,
2396            LogicExpr::Predicate { .. } => true,
2397            LogicExpr::Quantifier { .. } => true,
2398            LogicExpr::Modal { .. } => true,
2399            LogicExpr::Temporal { .. } => true,
2400            LogicExpr::Aspectual { .. } => true,
2401            LogicExpr::BinaryOp { .. } => true,
2402            LogicExpr::UnaryOp { .. } => true,
2403            LogicExpr::Control { .. } => true,
2404            LogicExpr::Presupposition { .. } => true,
2405            LogicExpr::Categorical(_) => true,
2406            LogicExpr::Relation(_) => true,
2407            _ => true,
2408        }
2409    }
2410
2411    /// Parse disjunction (Or/Iff) - lowest precedence logical connectives.
2412    /// Calls parse_conjunction for operands to ensure And binds tighter.
2413    fn parse_disjunction(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
2414        let mut expr = self.parse_conjunction()?;
2415
2416        while self.check(&TokenType::Comma) || self.check(&TokenType::Or) {
2417            if self.check(&TokenType::Comma) {
2418                self.advance();
2419            }
2420            // Iff is handled at a LOOSER precedence tier below (standard
2421            // precedence ∨ > ↔); only Or folds here.
2422            if !self.match_token(&[TokenType::Or]) {
2423                break;
2424            }
2425            let operator = self.previous().kind.clone();
2426            self.current_island += 1;
2427
2428            let saved_pos = self.backtrack_point();
2429            let standard_attempt = self.try_parse(|p| p.parse_conjunction());
2430
2431            // Gapping in disjunction: only for Or, not Iff. Use original (non-expanded) trigger.
2432            // Expanded gapping (with Period/is_at_end) only applies in parse_conjunction.
2433            let use_gapping = match &standard_attempt {
2434                Some(right) => {
2435                    !self.is_complete_clause(right)
2436                        && (self.check(&TokenType::Comma) || self.check_content_word())
2437                        && operator != TokenType::Iff // Don't gap on biconditional
2438                }
2439                None => operator != TokenType::Iff, // For Iff, require successful parse
2440            };
2441
2442            if !use_gapping {
2443                if let Some(right) = standard_attempt {
2444                    expr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2445                        left: expr,
2446                        op: operator,
2447                        right,
2448                    });
2449                }
2450            } else {
2451                self.backtrack_to(&saved_pos);
2452
2453                let borrowed_verb = self.extract_verb_from_expr(expr).ok_or(ParseError {
2454                    kind: ParseErrorKind::GappingResolutionFailed,
2455                    span: self.current_span(),
2456                })?;
2457
2458                let right = self.parse_gapped_clause(borrowed_verb)?;
2459
2460                expr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2461                    left: expr,
2462                    op: operator,
2463                    right,
2464                });
2465            }
2466        }
2467
2468        // Handle binary temporal connectives (lowest precedence temporal)
2469        // "P until Q" → TemporalBinary { Until, P, Q }
2470        // "P release Q" → TemporalBinary { Release, P, Q }
2471        // "P weak-until Q" → TemporalBinary { WeakUntil, P, Q }
2472        if self.check(&TokenType::Until)
2473            || self.check(&TokenType::Release)
2474            || self.check(&TokenType::WeakUntil)
2475        {
2476            let op = match self.peek().kind {
2477                TokenType::Release => crate::ast::logic::BinaryTemporalOp::Release,
2478                TokenType::WeakUntil => crate::ast::logic::BinaryTemporalOp::WeakUntil,
2479                _ => crate::ast::logic::BinaryTemporalOp::Until,
2480            };
2481            self.advance();
2482            let right = self.parse_conjunction()?;
2483            expr = self.ctx.exprs.alloc(LogicExpr::TemporalBinary {
2484                operator: op,
2485                left: expr,
2486                right,
2487            });
2488        }
2489
2490        // Check for trailing "within N cycles" bounded temporal delay
2491        let expr = self.try_wrap_bounded_delay(expr);
2492
2493        // Trailing "in the next cycle" → X(P)
2494        let mut expr = self.try_wrap_next_cycle(expr);
2495
2496        // Sentence-final temporal anchor ("…eat Bill first.", "…left
2497        // yesterday.") for clauses whose path didn't consume it in the VP.
2498        if let TokenType::TemporalAdverb(anchor) = self.peek().kind {
2499            if matches!(
2500                self.tokens.get(self.current + 1).map(|t| &t.kind),
2501                Some(TokenType::Period)
2502                    | Some(TokenType::Exclamation)
2503                    | Some(TokenType::EOF)
2504                    | None
2505            ) {
2506                self.advance();
2507                expr = self
2508                    .ctx
2509                    .exprs
2510                    .alloc(LogicExpr::TemporalAnchor { anchor, body: expr });
2511            }
2512        }
2513
2514        // Postposed necessary condition: "Y only when X." / "Y only if X." ⇔ Y → X (X is
2515        // *necessary* for Y — the textbook reading of "only if"). This is the converse direction
2516        // of the sufficient "Y when X" below, so it must be matched first.
2517        if self
2518            .interner
2519            .resolve(self.peek().lexeme)
2520            .eq_ignore_ascii_case("only")
2521            && matches!(
2522                self.tokens.get(self.current + 1).map(|t| &t.kind),
2523                Some(TokenType::When) | Some(TokenType::If)
2524            )
2525        {
2526            self.advance(); // only
2527            self.advance(); // when | if
2528            let condition = self.parse_conjunction()?;
2529            expr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2530                left: expr,
2531                op: TokenType::If,
2532                right: condition,
2533            });
2534        }
2535        // Postposed "when": "Y when X." ⇔ "When X, Y." → X → Y
2536        else if self.check(&TokenType::When) {
2537            self.advance();
2538            let condition = self.parse_conjunction()?;
2539            expr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2540                left: condition,
2541                op: TokenType::Implies,
2542                right: expr,
2543            });
2544        }
2545
2546        // Biconditional binds LOOSER than disjunction (standard precedence
2547        // ∨ > ↔). Fold any trailing `iff` with a FULL disjunction as its right
2548        // operand, so "P if and only if Q or R" is P ↔ (Q ∨ R), not (P ↔ Q) ∨ R.
2549        while self.check(&TokenType::Iff) {
2550            self.advance();
2551            self.current_island += 1;
2552            let right = self.parse_disjunction()?;
2553            expr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2554                left: expr,
2555                op: TokenType::Iff,
2556                right,
2557            });
2558        }
2559
2560        Ok(expr)
2561    }
2562
2563    /// Parse conjunction (And) - higher precedence than Or.
2564    /// Calls parse_atom for operands.
2565    /// Extracts the subject of a copular predication (the first `Constant` argument
2566    /// of a copular `Predicate`), digging through degree/aspect/boolean wrappers.
2567    /// Returns `None` for event predications (NeoEvent) and variable subjects, so
2568    /// only true copular clauses ("X is ADJ/NP") trigger predicate coordination.
2569    fn extract_copular_subject(&self, expr: &'a LogicExpr<'a>) -> Option<Symbol> {
2570        match expr {
2571            LogicExpr::Predicate { args, .. } => match args.first() {
2572                Some(Term::Constant(s)) => Some(*s),
2573                _ => None,
2574            },
2575            LogicExpr::Quantifier { body, .. } => self.extract_copular_subject(body),
2576            LogicExpr::Aspectual { body, .. } => self.extract_copular_subject(body),
2577            LogicExpr::UnaryOp { operand, .. } => self.extract_copular_subject(operand),
2578            LogicExpr::BinaryOp { left, .. } => self.extract_copular_subject(left),
2579            _ => None,
2580        }
2581    }
2582
2583    /// Parses a bare copular-predicate remnant — an adjective ("wealthy") or a
2584    /// predicate nominal ("a philanthropist") — as `Predicate(subject)`. Returns
2585    /// `None` (consuming nothing) if the next tokens are not such a remnant.
2586    fn try_parse_copular_predicate(
2587        &mut self,
2588        subject: Symbol,
2589    ) -> ParseResult<Option<&'a LogicExpr<'a>>> {
2590        let pred_sym = if let TokenType::Adjective(adj) = self.peek().kind {
2591            // An adjective-classified word followed by a copula is the
2592            // SUBJECT of a new clause ("…and ready is not asserted"), not a
2593            // predicate remnant of the previous one.
2594            if matches!(
2595                self.tokens.get(self.current + 1).map(|t| &t.kind),
2596                Some(TokenType::Is)
2597                    | Some(TokenType::Are)
2598                    | Some(TokenType::Was)
2599                    | Some(TokenType::Were)
2600            ) {
2601                return Ok(None);
2602            }
2603            self.advance();
2604            adj
2605        } else if self.check_article() {
2606            // "a/an N" predicate nominal — parse the NP and use its head noun.
2607            let np = self.parse_noun_phrase(false)?;
2608            np.noun
2609        } else {
2610            return Ok(None);
2611        };
2612        Ok(Some(self.ctx.exprs.alloc(LogicExpr::Predicate {
2613            name: pred_sym,
2614            args: self.ctx.terms.alloc_slice([Term::Constant(subject)]),
2615            world: None,
2616        })))
2617    }
2618
2619    fn parse_conjunction(&mut self) -> ParseResult<&'a LogicExpr<'a>> {
2620        let mut expr = self.parse_atom()?;
2621
2622        // Handle causal "because" at conjunction level
2623        // Phase 35: Do NOT consume if followed by string literal (Trust justification)
2624        if self.check(&TokenType::Because) && !self.peek_next_is_string_literal() {
2625            self.advance();
2626            let cause = self.parse_atom()?;
2627            return Ok(self.ctx.exprs.alloc(LogicExpr::Causal {
2628                effect: expr,
2629                cause,
2630            }));
2631        }
2632
2633        while self.check(&TokenType::Comma) || self.check(&TokenType::And) {
2634            // A list of objects after the verb ("sees Mary, Bill and Sue") gives the verb
2635            // to each of them, inside the subject's scope — not a clause per name.
2636            if let Some(coordinated) = self.try_coordinated_objects(expr)? {
2637                expr = coordinated;
2638                continue;
2639            }
2640            // "…and sees Bill": a verb phrase with no subject of its own is the clause's
2641            // subject doing a second thing, inside the same scope.
2642            if let Some(coordinated) = self.try_coordinated_verb_phrase(expr)? {
2643                expr = coordinated;
2644                continue;
2645            }
2646            if self.check(&TokenType::Comma) {
2647                self.advance();
2648            }
2649            if !self.match_token(&[TokenType::And]) {
2650                break;
2651            }
2652            let operator = self.previous().kind.clone();
2653            self.current_island += 1;
2654
2655            // Non-parallel copular coordination (§2.2): "X is wealthy and a
2656            // philanthropist" — the remnant after "and" is a bare predicate (an
2657            // adjective or a predicate nominal) attributed to the SAME copular
2658            // subject, not a gapped event verb.
2659            if let Some(subj) = self.extract_copular_subject(expr) {
2660                let cop_pos = self.backtrack_point();
2661                if let Some(p2) = self.try_parse_copular_predicate(subj)? {
2662                    expr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2663                        left: expr,
2664                        op: operator,
2665                        right: p2,
2666                    });
2667                    continue;
2668                }
2669                self.backtrack_to(&cop_pos);
2670            }
2671
2672            let saved_pos = self.backtrack_point();
2673            let standard_attempt = self.try_parse(|p| p.parse_atom());
2674
2675            // Phase 46: Expanded gapping trigger to support PP gapping, temporal override,
2676            // and intransitive gapping (bare subject at clause boundary)
2677            let use_gapping = match &standard_attempt {
2678                Some(right) => {
2679                    !self.is_complete_clause(right)
2680                        && (self.check(&TokenType::Comma)
2681                            || self.check_content_word()
2682                            || self.check_preposition()
2683                            || self.check_temporal_adverb()
2684                            || self.check(&TokenType::Period)
2685                            || self.is_at_end())
2686                }
2687                None => true,
2688            };
2689
2690            if !use_gapping {
2691                if let Some(right) = standard_attempt {
2692                    expr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2693                        left: expr,
2694                        op: operator,
2695                        right,
2696                    });
2697                }
2698            } else {
2699                self.backtrack_to(&saved_pos);
2700
2701                let borrowed_verb = self.extract_verb_from_expr(expr).ok_or(ParseError {
2702                    kind: ParseErrorKind::GappingResolutionFailed,
2703                    span: self.current_span(),
2704                })?;
2705
2706                let right = self.parse_gapped_clause(borrowed_verb)?;
2707
2708                expr = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2709                    left: expr,
2710                    op: operator,
2711                    right,
2712                });
2713            }
2714        }
2715
2716        Ok(expr)
2717    }
2718
2719    fn parse_relative_clause(&mut self, gap_var: Symbol) -> ParseResult<&'a LogicExpr<'a>> {
2720        // A clause-initial adverb ("who FIRST started in 1983", "who ORIGINALLY came
2721        // out in 1866") modifies the relative clause's event. It hid the verb from the
2722        // dispatch below, stranding the clue (TrailingTokens) or dropping the clause to
2723        // `?`. Consume it, parse the rest of the clause, then conjoin the adverb over
2724        // the gap so nothing is lost. Only when a clause predicate (verb / perfect /
2725        // modal / auxiliary / copula / negation) actually follows the adverb.
2726        if matches!(
2727            self.peek().kind,
2728            TokenType::Adverb(_) | TokenType::TemporalAdverb(_)
2729        ) {
2730            let next_opens_predicate = self.tokens.get(self.current + 1).map_or(false, |t| {
2731                self.kind_is_verb(&t.kind)
2732                    || matches!(
2733                        t.kind,
2734                        TokenType::Had
2735                            | TokenType::Auxiliary(_)
2736                            | TokenType::Not
2737                            | TokenType::Is
2738                            | TokenType::Are
2739                            | TokenType::Was
2740                            | TokenType::Were
2741                            | TokenType::Can
2742                            | TokenType::Could
2743                            | TokenType::Must
2744                            | TokenType::Should
2745                            | TokenType::May
2746                            | TokenType::Might
2747                            | TokenType::Would
2748                            | TokenType::Shall
2749                            | TokenType::Cannot
2750                    )
2751            });
2752            if next_opens_predicate {
2753                let adv = match self.peek().kind {
2754                    TokenType::Adverb(s) | TokenType::TemporalAdverb(s) => s,
2755                    _ => unreachable!(),
2756                };
2757                self.advance();
2758                let rest = self.parse_relative_clause(gap_var)?;
2759                let adv_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
2760                    name: adv,
2761                    args: self.ctx.terms.alloc_slice([Term::Variable(gap_var)]),
2762                    world: None,
2763                });
2764                return Ok(self.ctx.exprs.alloc(LogicExpr::BinaryOp {
2765                    left: rest,
2766                    op: TokenType::And,
2767                    right: adv_pred,
2768                }));
2769            }
2770        }
2771
2772        // "who had the port" — possessive HAVE (past) as the clause verb, NOT a
2773        // perfect auxiliary (no participle follows); re-tag so check_verb handles it.
2774        if self.check(&TokenType::Had)
2775            && !matches!(
2776                self.tokens.get(self.current + 1).map(|t| &t.kind),
2777                Some(TokenType::Verb { .. })
2778            )
2779        {
2780            let have_lemma = self.interner.intern("Have");
2781            self.tokens[self.current].kind = TokenType::Verb {
2782                lemma: have_lemma,
2783                time: Time::Past,
2784                aspect: crate::lexicon::Aspect::Simple,
2785                class: crate::lexicon::VerbClass::State,
2786            };
2787        }
2788
2789        // "who did 49 jumps" / "who does the dishes" — main verb "do" (performed),
2790        // NOT do-support (no verb follows); re-tag so check_verb handles it.
2791        if matches!(self.peek().kind, TokenType::Auxiliary(_))
2792            && !matches!(
2793                self.tokens.get(self.current + 1).map(|t| &t.kind),
2794                Some(TokenType::Verb { .. })
2795            )
2796        {
2797            let lex = self.interner.resolve(self.peek().lexeme).to_lowercase();
2798            if matches!(lex.as_str(), "did" | "do" | "does") {
2799                let do_lemma = self.interner.intern("Do");
2800                let time = if lex == "did" {
2801                    Time::Past
2802                } else {
2803                    Time::Present
2804                };
2805                self.tokens[self.current].kind = TokenType::Verb {
2806                    lemma: do_lemma,
2807                    time,
2808                    aspect: crate::lexicon::Aspect::Simple,
2809                    class: crate::lexicon::VerbClass::Activity,
2810                };
2811            }
2812        }
2813
2814        // Perfect-aspect relative clause: "who HAS done 49 jumps", "who HAVE won",
2815        // "that HAD been issued in 1868". The perfect auxiliary + a participle is an
2816        // aspect chain over the gap, NOT possessive HAVE — which the `check_verb` below
2817        // would greedily consume, stranding the participle (TrailingTokens). Mirror the
2818        // main-clause perfect dispatch (`parse_aspect_chain`). The participle may be an
2819        // Ambiguous noun/verb ("done"), so judge it with `kind_is_verb`, and allow an
2820        // intervening negation ("who has not won").
2821        let head_word = self.interner.resolve(self.peek().lexeme).to_lowercase();
2822        let is_perfect_head =
2823            matches!(head_word.as_str(), "has" | "have") || self.check(&TokenType::Had);
2824        let next_opens_participle = self.tokens.get(self.current + 1).map_or(false, |t| {
2825            self.kind_is_verb(&t.kind) || matches!(t.kind, TokenType::Not)
2826        });
2827        if is_perfect_head && next_opens_participle {
2828            return self.parse_aspect_chain_with_term(Term::Variable(gap_var));
2829        }
2830
2831        if self.check_verb() {
2832            return self.parse_verb_phrase_for_restriction(gap_var);
2833        }
2834
2835        // Modal-headed relative clause: "that can fly for 40 minutes", "who must
2836        // attend", "that should win". The modal scopes the event over the gap
2837        // variable — "the device that can fly" → ◇ ∃e(Fly(e) ∧ Agent(e, x)).
2838        if self.check_modal() {
2839            return self.parse_aspect_chain_with_term(Term::Variable(gap_var));
2840        }
2841
2842        // Auxiliary-headed relative clause: "who will be studying radiation",
2843        // "who would win". Record the modality/tense, drop an optional "be" of
2844        // the progressive, then parse the verb phrase as the restriction.
2845        if let TokenType::Auxiliary(time) = self.peek().kind {
2846            self.advance(); // "will" / "would" / "did"
2847                            // Drop the progressive's "be" ("will be studying"). It tokenizes
2848                            // either as TokenType::Be or as a verb with lemma "be".
2849            let is_be = self.check(&TokenType::Be)
2850                || matches!(self.peek().kind, TokenType::Verb { lemma, .. }
2851                    if self.interner.resolve(lemma).eq_ignore_ascii_case("be"));
2852            if is_be {
2853                self.advance();
2854            }
2855            if self.check_verb() {
2856                let restriction = self.parse_verb_phrase_for_restriction(gap_var)?;
2857                return Ok(if time == Time::Future {
2858                    self.ctx.exprs.alloc(LogicExpr::Temporal {
2859                        operator: TemporalOperator::Future,
2860                        body: restriction,
2861                    })
2862                } else {
2863                    restriction
2864                });
2865            }
2866            // "who will be ready" — copular future with an adjective/noun.
2867            if self.check_content_word() || self.check_article() {
2868                let pred_np = self.parse_noun_phrase(false)?;
2869                let base = self.ctx.exprs.alloc(LogicExpr::Predicate {
2870                    name: pred_np.noun,
2871                    args: self.ctx.terms.alloc_slice([Term::Variable(gap_var)]),
2872                    world: None,
2873                });
2874                return Ok(if time == Time::Future {
2875                    self.ctx.exprs.alloc(LogicExpr::Temporal {
2876                        operator: TemporalOperator::Future,
2877                        body: base,
2878                    })
2879                } else {
2880                    base
2881                });
2882            }
2883        }
2884
2885        // Copular relative: "that is on the table", "that is red".
2886        if matches!(
2887            self.peek().kind,
2888            TokenType::Is | TokenType::Are | TokenType::Was | TokenType::Were
2889        ) {
2890            let copula_past = matches!(self.peek().kind, TokenType::Was | TokenType::Were);
2891            self.advance(); // copula
2892            let negated = self.check(&TokenType::Not);
2893            if negated {
2894                self.advance();
2895            }
2896            // A temporal adverb after the copula ("who is NOW with the Tigers", "that
2897            // was THEN the leader") frames the predication; consume it and conjoin it
2898            // over the gap once the complement is built, so it is not stranded
2899            // (ExpectedContentWord at the adverb).
2900            let rel_temporal_adv = if let TokenType::TemporalAdverb(s) = self.peek().kind {
2901                self.advance();
2902                Some(s)
2903            } else {
2904                None
2905            };
2906            // "that is printing 100 pages", "that is paying the rent" — a
2907            // PROGRESSIVE verb after the copula is a verb phrase (∃e(Print(e) ∧
2908            // Agent(e,x) ∧ Theme(e,…))), not a predicate adjective. Gate strictly
2909            // on Progressive aspect so a PASSIVE past participle ("that was ISSUED
2910            // in 1868") is NOT mis-read as an active VP — that stays the
2911            // passive/PP path below.
2912            if matches!(
2913                self.peek().kind,
2914                TokenType::Verb {
2915                    aspect: crate::lexicon::Aspect::Progressive,
2916                    ..
2917                }
2918            ) {
2919                let vp = self.parse_verb_phrase_for_restriction(gap_var)?;
2920                let vp = self.conjoin_relative_temporal_adverb(vp, gap_var, rel_temporal_adv);
2921                let vp = if negated {
2922                    self.ctx.exprs.alloc(LogicExpr::UnaryOp {
2923                        op: TokenType::Not,
2924                        operand: vp,
2925                    })
2926                } else {
2927                    vp
2928                };
2929                return Ok(if copula_past {
2930                    self.ctx.exprs.alloc(LogicExpr::Temporal {
2931                        operator: TemporalOperator::Past,
2932                        body: vp,
2933                    })
2934                } else {
2935                    vp
2936                });
2937            }
2938            let pred: &'a LogicExpr<'a> = if self.check_preposition() {
2939                let prep = if let TokenType::Preposition(sym) = self.advance().kind {
2940                    sym
2941                } else {
2942                    self.interner.intern("At")
2943                };
2944                let obj = self.parse_noun_phrase(false)?;
2945                self.ctx.exprs.alloc(LogicExpr::Predicate {
2946                    name: prep,
2947                    args: self
2948                        .ctx
2949                        .terms
2950                        .alloc_slice([Term::Variable(gap_var), Term::Constant(obj.noun)]),
2951                    world: None,
2952                })
2953            } else if self.check_number() {
2954                // Measure complement: "that is 30 inches long" → Long(x, 30 inches);
2955                // bare "that is 30 inches" → Measure(x, 30 inches).
2956                let measure = self.parse_measure_phrase()?;
2957                let dim = if self.check_content_word() {
2958                    self.consume_content_word()?
2959                } else {
2960                    self.interner.intern("Measure")
2961                };
2962                self.ctx.exprs.alloc(LogicExpr::Predicate {
2963                    name: dim,
2964                    args: self
2965                        .ctx
2966                        .terms
2967                        .alloc_slice([Term::Variable(gap_var), *measure]),
2968                    world: None,
2969                })
2970            } else {
2971                let adj = self.consume_content_word()?;
2972                self.ctx.exprs.alloc(LogicExpr::Predicate {
2973                    name: adj,
2974                    args: self.ctx.terms.alloc_slice([Term::Variable(gap_var)]),
2975                    world: None,
2976                })
2977            };
2978            // Trailing PPs on a copular relative ("that was issued in 1868",
2979            // "that is from Spain") — conjoin each as a predicate over the gap.
2980            let mut pred = pred;
2981            while self.check_preposition() {
2982                let prep = if let TokenType::Preposition(s) = self.advance().kind {
2983                    s
2984                } else {
2985                    break;
2986                };
2987                let obj_term = if self.check_number() {
2988                    *self.parse_measure_phrase()?
2989                } else if self.check_content_word() || self.check_article() {
2990                    Term::Constant(self.parse_noun_phrase(false)?.noun)
2991                } else {
2992                    self.current -= 1;
2993                    break;
2994                };
2995                let pp = self.ctx.exprs.alloc(LogicExpr::Predicate {
2996                    name: prep,
2997                    args: self
2998                        .ctx
2999                        .terms
3000                        .alloc_slice([Term::Variable(gap_var), obj_term]),
3001                    world: None,
3002                });
3003                pred = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3004                    left: pred,
3005                    op: TokenType::And,
3006                    right: pp,
3007                });
3008            }
3009            let pred = self.conjoin_relative_temporal_adverb(pred, gap_var, rel_temporal_adv);
3010            let pred = if copula_past {
3011                &*self.ctx.exprs.alloc(LogicExpr::Temporal {
3012                    operator: TemporalOperator::Past,
3013                    body: pred,
3014                })
3015            } else {
3016                pred
3017            };
3018            return Ok(if negated {
3019                self.ctx.exprs.alloc(LogicExpr::UnaryOp {
3020                    op: TokenType::Not,
3021                    operand: pred,
3022                })
3023            } else {
3024                pred
3025            });
3026        }
3027
3028        // Handle "do/does (not)" in relative clauses: "who do not shave themselves"
3029        if self.check(&TokenType::Do) || self.check(&TokenType::Does) {
3030            self.advance(); // consume "do/does"
3031
3032            let is_negated = self.check(&TokenType::Not);
3033            if is_negated {
3034                self.advance(); // consume "not"
3035            }
3036
3037            if self.check_verb() {
3038                let verb = self.consume_verb();
3039
3040                // Check for reflexive object: "shave themselves"
3041                let roles = if self.check(&TokenType::Reflexive) {
3042                    self.advance(); // consume "themselves/himself"
3043                    vec![
3044                        (ThematicRole::Agent, Term::Variable(gap_var)),
3045                        (ThematicRole::Theme, Term::Variable(gap_var)),
3046                    ]
3047                } else if self.check_content_word() || self.check_article() {
3048                    // Parse object NP
3049                    let obj = self.parse_noun_phrase(false)?;
3050                    vec![
3051                        (ThematicRole::Agent, Term::Variable(gap_var)),
3052                        (ThematicRole::Theme, Term::Constant(obj.noun)),
3053                    ]
3054                } else {
3055                    // Intransitive
3056                    vec![(ThematicRole::Agent, Term::Variable(gap_var))]
3057                };
3058
3059                let event_var = self.get_event_var();
3060                let suppress_existential = self.drs.in_conditional_antecedent();
3061                let event = self
3062                    .ctx
3063                    .exprs
3064                    .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3065                        event_var,
3066                        verb,
3067                        roles: self.ctx.roles.alloc_slice(roles),
3068                        modifiers: self.ctx.syms.alloc_slice(vec![]),
3069                        suppress_existential,
3070                        world: None,
3071                    })));
3072
3073                if is_negated {
3074                    return Ok(self.ctx.exprs.alloc(LogicExpr::UnaryOp {
3075                        op: TokenType::Not,
3076                        operand: event,
3077                    }));
3078                }
3079                return Ok(event);
3080            }
3081        }
3082
3083        if self.check_content_word() || self.check_article() {
3084            let rel_subject = self.parse_noun_phrase_for_relative()?;
3085
3086            let nested_relative = if matches!(self.peek().kind, TokenType::Article(_)) {
3087                let nested_var = self.next_var_name();
3088                Some((nested_var, self.parse_relative_clause(nested_var)?))
3089            } else {
3090                None
3091            };
3092
3093            if self.check_verb() {
3094                let verb = self.consume_verb();
3095
3096                // A STRANDED preposition ("the animal Eva works WITH", "the case Bob
3097                // paid FOR") makes the GAP the object of that preposition, not the
3098                // verb's direct Theme. Detect a preposition with NO overt object (the
3099                // matrix clause follows immediately) and bind the gap to it below.
3100                let stranded_prep: Option<Symbol> =
3101                    if self.check_preposition() && !self.check_to_preposition() {
3102                        let has_overt_object = matches!(
3103                            self.tokens.get(self.current + 1).map(|t| &t.kind),
3104                            Some(TokenType::Article(_))
3105                                | Some(TokenType::Noun(_))
3106                                | Some(TokenType::ProperName(_))
3107                                | Some(TokenType::Number(_))
3108                                | Some(TokenType::Cardinal(_))
3109                                | Some(TokenType::Pronoun { .. })
3110                                | Some(TokenType::Possessive)
3111                        );
3112                        let prep_sym = match &self.peek().kind {
3113                            TokenType::Preposition(s) => Some(*s),
3114                            _ => None,
3115                        };
3116                        if !has_overt_object && prep_sym.is_some() {
3117                            self.advance();
3118                            prep_sym
3119                        } else {
3120                            None
3121                        }
3122                    } else {
3123                        None
3124                    };
3125
3126                let mut roles: Vec<(ThematicRole, Term<'a>)> =
3127                    vec![(ThematicRole::Agent, Term::Constant(rel_subject.noun))];
3128                if stranded_prep.is_none() {
3129                    roles.push((ThematicRole::Theme, Term::Variable(gap_var)));
3130                }
3131
3132                while self.check_to_preposition() {
3133                    self.advance();
3134                    if self.check_content_word() || self.check_article() {
3135                        let recipient = self.parse_noun_phrase(false)?;
3136                        roles.push((ThematicRole::Recipient, Term::Constant(recipient.noun)));
3137                    }
3138                }
3139
3140                let event_var = self.get_event_var();
3141
3142                // Absorb the embedded clause's trailing PP complements onto the
3143                // EVENT ("photographed in 1989" → In(e, 1989), "issued at the depot"
3144                // → At(e, depot)) so an object-gap reduced relative does not strand
3145                // them. They attach over the event var, inside its existential scope.
3146                let mut pp_preds: Vec<&'a LogicExpr<'a>> = Vec::new();
3147                // The stranded preposition's object IS the gap ("Eva works with [x]" →
3148                // With(e, x)); attach it over the event so it falls in the event scope.
3149                if let Some(prep) = stranded_prep {
3150                    pp_preds.push(self.ctx.exprs.alloc(
3151                        LogicExpr::Predicate {
3152                            name: prep,
3153                            args:
3154                                self.ctx.terms.alloc_slice([
3155                                    Term::Variable(event_var),
3156                                    Term::Variable(gap_var),
3157                                ]),
3158                            world: None,
3159                        },
3160                    ));
3161                }
3162                while self.check_preposition() {
3163                    let prep = if let TokenType::Preposition(s) = self.advance().kind {
3164                        s
3165                    } else {
3166                        break;
3167                    };
3168                    let obj_term = if self.check_number() {
3169                        *self.parse_measure_phrase()?
3170                    } else if self.check_content_word() || self.check_article() {
3171                        Term::Constant(self.parse_noun_phrase(false)?.noun)
3172                    } else {
3173                        self.current -= 1;
3174                        break;
3175                    };
3176                    pp_preds.push(
3177                        self.ctx.exprs.alloc(LogicExpr::Predicate {
3178                            name: prep,
3179                            args: self
3180                                .ctx
3181                                .terms
3182                                .alloc_slice([Term::Variable(event_var), obj_term]),
3183                            world: None,
3184                        }),
3185                    );
3186                }
3187                let has_pps = !pp_preds.is_empty();
3188
3189                // With PPs, suppress the NeoEvent's own ∃e and wrap an explicit one so
3190                // the PP conjuncts fall inside the event's scope; without PPs, the
3191                // NeoEvent emits its own ∃e exactly as before (byte-identical).
3192                let suppress_existential = self.drs.in_conditional_antecedent() || has_pps;
3193                let neo = self
3194                    .ctx
3195                    .exprs
3196                    .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3197                        event_var,
3198                        verb,
3199                        roles: self.ctx.roles.alloc_slice(roles),
3200                        modifiers: self.ctx.syms.alloc_slice(vec![]),
3201                        suppress_existential,
3202                        world: None,
3203                    })));
3204                let mut event_body = neo;
3205                for pp in pp_preds {
3206                    event_body = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3207                        left: event_body,
3208                        op: TokenType::And,
3209                        right: pp,
3210                    });
3211                }
3212                let this_event: &'a LogicExpr<'a> = if has_pps {
3213                    self.ctx.exprs.alloc(LogicExpr::Quantifier {
3214                        kind: crate::ast::QuantifierKind::Existential,
3215                        variable: event_var,
3216                        body: event_body,
3217                        island_id: self.current_island,
3218                    })
3219                } else {
3220                    event_body
3221                };
3222
3223                if let Some((nested_var, nested_clause)) = nested_relative {
3224                    let type_pred = self.ctx.exprs.alloc(LogicExpr::Predicate {
3225                        name: rel_subject.noun,
3226                        args: self.ctx.terms.alloc_slice([Term::Variable(nested_var)]),
3227                        world: None,
3228                    });
3229
3230                    let inner = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3231                        left: type_pred,
3232                        op: TokenType::And,
3233                        right: nested_clause,
3234                    });
3235
3236                    let combined = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3237                        left: inner,
3238                        op: TokenType::And,
3239                        right: this_event,
3240                    });
3241
3242                    return Ok(self.ctx.exprs.alloc(LogicExpr::Quantifier {
3243                        kind: crate::ast::QuantifierKind::Existential,
3244                        variable: nested_var,
3245                        body: combined,
3246                        island_id: self.current_island,
3247                    }));
3248                }
3249
3250                return Ok(this_event);
3251            }
3252        }
3253
3254        if self.check_verb() {
3255            return self.parse_verb_phrase_for_restriction(gap_var);
3256        }
3257
3258        let unknown = self.interner.intern("?");
3259        Ok(self.ctx.exprs.alloc(LogicExpr::Atom(unknown)))
3260    }
3261
3262    fn check_ellipsis_auxiliary(&self) -> bool {
3263        matches!(
3264            self.peek().kind,
3265            TokenType::Does
3266                | TokenType::Do
3267                | TokenType::Can
3268                | TokenType::Could
3269                | TokenType::Would
3270                | TokenType::May
3271                | TokenType::Must
3272                | TokenType::Should
3273        )
3274    }
3275
3276    fn check_ellipsis_terminator(&self) -> bool {
3277        if self.is_at_end() || self.check(&TokenType::Period) {
3278            return true;
3279        }
3280        if self.check_content_word() {
3281            let word = self.interner.resolve(self.peek().lexeme).to_lowercase();
3282            return word == "too" || word == "also";
3283        }
3284        false
3285    }
3286
3287    fn try_parse_ellipsis(&mut self) -> Option<ParseResult<&'a LogicExpr<'a>>> {
3288        // Need a stored template to reconstruct from
3289        if self.last_event_template.is_none() {
3290            return None;
3291        }
3292
3293        let saved_pos = self.backtrack_point();
3294
3295        // Pattern: Subject + Auxiliary + (not)? + Terminator
3296        // Subject must be proper name or pronoun
3297        let subject_sym = if matches!(self.peek().kind, TokenType::ProperName(_)) {
3298            if let TokenType::ProperName(sym) = self.advance().kind {
3299                sym
3300            } else {
3301                self.backtrack_to(&saved_pos);
3302                return None;
3303            }
3304        } else if self.check_pronoun() {
3305            let token = self.advance().clone();
3306            if let TokenType::Pronoun { gender, number, .. } = token.kind {
3307                match self.resolve_pronoun(gender, number) {
3308                    Ok(resolved) => match resolved {
3309                        super::ResolvedPronoun::Variable(s)
3310                        | super::ResolvedPronoun::Constant(s) => s,
3311                    },
3312                    Err(e) => return Some(Err(e)),
3313                }
3314            } else {
3315                self.backtrack_to(&saved_pos);
3316                return None;
3317            }
3318        } else {
3319            return None;
3320        };
3321
3322        // Must be followed by ellipsis auxiliary
3323        if !self.check_ellipsis_auxiliary() {
3324            self.backtrack_to(&saved_pos);
3325            return None;
3326        }
3327        let aux_token = self.advance().kind.clone();
3328
3329        // Check for negation
3330        let is_negated = self.match_token(&[TokenType::Not]);
3331
3332        // Must end with terminator
3333        if !self.check_ellipsis_terminator() {
3334            self.backtrack_to(&saved_pos);
3335            return None;
3336        }
3337
3338        // Consume "too"/"also" if present
3339        if self.check_content_word() {
3340            let word = self.interner.resolve(self.peek().lexeme).to_lowercase();
3341            if word == "too" || word == "also" {
3342                self.advance();
3343            }
3344        }
3345
3346        // Reconstruct from template
3347        let template = self.last_event_template.clone().unwrap();
3348        let event_var = self.get_event_var();
3349        let suppress_existential = self.drs.in_conditional_antecedent();
3350
3351        // Build roles with new subject as Agent
3352        let mut roles: Vec<(ThematicRole, Term<'a>)> =
3353            vec![(ThematicRole::Agent, Term::Constant(subject_sym))];
3354        roles.extend(template.non_agent_roles.iter().cloned());
3355
3356        let neo_event = self
3357            .ctx
3358            .exprs
3359            .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
3360                event_var,
3361                verb: template.verb,
3362                roles: self.ctx.roles.alloc_slice(roles),
3363                modifiers: self.ctx.syms.alloc_slice(template.modifiers.clone()),
3364                suppress_existential,
3365                world: None,
3366            })));
3367
3368        // Apply modal if auxiliary is modal
3369        let with_modal = match aux_token {
3370            TokenType::Can | TokenType::Could => {
3371                let vector = self.token_to_vector(&aux_token);
3372                self.ctx.modal(vector, neo_event)
3373            }
3374            TokenType::Would | TokenType::May | TokenType::Must | TokenType::Should => {
3375                let vector = self.token_to_vector(&aux_token);
3376                self.ctx.modal(vector, neo_event)
3377            }
3378            _ => neo_event,
3379        };
3380
3381        // Apply negation if present
3382        let result = if is_negated {
3383            self.ctx.exprs.alloc(LogicExpr::UnaryOp {
3384                op: TokenType::Not,
3385                operand: with_modal,
3386            })
3387        } else {
3388            with_modal
3389        };
3390
3391        Some(Ok(result))
3392    }
3393
3394    fn try_parse_of_pair_xor(&mut self) -> ParseResult<Option<&'a LogicExpr<'a>>> {
3395        let start = self.backtrack_point();
3396
3397        // Must start with the preposition "of"
3398        let is_of = {
3399            let text = self.interner.resolve(self.peek().lexeme).to_lowercase();
3400            text == "of" && matches!(self.peek().kind, TokenType::Preposition(_))
3401        };
3402        if !is_of {
3403            return Ok(None);
3404        }
3405
3406        // Scan for the structural boundaries: the comma ending "Of NP₁ and NP₂,"
3407        // and the last "and" before it (the NP₁/NP₂ separator). These give a
3408        // robust fallback when full-NP parsing misaligns with the boundary.
3409        let scan_start = self.current + 1; // one past "of"
3410        let comma_pos = {
3411            let mut found = None;
3412            for i in scan_start..self.tokens.len() {
3413                match &self.tokens[i].kind {
3414                    TokenType::Period | TokenType::EOF => break,
3415                    TokenType::Comma => {
3416                        found = Some(i);
3417                        break;
3418                    }
3419                    _ => {}
3420                }
3421            }
3422            match found {
3423                Some(p) => p,
3424                None => return Ok(None),
3425            }
3426        };
3427        let and_pos = {
3428            let mut found = None;
3429            for i in scan_start..comma_pos {
3430                if self.interner.resolve(self.tokens[i].lexeme).to_lowercase() == "and" {
3431                    found = Some(i);
3432                }
3433            }
3434            match found {
3435                Some(p) => p,
3436                None => return Ok(None),
3437            }
3438        };
3439        let one_ok = self
3440            .tokens
3441            .get(comma_pos + 1)
3442            .map(|t| self.interner.resolve(t.lexeme).to_lowercase() == "one")
3443            .unwrap_or(false);
3444        if !one_ok {
3445            return Ok(None);
3446        }
3447
3448        // Last content head in [lo, hi) (compounding a preceding cardinal) — the
3449        // robust fallback when parse_noun_phrase misaligns. A verb-only word
3450        // ("stamp", "print") or an ambiguous noun/verb token can head a puzzle NP
3451        // too, so they count as heads here; the fallback yields a bare constant
3452        // (its modifiers are lost — only reached when the full parse failed).
3453        fn scan_head<'a, 'ctx, 'int>(
3454            p: &mut Parser<'a, 'ctx, 'int>,
3455            lo: usize,
3456            hi: usize,
3457        ) -> Option<Symbol> {
3458            let mut i = hi;
3459            while i > lo {
3460                i -= 1;
3461                let head = match p.tokens[i].kind {
3462                    TokenType::ProperName(s) | TokenType::Noun(s) => Some(s),
3463                    TokenType::Verb { lemma, .. } => Some(lemma),
3464                    TokenType::Ambiguous {
3465                        ref primary,
3466                        ref alternatives,
3467                    } => match **primary {
3468                        TokenType::Noun(s) | TokenType::ProperName(s) => Some(s),
3469                        TokenType::Verb { lemma, .. } => Some(lemma),
3470                        _ => alternatives.iter().find_map(|t| match t {
3471                            TokenType::Noun(s) | TokenType::ProperName(s) => Some(*s),
3472                            TokenType::Verb { lemma, .. } => Some(*lemma),
3473                            _ => None,
3474                        }),
3475                    },
3476                    _ => None,
3477                };
3478                if let Some(s) = head {
3479                    if i > lo {
3480                        if let TokenType::Cardinal(n) = p.tokens[i - 1].kind {
3481                            return Some(p.interner.intern(&format!(
3482                                "{}_{}",
3483                                n,
3484                                p.interner.resolve(s)
3485                            )));
3486                        }
3487                    }
3488                    return Some(s);
3489                }
3490            }
3491            None
3492        }
3493
3494        // Build one side of the pair, parsing the full NP for correctness but
3495        // committing only if it lands exactly at `boundary` without erroring;
3496        // otherwise fall back to the robust scan head (a bare constant). A
3497        // descriptive NP (determiner / adjective / possessor / PP / relative
3498        // clause) becomes a fresh existential variable carrying a restrictor so
3499        // two NPs sharing a head noun stay distinct; a bare proper name stays a
3500        // referring constant. Parsing is non-fatal so a malformed NP never breaks
3501        // an otherwise-valid clue.
3502        fn build_entity<'a, 'ctx, 'int>(
3503            p: &mut Parser<'a, 'ctx, 'int>,
3504            boundary: usize,
3505        ) -> ParseResult<OfEntity<'a>> {
3506            // An of-pair member is a nominal description ("the skydiving trip"),
3507            // so a verb-ambiguous head ("trip", "place") folds its modifier into
3508            // the head noun instead of being read as a verb — without this the NP
3509            // misaligns at the following "and" and the lossy scan_head fallback
3510            // drops the modifier ("the skydiving trip" → bare `Trip`).
3511            let saved_ctx = p.nominal_np_context;
3512            p.nominal_np_context = true;
3513            let np_result = p.parse_noun_phrase(true);
3514            p.nominal_np_context = saved_ctx;
3515            let np = np_result?;
3516            // who/that/where/whose relative, or a REDUCED relative ("the island first
3517            // seen by Captain Norris", "the well cut through chalk") — both restrict
3518            // the member and run up to the structural boundary ("and"/comma).
3519            let has_rel = (p.check(&TokenType::Who)
3520                || p.check(&TokenType::That)
3521                || p.check(&TokenType::Where)
3522                || p.check(&TokenType::Whose))
3523                && p.current < boundary;
3524            let has_reduced = p.peek_heads_reduced_relative_participle() && p.current < boundary;
3525            let is_desc = np.definiteness.is_some()
3526                || !np.adjectives.is_empty()
3527                || np.possessor.is_some()
3528                || !np.pps.is_empty()
3529                || has_rel
3530                || has_reduced;
3531            let (sym, is_var) = if is_desc {
3532                (p.next_var_name(), true)
3533            } else {
3534                (np.noun, false)
3535            };
3536            let term = if is_var {
3537                Term::Variable(sym)
3538            } else {
3539                Term::Constant(sym)
3540            };
3541            let rel = if has_rel {
3542                p.try_attach_relative(term)?
3543            } else {
3544                None
3545            };
3546            let reduced = if has_reduced {
3547                p.try_consume_reduced_relative(term)?
3548            } else {
3549                None
3550            };
3551            if p.current != boundary {
3552                return Err(ParseError {
3553                    kind: ParseErrorKind::Custom("of-pair NP misaligned".into()),
3554                    span: p.current_span(),
3555                });
3556            }
3557            let restrictor = if is_var {
3558                // Head noun + adjectives + possessor, all over the fresh variable.
3559                let mut r = p.nominal_predication(term, &np);
3560                for pp in np.pps {
3561                    let pp_sub = p.substitute_pp_placeholder(pp, sym);
3562                    r = p.ctx.exprs.alloc(LogicExpr::BinaryOp {
3563                        left: r,
3564                        op: TokenType::And,
3565                        right: pp_sub,
3566                    });
3567                }
3568                for rc in rel.into_iter().chain(reduced) {
3569                    r = p.ctx.exprs.alloc(LogicExpr::BinaryOp {
3570                        left: r,
3571                        op: TokenType::And,
3572                        right: rc,
3573                    });
3574                }
3575                Some(r)
3576            } else {
3577                None
3578            };
3579            Ok(OfEntity {
3580                sym,
3581                is_var,
3582                term,
3583                restrictor,
3584            })
3585        }
3586
3587        self.advance(); // consume "of"
3588
3589        // NP₁, bounded by the "and".
3590        let e1 = match self.try_parse(|p| build_entity(p, and_pos)) {
3591            Some(e) => e,
3592            None => {
3593                self.current = and_pos;
3594                match scan_head(self, scan_start, and_pos) {
3595                    Some(h) => OfEntity {
3596                        sym: h,
3597                        is_var: false,
3598                        term: Term::Constant(h),
3599                        restrictor: None,
3600                    },
3601                    None => {
3602                        self.backtrack_to(&start);
3603                        return Ok(None);
3604                    }
3605                }
3606            }
3607        };
3608        self.advance(); // "and" separating NP₁ from NP₂
3609
3610        // NP₂, bounded by the comma.
3611        let e2 = match self.try_parse(|p| build_entity(p, comma_pos)) {
3612            Some(e) => e,
3613            None => {
3614                self.current = comma_pos;
3615                match scan_head(self, and_pos + 1, comma_pos) {
3616                    Some(h) => OfEntity {
3617                        sym: h,
3618                        is_var: false,
3619                        term: Term::Constant(h),
3620                        restrictor: None,
3621                    },
3622                    None => {
3623                        self.backtrack_to(&start);
3624                        return Ok(None);
3625                    }
3626                }
3627            }
3628        };
3629        self.advance(); // ","
3630        self.advance(); // "one" (validated above)
3631                        // "one TYPE is …" / "one PERSON did …" — a redundant classifier noun
3632                        // after "one" (the of-pair already binds the entity); skip it so VP₁
3633                        // starts at the real predicate. Only when a Noun is directly followed by
3634                        // a copula / auxiliary / verb (the predicate), never a bare object NP.
3635        {
3636            // A classifier is a generic noun ("one PERSON …") or a noun-or-verb
3637            // ambiguous word the lexicon also reads as a verb ("one TYPE …", "one
3638            // KIND …") — matched by lexeme so the verb tagging doesn't hide it. A
3639            // genuine aspectual verb ("one STARTED running") is never a classifier.
3640            let cur_is_classifier = matches!(
3641                self.tokens.get(self.current).map(|t| &t.kind),
3642                Some(TokenType::Noun(_))
3643            ) || self
3644                .tokens
3645                .get(self.current)
3646                .map(|t| {
3647                    matches!(
3648                        self.interner.resolve(t.lexeme).to_lowercase().as_str(),
3649                        "type" | "kind" | "sort" | "variety" | "category" | "version"
3650                    )
3651                })
3652                .unwrap_or(false);
3653            if cur_is_classifier
3654                && matches!(
3655                    self.tokens.get(self.current + 1).map(|t| &t.kind),
3656                    Some(
3657                        TokenType::Is
3658                            | TokenType::Are
3659                            | TokenType::Was
3660                            | TokenType::Were
3661                            | TokenType::Verb { .. }
3662                            | TokenType::Auxiliary(_)
3663                    )
3664                )
3665            {
3666                self.advance(); // skip the classifier noun
3667            }
3668        }
3669
3670        // Bound VP₁ at the "and the other" marker so a verb-object VP ("one teaches
3671        // yoga and the other is …") does not swallow "and the other …" as
3672        // coordinated objects. Scan for And + (article) + "other" and temporarily
3673        // turn that "and" into a clause terminator (a Period the VP parser stops
3674        // at); it is RESTORED on every exit path (errors, misalign, success).
3675        let other_and_pos = {
3676            let mut found = None;
3677            let mut i = self.current;
3678            while i + 2 < self.tokens.len() {
3679                if matches!(self.tokens[i].kind, TokenType::Period | TokenType::EOF) {
3680                    break;
3681                }
3682                if matches!(self.tokens[i].kind, TokenType::And)
3683                    && matches!(self.tokens[i + 1].kind, TokenType::Article(_))
3684                    && self
3685                        .interner
3686                        .resolve(self.tokens[i + 2].lexeme)
3687                        .eq_ignore_ascii_case("other")
3688                {
3689                    found = Some(i);
3690                    break;
3691                }
3692                i += 1;
3693            }
3694            found
3695        };
3696        let saved_and_tok = other_and_pos.map(|p| self.tokens[p].clone());
3697        if let Some(p) = other_and_pos {
3698            let mut t = self.tokens[p].clone();
3699            t.kind = TokenType::Period;
3700            self.tokens[p] = t;
3701        }
3702
3703        macro_rules! restore_and {
3704            () => {
3705                if let (Some(p), Some(tok)) = (other_and_pos, saved_and_tok.as_ref()) {
3706                    self.tokens[p] = tok.clone();
3707                }
3708            };
3709        }
3710
3711        // A verb phrase parsed from `start`, with `e` as its subject — restoring the
3712        // bounded "and" before propagating any parse error.
3713        macro_rules! vp_with {
3714            ($start:expr, $e:expr) => {{
3715                self.current = $start;
3716                let __r = if $e.is_var {
3717                    self.parse_predicate_with_subject_as_var($e.sym)
3718                } else {
3719                    self.parse_predicate_with_subject($e.sym)
3720                };
3721                match __r {
3722                    Ok(v) => v,
3723                    Err(err) => {
3724                        restore_and!();
3725                        return Err(err);
3726                    }
3727                }
3728            }};
3729        }
3730
3731        // VP₁ with e1 as subject (stops at the bounded marker).
3732        let vp1_start = self.current;
3733        let vp1_e1 = vp_with!(vp1_start, e1);
3734
3735        // Expect the "and the other" marker. When bounded, VP₁ stopped at the
3736        // Period that replaced "and"; an optional comma may precede it.
3737        if self.check(&TokenType::Comma) {
3738            self.advance();
3739        }
3740        if let Some(marker) = other_and_pos {
3741            if self.current != marker || !self.check(&TokenType::Period) {
3742                restore_and!();
3743                self.backtrack_to(&start);
3744                return Ok(None);
3745            }
3746            self.advance(); // the bounded "and"
3747        } else {
3748            if self.interner.resolve(self.peek().lexeme).to_lowercase() != "and" {
3749                self.backtrack_to(&start);
3750                return Ok(None);
3751            }
3752            self.advance(); // consume "and"
3753        }
3754
3755        // Expect "the"
3756        if !self.check_article() {
3757            restore_and!();
3758            self.backtrack_to(&start);
3759            return Ok(None);
3760        }
3761        self.advance(); // consume "the"
3762
3763        // Expect "other"
3764        if self.interner.resolve(self.peek().lexeme).to_lowercase() != "other" {
3765            restore_and!();
3766            self.backtrack_to(&start);
3767            return Ok(None);
3768        }
3769        self.advance(); // consume "other"
3770                        // "the other TYPE is …" — skip the redundant classifier noun (mirrors the
3771                        // "one TYPE" skip above) so VP₂ starts at the real predicate.
3772        {
3773            // A classifier is a generic noun ("one PERSON …") or a noun-or-verb
3774            // ambiguous word the lexicon also reads as a verb ("one TYPE …", "one
3775            // KIND …") — matched by lexeme so the verb tagging doesn't hide it. A
3776            // genuine aspectual verb ("one STARTED running") is never a classifier.
3777            let cur_is_classifier = matches!(
3778                self.tokens.get(self.current).map(|t| &t.kind),
3779                Some(TokenType::Noun(_))
3780            ) || self
3781                .tokens
3782                .get(self.current)
3783                .map(|t| {
3784                    matches!(
3785                        self.interner.resolve(t.lexeme).to_lowercase().as_str(),
3786                        "type" | "kind" | "sort" | "variety" | "category" | "version"
3787                    )
3788                })
3789                .unwrap_or(false);
3790            if cur_is_classifier
3791                && matches!(
3792                    self.tokens.get(self.current + 1).map(|t| &t.kind),
3793                    Some(
3794                        TokenType::Is
3795                            | TokenType::Are
3796                            | TokenType::Was
3797                            | TokenType::Were
3798                            | TokenType::Verb { .. }
3799                            | TokenType::Auxiliary(_)
3800                    )
3801                )
3802            {
3803                self.advance(); // skip the classifier noun
3804            }
3805        }
3806
3807        // VP₂ with e2 as subject, then re-parse each VP with the other entity.
3808        let vp2_start = self.current;
3809        let vp2_e2 = vp_with!(vp2_start, e2);
3810        let end_pos = self.backtrack_point();
3811        let vp1_e2 = vp_with!(vp1_start, e2);
3812        let vp2_e1 = vp_with!(vp2_start, e1);
3813        self.backtrack_to(&end_pos);
3814
3815        // All VP parses done — the bounded "and" is no longer needed; restore it
3816        // before building the result so the token stream is left pristine.
3817        restore_and!();
3818
3819        // Build: (VP₁(e1) ∧ VP₂(e2)) ∨ (VP₁(e2) ∧ VP₂(e1))
3820        let branch1 = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3821            left: vp1_e1,
3822            op: TokenType::And,
3823            right: vp2_e2,
3824        });
3825        let branch2 = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3826            left: vp1_e2,
3827            op: TokenType::And,
3828            right: vp2_e1,
3829        });
3830        let mut result: &'a LogicExpr<'a> = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3831            left: branch1,
3832            op: TokenType::Or,
3833            right: branch2,
3834        });
3835
3836        // "Of A and B" presents two DISTINCT entities. A variable entity could
3837        // otherwise co-refer with the other side and collapse the XOR, so assert
3838        // the inequality whenever either side is a variable; two proper-name
3839        // constants are distinct by the unique-name assumption already.
3840        if e1.is_var || e2.is_var {
3841            let identity = self.ctx.exprs.alloc(LogicExpr::Identity {
3842                left: self.ctx.terms.alloc(e1.term),
3843                right: self.ctx.terms.alloc(e2.term),
3844            });
3845            let ineq = self.ctx.exprs.alloc(LogicExpr::UnaryOp {
3846                op: TokenType::Not,
3847                operand: identity,
3848            });
3849            result = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3850                left: ineq,
3851                op: TokenType::And,
3852                right: result,
3853            });
3854        }
3855
3856        // A description's restrictor (head noun, adjectives, possessor, PPs,
3857        // relative clause) holds in BOTH XOR branches, so it conjoins outside the
3858        // disjunction and is bound by the existential opened below.
3859        if let Some(r2) = e2.restrictor {
3860            result = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3861                left: r2,
3862                op: TokenType::And,
3863                right: result,
3864            });
3865        }
3866        if let Some(r1) = e1.restrictor {
3867            result = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
3868                left: r1,
3869                op: TokenType::And,
3870                right: result,
3871            });
3872        }
3873        if e2.is_var {
3874            result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
3875                kind: QuantifierKind::Existential,
3876                variable: e2.sym,
3877                body: result,
3878                island_id: self.current_island,
3879            });
3880        }
3881        if e1.is_var {
3882            result = self.ctx.exprs.alloc(LogicExpr::Quantifier {
3883                kind: QuantifierKind::Existential,
3884                variable: e1.sym,
3885                body: result,
3886                island_id: self.current_island,
3887            });
3888        }
3889        Ok(Some(result))
3890    }
3891}
3892
3893/// Where a coordinated object joins its clause ([`Parser::try_coordinated_objects`]).
3894struct ObjectSite<'a> {
3895    /// The subexpression the first object's verb phrase occupies; each further object's is
3896    /// conjoined beside it.
3897    node: &'a LogicExpr<'a>,
3898    /// The event whose Theme the first object is.
3899    template: &'a NeoEventData<'a>,
3900    /// Whether that event's own ∃e is written in the clause (it holds conditions such as a PP),
3901    /// rather than bound by an if-clause outside it.
3902    event_bound_in_clause: bool,
3903}
3904
3905// Phase 46: Helper methods for generalized gapping (not part of trait)
3906impl<'a, 'ctx, 'int> Parser<'a, 'ctx, 'int> {
3907    /// "Any" in an if-clause is the indefinite: "If any dog barks, John runs" says what "If a
3908    /// dog barks, John runs" says — whichever dog barks, John runs — not "if every dog barks".
3909    /// Retag each determiner "any" of the if-clause as the indefinite article, so the DRS gives
3910    /// it the antecedent indefinite's universal force over the whole conditional and a pronoun
3911    /// in the consequent ("…, it runs") finds the individual it introduces. The if-clause runs
3912    /// to its comma or its "then" (written without either, to the end of the sentence), and
3913    /// "any time" keeps its temporal reading.
3914    fn retag_antecedent_any(&mut self) {
3915        let mut i = self.current;
3916        while let Some(token) = self.tokens.get(i) {
3917            match token.kind {
3918                TokenType::Comma
3919                | TokenType::Then
3920                | TokenType::Period
3921                | TokenType::Exclamation
3922                | TokenType::EOF => break,
3923                TokenType::Any
3924                    if self
3925                        .tokens
3926                        .get(i + 1)
3927                        .is_some_and(|next| self.heads_a_noun_phrase(next)) =>
3928                {
3929                    self.tokens[i].kind = TokenType::Article(Definiteness::Indefinite);
3930                }
3931                _ => {}
3932            }
3933            i += 1;
3934        }
3935    }
3936
3937    /// Whether `token`, just after a determiner, begins the noun phrase it determines — and is
3938    /// not the "time" of the temporal "any time".
3939    fn heads_a_noun_phrase(&self, token: &Token) -> bool {
3940        matches!(
3941            token.kind,
3942            TokenType::Noun(_)
3943                | TokenType::Adjective(_)
3944                | TokenType::NonIntersectiveAdjective(_)
3945                | TokenType::Ambiguous { .. }
3946        ) && !self
3947            .interner
3948            .resolve(token.lexeme)
3949            .eq_ignore_ascii_case("time")
3950    }
3951
3952    /// A gapped clause's remnant of two names side by side — "…and Bill Susan" after "John loves
3953    /// Mary" — is its subject and its object: Bill loves Susan. It is when the lexicon knows both
3954    /// names as people, nothing more of a name follows them, the borrowed verb takes one object,
3955    /// and the first name contrasts with the subject of the clause it echoes. "Bill Smith" (a
3956    /// surname the lexicon does not know) and "John Paul" after "John loves Mary" stay one name.
3957    fn remnant_names_two_people(&self) -> bool {
3958        let kind_at = |offset: usize| self.tokens.get(self.current + offset).map(|t| &t.kind);
3959        let (Some(TokenType::ProperName(first)), Some(TokenType::ProperName(second))) =
3960            (kind_at(0), kind_at(1))
3961        else {
3962            return false;
3963        };
3964        let known = |name: &Symbol| crate::lexicon::is_proper_name(self.interner.resolve(*name));
3965        if !known(first)
3966            || !known(second)
3967            || kind_at(2).is_some_and(|k| self.is_proper_name_or_label(k))
3968        {
3969            return false;
3970        }
3971        let Some(template) = &self.last_event_template else {
3972            return false;
3973        };
3974        let objects = template
3975            .non_agent_roles
3976            .iter()
3977            .filter(|(role, _)| {
3978                matches!(
3979                    role,
3980                    ThematicRole::Theme | ThematicRole::Recipient | ThematicRole::Patient
3981                )
3982            })
3983            .count();
3984        objects == 1 && !matches!(&template.agent, Some(Term::Constant(agent)) if agent == first)
3985    }
3986
3987    /// A list of objects coordinated after a clause's verb — "John sees Mary, Bill and Sue",
3988    /// "Every man sees Mary and Bill", "John sees a cat and a dog" — ends the sentence and is
3989    /// nothing but noun phrases. Each one gets the verb: the clause's event is rebuilt with that
3990    /// object as its Theme (in its own determiner's scope) and conjoined beside the first
3991    /// object, inside the subject's scope. `None`, consuming nothing, when what follows is not
3992    /// such a list (a new clause, a gapped one, a coordinated verb phrase).
3993    fn try_coordinated_objects(
3994        &mut self,
3995        left: &'a LogicExpr<'a>,
3996    ) -> ParseResult<Option<&'a LogicExpr<'a>>> {
3997        let Some(site) = self.object_coordination_site(left, &mut Vec::new(), true) else {
3998            return Ok(None);
3999        };
4000        let start = self.checkpoint();
4001        // A list has the shape "A, B and C" (or "A, B, and C", or "A and B"): commas between
4002        // its members and one "and" before the last. "…, and Mary, a pear" is a gapped clause.
4003        let mut objects: Vec<NounPhrase<'a>> = Vec::new();
4004        let mut closed_by_and = false;
4005        loop {
4006            let mut saw_comma = false;
4007            if self.check(&TokenType::Comma) {
4008                self.advance();
4009                saw_comma = true;
4010            }
4011            let saw_and = self.check(&TokenType::And);
4012            if saw_and {
4013                self.advance();
4014            }
4015            if !saw_comma && !saw_and {
4016                break;
4017            }
4018            let object_start = self.current;
4019            // A verb after the coordinator starts a verb phrase ("…and loves Sue"), not an object.
4020            let opens_verb_phrase = self
4021                .tokens
4022                .get(self.current)
4023                .is_some_and(|t| self.kind_is_verb(&t.kind));
4024            let object = if !closed_by_and
4025                && !opens_verb_phrase
4026                && (self.check_content_word() || self.check_article())
4027            {
4028                self.parse_noun_phrase(false).ok()
4029            } else {
4030                None
4031            };
4032            // Two names side by side ("… and Bill Susan") are a gapped clause's subject and
4033            // object — Bill loves Susan — not one object with a two-word name.
4034            let names_read = self.tokens[object_start..self.current]
4035                .iter()
4036                .filter(|t| matches!(t.kind, TokenType::ProperName(_)))
4037                .count();
4038            match object {
4039                Some(np) if np.pps.is_empty() && np.superlative.is_none() && names_read <= 1 => {
4040                    objects.push(np)
4041                }
4042                _ => {
4043                    self.restore(start);
4044                    return Ok(None);
4045                }
4046            }
4047            closed_by_and = saw_and;
4048        }
4049        let ends_sentence = self.check(&TokenType::Period)
4050            || self.check(&TokenType::Exclamation)
4051            || self.is_at_end();
4052        if !closed_by_and || !(ends_sentence || self.check(&TokenType::Respectively)) {
4053            self.restore(start);
4054            return Ok(None);
4055        }
4056        if self.check(&TokenType::Respectively) {
4057            return Err(ParseError {
4058                kind: ParseErrorKind::RespectivelyLengthMismatch {
4059                    subject_count: 1,
4060                    object_count: objects.len() + 1,
4061                },
4062                span: self.current_span(),
4063            });
4064        }
4065
4066        let mut coordinated = site.node;
4067        for object in &objects {
4068            let vp = self.event_with_object(site.template, site.event_bound_in_clause, object)?;
4069            coordinated = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
4070                left: coordinated,
4071                op: TokenType::And,
4072                right: vp,
4073            });
4074        }
4075        match self.replace_subexpr(left, site.node, coordinated) {
4076            Some(rebuilt) => Ok(Some(rebuilt)),
4077            None => {
4078                self.restore(start);
4079                Ok(None)
4080            }
4081        }
4082    }
4083
4084    /// Where `expr`'s most recent event with a Theme meets its object: the event itself, or —
4085    /// when the event's own ∃e (holding its PP conditions) or the object's determiner binds
4086    /// inside `expr` — the outermost of those quantifiers, so the whole verb phrase for the
4087    /// first object sits under the site. Descends only through what keeps a coordinated object
4088    /// in the same clause and scope: conjunction (most recent conjunct first), the consequent
4089    /// of an implication, quantifiers, and tense, aspect and voice.
4090    fn object_coordination_site(
4091        &self,
4092        expr: &'a LogicExpr<'a>,
4093        binders: &mut Vec<&'a LogicExpr<'a>>,
4094        needs_theme: bool,
4095    ) -> Option<ObjectSite<'a>> {
4096        match expr {
4097            LogicExpr::NeoEvent(data) => {
4098                let theme = data
4099                    .roles
4100                    .iter()
4101                    .find(|(role, _)| *role == ThematicRole::Theme);
4102                if needs_theme && theme.is_none() {
4103                    return None;
4104                }
4105                let bound_at = |v: Symbol| {
4106                    binders.iter().rposition(
4107                        |b| matches!(b, LogicExpr::Quantifier { variable, .. } if *variable == v),
4108                    )
4109                };
4110                let object_binder = match theme.map(|(_, term)| *term) {
4111                    Some(Term::Variable(v)) => bound_at(v),
4112                    _ => None,
4113                };
4114                let event_binder = bound_at(data.event_var);
4115                let node = match (object_binder, event_binder) {
4116                    (Some(o), Some(e)) => binders[o.min(e)],
4117                    (Some(i), None) | (None, Some(i)) => binders[i],
4118                    (None, None) => expr,
4119                };
4120                Some(ObjectSite {
4121                    node,
4122                    template: data,
4123                    event_bound_in_clause: event_binder.is_some(),
4124                })
4125            }
4126            LogicExpr::BinaryOp {
4127                left,
4128                op: TokenType::And,
4129                right,
4130            } => self
4131                .object_coordination_site(right, binders, needs_theme)
4132                .or_else(|| self.object_coordination_site(left, binders, needs_theme)),
4133            LogicExpr::BinaryOp {
4134                right,
4135                op: TokenType::Implies,
4136                ..
4137            } => self.object_coordination_site(right, binders, needs_theme),
4138            LogicExpr::Quantifier { body, .. } => {
4139                binders.push(expr);
4140                let found = self.object_coordination_site(body, binders, needs_theme);
4141                binders.pop();
4142                found
4143            }
4144            LogicExpr::Temporal { body, .. }
4145            | LogicExpr::Aspectual { body, .. }
4146            | LogicExpr::Voice { body, .. } => {
4147                self.object_coordination_site(body, binders, needs_theme)
4148            }
4149            _ => None,
4150        }
4151    }
4152
4153    /// "…and sees Bill", "…and loves Sue": a verb phrase after "and" with no subject of its own
4154    /// is the clause's subject — its most recent event's Agent, a variable or a name — doing a
4155    /// second thing. It is parsed for that subject and conjoined beside the first verb phrase,
4156    /// inside the subject's scope, so "Some man sees Mary and sees Bill" is one man seeing both.
4157    /// `None`, consuming nothing, when no verb follows the "and" or the clause has no agent.
4158    fn try_coordinated_verb_phrase(
4159        &mut self,
4160        left: &'a LogicExpr<'a>,
4161    ) -> ParseResult<Option<&'a LogicExpr<'a>>> {
4162        let at_and = if self.check(&TokenType::Comma) {
4163            self.current + 1
4164        } else {
4165            self.current
4166        };
4167        if !matches!(
4168            self.tokens.get(at_and).map(|t| &t.kind),
4169            Some(TokenType::And)
4170        ) {
4171            return Ok(None);
4172        }
4173        let verb_follows = self
4174            .tokens
4175            .get(at_and + 1)
4176            .is_some_and(|t| self.kind_is_verb(&t.kind));
4177        if !verb_follows {
4178            return Ok(None);
4179        }
4180        let Some(site) = self.object_coordination_site(left, &mut Vec::new(), false) else {
4181            return Ok(None);
4182        };
4183        let Some((_, subject)) = site
4184            .template
4185            .roles
4186            .iter()
4187            .find(|(role, _)| *role == ThematicRole::Agent)
4188        else {
4189            return Ok(None);
4190        };
4191        let start = self.checkpoint();
4192        self.current = at_and + 1;
4193        let second = match *subject {
4194            Term::Variable(v) => self.parse_predicate_with_subject_as_var(v),
4195            Term::Constant(c) => self.parse_predicate_with_subject(c),
4196            _ => {
4197                self.restore(start);
4198                return Ok(None);
4199            }
4200        };
4201        let Ok(second) = second else {
4202            self.restore(start);
4203            return Ok(None);
4204        };
4205        let coordinated = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
4206            left: site.node,
4207            op: TokenType::And,
4208            right: second,
4209        });
4210        match self.replace_subexpr(left, site.node, coordinated) {
4211            Some(rebuilt) => Ok(Some(rebuilt)),
4212            None => {
4213                self.restore(start);
4214                Ok(None)
4215            }
4216        }
4217    }
4218
4219    /// The event of `template` with `object` as its Theme, in the object's own scope: a name
4220    /// or a definite is the constant the clause's builders give it, an indefinite brings its
4221    /// own existential, and the object's adjectives come with it. The event is its own: bound
4222    /// by its own ∃e — or, in an if-clause, by the DRS under a fresh variable.
4223    fn event_with_object(
4224        &mut self,
4225        template: &'a NeoEventData<'a>,
4226        event_bound_in_clause: bool,
4227        object: &NounPhrase<'a>,
4228    ) -> ParseResult<&'a LogicExpr<'a>> {
4229        let object_term = self.noun_phrase_to_term(object);
4230        let roles: Vec<(ThematicRole, Term<'a>)> = template
4231            .roles
4232            .iter()
4233            .map(|(role, term)| {
4234                if *role == ThematicRole::Theme {
4235                    (*role, object_term)
4236                } else {
4237                    (*role, *term)
4238                }
4239            })
4240            .collect();
4241        let in_if_clause = template.suppress_existential && !event_bound_in_clause;
4242        let event_var = if in_if_clause {
4243            // In an if-clause the DRS binds each event; this one is its own.
4244            let fresh = self.world_state.next_event_var();
4245            let fresh = self.interner.intern(&fresh);
4246            let event_class = self.interner.intern("Event");
4247            self.drs.introduce_event_referent(fresh, event_class);
4248            fresh
4249        } else {
4250            template.event_var
4251        };
4252        let mut vp: &'a LogicExpr<'a> =
4253            self.ctx
4254                .exprs
4255                .alloc(LogicExpr::NeoEvent(Box::new(NeoEventData {
4256                    event_var,
4257                    verb: template.verb,
4258                    roles: self.ctx.roles.alloc_slice(roles),
4259                    modifiers: template.modifiers,
4260                    suppress_existential: in_if_clause,
4261                    world: template.world,
4262                })));
4263        for &adjective in object.adjectives.iter().rev() {
4264            let described = self.ctx.exprs.alloc(LogicExpr::Predicate {
4265                name: adjective,
4266                args: self.ctx.terms.alloc_slice([object_term]),
4267                world: None,
4268            });
4269            vp = self.ctx.exprs.alloc(LogicExpr::BinaryOp {
4270                left: described,
4271                op: TokenType::And,
4272                right: vp,
4273            });
4274        }
4275        if object.definiteness == Some(Definiteness::Indefinite) && object.possessor.is_none() {
4276            return self.wrap_with_definiteness_for_object(object.definiteness, object.noun, vp);
4277        }
4278        Ok(vp)
4279    }
4280
4281    /// `expr` with the subexpression `target` (by identity) replaced by `with`, rebuilding the
4282    /// path to it through the containers `object_coordination_site` descends.
4283    fn replace_subexpr(
4284        &self,
4285        expr: &'a LogicExpr<'a>,
4286        target: &'a LogicExpr<'a>,
4287        with: &'a LogicExpr<'a>,
4288    ) -> Option<&'a LogicExpr<'a>> {
4289        if std::ptr::eq(expr, target) {
4290            return Some(with);
4291        }
4292        let rebuilt = match expr {
4293            LogicExpr::BinaryOp { left, op, right } => {
4294                if let Some(right) = self.replace_subexpr(right, target, with) {
4295                    LogicExpr::BinaryOp {
4296                        left,
4297                        op: op.clone(),
4298                        right,
4299                    }
4300                } else {
4301                    let left = self.replace_subexpr(left, target, with)?;
4302                    LogicExpr::BinaryOp {
4303                        left,
4304                        op: op.clone(),
4305                        right,
4306                    }
4307                }
4308            }
4309            LogicExpr::Quantifier {
4310                kind,
4311                variable,
4312                body,
4313                island_id,
4314            } => LogicExpr::Quantifier {
4315                kind: *kind,
4316                variable: *variable,
4317                body: self.replace_subexpr(body, target, with)?,
4318                island_id: *island_id,
4319            },
4320            LogicExpr::Temporal { operator, body } => LogicExpr::Temporal {
4321                operator: *operator,
4322                body: self.replace_subexpr(body, target, with)?,
4323            },
4324            LogicExpr::Aspectual { operator, body } => LogicExpr::Aspectual {
4325                operator: *operator,
4326                body: self.replace_subexpr(body, target, with)?,
4327            },
4328            LogicExpr::Voice { operator, body } => LogicExpr::Voice {
4329                operator: *operator,
4330                body: self.replace_subexpr(body, target, with)?,
4331            },
4332            _ => return None,
4333        };
4334        Some(self.ctx.exprs.alloc(rebuilt))
4335    }
4336
4337    /// `body` recurring without end: G(F(body)).
4338    fn infinitely_often(&self, body: &'a LogicExpr<'a>) -> &'a LogicExpr<'a> {
4339        let eventually = self.ctx.exprs.alloc(LogicExpr::Temporal {
4340            operator: TemporalOperator::Eventually,
4341            body,
4342        });
4343        self.ctx.exprs.alloc(LogicExpr::Temporal {
4344            operator: TemporalOperator::Always,
4345            body: eventually,
4346        })
4347    }
4348
4349    /// Helper to extract verb specifically from NeoEvent structures
4350    fn extract_neo_event_verb(&self, expr: &LogicExpr<'a>) -> Option<Symbol> {
4351        match expr {
4352            LogicExpr::NeoEvent(data) => Some(data.verb),
4353            LogicExpr::Quantifier { body, .. } => self.extract_neo_event_verb(body),
4354            LogicExpr::BinaryOp { left, right, .. } => self
4355                .extract_neo_event_verb(left)
4356                .or_else(|| self.extract_neo_event_verb(right)),
4357            LogicExpr::Temporal { body, .. } => self.extract_neo_event_verb(body),
4358            LogicExpr::Aspectual { body, .. } => self.extract_neo_event_verb(body),
4359            _ => None,
4360        }
4361    }
4362
4363    /// Build roles for gapped clause using template guidance.
4364    /// NP args map to Theme/Recipient roles, PP args map by preposition type.
4365    fn build_gapped_roles(
4366        &self,
4367        subject_term: Term<'a>,
4368        np_args: &[Term<'a>],
4369        pp_args: &[(Symbol, Term<'a>)],
4370        template: &Option<EventTemplate<'a>>,
4371    ) -> Vec<(ThematicRole, Term<'a>)> {
4372        // Agent-gapping (non-constituent coordination, §2.1): "John gave Mary a book
4373        // and Sue a pen" — the remnant (Sue, a pen) fills the template's non-agent
4374        // NP roles (Recipient, Theme) IN ORDER and the agent is SHARED from the
4375        // template (John). Detected when the remnant count (subject + np_args) equals
4376        // the number of non-agent NP roles (≥ 2), i.e. the agent is the gap.
4377        if let Some(tmpl) = template {
4378            if let Some(shared_agent) = &tmpl.agent {
4379                let np_template_roles: Vec<_> = tmpl
4380                    .non_agent_roles
4381                    .iter()
4382                    .filter(|(r, _)| {
4383                        matches!(
4384                            r,
4385                            ThematicRole::Theme | ThematicRole::Recipient | ThematicRole::Patient
4386                        )
4387                    })
4388                    .collect();
4389                // A LONE bare-NP remnant after a complete transitive clause is
4390                // object coordination ("John saw himself and Mary" — Mary is
4391                // a second THEME, the agent is shared), not a new agent
4392                // inheriting the template's object.
4393                if np_template_roles.len() == 1 && np_args.is_empty() && pp_args.is_empty() {
4394                    let (role, _) = np_template_roles[0];
4395                    return vec![
4396                        (ThematicRole::Agent, shared_agent.clone()),
4397                        (*role, subject_term),
4398                    ];
4399                }
4400                if np_template_roles.len() >= 2 && 1 + np_args.len() == np_template_roles.len() {
4401                    let mut roles = vec![(ThematicRole::Agent, shared_agent.clone())];
4402                    let remnants: Vec<Term<'a>> = std::iter::once(subject_term)
4403                        .chain(np_args.iter().cloned())
4404                        .collect();
4405                    for ((role, _), arg) in np_template_roles.iter().zip(remnants.iter()) {
4406                        roles.push((*role, arg.clone()));
4407                    }
4408                    // Inherit template PP roles when none are overt in the remnant.
4409                    if pp_args.is_empty() {
4410                        for (role, term) in tmpl.non_agent_roles.iter().filter(|(r, _)| {
4411                            matches!(
4412                                r,
4413                                ThematicRole::Goal
4414                                    | ThematicRole::Source
4415                                    | ThematicRole::Location
4416                                    | ThematicRole::Instrument
4417                            )
4418                        }) {
4419                            roles.push((*role, term.clone()));
4420                        }
4421                    } else {
4422                        for (prep, term) in pp_args {
4423                            roles.push((self.preposition_to_role(*prep), term.clone()));
4424                        }
4425                    }
4426                    return roles;
4427                }
4428            }
4429        }
4430
4431        let mut roles = vec![(ThematicRole::Agent, subject_term)];
4432
4433        match template {
4434            Some(tmpl) => {
4435                let template_roles = &tmpl.non_agent_roles;
4436
4437                // Separate template roles into NP-type and PP-type
4438                let np_template_roles: Vec<_> = template_roles
4439                    .iter()
4440                    .filter(|(r, _)| {
4441                        matches!(
4442                            r,
4443                            ThematicRole::Theme | ThematicRole::Recipient | ThematicRole::Patient
4444                        )
4445                    })
4446                    .collect();
4447
4448                let pp_template_roles: Vec<_> = template_roles
4449                    .iter()
4450                    .filter(|(r, _)| {
4451                        matches!(
4452                            r,
4453                            ThematicRole::Goal
4454                                | ThematicRole::Source
4455                                | ThematicRole::Location
4456                                | ThematicRole::Instrument
4457                        )
4458                    })
4459                    .collect();
4460
4461                // Handle NPs by matching to template NP roles
4462                match (np_template_roles.len(), np_args.len()) {
4463                    (0, 0) => {} // Intransitive - no NP roles
4464                    (_, 0) => {
4465                        // Use all template NP roles unchanged
4466                        for (role, term) in &np_template_roles {
4467                            roles.push((*role, term.clone()));
4468                        }
4469                    }
4470                    (n, 1) if n > 0 => {
4471                        // 1 NP arg: replace LAST NP role (usually Theme), keep others
4472                        for (role, term) in np_template_roles.iter().take(n - 1) {
4473                            roles.push((*role, term.clone()));
4474                        }
4475                        if let Some((last_role, _)) = np_template_roles.last() {
4476                            roles.push((*last_role, np_args[0].clone()));
4477                        }
4478                    }
4479                    (n, m) if m == n => {
4480                        // Same count: replace all NP roles in order
4481                        for ((role, _), arg) in np_template_roles.iter().zip(np_args.iter()) {
4482                            roles.push((*role, arg.clone()));
4483                        }
4484                    }
4485                    (_, _) => {
4486                        // Fallback: assign Theme to each NP
4487                        for (i, arg) in np_args.iter().enumerate() {
4488                            let role = np_template_roles
4489                                .get(i)
4490                                .map(|(r, _)| *r)
4491                                .unwrap_or(ThematicRole::Theme);
4492                            roles.push((role, arg.clone()));
4493                        }
4494                    }
4495                }
4496
4497                // Handle PPs: use parsed PPs if provided, else use template
4498                if pp_args.is_empty() {
4499                    // Use template PP roles unchanged
4500                    for (role, term) in &pp_template_roles {
4501                        roles.push((*role, term.clone()));
4502                    }
4503                } else {
4504                    // Use parsed PPs, map preposition to role
4505                    for (prep, term) in pp_args {
4506                        let role = self.preposition_to_role(*prep);
4507                        roles.push((role, term.clone()));
4508                    }
4509                }
4510            }
4511            None => {
4512                // No template: backward-compat hardcoded Agent + Theme
4513                for arg in np_args {
4514                    roles.push((ThematicRole::Theme, arg.clone()));
4515                }
4516                for (prep, term) in pp_args {
4517                    let role = self.preposition_to_role(*prep);
4518                    roles.push((role, term.clone()));
4519                }
4520            }
4521        }
4522        roles
4523    }
4524
4525    /// Map preposition to thematic role
4526    fn preposition_to_role(&self, prep: Symbol) -> ThematicRole {
4527        let prep_str = self.interner.resolve(prep).to_lowercase();
4528        match prep_str.as_str() {
4529            "to" | "toward" | "towards" => ThematicRole::Goal,
4530            "from" => ThematicRole::Source,
4531            "in" | "on" | "at" => ThematicRole::Location,
4532            "with" | "by" => ThematicRole::Instrument,
4533            _ => ThematicRole::Location, // Default fallback
4534        }
4535    }
4536
4537    /// Check if modifier is temporal (for override filtering)
4538    fn is_temporal_modifier(&self, sym: Symbol) -> bool {
4539        let s = self.interner.resolve(sym).to_lowercase();
4540        matches!(
4541            s.as_str(),
4542            "yesterday" | "today" | "tomorrow" | "now" | "then" | "past" | "future"
4543        )
4544    }
4545}